What is String in Java?

In this chapter, we are going to discuss String in java and different ways to create strings in Java. So I guess you have gone through the Classes and Objects in Java. 

1. What is String in Java?

In Java, String is one of the most widely used Java class. The string is an Object which represents the sequence of characters and it’s not of primitive type.

When we create a string object it means we are going to add a sequence of characters to the object and this object is immutable that means once String is created its value can never be changed or modified.

Remember:

  • A string is Immutable.
  • It is defined under java.lang package.
  • A string is a sequence of character.

Let’s move forward and learn something more about Strings.

2. Syntax of String

There are multiple ways to define a string in java but the most efficient way is below:

String {variable_name} = “ { sequence of character }“;

For example:

String message = “MasterInCoding”;

In Java,

Char ch[] = {‘H’,’e’,’l’,’l,’o’ };

Is same as

String name = “Hello”;

3. How to Create Strings in Java:

Let’s discuss all possible ways to create a string object.

3.1 Using String Literals:

This is the most common and efficient way to create a String object in terms of memory management. 

String name = “Tim”;

Remember: Whenever we create any string object then two objects are created in the memory, one in the heap memory and second one in the string constant pool.

So why I called String literals the most efficient approach in term of memory management because when we create string object using double-quotes then JVM looks into the string constant pool and check whether there is some other object holding the same value.

If yes then JVM will return the same object reference or else it will create a new object.

Creating-Strings-In-Java-Using-Literals

For example:

I created

String firstName = “Tim”;

Here, the value of the variable firstName is stored into the string pool. 

If I try to create

String firstName1 = “Tim”;

then it will not create another object because an object named “firstName” is already holding the value “Tim”.

Therefore, it will return “firstName” object reference to “firstName1” variable.

In this way, JVM will save memory.

3.2 Using new keyword:

In this way of creating strings, JVM will create a new String object every time.

String name1 = new String(“Tim”);

String name2 = new String(“Tim”);

Here, two objects will be created.

Example of String in Java using Equals Methods:

public class StringExample {

	public static void main(String... args) {
		//here two string objects will be created.
		String s1 = "hello";
		String s2 = "hello";
		String s3 = "nice";
		
		System.out.println(s1.equals(s2));//true
		System.out.println(s2.equals(s3));//false
	}

}

Happy Learning!