wiki:ControlSystems/SoftwareTeam/Training/GettingStarted/IntroJava

Version 16 (modified by David Albert, 6 years ago) (diff)

--

Introduction to Java

Java is a programming language. It consists of a small, concise set of words that let you describe to the computer exactly what you want it to do. A Java program consists of one or more files. We use a Microsoft program called VSCode to write and run Java programs. Each program must have its own folder. To write your first Java program, you need to create a new folder for it. First create a folder to hold all of your Java projects in your Documents folder named Java Projects. Then in the Java Projects folder, create another new folder named Hello World that will hold your first program. Java Projects Folder

In VSCode:

  1. Select File->Open Folder and choose the JavaProjects?\Hello World folder you just created.
  2. Select File->New which will open the editor for you to enter a new program
  3. Cut and paste the following program into the editor:
    public class Hello {
        public static void main(String args[]) {
            System.out.println("Hello world");
        }
    }
    
  4. Select File->Save and name the file Hello.java the name is important; it must be Hello.java with a capital H (case matters to Java). The name of the file must be the same as the name of the class (more on classes later)
  5. In the left navigation window, you'll now see Hello.java with a red J icon next to it; right click on the Hello.java and select Run
  6. A terminal window will open, the program will be compiled and then run; you'll see the output: Hello world!

Variables

Let's try a slightly more complex program that will introduce variables. A variable is like a box; you can put only one type of thing in the box, for example an integer number or a character or a string of characters. Variables are an important part of every program because they allow the program to do different things depending on what's in the box.

  1. Close the Hello World folder (File->Close Folder)
  2. Make a new folder in your Java Projects folder named VariablesExample
  3. Open the folder (File->Open Folder)
  4. Create a new file: (File->New)
  5. Cut and paste the program below into the editor window:
    public class VariablesExample {
        public static void main(String args[]) {
            int a;  // create a variable that can hold an integer number
            int b;  // create another integer variable named b
            int c;
    
            a = 3;
            b = 4;
            c = a * b;
            System.out.println(c);
        }
    }
    
  6. Save the file as VariablesExample.java (File->Save)
  7. Run the program: right click on VariablesExample.java in the left panel and select Run
  8. In the output terminal window, observe that the number 12 is output.
  9. Change the program, adding more variables, changing numbers and the formula and run it again.

Debugger

With the VariablesExample.java program above open in the editor click to the left of the line number (7) for the line a=3; and a red dot will appear called a breakpoint. Breakpoint

  1. Click Debug->Start Debugging
  2. The program will start running but will stop (break) at line 7

Program stopped at breakpoint

  1. Click on the Step-over icon Step Over Tool Icon above the editor (or press function key F10) to execute that line of code and then stop again
  2. Observe the Variables window in the left navigation panel and note that there is now a variable named 'a' with the value 3

Variables window

  1. Press F10 again to execute the line b=4 and observe the variable appearing in the Variables window
  2. Double click on the variable b in the Variables window and change its value to 5
  3. Press F10 again to execute the line c=a*b and observe the variable c appearing in the Variables window with the value 15.
  4. Press the Continue tool Continue tool icon (or function key F5) above the editor window to allow the program to continue running to the end. Observe the value printed in the output terminal window.

Conditionals

Programs need to be able to react differently to varying data. Conditional statements let us do this. For example, a robot must be able to monitor its sensors to prevent collisions. Consider (and try running) the following program:

  • Create a new folder and new file; cut and paste this program into it and save it as ConditionalExample.java
    public class ConditionalExample {
        public static void main(String args[]) {
            int rangeInInches;
    
            rangeInInches = 10;
    
            if (rangeInInches < 20) {
               System.out.println("stop motors so we don't crash!");
            } else {
               System.out.println("full speed ahead!");
            }
        }
    }
    
  • Save the program as ConditionalExample.java (notice how the name of the file must match the name of the class)
  • Run the program using the debugger with a breakpoint set on the first executable line (rangeInInches=10); step through the program using the stepover tool and observe the flow of the program.
  • What happens if you change the values stored in the variable rangeInInches to 25?

