String in Java

If you remember, we had used String as data type earlier. Actually String is a class. It is used to store sequence of characters. Java String class provides a lot of options to perform operations on strings such as compare, concat, split, find length, replace, etc.

See the codes below:

char[] ch = {'B','C','A','B','O','O','S','T'}; String word = new String(ch);
String word = new String("BCABOOST");
String word="BCABOOST";
These all codes means same.

In first code, we created array and then created object with that variable. In Second code, we directly created object of String class with actual data.
Sounds confusing? Don't worry we will learn array, class, object and method in detail later.
And in third code, it is easy right, same as we learnt before. We have too many methods to do operation in String. We will talk about that here.

String Length

With the help of this method, we can find the length of our String.

String word = "BCABOOST"; System.out.println("The length of the word string is: " + word.length());
It will print The length of the txt string is: 8 as output.

Uppercase and Lowercase

var.toUpperCase() and var.toLowerCase()
With the help of this method, we can change case of our String.

String word = "BcaBOOst"; System.out.println(word.toUpperCase()); System.out.println(word.toLowerCase());
It will print BCABOOST and bcaboost as output.

Joining Strings

var1.concat(var2) and var1 + " " + var2
With the help of this method, we can join two srtings. Note that this will not update existing variable. It will be joined for that operation only. It is also called String Concatenation.

String word = "BCA"; String word2 = "BOOST"; System.out.println(word.concat(word2)); System.out.println(word + " " word2);
It will print BCABOOST and BCA BOOST as output. Note that we used " " for space in between two Strings.

These are some basic String methods. We have many more String methods in java. Click here to read them in details.

Test it yourself


public class JavaStrings { public static void main(String[] args) { String first = "BCA"; String last = "BOOST"; System.out.println("Length of first String: " + first.length()); System.out.println("Lowercase of last String: " + last.toLowerCase()); System.out.println("first + last: " + first.concat(last)); System.out.println("Still first String: " + first); first = first.concat(last); System.out.println("Now first String: " + first); } }


Length of first String: 3
Lowercase of last String: boost
first + last: BCABOOST
Still first String: BCA
Now first String: BCABOOST

Type Casting in Java Previous Next Math in Java