MIDTERM ANSWERS -- SUMMER 2003 Part A 1. True. The main method is the very first method to execute before any objects are created so it must be static. 2. True. A string is an object of the String class. 3. True. The + operator means addition in the case of number+number, but it means concatenation in the cases String+String, String+number, or number+String. Since + associates from left to right, we have the following sequence: " " + 1 + 2 + 3 + 4 + 5 --> " 1" + 2 + 3 + 4 + 5 --> " 12" + 3 + 4 + 5 --> " 123" + 4 + 5 --> " 1234" + 5 --> " 12345". 4. True. f = (!(x > y) || ((y != 7) && (x - y == 1)) = (!(7 > 9) || ((9 != 7) && (7 - 9 == 1)) = (!false || ( false && false ) = true || false = true 5. False. It will execute 5 times, printing 4 7 10 13 16. 6. False. The init method executes only once when the applet first starts up. The paint method executes every time a paint event occurs, including whenever the applet is restored after being minimized. Part B. 1. t s.charAt(x) x y y > 1 --------+-----------+-----+-----+-------- "" 'c' 2 32 true "c" 'h' 7 16 true "ch" 'm' 12 8 true "chm" 'r' 17 4 true "chmr" 'w' 22 2 true "chmrw" 27 1 false 2. public void static main(String[] args) { double miles, cm; miles = Double.parseDouble(JOptionPane.showInputDialog( "Enter distance in miles.")); cm = 2.54 * 12 * 5280 * miles; System.out.println("Distance in cm is " + cm + "."); } 3. public void static main(String[] args) { String s; char first, x; int i; boolean flag = true; s = JOptionPane.showInputDialog("Enter string to check."); // Variable name cannot have length 0. if (s.length() == 0) { System.out.println(false); System.exit(0); } // Variable name must start with a lower case letter. first = s.charAt(0); if (!('a' <= first && first <= 'z')) { System.out.println(false); System.exit(0); } // Quit if variable name consists of only a single letter. if (s.length() == 1) { System.out.println(true); System.exit(0); } // Remaining characters must be digits or letters. for(i = 2; i < s.length(); i++) if (!('a' <= first && first <= 'z') || !('A' <= first && first <= 'Z') || !('0' <= first && first <= '9')) flag = false; System.out.println(flag); } 4. See link to image.