Learn Java - Classes, Methods, Inheritance, and Polymorphism - String Methods Cheatsheet - Codecademy
Learn Java - Classes, Methods, Inheritance, and Polymorphism - String Methods Cheatsheet - Codecademy
String Methods
In Java, the length() string method returns the total String str = "Codecademy";
number of characters – the length – of a String .
System.out.println(str.length());
// prints 10
In Java, the indexOf() string method returns the String str = "Hello World!";
first occurence of a character or a substring in a
String . The character/substring that you want to find
the index of goes inside of the () . System.out.println(str.indexOf("l"));
If indexOf() cannot find the character or substring, // prints 2
it will return -1.
System.out.println(str.indexOf("Wor"));
// prints 6
System.out.println(str.indexOf("z"));
// prints -1
System.out.println(s3);
// prints "Hello World!"
String Method equals() in Java
System.out.println(s2.equalsIgnoreCase("wo
rld"));
// prints true
In Java, the charAt() string method returns the String str = "This is a string";
character of a String at a specified index. The index
value is passed inside of the () , and should lie between
0 and length()-1 . System.out.println(str.charAt(0));
// prints 'T'
System.out.println(str.charAt(15));
// prints 'g'
In Java, we can easily convert a String to upper and String str = "Hello World!";
lower case with the help of a few string methods:
toUpperCase() returns the string value
converted to uppercase. String uppercase = str.toUpperCase();
toLowerCase() returns the string value // uppercase = "HELLO WORLD!"
converted to lowercase.