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

String nameOfSchoool = new String("DPS");

Execute below:

package com.test.test1;
public class StringMethod1 {
	public static void main(String[] args) {
		String nameOfSchoool = new String("DPS");
		System.out.println(nameOfSchoool);
	}
}

Method 2: Using "+" operator

String nameOfSchoool = "DPS";

Execute below:

package com.test.test1;
public class StringMethod2 {
	public static void main(String[] args) {
		String nameOfSchoool = "DPS";
		System.out.println(nameOfSchoool);
	}
}

Method 3: Using char[ ] array and passing it to overloaded String constructor.

char[] nameOfSchoolArray = { 'D', 'P', 'S' };
String nameOfSchoool = new String(nameOfSchoolArray);

Execute below:

package com.test.test1;
public class StringMethod3 {
	public static void main(String[] args) {
		char[] nameOfSchoolArray = { 'D', 'P', 'S' };
		String nameOfSchoool = new String(nameOfSchoolArray);
		System.out.println(nameOfSchoool);
	}
}

Last updated