x

Java – String

PREV     NEXT

  •  String represents a group of character.
  • In java, string is an object of String class in java.lang package but in C language, it is an array of characters in which the last character is ‘\0’.
  • Java has character array too but String is a class. String is also a data type since a class is also called user defined data type.

Syntax :


String welcome = “hello”;

where, ‘welcome’ is a variable to store the data which is of type ‘String’. Thus a group of characters is assigned to the variable ‘welcome’ . As already mentioned, String is a class, therefore an object of type String is created and referenced by a variable ‘welcome’.

We have another way of creating String by using new operator as

String welcome = new String(“hello”);

The string ‘hello’ is assigned to the String variable ‘welcome’.

This would produce following result:

Output:

Hello

 Note: String class is made ‘final’ class. Strings are constant which means, their values cannot be changed once they are created.

String Class Methods:

int length(): To find the length of a string.
s.length(); gives the length of string s.


Output:

C:\> javac StringLengthExample.java
C:\> java StringLengthExample
Enter a string to find its length:
Hello
length of string is : 5

String concat(String s): To concatenate or join two strings.
String s3 = s1.concat(s2);  String s1 and s2 are concatenated or joined and the resulting String is stored in String object s3.

Output:

C:\> javac StringConcatExample.java
C:\> java StringConcatExample
Enter Your First String:
Hello
Enter Your Second String:
World
Concatenated string is: HelloWorld

Pls refer the below link to explore more String methods.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#method_detail

 Strings are immutable:

Strings are immutabe which means, their value cannot be changed once they are created. But if we try to modify the contents of a String object, then the JVM will modify the content and store it in a new object instead of the original object. The original object will remain unmodified.

Output:

xyz

When you see the output of the program, it looks like the String s is modified. But what happened is that the original object remains unchanged and a new object is created with the modified data during its construction and the variable s refers to the newly created object.
But there are some conditions where we will need mutable Strings and is achieved by StringBuffer which we will discuss in the next chapter.

PREV     NEXT



Like it? Please Spread the word!