Java String type
In this chapter you will learn:
- How to declare Java String type
- Literals for Java String types
- Example - Java String type
- What are the difference between equals() and ==
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 www. j a v a 2 s .co m*/
}
}
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 . java2 s . c o 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:
Next chapter...
What you will learn in the next chapter:
- How to escape Java String Literals
- Syntax for String escape
- List value for string escape
- Example - Escape string value
- Example - Java strings must begin and end on the same line