how2examples.com
Home - Introduction to Java Programming

Java Strings

The java.lang.String class is used to represent character strings.

String literals

A String literal is a sequence of zero, one or more characters enclosed in double quotes (e.g. "aBc $_12").

String concatenation

String concatenation is the process of creating a new String which is the result of combining (i.e. joining) the values of two other String objects. Java provides built-in support for the use of the + operator for the concatenation of String objects. At compile-time, when either operand of a + (i.e. what appears on the left and right of the + sign) is a String the compiler recognises that string concatenation, rather than arithmetic addition, is required.

Code snippet:
String a = "abcdefg";
String b = "qwerty";
String c = a+b;
System.out.println("c "+c);
Output from running code snippet:
c abcdefgqwerty
Code snippet:
Object o = new Object();
String s = "abcdefg"+o;
System.out.println(s);
Output from running code snippet:
abcdefgjava.lang.Object@3e25a5
Code snippet:
Integer i1 = 12;
Integer i2 = 34;
System.out.println(i1+i2+1+2+"abcdefg");
System.out.println("abcdefg"+i1+i2+1+2);
Output from running code snippet:
49abcdefg
abcdefg123412

Note that the + operator is only supported for arithmetic addition and string concatenation.

Code snippet:
Object o1 = new Object();
Object o2 = new Object();
System.out.println(o1+o2);
Result of trying to compile code snippet:
operator + cannot be applied to java.lang.Object,java.lang.Object
System.out.println(o1+o2);
                     ^
1 error

String methods

The String class defines a number of methods, some of which are listed below. As all String instances are immutable (i.e. cannot change their state after they are constructed) none of these methods alter the value of the String they are invoked on. The methods that perform a transformation on the the value of a String (e.g. trim()) return a newly constructed instance of String without altering the original.


See Also