i

JAVA Complete Course

String Operations

Before we start talking about String and operations on it, let’s shortly describe what it is at all. We can look at String as a sequence of chars. Strings are treated as objects in Java and we have class which represents it and give us opportunity to manipulate on it.

Strings are immutable objects which means that they are not changeable and any operation, for example concatenation, is giving another new object instead of changing existing one.

The easiest way to create a string variable is:

String var = “This is String”;

When compiler sees the literal “String” in code, it automatically creates an object with its value, in this case, "This is String'. Strings, like other objects, can be created with new keyword. First, let me show few examples of creating String variables and then describe each of them:

The first way of creating string is widely used. It is creating String in sting pool (memory). The created String (“Hello dear student”) is saved in string pool and if in any other place of application we will create another String variable with the same value, JVM won’t create new object, it will make reference to existing String in string pool.

The second way of creating string is very rarely used. It is just demonstration that each String in java is represented as an array of chars. So that, we can treat each string as an array and print each character of it.

This third way is almost never used as the new operators always creates new object and the created string is not saved in string pool. So if in any other place of application we will create another String variable with the same value, JVM will always create new object.

Accessor methods are ones which are used to obtain the information about object. One of the such methods is the length() method, which gives the number of characters in the string object. Code snippet below is an example of length(), method String class.

The String class has a method which provides concatenation of two strings and returns a new string that is string1 with string2 added to it at the end. We can also use the concat() method with string literals, as in this example below: