Java Strings

String methods and concatenation.

✍️ 2 exercises in this lesson

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.

Java Strings Practice Exercises

Check what you learned in “Java Strings”.

/ 2 solved
Fill in the blank

Compare two strings by content.

if (a.(b)) { }
✓ Correct! Not quite. Try again.
Multiple choice

Which method returns part of a string?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services