Exploring the String objects

The objects of String are immutable.

Each time you alter an existing string, a new String object is created.

The original string is left unchanged.

A String type variable can be changed to point at other String object.

Create a string object


String myString = "this is a test";

For example, this statement displays myString:


String myString = "this is a test"; 
System.out.println(myString);

You can use + to concatenate two strings. For example, this statement


String myString = "A" + " B " + "C";

results in myString containing "A B C". The following program demonstrates the preceding concepts:


public class Main {

  public static void main(String args[]) {
    String strOb1 = "A ";
    String strOb2 = "B ";
    String strOb3 = strOb1 + " and " + strOb2;

    System.out.println(strOb1);
    System.out.println(strOb2);
    System.out.println(strOb3);

  }
}

The output produced by this program is shown here:


A 
B 
A  and B
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.