Loops

It's also important for a program to be able to do things repeatedly; for example, the robot must read its sensors repeatedly and react only when certain conditions are met. Consider (and try running) the following program:

public class LoopExample {
    public static void main(String args[]) {
        int counter;  

        counter = 1;
        while (counter <= 10) {
            System.out.println(counter);
            counter = counter + 1;
        }
    }
}
  • Save this program as LoopExample.java
  • Run the program in the debugger with a breakpoint set at the line while (counter <= 10)
  • Step through the program a line at a time, observing the program output, variables, and flow of execution
  • There are three types of loops in Java including while, for, and do loops. Read about them and try a few!

Functions/Methods

All modern programming languages allow you to extend the language by creating new command words. In Java, a new word is called a function. Functions are like machines that have an input and an output; you put something(s) into the function execute the function and the function does something that might include providing an output. Every Java function has 4 primary characteristics:

  • a name
  • optional inputs (called parameters)
  • a body (the code that defines what the function does)
  • an optional output (called a return value)

Consider the following example of a function:

   int squared(int a) {
       return a * a;
   }

The function's name is 'squared' and it takes an input parameter that is an integer and is referred to within the function as a. The function returns an integer that it computes by multiplying a by itself.

Functions can take more than one parameter, but they can only return 1 value (or no values). Consider this function that takes two input parameters and returns no value:

   void sayit(String msg, int times) {
        for (int n=0; n<times; n++) {
            System.out.println(msg);
        }
   }

Open your Hello World project folder and modify the Hello.java program as follows:

public class Hello {

    static void sayit(String msg, int times) {
        for (int n=0; n<times; n++) {
            System.out.println(msg);
        }
   }
    public static void main(String args[]) {
        System.out.println("Hello world");
        sayit("howdy", 10);
    }
}
  • Run the program and observe the output
  • For now, we're going to ignore the keywords public and static, we'll get to those soon

Objects and Classes

Java is an object-oriented language; it doesn't limit you to the pre-defined types of data (integers, doubles, chars, etc.); it allows you to create new types of data. New data types are called "classes". A class can hold data and can contain functions (called methods) that act on that data. Java comes with many pre-defined classes such as String and you can define new classes; for example:

    public class MyClass {
        int x = 5;

        static void printX(void) {
            System.out.println("X="+x);
        }
    }

NOTE: Class names start with an upper-case letter and must be in a file with the class name (e.g. MyClass.java)

You can create and use new variables (objects) of the MyClass type:

   MyClass myObject;         // declare an object variable

   myObject = new MyClass(); // create object and store in variable
   myObject.printX();        // invoke a method on the object

Constructors

You create an object by calling a special method called the constructor. In the example above, the constructor was MyClass() and is the default constructor that any class has. You can create additional constructor methods for your classes that do things like initializing their data members or preparing hardware they are associated with for use. For example, when creating an xbox object, you would call the constructor XboxController(0); to indicate that you want to use the first (0th) xbox controller. Consider this example:

class Student {
    private String name;
    public int averageGrade;


    public Student(String n, int avg) {
        name = n;
        averageGrade = avg;
    }

    public static void main(String[] args) {
        Student s = new Student("John", 9);
    }
}

Class relationships

There two main ways classes can be related:

  • Hierarchical: Classes that are related hierarchically will pass the "isa" test. For example, an Apple isa Fruit. A Car isa Vehicle.
  • Containment : Classes that are related by containment will pass the "hasa" test. For example, an Apple hasa Seed. A Car hasa Passenger.

Class Hierarchy (Inheritance)

Inheritance provides a clean method for "factoring" your software. If many objects of the same type share some functionality, it's useful (important) to write and maintain that functionality in one place. With large code-bases, this makes code smaller, easier to write, easier to understand, and easier to repair (if you find a bug, you only need to fix it in one place).

