Sample Exam Questions: Java and Physics Simulation Spring 2006 Instructions: a. No books or notes allowed. b. Answers to questions involving Java code do not need to show correct Java syntax. The answers just need to display an understanding of the basic Java programming language and techniques. [Answers at bottom] 1. List 3 features of Java that are of benefit to technical programming. 2. Explain the difference between the instance variables of a class andstatic variables. 3. Convert float variable "f" to int variable "j". 4. Since the Virtual Machine in which you run your threaded program may not necessarily have a preemptive (time-slicing) design, name at least one of the 2 ways that you can insure that your threads surrender processing time to the other threads. 5. Lets say that you have a program called MyApplet in directory "myjava" that uses the helper classes A, B, and C , which are in files A.java, B.java, and C.java and their corresponding ".class" files. You decide to clean things up a bit and put the helper classes into a package. How do you do this? 6. Give an example of an abstract class and an example of a real class that inherits the abstract class. 7. Java provides basic math functions and constants. Write an example of a Java statement witha Java math function and constant.[3p] 8. Create an Integer array in which the Integer objects hold the int values 4,20,15. 9.What does the following code print out: aURL = new URL ("http://java.sun.com:80/tutorial/intro.html#DOWNLOAD"); System.out.println ("protocol = " + aURL.getProtocol ()); System.out.println ("host = " + aURL.getHost ()); System.out.println ("filename = " + aURL.getFile ()); System.out.println ("port = " + aURL.getPort ()); System.out.println ("ref = " + aURL.getRef ()); 10. What happens when repaint() is called in an applet (for either an Applet or JApplet subclass)? 11. Create a simple interface and a simple class that implements that interface. 12. Show the code that for creating a panel and adding 5 buttons to it with a BorderLayout manager. 13. Explain what happens to the image when Image img = getImage (getCodeBase (),"a.gif"); is executed. 14. In the following simple Java class, the main method passes a primitive and an array to a method. What will the output for this program look like and explain why? public class MyClass { public static void main (String [] args) { int x = 5; double [] array = {5.0, 4.0, 3.0, 2.0, 1.0, 0.0}; myMethod (x, array); System.out.println ("x = " + x); System.out.println ("array[0] = " + array [0]); } static void myMethod (int x, double [] array) { x = 3; array [0] = 3.0; } } 15. Show code examples of how the "this" and "super" references are used. Show code examples of this() and super() constructor invocations. 16. Give the Java code and html code (applet tag only) to make an applet that passes a string to be displayed on the applet panel and also passes the colors "red" or "blue" that should be used for drawing the string. 17. For the paint() method of a Panel component or the paintComponent() method of a Swing JPanel, give the code to fill the whole drawing area with yellow and then to draw a solid red rectangle one third the size of the drawing area and centered in the area.[4p] 18. Give Java code to create an application with a frame to hold an applet called MyApplet (assume MyApplet is available in a separate java file in same directory, so you don't need to include code for it.)[4p] ================================================================================== QUESTIONS WITH ANSWERS . List 3 features of Java that are of benefit to technical programming. --- - Platform independence, which is important in science since many types of computers are used. - Strong graphical capabiities for use in simulations, data analysis graphics, animations, etc. - Networking of experiments and equipment for remote monitoring and control. - Access and interfacing to large online databases. - Education such as online demonstrations with applets - Enhances collaborative work. 2. Explain the difference between the instance variables of a class andstatic variables. --- A static property belongs to a class rather than an instance of the class. A static property exists, i.e. has memory allocated to it, even when there are no instances of the class. An object has its own independent set of instance variables. Their values do not affect the values of the instance variables in other objects for that same class. public class MyClass { int a; // instance variable static double MY_CONSTANT = 3.14; // static variable ... } 3. Convert float variable "f" to int variable "j". --- j = (int)f; 4. Since the Virtual Machine in which you run your threaded program may not necessarily have a preemptive (time-slicing) design, name at least one of the 2 ways that you can insure that your threads surrender processing time to the other threads. --- Add yield() or sleep() calls to release control in the run(). 5. Lets say that you have a program called MyApplet in directory "myjava" that uses the helper classes A, B, and C , which are in files A.java, B.java, and C.java and their corresponding ".class" files. You decide to clean things up a bit and put the helper classes into a package. How do you do this? --- Put the line: package mypackage; at the top of files A.java, B.java, and C.java. Then put them into a sub-directory: myjava/mypackage Compile the files A, B, and C from directory myjava. >javac mypackage/A.java >javac mypackage/B.java In MyApplet, put the line: import mypackage.*; or use the full name of each class, e.g. mypackage.A wherever in your code that you use this class. 6. Give an example of an abstract class and an example of a real class that inherits the abstract class. --- abstract class A { abstract int doSomething (int a); int doSomethingElse (int a) { return a * a; } } class B extends A { int doSomething (int a) { return 2 * a; } } 7. Java provides basic math functions and constants. Write an example of a Java statement witha Java math function and constant.[3p] --- a=Math.cos(x*Math.PI); 8. Create an Integer array in which the Integer objects hold the int values 4,20,15. --- Integer[] iarray = new Integer[3]; iarray[0] = new Integer (4); iarray[1] = new Integer (20); iarray[1] = new Integer (15); 9.What does the following code print out: aURL = new URL ("http://java.sun.com:80/tutorial/intro.html#DOWNLOAD"); System.out.println ("protocol = " + aURL.getProtocol ()); System.out.println ("host = " + aURL.getHost ()); System.out.println ("filename = " + aURL.getFile ()); System.out.println ("port = " + aURL.getPort ()); System.out.println ("ref = " + aURL.getRef ()); --- protocol = http host = java.sun.com filename = /tutorial/intro.html port = 80 ref = DOWNLOAD 10. What happens when repaint() is called in an applet (for either an Applet or JApplet subclass)? --- You would typically invoke repaint() to redraw a panel such as for a new frame in an animation. The repaint() invocation adds an entry to the queue of calls for repainting components. Allowing the AWT system to decide when a component is repainted, rather than directly invoking a paint () or paintComponent () method, avoids interference with the GUI event handling. For AWT components the default update() method will be invoked. This method will clear the drawing area by filling a rectangle of the size of the component with the background color. It then calls the paint() method. For Swing components (i.e. JComponent subclasses) the paintComponent () method will be invoked. This method must either invoke super.paintComponent() to repaint the whole area or it should paint the area itself. 11. Create a simple interface and a simple class that implements that interface. -- public interface Remakable { public void remake (); } /** This close holds an array of random numbers **/ public class RanNumArray implements Remakable { private double [] fRanNums; private int fNumRans=0; // Pass the constructor the size of the array public RanNumArray (int n) { fNumRans = n; fRanNums = new double [fNumRans]; remake (); } // ctor // Get the array public double [] getRans () { return fRanNums; } // getRans // Remake the randome numbers public void remake () { for (int i=0; i < fNumRans; i++) { fRanNums [i] = Math.random (); } } // remake } // RanNumArray 12. Show the code that for creating a panel and adding 5 buttons to it with a BorderLayout manager. --- JPanel panel = new JPanel (); panel.setLayout (new BorderLayout()); [An alternative is JPanel panel = new JPanel (new BorderLayout()); ] panel.add ("East", new Button ("East")); panel.add ("West", new Button ("West")); panel.add ("North",new Button ("North")); panel.add ("South",new Button ("South") ); panel.add ("Center",new Button ("Center")); 13. Explain what happens to the image when Image img = getImage (getCodeBase (),"a.gif"); is executed. --- Nothing. The image is not actually loaded until an attempt is made to draw the image or if a MediaTracker or other such technique is used to force the image to load. 14. In the following simple Java class, the main method passes a primitive and an array to a method. What will the output for this program look like and explain why? public class MyClass { public static void main (String [] args) { int x = 5; double [] array = {5.0, 4.0, 3.0, 2.0, 1.0, 0.0}; myMethod (x, array); System.out.println ("x = " + x); System.out.println ("array[0] = " + array [0]); } static void myMethod (int x, double [] array) { x = 3; array [0] = 3.0; } } -- x = 5 array[0] = 3.0 Primitive variables are handle by their value, i.e. the number in their memory location, and not by a pointer to their memory location. When a primitive varible is passed in a method argument, a copy of its value is passed, i.e. the variable is passed by "value". The method cannot change the value of the variable in the method that invoked it. Arrays, like all objects (remember that an array is an object in Java), are handled by reference variables. A reference is a pointer to a location in memory where the object data is stored. Unlike C/C++, the actual memory pointer value is not accessible. References in a method argument are passed to the method. That method can then use the reference to the object possibly to alter that object. (Note that the reference itself, i.e. the internal memory pointer, is copied and passed to the method. So it is also passed by value.) 15. Show code examples of how the "this" and "super" references are used. Show code examples of this() and super() constructor invocations. --- public class A { int a; int b; public A (int a) { this.a = a; } public A (int a, int b) { this (a); this.b = b; } void doSomething (int x) { a = 10 * x; } } class B extends A { public B (int a, int b, double c) { super (a, b); this.c = c; } void doSomething (int x) { super.doSomething (x); a = a + 10; } } 16. Give the Java code and html code (applet tag only) to make an applet that passes a string to be displayed on the applet panel and also passes the colors "red" or "blue" that should be used for drawing the string. --- import java.applet.*; import java.awt.*; public class HelloWorld extends Applet { String astring; Color color; public void init(){ astring = getParameter("aString"); // Get color. Black is the default. color = Color.BLACK; String colorStr = getParameter("color"); if(colorStr.equals("red")) color = Color.RED; else if( colorStr.equals("blue")) color = Color.BLUE; } void paint(Graphics g){ g.setColor(color); g.drawString(0,0,astring); } } In the applet web page: < applet code="HelloWorld" width="100" height="100"> < /applet> 17. For the paint() method of a Panel component or the paintComponent() method of a Swing JPanel, give the code to fill the whole drawing area with yellow and then to draw a solid red rectangle one third the size of the drawing area and centered in the area.[4p] --- public void paint (java.awt.Graphics g) { int w = getSize().width; int h = getSize().height; g.setColor (java.awt.Color.yellow); g.fillRect (0,0,w,h); int rw = w/3; int rh = h/3; rx = (w - rw)/2; ry = (h - rh)/2; g.setColor (java.awt.Color.red); g.drawRect (rx,ry,rw,rh); } 18. Give Java code to create an application with a frame to hold an applet called MyApplet (assume MyApplet is available in a separate java file in same directory, so you don't need to include code for it.)[4p] --- import java.awt.*; public class MyApp extends Frame { public static void main(String [] args){ MyApplet myapplet = new MyApplet(); MyApp myapp = new MyApp(); myapp.resize(400,400); myapp.add("Center",myapplet); myapple.init(); myapplet.start(); myapp.pack(); myapp.show(); } }