C
C
Core Java
Search…
30) String
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which means it is constant and can cannot be changed once it has been created.
Java String class is defined in java.lang package.

Ways to Create a String Object:

Method 1: Using "new" keyword

1
String nameOfSchoool = new String("DPS");
Copied!
Execute below:
1
package com.test.test1;
2
public class StringMethod1 {
3
public static void main(String[] args) {
4
String nameOfSchoool = new String("DPS");
5
System.out.println(nameOfSchoool);
6
}
7
}
Copied!
Method 2: Using "+" operator
1
String nameOfSchoool = "DPS";
Copied!
Execute below:
1
package com.test.test1;
2
public class StringMethod2 {
3
public static void main(String[] args) {
4
String nameOfSchoool = "DPS";
5
System.out.println(nameOfSchoool);
6
}
7
}
Copied!
Method 3: Using char[ ] array and passing it to overloaded String constructor.
1
char[] nameOfSchoolArray = { 'D', 'P', 'S' };
2
String nameOfSchoool = new String(nameOfSchoolArray);
Copied!
Execute below:
1
package com.test.test1;
2
public class StringMethod3 {
3
public static void main(String[] args) {
4
char[] nameOfSchoolArray = { 'D', 'P', 'S' };
5
String nameOfSchoool = new String(nameOfSchoolArray);
6
System.out.println(nameOfSchoool);
7
}
8
}
9
Copied!
Last modified 2yr ago