For example, you can define a class Fruit and then extend it with sub-classes such as Apple (and Orange, Banana, Kiwi, etc.). Each sub-class meets the "isa" test: an Apple isa Fruit.

When a class extends another class, it inherits all of the attributes and functions of the parent (super) class.

Create a new folder (InheritanceExample) and in it create the following java files:

Fruit.java:

public class Fruit {
    int weight;           // weight of the fruit (grams)
    int sugar;            // sugar contained (grams)
    final int sweet = 10; // ratio to be "sweet" (percent)

    public Fruit(int weight_grams, int sugar_grams) {
        this.weight = weight_grams;
        this.sugar  = sugar_grams;
    }

    // Fruit is sweet if more than 10% sugar
    public void eat() {
        if (sugar * sweet > weight) {
            System.out.println("Sweet!");
        } else {
            System.out.println("Tart.");
        }
    }
}

Apple.java:

import java.lang.String;

public class Apple extends Fruit {
    String variant;

    public Apple(String variant, int weight_grams, int sugar_grams) {
        super(weight_grams, sugar_grams);
        this.variant = variant;
    }

    @Override
    public void eat() {
        System.out.print("Eating a "+variant+" Apple: ");
        super.eat();
    }
}

Grapefruit.java:

import java.lang.String;

public class Grapefruit extends Fruit {
    String color;

    public Grapefruit(String color, int weight_grams, int sugar_grams) {
        super(weight_grams, sugar_grams);
        this.color= color;
    }

    @Override
    public void eat() {
        System.out.print("Eating a "+color+" Grapefruit: ");
        super.eat();
    }
}

You can then create a program that uses these classes named Inheritance.java

public class Inheritance {
    public static void main(String args[]) {
        Apple a      = new Apple("Honeycrisp", 100, 12);
        Grapefruit g = new Grapefruit("Pink", 100, 4);
        Fruit f = a;
        f.eat();
        g.eat();
        // g=a; <<< illegal because an Apple is not a Grapefruit (fails isa test)
    }
}

Use the debugger to run and explore the Inheritance program and explore what happens in each line of the program. Be sure to step into functions to see how the code flows between the classes. Examine how the Apple class overrides and extends the eat() method of the Fruit class including:

  • the use of the @Override notation to indicate to the reader that a superclass method is being overridden
  • the use of the super.eat() call to invoke the eat method of the extended super class (Fruit)

Class containment

Sometimes it's useful to model the containment relationship between classes. For example, consider the following classes:

Plane.java:

import java.util.ArrayList;

public class Plane {
    ArrayList<Passenger> passengers;
    int seats;

    public Plane(int seats) {
        this.seats = seats;
        passengers = new ArrayList<>();
    }

    public void board(Passenger p) {
        if (passengers.size() < seats) {
            passengers.add(p);
        } else {
            System.out.println("Sorry, plane is full.");
        }
    }

    public int weight() {
        int w=0;
        for (Passenger p:passengers) {
             w += p.weight;
        }
        return w;
    }
}

Passenger.java

public class Passenger {
    public int weight;
    String name;

    public Passenger(String name, int weight) {
        this.name = name;
        this.weight=weight;
    }
}

Containment.java

public class Containment {
    public static void main(String args[]) {
        Plane puddleHopper = new Plane(10);
        Passenger p1 = new Passenger("Bob", 180);
        Passenger p2 = new Passenger("Alice", 135);

        puddleHopper.board(p1);
        puddleHopper.board(p2);

        System.out.println("Passengers weigh "+puddleHopper.weight()+" lbs");
    }
}

Princeton Java

There's a lot to programming and you'll get to the fun stuff a lot faster if you do some self-study. There are many Java tutorials, but if you'd like to try learning the Princeton way, try this one.

Attachments (7)

Download all attachments as: .zip