Cheatsheets / Learn Java
String Methods
length() String Method in Java
In Java, the length() string method returns the total
number of characters – the length – of a String . String str = "Codecademy";
[Link]([Link]());
// prints 10
concat() String Method in Java
In Java, the concat() string method is used to append
one String to the end of another String . This String s1 = "Hello";
method returns a String representing the text of the String s2 = " World!";
combined strings.
String s3 = [Link](s2);
// concatenates strings s1 and s2
[Link](s3);
// prints "Hello World!"
String Method equals() in Java
In Java, the equals() string method tests for equality
between two String s. String s1 = "Hello";
equals() compares the contents of each String . If all String s2 = "World";
of the characters between the two match, the method
returns true . If any of the characters do not match, it [Link]([Link]("Hello"));
returns false .
// prints true
Additionally, if you want to compare two strings without
considering upper/lower cases, you can use
[Link]([Link]("Hello"));
.equalsIgnoreCase() .
// prints false
[Link]([Link]("w
orld"));
// prints true
indexOf() String Method in Java
In Java, the indexOf() string method returns the first
occurence of a character or a substring in a String . String str = "Hello World!";
The character/substring that you want to find the index
of goes inside of the () . [Link]([Link]("l"));
If indexOf() cannot find the character or substring, it // prints 2
will return -1.
[Link]([Link]("Wor"));
// prints 6
[Link]([Link]("z"));
// prints -1
charAt() String Method in Java
In Java, the charAt() string method returns the
character of a String at a specified index. The index String str = "This is a string";
value is passed inside of the () , and should lie
between 0 and length()-1 . [Link]([Link](0));
// prints 'T'
[Link]([Link](15));
// prints 'g'
toUpperCase() and toLowerCase() String Methods
In Java, we can easily convert a String to upper and
lower case with the help of a few string methods: String str = "Hello World!";
toUpperCase() returns the string value converted
String uppercase = [Link]();
to uppercase.
// uppercase = "HELLO WORLD!"
toLowerCase() returns the string value converted
to lowercase. String lowercase = [Link]();
// lowercase = "hello world!"