
Now we are going to learn some interesting things about the java String type.
Can you remember the HelloWorld program that we’ve written? There, the statement;
1 |
System.out.println("Hello World!"); |
is the basic output format that we have learnt. When you write this statement and run the program, the sentence “Hello World!” will be given out.
Now, this “Hello World!” is a String. So you output a String. Just like 17 is an example of type int, “Hello World!” is an example of type String. Now try to modify the statement as follows;
1 |
System.out.println("Hello "+"my "+"World!"); |
OUTPUT:
Hello my World!
Now the + symbol joins two strings together.
Note the space after “o” in Hello and “y” in my. Without those spaces the output will be “HellomyWorld!“.
You can type almost any character within “ “ marks.
But, what if you want to type the double quotation marks themselves?
For that, you can use the “\” symbol before the quotation mark.
Eg:
1 |
System.out.println("Mary says, \"Hello World!\""); |
OUTPUT:
Mary says, “Hello World!”
Escape Character
This backslash “\” character is a special one. This is called the “escape character”. If you add it, most often it will produce an error. Check it!
1 |
System.out.println("I want to print \ character"); // :( ERROR! |
Now can you guess how to add the backslash character itself to the string? Use \\ twice 🙂
1 |
System.out.println("I want to print \\ character"); // :) CORRECT! |
How did we add a new line to the output?
Yeh we wrote again. But there’s a technique to add a linefeed without writing the code again. Use “\n” for that.
1 |
System.out.println("This is the 1st line \nThis is the 2nd line"); |
OUTPUT:
This is the 1st line
This is the 2nd line
Check this as well.
The “\t” will add a little gap(tab) between the two sentences in left and right of “\t”.
1 |
System.out.println("No. of students: \t 25 "); |
OUTPUT:
No. of students: 25
Actually, allowed characters with the backslash are follows: \n, \t, \b, \f, \r, \”, \’ and \\.
If you are interested, check the use of each one by googling. I have told you the most often used ones.
This is the end of part 1 of the String operation tutorial. Let’s go to the part 2 quickly…