A String is an object holding text. Useful methods:
length(), toUpperCase(), toLowerCase()
indexOf(), contains(), startsWith()
substring(start, end), charAt(i)
replace(), trim(), split()
String.format() and String.join()
Compare strings with a.equals(b), not ==. == checks whether they are the same object.
💡 Key Takeaways: Java Strings
Mastering Java Strings helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
Java Strings Code Example
Java
public class Main {
public static void main(String[] args) {
String s = " Learn Java at CodesInTech ".trim();
System.out.println(s.length());
System.out.println(s.toUpperCase());
System.out.println(s.substring(6, 10));
System.out.println(s.contains("Codes"));
System.out.println(s.replace("Java", "Kotlin"));
System.out.println(String.join("-", s.split(" ")));
System.out.println(String.format("%s has %d chars", "Java", 4));
System.out.println("java".equals("java"));
}
}
Output
25
LEARN JAVA AT CODESINTECH
Java
true
Learn Kotlin at CodesInTech
Learn-Java-at-CodesInTech
Java has 4 chars
true
Run this example on your own computer. The "Get Started" lesson shows how to set it up.