×

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 Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Factorial Program in Java using Recursion

Factorial Program in Java Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.