660 likes | 758 Views
Java I Refresher. Jonathan F. Gemmell Saturday, January 7 th / Friday, January 13 th Room 819 CTI. Before we begin. Sign up sheet Survey Does everyone’s computer work? These slide are new (let me know if you spot a typo)
E N D
Java I Refresher Jonathan F. Gemmell Saturday, January 7th / Friday, January 13th Room 819 CTI
Before we begin • Sign up sheet • Survey • Does everyone’s computer work? • These slide are new (let me know if you spot a typo) • This is meant to be a hands-on review. We will spend about 50% of the time working through problems. Make sure I have your email address, so I can send you the solutions to the problems. • Please feel free to raise your hand, shout out questions, or throw rotten fruit during the review.
Outline • Basic structure of an application • Demo: HelloWorld • Primitive data types and operations • Demo: MathProblems • Using predefined objects • Demo: StringDemo, ScannerDemo • Branching structures (if, if-else, switch) • Demo: ZipCode • Loops (for, while, do-while) • Demo: Factor • Demo: MultiplicationTable
Outline continued • Arrays • Demo: CalculateAverage • More on the structure of an application • Demo: CircleCalculations • Method Overloading • Demo: PrintNames • Objects • Demo: Rectangle • Demo: Country and CalculatePopulations
Basic structure of an application • A Java application consists of a definition of a class. • The name of the class (ClassName) and the name of the file (ClassName.java) must be identical. • The class definition has a header (public class ClassName) followed by a body inside braces. • The body of the class may contain a method called “main”. The main method always has the modifiers public, static and void in front of it.
Demo: HelloWorld • Write the following program on your computer public class HelloWorld { public static void main (String[] args) { System.out.println("Hello World!"); } }
Primitive data types and operations • There are eight java primitives • boolean true or false • byte signed 8-bit integer • char 16-bit Unicode 2.0 character • short signed 16-bit integer • int signed 32-bit integer • long signed 64-bit integer • float signed 32-bit floating-point • double signed 64-bit floating-point
Primitive data types and operations • Most often you will use…. • booleans for true/false variables • true, false • chars for characters • a, b, c … • ints for integers • 1, 2, 3 … (not 1.00) • doubles for decimals • 1.0, 3.14, 9.9999999 …
Primitive data types and operations • Java is a strongly typed language. An explicit type must be assigned to every data value. • Ex: int x = 5; int y; y = 7; int z = x + y; System.out.println(z); • Output: 12 • Notice that • x, y and z are all declared as ints • You can only declare a variable once!!! int x = 5; int x = 6; Can’t re-declare x!!
Primitive data types and operations • Common operations on primitives • Addition, Multiplication, etc • double z = x + y, • double z = x * y • Modulus • int z = x % y • Numerical comparison and equality • boolean z = ( x < y ) • boolean a = (x = = y) • Recall that one equals sign ( = ) is an assignment • Two equals signs ( = = ) is a comparison
Primitive data types and operations • Casting • Will this compile? double x = 3; double y = 2; int z = x / y; • Notice that a double has 64 bits, while an int has only 32. Trying to assign the value of x/y to z is like trying to pour a gallon of water into a 2-liter bottle. Try this instead…. double x = 3; double y = 2; int z = (double)(x / y); • This is called casting. But be careful! You could lose precision. In the above example z will equal 1, not 1.5
Primitive data types and operations • What is the value of z? Why? int x = 3; int y = 2; int z = x / y; • In “integer math” the decimal gets thrown out. z equals 1, not 1.5
Primitive data types and operations • Modulus is a useful operation. It results in the remainder of the division operation. • 10 % 3 = 1 • 6 % 2 = 0 • 5 % 3 = 2 • 14 % 5 = 4 • What is the value of z? int z = 8 % 3;
Demo: MathProblems (5 minutes) • Write an application called MathProblems. Declare variables where appropriate. Try some of the examples in the previous slides. Be sure to try at least one example of primitive operations, casting, “integer math”, and modulus.
Using predefined objects • One of the strengths of Java is the ability to create objects in your program from a large variety of pre-defined classes. • REMEMBER THIS WEBSITE!!!!! • http://java.sun.com/j2se/1.5.0/docs/api/index.html • Notice that primitive data types create a variable, whereas a class produces an object. • Each pre-defined class has a collection of public methods defined for it.
Using predefined objects • The String class • One of the first classes you used in Java 211 was the String class. A String represents a sequence of characters. • To create a String object: • String s = new String(“A string of characters”); • There is also a short-hand way to create a String: • String s = “Another string of characters”;
Using predefined objects • Methods of the String class • int length(): returns the number of characters in a String String s = "this is a String"; int i = s.length(); • char charAt(int index): returns the character at the index specified String s = "this is a String"; char c = s.charAt(3); • int indexOf(char target): returns the index of the first occurrence of the target. -1 otherwise. String s = "this is a String"; int i = s.indexOf('S');
Using predefined objects • String substring(int start, int end): returns a String that represents the characters from positions “start” to “end” String s = "this is a String"; String t = s.substring(5,10); • Many more! • Concatenation • You can concatenate two Strings together with the ‘+’ operator. You can also concatenate a String and a primitive. String s = "this is a String."; String t = "this is also a String"; String u = s + t;
StringDemo • Write an application that declares some Strings. Use the methods described in the previous slide. Concatenate two Strings together. Try concatenating a String and a primitive.
Using predefined objects • The Scanner class • The Scanner class allows a program to read input taken from standard input. It can be found in the java.util package so you must put “import java.util.*;” in the program in order to use it. • Declare and initialize a Scanner object: • Scanner s = new Scanner(System.in); • Use the Scanner object to obtain an integer value: • int x = s.nextInt(); • Use the Scanner object to obtain a decimal value: • double y = s.nextDouble();
Using predefined objects • The Scanner class cont. • In order to use the Scanner class to input a String: • 1. Declare and initialize the Scanner object • 2. Change the delimiter from whitespace to the line separator • 3. Use the Scanner object to input a String Scanner s = new Scanner(System.in); s.useDelimiter( System.getProperty("line.separator") ); String str = s.next();
ScannerDemo • Write an application that declares and initializes a Scanner object. Use it to input integer values, decimal values, and Strings. Print the input values to the screen.
Branching structures • This is the most basic if-statement if (boolean expression) { //do this block of } • If the boolean expression is true, the program will execute the next block of code.
Branching structures • Compound if–else statements if (boolean expression) { //do this } else if (boolean expression) { //do something else } else { //do yet something else }
Branching structures • A switch statement evaluates the given integer and execute the appropriate block of code. switch (x) { case 1: //this block of code will be executed if x equals 1 { System.out.println("first case"); break; } case 2: //this block of code will be executed if x equals 2 { System.out.println("second case"); break; } default: //this block of code will be executed as a default { System.out.println("third case"); break; } }
Demo: ZipCode • Write an application that takes a three digit area code from a user and then tells a user where s/he lives. • 312 Chicago • 212 New York • 510 San Francisco • 972 Dallas • Write one version that uses a switch statement and a second version that uses a compound if-else statement.
Loops • The purpose of a loops is to repeat a block of code many times. • for loop • while loop • do- while loop
Loops • for loop • Use a for loop when you know exactly how many times you want to repeat the loop. You may know the particular value, or know a variable that contains the value. • The for loop has three crucial parts • The initialization of the counter • The boolean statement that tests the continuation condition • Incrementing the counter • For loops are useful when working with arrays (as we will see) • EX: print hello 5 times. for(int i=0; i<5; i++) { System.out.println("hello"); }
Loops • while loop • Use a while loop when you want to repeat a block of code an unknown number of times (maybe not at all) • A while loop will repeat the block of code until the boolean statement is no longer true while (boolean expression) { //do this block of code }
Loops • do-while • Use a do-while loop when you want to repeat a block of code an unknown number of times, but at least once. • Perfect for user inputs. • EX: ask a user for a number between 1 and 10, repeat until the user enters a valid number. Scanner s = new Scanner(System.in); int input; do { System.out.print("Enter a number between 1 and 10: "); input = s.nextInt(); }while(input < 1 || input > 10);
Demo: Factor • Write an application that prompts the user for a positive integer and prints to the screen the factors of the input. The program should not accept negative numbers as an input, and should continue to ask for a value until the user enters a proper input. • For example, if the user enters 7, the output should be 1 and 7. If the user enters 12, the output should be 1, 2, 3, 4, 6, and 12.
Demo: MultiplicationTable • It is crucial for you to understand and be able to implement nested loops. A nested loop is a loop inside another. Using nested loops, write an application that prints to the screen a five by five multiplication table.
Arrays • In Java, arrays are objects • You can create an array of any primitive or object class by using “[]” • The declaration of an integer array: • int[] x; • The declaration of a String array: • String[] s; • Declaring an array does not create the object or allocate memory. It merely creates the variable.
Arrays • Initializing arrays: • Use the key word “new” to initialize an array and provide the type of the array, and the size of the array within the brackets. • int[] x = new int[100]; • Creates an int array x, 100 elements long • String[] s = new String[10]; • Creates a String array s, 10 elements long
Arrays • Modifying elements int[] x = new int[10]; x[0] = 5; x[2] = 8; • In the above example, a new array is declared and initialized. The 0th element is set to 5, while the 2nd element is set to 8. Recall that a 10 element array is numbered 0 through 9. • Accessing elements int i = x[2]; • In the above example, the program will access the 2nd element of the array and assign its value to the integer variable i. • Array Length • In Java, an array knows how long it is. int[] x = new int[20]; int l = x.length;
Demo: CalculateAverage • Write an application that creates an int array of size 20, fills it with random numbers in the range 0 through 99, prints the array to the screen, and then calculates and prints the average of the numbers. (hint: use for loops) • To generate a random number in the range 0 through 99: int x = (int)(Math.random() * 100);
More on the structure of an application • So far the example programs have had only one method (the main method) and none of the examples have had any class variables. In practice, most programs will have many class variables and many methods.
More on the structure of an application • Class variables • A class variable is declared at the class level, rather than inside the body of a method. Consequently, the scope of variable extends throughout the entire class. public class Test { static int i; public static void main (String[] args) { i = 5; } } • Notice that even while the variable i is declared outside the main method, it can still be accessed inside the main method. • Also notice the variable i has the modifier “static.” More on this later.
More on the structure of an application • Scope public class Scope { int x = 5; public static void main (String[] args) { int y = 6; if (y == 6) { int z = 7; } } } • What is the scope of the variables x, y and z? Notice how proper indentation makes determining the scope easier.
More on the structure of an application • Methods – A method has two parts • Header – Describes the method in general terms, including its name, visibility, inputs and outputs. • Visibility modifier • Return type • Method Name • List of parameters • Body – Describes the specific actions the method will perform • The body consists of a sequence of program statements to be executed. If the method returns a value, there must be a return statement.
More on the structure of an application • Visibility modifiers • public • Visible outside the class • Called a service method • private • Not visible outside the class • It can only be used by methods inside the class • Called a support method
More on the structure of an application • Return type • Can be any primitive, a class, or void. • It tells us what kind of result comes back from the method when it is evaluated. • If a method is supposed to return a value, there must be a return statement.
More on the structure of an application • Method Name • Gives the method a name, so that it can be called from elsewhere in the program. • The convention is to use lower case letters except for the first letter of subsequent words. No white spaces. • EX: calculateSum • EX: getLastName • EX: SetPhoneNumber not convention
More on the structure of an application • List of parameters • A list of the type and name of the expected inputs • Type gives what kind of data is expected for that input • Name gives the name by which it will be referred to during the method’s execution • Parameters are given in parentheses, separated by commas. • There does not need to be any parameters at all if the method does not require them.
More on the structure of an application • An example of a method public static int squareNumber(int n) { int result = n * n; return result; } • Visibility modifier - public • Return type - int • Method Name - squareNumber • List of parameters – an int named ‘n’
More on the structure of an application • Another Example private static void printSum(double x, double y) { double result = x + y; System.out.println(result); } • Visibility modifier - private • Return type - void • Method Name - printSum • List of parameters – a double named ‘x’ and a double named ‘y’
Demo: CircleCalculations • Write a program with a class variable named pi equal to 3.14. • Write a method (don’t put it in main!) that asks the user to enter a radius (double) and returns this value. • Write a method that accepts a radius (double) as a parameter and calculates the area of the circle with that radius. It should return the area. ( a = pi * r2 ) • Write a method that accepts a radius (double) as input and prints to the screen the circumference of a circle given the radius. The return type should be void. ( c = 2 * r * pi ) • In the main method call these three methods appropriately.
Method Overloading • Methods expect the proper input. The compiler will object if the wrong type or number of variables are supplied as arguments. • An overloaded method has several different definitions, all with the same method name, but different types and/or number of inputs.
Method Overloading • Signature • The ordered list of types of parameters in the header of a method is called a signature. • As long as they have different signatures, we can define as many methods as we want with the same name. The compiler will choose the correct method based on the method’s signature.
Demo: PrintNames • Write a method called printName that accepts a String called lastName as a parameter. It should print to the screen the name provided. • EX: if the input is “Smith”, it should print out “Mr. Smith.” • Write a method with the same method name. This method should take two Strings as parameters, firstName and lastName. • EX: if the inputs are “John” and “Smith,” it should print out “John Smith” • Write a third method with the same method name. This method should take two Strings as arguments and one char. • EX: if the inputs are “John”, ‘A’, and “Smith,” the method should print out “John A. Smith.” • Write a main method to test the overloaded methods.