In Java, String may relate to two different things :
- Object
- Special treatment is given to String in Java as it is treated as an Object.
- Objects that are backed internally by a char array.
- There are two ways to create a string object :
- By string literal
- If means special treatment is asked. JVM will search for an object that contains a hello string; if found, it will use its reference, i.e., its address will be assigned to g; if not found, a new object with a hello string will be created.
- E.g. : String g = “hello”;
- By new keyword
- If means no special treatment is asked. So JVM doesn’t apply a search, but definitely, a new object will be created with a hello string in it.
- E.g. : String g = new String(“hello”);
- String class
- A string is a class, and it contains several built-in methods and properties.
- It is used to create and manipulate strings or, let’s say, string objects.
- All string literals in Java are implemented as instances of this class.
- The class includes methods like compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
- E.g. : String g = new String(“hello”);