Java String type
Description
The String class represents character strings. A quoted string constant can be assigned to a String variable.
Literal
String literals in Java are specified by enclosing a sequence of characters between a pair of double quotes. In Java strings are actually object types.
Example
Declare String type variable.
public class Main{
public static void main(String[] argv){
String str = "this is a test from java2s.com";
System.out.println(str);/*from w w w . j av a2 s. com*/
}
}
The output:
equals() vs ==
equals( )
method and the ==
operator perform two different operations.
equals( )
method compares the characters inside a String object.
The ==
operator compares two object references to see whether they refer to the same instance.
The following program shows the differences:
public class Main {
public static void main(String args[]) {
String s1 = "demo2s.com";
String s2 = new String(s1);
/*ww w . j a va 2s . co m*/
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
Here is the output of the preceding example: