×

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 StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

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.