CECS 220 (Java) – Test 1 REACH TEST REVIEW Overview During this PowerPoint we will go over possible questions that could be on the test. I assume you know some if not all the syntax. If you have any questions during the examples let me know. Variables and Constants public class Test { public static void main(String[] args) { final int x; System.out.println(x); } } Is this acceptable in Java? A.) Yes B.) No Variables and Constants Is the following a valid name for a variable in Java? _special_character A.) Yes B.) No Is the following a valid name for a variable in Java? $vari_A1 A.) Yes B.) No Variables and Constants Is the following a valid name for a variable in Java? #include A.) Yes B.) No what about include? The following variable name is not allowed in Java, why? 9pins+1 A.) It has an operator ‘+’ in it. B.) It has a number ‘9’ before a character. C.) Error: Incomplete expression Variables and Constants Is the following a valid name for a variable in Java? theIncrediblyEdiblySpiderManWithTheVeryLongNameOfMoreThan50Characters A.) Yes B.) No How many characters is the limit a variable can have in Java? A.) 128 B.) 256 C.) No Limit Variables and Constants What will the value of variable i be after executing these two lines of Java code? String s = “ABBA”; int i = s.indexOf('B'); A.) 2 B.) 3 C.) 1 Variables and Constants What is the value as evaluated by Java of the following line of code? Math.ceil(3.2); A.) 3.2 B.) 4.0 C.) 3.0 What is the other function opposite to ceil? Can you predict the printout? package test; /** * * @author eteleeb */ public class Test { public static void main(String[] args) { int x; for (x=0; x<10; x++){ System.out.format("%08d%n", x); } } } Can you predict the printout when the user enter 2 and 4? package test; public class Test { public static void main(String[] args) { System.out.println("Enter the first value: "); Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.println("Enter the second value: "); int y = sc.nextInt(); System.out.printf("The result is %d\n:", 24/(x*y)+6/3); } } Can you predict the printout? package test; public class Test { public static void main(String[] args) { int x = 4; int y = 9; int result1, result2; result1 = y/x; result2 = y%x; System.out.printf("The result is %d %d \n", result1, 25*result2); } } Boolean Operators Do you know the answers to these? A. !( 1 || 0 ) B. !( 1 || 1 && 0 ) C. !( ( 1 || 0 ) && 0 ) While(){} and Do {} While() What’s the syntax of While(Logical Condition){ } Do{ } While(Logical Condition) What’s the difference between While and Do- While()? Practice While (){} Write a public method that will accept a single integer parameter n that will print out only the odd numbers from 1 to n. Assume that n > 1. The value n may be either odd or even. Practice While (){} package test; import java.util.*; public class Test { public static void main(String[] args) { Scanner number = new Scanner (System.in); int x = number.nextInt(); printResult(x); } public static void printResult (int m){ int i=1; while (i <= m ){ if (i % 2 != 0) System.out.println(i + " "); ++i; } } } FOR Loops Use when the number of iterations is already known Syntax: for ( variable initialization; condition; variable increment/decrement) { Code to execute while the condition is true } Practice FOR Loops Write a program using a FOR Loop to print prime numbers between 1 and 100. Practice FOR Loops public class Test { public static void main(String[] args) { System.out.println("Prime numbers between 1 and 100"); for(int i=1; i < 100; i++){ boolean isPrime = true; for(int j=2; j < i ; j++){ if(i % j == 0){ isPrime = false; break; } } if(isPrime) System.out.print(i + " "); } } } Practice FOR Loops Predict the output package test; public class Test { public static void main(String[] args) { int m = 2; int n = 5; for (int i=1; i < n; ++i){ System.out.println("i is : " + i); for (int j=0; j < m; ++j ){ System.out.println("j is : " + j); } } } } BREAK and CONTINUE Use to manipulate flow in loops. What does a Break statement do when executed within a loop? What does a Continue statement do when executed within a loop? BREAK and CONTINUE public class Test { public class Test { public static void main(String[] args) { public static void main(String[] args) { for(int i=10; i >=5; i--){ for(int i=10; i >=5; i--){ if (i==7) break; if (i==7) continue; System.out.printf("%d\n", i ); System.out.printf("%d\n", i ); } } } } } } Arrays (Predict the output) Classes and Objects 1. Assume the following class declarations are given: class A { ... } class B extends A { ... } class C extends B { ... } (a) (b) (c) (d) Which class is the superclass of class B? Which class is the superclass of class A? Which types are the sub-types of type A? Which types are the super-types of type B? Classes and Objects 1. True or False: a) Java supports multiple-inheritance. b) If the data type of a reference variable is Object, that variable can store references to the objects of all classes. Classes and Objects 1. Fill in the blank with the correct term. (a) In the declaration of a class, the _________________ keyword specifies the super-class of that class. (b) The conversion of a sub-type to one of its supertypes is called ___________________ (c) The conversion of a super-type to one of its sub-types is called ______________________________ (d) A constructor of a sub-class can invoke one of its parent’s constructors using ___________________ Classes and Objects 1. Fill in the blank with the correct term. (a) In the declaration of a class, the extends keyword specifies the super-class of that class. (b) The conversion of a sub-type to one of its supertypes is called a widening conversion (or upcasting) (c) The conversion of a super-type to one of its sub-types is called narrowing conversion (or downcasting) (d) A constructor of a sub-class can invoke one of its parent’s constructors using super(...) Classes and Objects 1. Instance variables and instance methods that belong to a particular kind of object are grouped together into a 1. The keyword is used in Java to distinguish a class method from an instance method. 1. The job of a is to initialize instance variables at the time an object is created. 1. Objects have a state and Classes and Objects 1. Instance variables and instance methods that belong to a particular kind of object are grouped together into a class 1. The keyword static is used in Java to distinguish a class method from an instance method. 1. The job of a constructor is to initialize instance variables at the time an object is created. 1. Objects have a state and behavior Example 1 public int addMeeple(int x, int y) { int numMeeples = 1; numMeeples = askUser(numMeeples); return numMeeples; } Is numMeeples in or out of scope? Example 2 public boolean hammer(double force) { if (force >= NEEDED_FORCE) { int hammerTime = hammerGoHammer(force); } return hammerTime; } Is hammerTime in or out of scope? Example 3 public int notRandom(int check) { if (check == 3){return 3;} if (check > 4){return 13;} return 4; } If you call notRandom(2); what does it return to you? Example 4 True or False A child can access a field in the parent with access type protected. Acess Types Public: Full access. Protected: Class, Packages, Subclasses (like child) access. No Modifier: Class, and Packages access. Private: Class Only access. Example 5 public class Pirate { public int plunder(int hours, Crew crew) { // Do plundering steps here. return amount; } } Object Creation Steps: Pirate blackBeard = new Pirate("Black Beard"); Crew ruffians = new Crew(36); Which of the following lines would make Black Beard plunder for 3 hours with 36 crew? A.) blackBeard.plunder(3, ruffians); B.) blackBeard.plunder(3, 36); C.) blackBeard.plunder(3, crew); Example 6 Choose the correct constructor declaration for the following class: public class SocketWrench { A.) SocketWrench() { B.) public class SocketWrench() { C.) public SocketWrench() { Given class: public class SocketWrench() { The constructor would be public SocketWrench() { public class SocketWrench() { public SocketWrench() {...} } Example 7 Evaluate the following Java expression and provide the result: Double.MIN_VALUE + 1 A.) No output. B.) 1.0 C.) Static Error: No member of Double has name 'MIN_VALUE' Example 8 Evaluate the following Java expression and provide the result: false && (5 / 0 == 1) A.) java.lang.ArithmeticException: / by zero B.) False C.) 5 Example 9 How do you access the static method getNumBurgers after the following statement (getNumBurgers is contained within the Burger class): Burger b = new Burger(Burger.DOUBLE_STACK); public static int getNumBurgers() {return numBurgers;} A.) Static Error: Undefined name 'DOUBLE_STACK' B.) b.getNumBurgers(); C.) Burger.getNumBurgers(); Example 11 How do you access the static method getNumWorkers after the following statement: Worker w = new Worker(“Johnny Unitas”); public static int getNumWorkers() { return numWorkers; } A.) Worker.getNumWorkers() B.) w.getNumWorkers() C.) w.Worker.getNumWorkers() Example 12 Before you use a class like Vector in your program you need to include the class or package into your code. Which statement below does this for Vectors? The header for the Java API doc for the Vector class is below: java.lang.Object java.util.AbstractCollection<E> java.util.AbstractList<E> java.util.Vector<E> A.) import java.util.Vector; B.) import java.util.*; C.) import java.util.Vector<E>; Example 13 Below is sample code from a class that inherits from the JFrame class. What is the purpose of the line super("Water District"); public class WaterDistrictMapper extends JFrame { public WaterDistrictMapper() { super("Water District"); } } A.) This line calls the constructor in the JFrame class with a String parameter to initialize the JFrame fields. B.) This line calls the constructor in the WaterDistrictMapper class with a String parameter to initialize the Jframe fields. C.) There is no output so it has no purpose. Example 14 Class Tree contains one function diameter: public class Tree {public int diameter(int r){return r * 2;}} Class Redwood contains one function age: public class Redwood extends Tree {private int age; public void age(){age++;}} An object is created as follows: Redwood r = new Redwood(); What output does this line of code give: r.diameter(2); A.) 2 B.) 3 C.) 4 Example 15 Execute the following Java code. Then choose which answer is represents the current state of the ArrayList list. (Ignore initial size and capacity of array.) ArrayList<Double> list = new ArrayList<Double>(); list.add(2.5); list.add(3.6); list.add(5.7); list.add(7.5); list.remove(1); A.) B.) 0 1 2 2.5 5.7 7.5 0 1 2 3 5.7 7.5 2.5 3 Example 16 What value is output in the following code snippet: Set<Integer> set = new HashSet<Integer>(); set.add(1); set.add(3); set.add(3); set.add(7); System.out.println(set.size()); A.) 4 B.) 14 C.) 3 Example 17 What is the purpose of the <Double> reference? Vector<Double> vector = new Vector<>(); A.) It sets the type of object that may be added to the vector. B.) It doubles the vector size for larger storage. C.) It doubles the input put into the vector and turns into a double type. Example 18 Both the Vector and ArrayList classes represent "growable" lists of objects. Internally these classes store objects in arrays. If 10 was used as the initial capacity parameter, what happens when the 11th object is added to the vector? A.) The vector grows to size of 11 allowing up to 12 objects. B.) Nothing happens because 0 – 10 allows 11 objects. C.) The vector doubles in size if not specified by another variable. Example 19 public class Time { public int getHour(String time) { int index = time.indexOf(':'); String hourString = time.subsring(0, index); int hour = Integer.parseInt(hourString); return hour; } } Why do you get an error when you try to compile this code? Tips The test will probably consist of the following: Multiple Choice. Fill in the blank. Debug Code (What would cause X code not to run). Code Writing. Trick Questions.