Introduction to Java  
 
 

Week 3

Readings:

  • Chapters 4.1 - 4.10, 5.1 – 5.4, 6.1 – 6.7, 13.1 -13.4

Lesson Outline:

  • Loops and conditionals
  • Discussion of method types
  • Inheritance, constructors, and interfaces

Lesson Goals:

  • Understand and properly use loops
  • Learn how to create your own methods as needed
  • Understand and implement inheritance, constructors, and interfaces

Additional Reading:

You will start today off with exercises on loops and conditionals, which you will be using in almost every program you write. Conditionals are comparisons in which a decision is made by the computer based upon the available data. It allows you to specify what you want the computer to do in different situations. You will begin with “if-else” conditionals, which are used to determine what code a program will execute based on previous conditions. An “if-else” statement will first check if a given statement is true. If it is true, then code held within the brackets of the if statement is executed. If the statement isn’t true, this code is either skipped or code held within the else statement, which come immediately after the if statement is executed. Sample code:

int x = 5 if(x == 5){ System.out.println(“Yep, x is 5”); } else{ System.out.println(“Nope, try again.”); } This can also be used with booleans. Sample Code: boolean b = true; if(b){ System.out.println(“Hooray! It’s true”); } else{ System.out.println(“Uh-oh, it’s false”); } The following code demonstrates to the else if statement. This may be used to create more options for a conditional statement. The else if statement acts similarly to the if statement in that it runs whatever code is written within it if a given condition is true and skips to the next part of the program if false. The difference is that the else if statement is only checked if the if or any other else if statements above it are false. Sample code: int x = 5; int y = 10; int z = 8; if(x >= y && x >= z){ System.out.println(x); } else if(y >= x && y >= z){ System.out.println(y); } else if(z >= x && z >= y){ System.out.println(z); } else{ System.out.println("Darn, why didn't that work?"); }

Exercise:

  • Write a program from scratch that uses if-else statements to find the largest and smallest numbers in a set of integers. Then, using if-else statements, create different responses for every possible scenario in which you are given two booleans.
You will now learn for and while loops. While loops are extremely simple to understand. A while loop will check a condition just as an if statement would, and as long as that condition is true, the loop will continue to run through the code inside the loop’s brackets. Sample Code: Int x = 0; while(x < 10){ System.out.println(x); x = x + 1; } For loops are similar, except they only accept a very specific kind of condition. It’s rather hard to explain, so first look at an example of a for loop. Sample Code: for(x = 0; x < 10; x++){ System.out.println(x); } Look at the three arguments placed inside of the for parentheses. The first establishes what the value of the integer x is at the beginning of the loop. The second is the condition x is checked against, meaning that when this condition is no longer true, the loop will stop running through the code inside of the loop. The third argument, x++ (equivalent to x = x + 1), changes the value of x by adding 1 to x at every iteration of the loop. To sum this for loop up, x is given the value of 0, the condition x<10 is checked, and, because this condition is true, the code within the for loop is run. After the code is run, the value of x is incremented by 1. This continues until x is no longer less than 10.

Exercise:

  • You are going to create a nested for loop. This is where you place one for loop inside of another for loop. This means that every time the outer loop runs through once, the inner loop runs until it stops. Your challenge is to create a nested for loop where the outer loop counts from 0 to 30 in increments of 3(i.e. 0, 3, 6, 9, 12, etc.) and the inner loop counts from 0 to whatever the current outer loops step is. Design it so that in your terminal you see something like this. 0,1,2,3 0,1,2,3,4,5,6 0,1,2,3,4,5,6,7,8,9 etc, until it reaches 30. Good Luck.
Methods We are now going to cover methods in detail. As you have already done a little bit of work with them, you should be somewhat familiar with them. The first part of a method is its access modifier. The options available to you are private, public, protected and package (which is the default if not is listed). These determine what classes can access or use these methods. For the most part we will be working with public methods. There will be situations where you want a method accessible only by the class it is in. This is when you declare your method private. Private methods are also not inherited by subclasses, which we will be getting to later in this lesson. Public methods can be accessed and inherited by other classes. You will now learn about the return value, which is essentially the output of a method. Sample Methods: public void hello() public int add() public boolean bool() public String getString() As you can see above, these methods return (respectively) nothing, an integer, a boolean, and a string. Java needs to be informed of what is going to be returned from a method, even if it is nothing, so that when it compiles the program it can allocate memory accordingly. The way to end a method and return the correct type of value, is to use the return command. Sample Code: public int mult(int x, int y){ int answer = x*y; return answer; }

Exercise:

  • Use what you have just learned to write three different methods. One that compares two integers as arguments and returns a boolean that is true if the integers are equal. The second is one that takes two strings as arguments and returns them combined as a single String. The third is a method that takes three integers, adds two of them together, multiplies the product by the third, then returns the result as an int.
Class inheritance, constructors, and interfaces We are now going to move on to some of the more advanced aspects of classes. First, let’s discuss constructors. Recall from the last lesson where we created instance objects of different classes. The code looked something like this: BaseClass base = new BaseClass(); What this does is create an instance object using the BaseClass class’s default constructor. Every class has a default constructor, and it is the name of the class, followed by (). In this case, when the class is created, it automatically makes it identical to the code that it is made up of. However, you can modify the default class to set preexisting variables to different values. Sample Code: class Classiest{ int p; String q; public Classiest(){ p = 5; q = "Dogs are better than cats"; } } However, what you can also do is create additional constructors, which will be activated if and only if the correct type and number of arguments are placed within the constructor’s parenthesis. Sample Code: public Classiest(int x, String y){ p = x; q = y; }

Exercise:

  • Create a class called MultipleInputs. Inside of it, you are to create three different constructors. The first is the default constructor, but you are to modify it so that it prints out “I’m more of a default than you could ever hope to be!” when it is created. The second needs to take in a string and append it to the string “And that’s when he said: “ and print out the combination of the two. The third takes in two integers and prints out what the two multiplied together are.
Inheritance is another extremely important part of classes in Java. The idea behind inheritance is that you create a class to be a superclass to the other classes beneath it, which are referred to as subclasses. The subclass takes the superclass’ methods and makes them a part of itself. This means it can use any public methods in the superclass, and build off of them in various ways. Here is some sample code of this. class SuperClass{ public int mult(int r, int t){ int answer = r*t; return answer; } } class SubClass extends SuperClass{ public static void main(String args[]){ SubClass bob = new SubClass(); int x = bob.mult(10,15); System.out.println(x); } } Interfaces are the final aspect of the classes we will be covering. An interface in Java is simply a more formal way of defining what a class does. Most commonly, an interface is a list of related methods with nothing in the bodies of the methods (between the brackets). To implement the interface, in the class line of the program, you would write class <ClassName> implements <ClassInterface>{ } When implemented, this formalizes exactly what you expect the class to do, and every method listed in the interface must be in the source code of the class before the code will successfully compile.

Exercise:

  • For your final exercise, you will create a superclass that implements an interface of two different methods, one of which takes strings and combines them, and the others takes two integers and divides them. You will then write two subclasses to inherit the interface. However, in their constructor (or constructors, depending upon how you code it), you are to set the values of the Strings and integers to be different between the subclasses.

Files to Be Downloaded