Hello People😀 I hope you all are doing well. This short article will be introduction about String class in java.
Let's begin...
What is a String?
String is a collection of characters in sequence. In programming it is used to represent text rather than numbers. Numbers can also be considered as a string if they are specified correctly. To represent a string we enclose it in within quotes.
phrase = Hello
This is not considered as a string.
phrase = "Hello"
Since it is enclosed by quotes here this is a string.
number = 1234
This is not considered as a string, this is considered as a number or to be more precise in programming this is considered as integer vale or int. All arithmetic operations can be performed on it.
number = "1234"
Since it is enclosed by quotes so here this will be considered as a string.
Remember we are talking about Java so please do not forget :-
So in Java all those examples will look like:-
phrase = "Hello";
//and
number = "1234";
What is a String class?
In Java String is a class found in the java.lang package. String is a class and not a data type like int and char. The String class represents character strings. In Java Strings are treated as objects and all string objects in Java are the instance of this String class. Strings are immutable, once it is created a String object can not be changed. The String objects are backed internally by a char array it means an array of character in Java works same as a Java String.
This will be more clear from the example:-
char[] ch = {'H','e','l','l','o'};
String st = new String(ch);
This works same as:-
String st = "Hello";
How String is created?
There are two ways String is created:-
1. Using literal syntax
Create a variable of type String and directly assign it a value in quotes:-
String phrase = "Hello People";
Complete Code:-
public class StringDemo {
public static void main(String []args) {
String phrase = "Hello People";
System.out.println(phrase);
}
}
You can run your code online here
Output:-
Create a new String object and add the literal in quotes.
String phrase = new String("Hello People");
Complete Code:-
public class StringDemo {
public static void main(String []args) {
String phrase = new String("This one using new keyword");
System.out.println(phrase);
}
}
You can run your code online here
Top comments (0)