×

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in java can be treated as a string.

Example for string: “ Tutorials”

The strings are enclosed with the double quotes. The String class contains many methods. Strings in Java are available in java.lang package. The declaration of string in Java can be done in two ways:

  1. By using the string literal
  2. By using the heap area, i.e. new keyword

1. String literal

In the literal string, the string is created with double quotes.

Example:

String name =" Hello";

In the above example, the string is enclosed with double quotes. Each time you create the string literal, The Java virtual machine(JVM)  first checks the “string constant pool”. If the pool already has the string, then it will return the reference from the pool. If the string constant pool doesn’t contain the string, for the created string new instance will be treated and will store

 the string. Can be understood with the below example:

String str1 = "Hello"; 
String str2 =" Hello."  
String Declaration in Java

From the above example, the String str2 contains the same string which is declared in str1 will create one object. At the initial, the string object named  “hello“  is not found in JVM so it will create an instance for that variable. After the new string named str2 is created with the same value as str1, it will not create a new instance for that variable. So the new instance is not created for the string str2.

An example program for string declaration using the string literal.

StringExample.java

class StringExample {
  public static void main(String[] args) {
    
    // create strings
    String str1= "Programming";
    String str2= "Online";
    String str3= "competetions";


    // printing the string
    System.out.println(str1);   //programming will prints
    System.out.println(str2);  // online will prints
    System.out.println(str3);   // competetions will prints
  }
}

Output

String Declaration in Java

2) By using a new keyword

 A new keyword is used to allocate memory in the heap area.

Example:

String str = new String(“hello”);

JVM will create a new object in the heap memory area in this case. In the above example, the literal passed as parameter will store in the constant string pool, and the variable will point to the heap area.

Example 1

StringExampleNew.java

public class StringEx{    
public static void main(String args[]){    
String str1="Programming";// literal is created   
char ch[]={'R','e','c','u','r','s','i','o','n'};    
String str2=new String(ch);//character array is to string    
String str3=new String("Demo");// Programming string is created by new keyword    
System.out.println(str1);    
System.out.println(str2);    
System.out.println(str3);    
}
}    

Output:

String Declaration in Java

From the above program, the character array is converted to string, and str1,str2, and str3 display the result using the print( ) method.

StringExample.java

class StringExample{
public static void main(String args[])
{ 
  char c[]={'g','o','o','d'};
  String str1=new String (c); // new instance in heap area
  String str2=new String (str1); // copies the same instance as in str1
  System.out.println(str1);  // prints str1
  System.out.println(str2); // prints str2
}
}

Output

String Declaration in Java

From the above two examples, we can understand how to declare a string using the heap memory area.


Related Topics

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.