How does the string class differ from other classes?

We can do it:

String string = "ourstring";

But we cannot create such objects for user-defined classes:

UserClass uc="";

How does Java allow us to set values ​​directly in the java.lang.String class?

+4
source share
4 answers

java.lang.String is a special class.

Feel free to read http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

It says

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

...

The Java language provides special support for the string operator concatenation (+), and for converting other objects to strings. String concatenation is done through StringBuilder (or StringBuffer) and its add method. string conversions are implemented using the toString method defined by Object and inherited by all Java classes. For more information on concatenating and converting strings, see Gosling, Joy, and Steele, Java Language Specification.

No other classes support this special support in the Java language.

You have to be very careful with its + function: it is widely discussed as unsafe for performance and memory.

+6
source

"" is the syntactic sugar for returning a String object from an interned string pool.

Consider this as an exception, not a rule. Regular object assignments should take the form

 MyObject myObject = new MyObject(); 
+3
source

For more on this section, see the online Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

Strings are good in Java. They benefit from being used as primitives, but are internal objects. There is an internal "interned string pool" that tracks String objects for you. This is done primarily for the sake of efficiency, but the abstraction is neat enough that you can pretend that String is just primitive, like int or char.

Remember that you do not need to create a String manually using a constructor similar to most objects!

+1
source

actually String = "ourstring" call the default constructor String Class new String (value char []). if you do not already see, we advise you to read String.clss

this is String.class descripe / ** * The String class represents character strings. All * string literals in Java programs, such as "abc" , are * implemented as instances of this class. *

* Lines are constant; their values ​​cannot be changed after they are * created. String buffers support mutable strings. * Since String objects are immutable, they can be shared. For instance: *

 
  * String str = "abc"; 
  * 

* equivalent to: *

 
  * char data [] = {'a', 'b', 'c'}; 
  * String str = new String (data); 
  * 

* Here are some examples of how strings can be used: *

 
  * System.out.println ("abc"); 
  * String cde = "cde"; 
  * System.out.println ("abc" + cde); 
  * String c = "abc" .substring (2,3); 
  * String d = cde.substring (1, 2); 
  * 
*

* /

0
source

All Articles