×

Java String

Definition

A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you will acquire a knowledge of the String class and String methods, along with several other tutorials of the Java String .

Introduction

Java strings are objects that are internally supported by char arrays. Since the array is immutable (not extensible), the string is also immutable. Each time a string is changed, a whole updated string is genrated.

In Java, string is basically an object that depicts a sequence of character values. Arrays of characters work just like Java strings. For example:

char[] ch={'t','u','t','o','r','i','a','l','a','n','d','e','x','a','m','p','l','e'};  
            String name =new String(ch);  

It is same as:

String name ="tutorialandexample";  

Memory allotment of String

Whenever a String object is created as a literal, it is created in the String constant pool. This allows the JVM to streamline the initialization of string literals.
Example:

String str = "Hello"; 

The string can also be declared using the new operator. That is, it can be dynamically assigned. When the string is dynamically allocated, new space is allocated in the heap that means it is not included to the string constant pool. 

The java.lang.String class implements the Serializable, Comparable, and CharSequence interfaces.

java-string

CharSequence Interface

We already know that the CharSequence interface is utilized to represent a string. The String, StringBuffer, and StringBuilder are the classes that implements it. This means that you can utilize the following three classes with the help of which you can create strings in Java:

java-string

Java strings are immutable. That is, it cannot be changed. Every time the string gets changed, a new instance is created. For variable strings, you can use the StringBuffer and StringBuilder classes.
I'll talk about immutable strings later. First, let's understand what a String is in Java and how a String object is created.

Define String in Java

In general, a string is a series of chars. However, in Java, String is an object that depicts a series of characters. The java.lang.String class is utilized to generate a string object.

Creating a String object

Following are the two ways with the help of which we can create String object:

  1. By string literal
  2. By new keyword

String Literal

We can build Java String literal with the help of double quotes.

For Example:

String name ="TutorialandExample";  

Whenever you create a string literal, the JVM first checks for a "string constant pool". In case, the string exists in the pool previously, an instance to the pooled instance is returned. In case, the string does not exist in the pool, a new string instance is build and put down in the pool.

For example:

String name1 ="TutorialandExample";  
String name2 ="TutorialandExample";   //won’t create a new instance  

In the above example, single object will be created. First, the JVM does not find a string object with the value "TutorialandExample" in the string constant pool, so it builds a new object. It then searches the pool for a string containing the value "TutorialandExample" and does not create a new object, but returns an instance to the same.

Use Of String literal in Java

To increase Java memory efficiency (because no new object is created if it already exists in the string constant pool).


Disadvantages

As mentioned at the beginning, String is a Java object. However, I didn't build a String object with the help of new keyword mentioned above. The compiler does this and uses a String literal (which in this case provides "Welcome") to create a String object and assign it to the provided String instance.
However, if the object already exists in memory, no new object will be created, but the same old object will be assigned to the new instance. That is, a string object that has the above two string instances (str1 and str2), but was created by the compiler (with the value "TutorialandExample") and both instances were assigned the same thing. Considering the above example, there are 18 string instances with the same value. This means that there is only one object with a value in memory and all 18 string instances point to the same object.

By new keyword

String name=new String("TutorialandExample");

In such cases, the JVM creates a new String object in the regular (non-pooled) heap and the literal "TutorialandExample" is put down in the string constant pool. The variable name refers to an object in the heap (non-pool).


Related Topics

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.