Quantcast
Channel: Learn Java Programming
Viewing all articles
Browse latest Browse all 39

String Literals : String Handling in Java Programming

$
0
0

In the last tutorial we have studied the basics of String in Java Programming. In this Chapter we will focus on String Literals in Java Programming.

A. String Literals in Java :

In Simple words, we can say that String Literal is Sequence of characters written in double quotes.

class FirstProgram {
public static void main(String[] args) {
   System.out.println("Hello World");
   }
}

In the above example we can say that String – “Hello World” written inside “System.out.println” will be called as String Literal.

B. String Literals is used to Create and Initialize String Object :

We know that in Java Programming, String is considered as Object not an array like C/C++.

class FirstProgram {
public static void main(String[] args) {
   String name = "Pritesh";
   System.out.println("Hello " + name + "!")
   }
}

Output of the Program :

Hello Pritesh !

Lets See how String Literal Works.

C. Working of String Literals :

JVM always maintains a String Constant Pool. If we declared a String and initialized it with String literal then String will be searched in String Constant Pool.
String Literal - String Constant Pool

class FirstProgram {
public static void main(String[] args) {
   String Str1;
   String Str2 = "Hello";
   }
}

Consider above program we can see, String “Hello” will be created inside “String Constant Pool” and then reference to that String is being assigned to a String Object “Str2″.

Consider the below program –

class FirstProgram {
public static void main(String[] args) {
   String Str1 = "Hello";
   String Str2 = "Hello";
   }
}

In this program, Only Single Object will be created inside Constant Pool and reference to that String will be returned to both Objects Str1 and Str2.
Assigning String Literals to 2 String Objects

D. Unicode Characters in Literals

In order to print PI Symbol we can use following Syntax –

class FirstProgram {
public static void main(String[] args) {
   String Str1 = "\u03C0";
   System.out.println(Str1);
   }
}

Similarly we can print multiple unicode characters in Java.

The post String Literals : String Handling in Java Programming appeared first on Learn Java Programming.


Viewing all articles
Browse latest Browse all 39

Trending Articles