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.
Example:
String myString = "I am a string!"; System.out.println(myString);
Output:
I am a String!
Recommended Books
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().
Example:
String string_len = "I am a String!"; System.out.println("The length of the string is " + string_len.length());
Output:
The length of the string is 14
Let’s look at some more methods that are commonly used
- toUpperCase()
Example
String string_case = "I am a String!"; System.out.println(string_case.toUpperCase());
Output
I AM A STRING!
- toLowerCase()
Example
String string_case = "I am a String!"; System.out.println(string_case.toLowerCase());
Output
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:
Example:
String string_index = "I am a String!"; System.out.println(string_index.indexOf("am"));
Output
2
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.
Example:
String first = "John"; String second = "Smith"; System.out.println(first + " " + second);
Output
John Smith
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”.
Example
String quoted_txt = "She said \"I do not want to live in New York\" angrily"; System.out.println(quoted_txt);
Output
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.
Example
int x = 10; String text = "Number ten in numerical form is written as "; System.out.println(text + x);
Output
Number ten in numerical form is written as 10