== 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. [[Image(ProjectFolder.jpg, 50%)]] 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. [[Image(breakpoint.jpg, 50%, margin=10)]] 1. Click Debug->Start Debugging 2. The program will start running but will stop (break) at line 7 [[Image(stopped.jpg, 50%, margin=10)]] 3. Click on the Step-over icon [[Image(stepover.jpg)]] above the editor (or press function key F10) to execute that line of code and then stop again 4. Observe the Variables window in the left navigation panel and note that there is now a variable named 'a' with the value 3 [[Image(variables.jpg)]] 5. Press F10 again to execute the line b=4 and observe the variable appearing in the Variables window 6. Double click on the variable b in the Variables window and change its value to 5 7. Press F10 again to execute the line c=a*b and observe the variable c appearing in the Variables window with the value 15. 8. Press the Continue tool [[Image(continue.jpg)]] (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. The VSCode debug toolbar [[Image(VSC_toolbar.png)]] offers a complete set of tools to control the execution of your program: * Continue / Pause F5 * Step Over F10 * Step Into F11 * Step Out Shift+F11 * Restart Ctrl+Shift+F5 * Stop Shift+F5 == 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 [https://www.geeksforgeeks.org/loops-in-java/ 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 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 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"); } } }}} == Learn More 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, more examples, games, and other Java training material on the [wiki:ControlSystems/SoftwareTeam/Training training pages].