String
String
What is a string?
● In many other programming languages, string is a sequence of characters.
● In Java, strings are objects.
● Strings are surrounded by double quotes.
● Strings are immutable. Once a string is created, it can’t be changed.
● If we want to to modify a string, it will create a new string which contains the
modifications.
String Input and Output
● .next() and .nextLine() of the scanner class is used to take string as input.
● .next() only takes input until it finds a “ ” or space in the given input.
● .nextLine() takes input until it finds a “\n” in the given input.
1. class stringInput{
2. public static void main(String[] args) {
3. Scanner sc = new Scanner(System.in);
4. String input1 = sc.next();
5. String input2 = sc.nextLine();
6. System.out.println(input1);
7. System.out.println(input2);
8. }
9. }
Welcome to DrJava. Working directory is C:\Users\Desktop
CSE IS FUN.
>
CSE IS FUN.
>
CSE
CSE IS FUN.
String Initialization
● Initialization using String literals:
Literal String
Variable
name
String Initialization
● Creating an object of String class:
To create an object
Class name of String class
1. class stringLength {
2. public static void main(String[] args) {
3. String str1 = "Hello World";
4. String str2 = ""; // Empty string
5. System.out.println(str1.length());
6. System.out.println(str2.length());
7. }
8. }
0 1 2 3 4 5 6 7 8 9 10
C S E I S F U N .
1. class StringIteration {
2. public static void main(String[] args) {
3. String str = new String("Hello");
4. for (int i = 0; i <str.length(); i++){
5. System.out.println(str.charAt(i));
6. }
7. }
8. }
Welcome to DrJava. Working directory is C:\Users\Desktop
> run StringIteration
H
e
l
l
o
String Concatenation
● “+” is used to concatenate two or more strings 1. String str1 = "We are learning";
together. 2. String str2 = "Java.";
● New string created after concatenation. 3. int num = 123;
● If a different data type follows a string data type 4. String str3 = str1 + str2;
5. String str4 = str1 + num;
in concatenation, that data is automatically
6. System.out.println(str3);
converted to string. 7. System.out.println(str4);
int semester
y1 =output
String = “Fall ” +; y1 + 23;
20; = semester
System.out.println(output); Output:
Fall2023
String
int y1 =semester = “Fall
20; = y1
output + 23 ”+;semester;
System.out.println(output); Output:
43Fall
Comparing Strings
● String str1 = new String(“Hello”); String str2 = new String(“hello”);