Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Java Basics

    Strings, Printing and Input Conversion

    String is Java's type for text. Unlike the 8 primitives, it's a class — an object type (fully explained in

    Chapter 4 of 94 min read

    The Plain Picture#

    A string of beads, each bead a letter. You can count the beads, look at bead number 3, or cut out a section. And you can glue two strings together.

    The Real Names#

    • String is Java's type for text. Unlike the 8 primitives, it's a class — an object type (fully explained in Classes, Objects and Memory, including why it's immutable and why == is the wrong way to compare strings).

    • Joining strings is concatenation, with +.

    Under the Hood#

    Java
    String s = "StudyBuddy";
    s.length()            // 10
    s.charAt(0)           // 'S'      ← positions (indexes) start at 0, so the last is s.length() - 1
    s.substring(5)        // "Buddy"  ← from index 5 to the end
    s.substring(0, 5)     // "Study"  ← from 0 up to but NOT including 5
    s.indexOf("Buddy")    // 5        ← -1 if not found
    s.toUpperCase()   s.toLowerCase()   s.trim()   s.isEmpty()   s.contains("Bud")   s.startsWith("Stu")
    s.split(" ")          // cut into an array of pieces (Ch 8)

    Real output of several at once:

    Java
    System.out.println(
        s.length() +
            " " +
            s.charAt(0) +
            " " +
            s.substring(5) +
            " " +
            s.substring(0, 5) +
            " " +
            s.indexOf("Buddy")
    );
    // 10 S Buddy Study 5

    Comparing strings — always .equals:

    Java
    if (name.equals("Priya")) { ... }        // ✔ compares the text
    if (name == "Priya") { ... }             // ✘ compares whether they're the SAME object in memory — sometimes true, sometimes not

    (Why == "sometimes works" is explained with the String pool in Classes, Objects and Memory. For now: strings are compared with .equals, always.)

    Printing#

    Java
    System.out.println("with a new line");
    
    System.out.print("no new line");
    
    System.out.printf("Score: %d, avg: %.2f, name: %s%n", 200, 86.6666, "Priya");
    // Score: 200, avg: 86.67, name: Priya

    printf format specifiers: %d whole number, %.2f decimal with 2 places, %s string, %c char, %n new line, %5d pad to width 5, %-7s left-align in width 7. String.format(...) builds the same text without printing it.

    Converting between text and numbers#

    From How Computers Work Ch 9: the number 200 and the text "200" are different things. Converting text → number is parsing:

    Java
    int score = Integer.parseInt("200"); // text → int
    
    System.out.println(score + 1); // 201
    
    String text = String.valueOf(200); // int → text
    
    System.out.println(text + 1); // 2001    ← string + number = concatenation!
    
    double d = Double.parseDouble("86.5");
    
    Integer.parseInt("abc"); // runtime error: NumberFormatException

    Gotchas

    • "Score: " + 10 + 20 is "Score: 1020", not 30 — once the left side is a String, + means concatenation. Use parentheses: "Score: " + (10 + 20).

    • substring(a, b) excludes b. Its length is b - a.

    • Building a string in a loop with + is slow (a new string every time). Use StringBuilder — taught in Classes, Objects and Memory, and essential in DSA.

    Check yourself

    4 questions
    1

    What does "hello".substring(1, 4) return?

    Show answer

    "ell" (indexes 1, 2, 3).

    2

    How do you compare two strings for equal text?

    Show answer

    a.equals(b).

    3

    What does "Total: " + 5 + 5 print? How do you get "Total: 10"?

    Show answer

    Total: 55; write "Total: " + (5 + 5).

    4

    How do you turn the text "42" into a number you can add to?

    Show answer

    Integer.parseInt("42").