×

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

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

Types of Bitwise Operators in Java

In this tutorial, we will learn about the various types or kinds of bitwise operators in java. Before proceeding to bitwise operators, let us know what is meant by the...

6 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.