Lesson 3 of 20

Strings

Working with Strings

Java's String class has many useful methods:

String s = "Hello, Java!";

s.length()          // 12
s.toUpperCase()     // "HELLO, JAVA!"
s.toLowerCase()     // "hello, java!"
s.substring(0, 5)   // "Hello"
s.charAt(7)         // 'J'
s.indexOf("Java")   // 7
s.contains("Java")  // true
s.replace("Java", "World")  // "Hello, World!"
s.trim()            // removes leading/trailing whitespace
s.startsWith("Hello")  // true
s.endsWith("!")        // true

String Comparison

Always use .equals() for content comparison (not ==):

String a = "hello";
String b = "hello";
System.out.println(a.equals(b));   // true
System.out.println(a.equalsIgnoreCase("HELLO"));  // true

String Formatting

String.format works like printf:

String msg = String.format("Pi is %.2f", 3.14159);
// "Pi is 3.14"

Your Task

Given s = "Hello, Java!", print:

  1. Its length
  2. It in uppercase
  3. The substring from index 0 to 5 (exclusive)
  4. The string with "Java" replaced by "World"
  5. Whether it contains "Java"
TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.