Java String type

In this chapter you will learn:

  1. How to declare Java String type
  2. Literals for Java String types
  3. Example - Java String type
  4. 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:

  1. How to escape Java String Literals
  2. Syntax for String escape
  3. List value for string escape
  4. Example - Escape string value
  5. Example - Java strings must begin and end on the same line
Home »
  Java Tutorial »
    Java Langauge »
      Java Data Types
Java Primitive Data Types
Java boolean type
Java char type
Java char value escape
Java byte type
Java short type
Java int type
Java long type
Java float type
Java double type
Java String type
Java String Escape
Java String Concatenation