In this second chapter we learn how to declare and initialize local variables.

Local variables are defined in methods such as main. Before they're used they need to be initialized.

Variables hold values of various types. In this chapter we learn about int, double, String variables.

Some operators are overloaded, e.g.: + (for Strings and the numeric types), or / (for int and double), etc.

To convert between double and int one can use casting: int a = (int) 3.141592;

The Scanner class in java.util can be used to create objects of that type that can read from the keyboard.

int and double are primitive types. java.lang.String and java.util.Scanner are reference (or user-defined) types.

Instances of type Scanner and/or String are called objects; new instances are obtained using the new operator.

Objects usually have useful instance methods that we can (and should) invoke via references to them, using the dot operator.

Some examples for Strings and Scanners: nextLine(), hasNextLine(), contains(...), substring(...), charAt(...) etc.

Here's an example of a program that combines all of the above:

class MilitaryTime { // this is your problem P2.17 on page 73 
  public static void main(String[] args) {
    // read user input: 
    java.util.Scanner in = new java.util.Scanner(; 
    System.out.print("Enter the first time: "); 
    String time1, time2; 
    time1 = in.nextLine(); 
    System.out.print("Enter the second time: "); 
    time2 = in.nextLine();

    // express times in minutes from the start of the day: 
    int h1, m1, h2, m2; 
    int t1, t2, d; 
    h1 = Integer.parseInt(time1.substring(0, 2));
    m1 = Integer.parseInt(time1.substring(2));
    t1 = h1 * 60 + m1; 

    h2 = Integer.parseInt(time2.substring(0, 2));
    m2 = Integer.parseInt(time2.substring(2));
    t2 = h2 * 60 + m2; 

    // calculate difference in minutes correctly 
    d = (t2 - t1 + 24 * 60) % (24 * 60); // do you see why? 

    System.out.println(d / 60 + " hours " + d % 60 + " minutes");    
Various other classes (java.lang.Integer, java.lang.Double, java.lang.Math) also contain useful static methods.

Static methods are accessed via the class name, also using the dot operator.

Such is the case in the example above with Integer.parseInt(...).

The same is true of the popular methods Math.pow(..., ...) or Math.sqrt(...).

Classes in java.lang package are imported automatically. is a static variable in class java.lang.System that models the keyboard.

Check the frontmatter for string and mathematical operations, syntax of local variable declaration and initialization etc.

Check the backmatter for useful summaries on Input and Output.