×

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

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 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.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.