Java Strings
char[] str = {'S','T','R','I','N','G'};
String s = new String(str);
is same as :
String s = "String";
Syntax of strings in Java :
String <String_name> = "<sequence_of_string>";
Example :
String str = "JavaTutorial";
In the above example, str is a reference, and “JavaTutorial” is an object.
Different ways to create a string in Java :
In Java, strings can be created in two ways :
1.By using string literal
2.By using the new
Creating String using String literal :
String s1= "String literal"
We use double quotes("") to create string using string literal. Before creating a new string instance, JVM verifies if the same string is already present in the string pool or not. If it is already present, then JVM returns a reference to the pooled instance otherwise, a new string instance is created.
Creating String using new :
String s=new String("Harry");
When we create a string using "new", a new object is always created in the heap memory.
See the examples given below to get a better understanding of String literal and String object :
String str1 = "JavaTutorial";
String str2 = "JavaTutorial"
System.out.println(str1 == str2);
Output
True
Returns true because str1 and str2 are referencing the same object present in the string constant pool. Now, let's see the case of the String object :
String str1 = new String("Keep coding");
String str2 = new String("Keep coding"");
System.out.println(str1 == str2);
Output
False
Although the value of both the string object is the same, still false is displayed as output because str1 and str2 are two different string objects created in the heap. That's why it is not considered a good practice two compare two strings using the == operator. Always use the equals() method to compare two strings in Java.
Different ways to print in Java :
We can use the following ways to print in Java:
System.out.print() // No newline at the end
System.out.println() // Prints a new line at the end
System.out.printf()
System.out.format()
System.out.printf("%c",ch)
Example
package com.company;
import java.util.Scanner;
public class strings {
public static void main(String[] args) {
String name = new String("Java");
String name = "Java";
System.out.print("The name is: ");
System.out.print(name);
int a = 6;
float b = 5.6454f;
System.out.printf("The value of a is %d and value of b is %8.2f", a, b);
System.out.format("The value of a is %d and value of b is %f", a, b);
Scanner sc = new Scanner(System.in);
String st = sc.next();
System.out.println(st);
}
}
Output
The name is :
Java
The value of a is 6 and value of b is 5.65
The value of a is 6 and value of b is 5.645400
1
1
Java
The value of a is 6 and value of b is 5.65
The value of a is 6 and value of b is 5.645400
1
1