You are on page 1of 3

String with example

String is the datatype that defines and support the character strings. In java strings are object.

System.out.println(“in java, strings are objects”);

The string “in java, strings are objects” are automatically made into a string object by java.

Constructing an string
 We can construct the string by using the new and calling the string constructor

For ex : string str = new string(“HELLO”);

 We can also construct a string from another string

For ex : string str = new string(“HELLO”);

String str2 = new string (“str”);

Here, str2 will also contain the character string “HELLO”.

 Another way to create a string as,

String str = “java strings are powerfull”;

Here, str is initialized to the character sequence “java strings are powerfull”

 Once we created a string object, we can use it anywhere in the program,

For example: here we use string object as an argument to println() as,

Class stringDemo

Public static void main(string[] args)

String str1 = new string(“java strings are objects”);

String str2 = “they are constructed in various ways”;

String str3 = new string (str2);

System.out.println(str1);

System.out.println(str2);

System.out.println(str3);
}
}

Output:

java strings are objects

they are constructed in various ways

they are constructed in various ways

Three functions operates on string


length()
This function returns the length of the string. A string’s length is the number of characters that it
containes .

Syntax: int length()

Example: string str = “Theta”

System.out.println( str.length() );

It displays 5 because there are 5 characters in str.

You might also like