Strings in Java
In this tutorial, we are going to learn about strings in java. We will be going through some of the methods that most commonly used for string operations followed by some handy examples.
What is a String?
Strings in Java are used for storing text. String is a variable in Java that contains a collection of words which are surrounded within the double quotation.
Let’s look at an example of how we can create a variable string and assign some text to it.
String myString = "I am a string!"; System.out.println(myString);
I am a String!
The Length of a String
Any text that goes inside the variable of string in Java is considered an object, which means that we can apply different methods on the string. For example if you want to find out the length of the string, we can use a method called length().
String string_len = "I am a String!"; System.out.println("The length of the string is " + string_len.length());
The length of the string is 14
Let’s look at some more methods that are commonly used
String string_case = "I am a String!"; System.out.println(string_case.toUpperCase());
I AM A STRING!
String string_case = "I am a String!"; System.out.println(string_case.toLowerCase());
i am a string!
Finding the Index Inside a String
We can find the index of the position of the first occurring character within the string that includes blank space as well to using an indexOf() method. For example:
String string_index = "I am a String!"; System.out.println(string_index.indexOf("am"));
Concatenation in String
The + operator in java is used for concatenating for joining strings. Let’s say you have two strings and you want to do I am both of them.
String first = "John"; String second = "Smith"; System.out.println(first + " " + second);
Special characters in String
Previously, we have learned that strings should be written within double quotes, however sometimes we may come across situations where we want to use a word or a sentence that is quoted by someone.
For example: “she said “I do not want to live in New York” angrily”.
String quoted_txt = "She said \"I do not want to live in New York\" angrily"; System.out.println(quoted_txt);
She said "I do not want to live in New York" angrily
To avoid this problem reuse a backslash escape character. This basically eliminates the problem for the error and turns the special character into a string character.
Strings and Numbers together
You can write strings in numbers together by using the concatenating method through + operator.
int x = 10; String text = "Number ten in numerical form is written as "; System.out.println(text + x);
Number ten in numerical form is written as 10