codegurukool.com · Free coding tutorials & online compiler

Home › Java Tutorial › Java strings

Java strings

Text is an object with many methods.

A String cannot be changed; methods return a new one. Useful methods: length(), toUpperCase(), substring(start, end), indexOf, replace, charAt. Compare text with equals(), never with ==. Join strings with + or String.join.

Example code

public class Main {
  public static void main(String[] args) {
    String s = "Hello, World";
    System.out.println(s.length());
    System.out.println(s.toUpperCase());
    System.out.println(s.substring(0, 5));
    System.out.println(s.indexOf("World"));
    System.out.println(s.replace("World", "Java"));
    System.out.println(s.charAt(1));
    System.out.println("a".equals("a"));
    System.out.println(String.join("-", "a", "b", "c"));
  }
}

Run this code in the online editor

← Java operatorsJava math →