Java
In this tutorial we will learn about the String class in Java programming language.
A string is a sequence of characters enclosed in double quotes.
To store string value in Java we take help of the String class.
String
So, all the string values that we create are actually objects of the String class.
String variableName = "Some string value.";
Where, String is the String class that we use to create the string. variableName is the name of the variable that will hold the string value.
variableName
"Some string value." within double quotes is a String constant i.e. a string value that is assigned to the string variable variableName.
"Some string value."
Following are the points to note about String.
"Hello World"
+
String class provides us several methods that we can use. Some of them are listed below.
length()
str.charAt(index)
index
str
str1.equals(str2)
str1
str2
true
false
toCharArray(str)
toLowerCase(str)
toUpperCase(str)
This problem can be solved using charAt() and length() method and using for loop.
charAt()
class Example { public static void main(String[] args) { // string String str = "Hello World"; // total characters int len = str.length(); // print characters for (int i = 0; i < len; i++) { System.out.println("Index: " + i + "\tChar: " + str.charAt(i)); } } }
Output:
$ javac Example.java $ java Example Index: 0 Char: H Index: 1 Char: e Index: 2 Char: l Index: 3 Char: l Index: 4 Char: o Index: 5 Char: Index: 6 Char: W Index: 7 Char: o Index: 8 Char: r Index: 9 Char: l Index: 10 Char: d
To convert a string into a character array we can use the toCharArray() method and then use the for loop to print the content of the array.
toCharArray()
for
class Example { public static void main(String[] args) { // string String str = "Hello World"; // character array char[] chArr = str.toCharArray(); // print the content for (char ch: chArr) { System.out.println(ch); } } }
$ javac Example.java $ java Example H e l l o W o r l d
class Example { public static void main(String[] args) { // string String str = "Hello World"; // to lower case String strLowerCase = str.toLowerCase(); // output System.out.println(strLowerCase); } }
$ javac Example.java $ java Example hello world