Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised September 1, 2025)

Previous: 2. Strings and Math

HelloStrings

//
// HelloStrings.java
//


public class HelloStrings
{
    public static void main(String[] args)
    {
        String hello = "HelloWorld";
        System.out.println("hello: " + hello);

        // A String variable is a reference to a String object,
        // which has methods (functions) like `length()`

        System.out.println("hello.length(): " + hello.length());

        // String indexing is 0-based

        System.out.println("hello.charAt(0): " + hello.charAt(0));
        System.out.println("hello.charAt(1): " + hello.charAt(1));
        System.out.println("hello.charAt(2): " + hello.charAt(2));

        // The String method `substring(a,b)` returns the substring
        // specified by the half-open interval [a,b)

        String firstPart = hello.substring(0,5); 
        System.out.println("firstPart:" + firstPart);

        // hello.substring(a) is shorthand for hello.substring(a,
        // hello.length())

        String secondPart = hello.substring(5);
        System.out.println("secondPart:" + secondPart);
    }
}

Output:

hello: HelloWorld
hello.length(): 10
hello.charAt(0): H
hello.charAt(1): e
hello.charAt(2): l
firstPart:Hello
secondPart:World

Next: