A LAB SESSION SAMPLE CORE JAVA – LAB i
Transcription
A LAB SESSION SAMPLE CORE JAVA – LAB i
A LAB SESSION SAMPLE CORE JAVA – LAB i Section 1: Sample Programs 1. Write program to calculate n!. class Fac { int factorial(int n) { int p = 1; for (int i=1; i<=n; i++) p *= i; return p; } public static void main(String s[]) { Fac a = new Fac(); System.out.println("The factorial of 5 is " + a.factorial(5)); } } Note: save as Fac.java, compile as javac Fac.java, and run as java Fac. 2. Write program to calculate values of mathematical functions in Math class. For example: max(5, 7), sin(10), cos (10), log(10), 10 . class Functions { public static void main(String s[]) { System.out.println("The max of 5 and 7 is " + Math.max(5, 7)); System.out.println("The value of sin(10) is " + Math.sin(10)); System.out.println("The value of cos(10) is " + Math.cos(10)); System.out.println("The value of log(10) is " + Math.log(10); System.out.println("The value of sqrt(10) is " + Math.sqrt(10)); } } 3. Write program to display the arguments of a java program. class readArgs { public static void main(String s[]) { for (int i=0; i < s.length; i++) System.out.println(“The argument s[“+ i + “] is “ + s[i]); } } When you run, type: java readArgs Hello World, the program will display: The argument s[0] is Hello The argument s[1] is World If you type: java readArgs Hello “My World” “of Java”, the program will display: The argument s[0] is Hello The argument s[1] is My World The argument s[2] is of Java The exercises 4, 5, 6 demonstrate naming convention of Java class files compiled from a Java source file. 4. Write program to read 3 integers, which are entered in one line from keyboard, separated by one or more spaces. The program will validate if the three integers are the lengths of three edges of a triangle. If yes, calculate and display the area of this triangle, if not display appropriate message. If the program name is Triangle.java, when you run, it will prompt: Enter 3 integers: 3 4 5↵ The program will display: The 3 integer numbers are the lengths of three edges of a triangle. The area of this triangle is 6. import java.util.*; import java.io.*; class Triangle { int x, y, z; double area() { double p = (x+y+z)/2.0; return Math.sqrt(p*(p-x)*(p-y)*(p-z)); } boolean isTriangle() { return ((x + y > z) && (x + z > y) && (y + z > x)); } void readInts() throws IOException, NumberFormatException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); StringTokenizer st = new StringTokenizer(s, “ “); int c=0; while (st.hasMoreElements()) { c++; if (c==1) x = Integer.parseInt(st.nextToken()); else if (c==2) y = Integer.parseInt(st.nextToken()); else if (c==3) z = Integer.parseInt(st.nextToken()); } } public static void main(String s[]) { Triangle b = new Triangle(); try { System.out.print("Enter 3 integers: "); b.readInts(); } catch (NumberFormatException e) {} catch (IOException e) {} if (b.isTriangle()) System.out.println("The area of this triangle is " + b.area()); else System.out.println(“The three numbers are not the lengths of a triangle”); } 2 } Section 2: Do More 1. Modify program 1 in Section I so that you do not need to create an object of Fac class in the main method (i.e. without the line Fac a = new Fac();). 2. Modify program 1 in Section I, where n is a natural number entered as a commandline parameter. ↵, the program will display: Note. If the program Fac.java is run, you type: java Fac 5↵ The factorial of 5 is 120. 3. Modify program 1 in Section I, where n is a natural number entered from keyboard. 4. Write program to calculate log2(8) (which is 3), log2(1024) (which is 10), 1.22.1 (which is 1.466), floor(3.7) (which is 3), and ceil(3.7) (which is 4). Section 3: Do Yourself 1. Write program to find the maximum number of a sequence of numbers, entered as command-line arguments of the program. If the program name is FindMax, when you run, type: java FindMax 6 5 7 23 14, the program will display: The max number is 23 2. Write program to check if a given natural number is a perfect number. Perfect number n is a number, for which the sum of all of its divisors (except n) is n. For example: 6 is a perfect number, because 6 = 1 + 2 + 3, 28 is a perfect number, because 28 = 1 + 2 + 4 + 7 + 14. 3. Write program to display all perfect numbers in the range 1..1000. Section 4: Self Test 1. Examine the following program: int i = 0; class A { public static void main(String s[]) { System.out.println(“Hello”); } } What will happen when you try to compile and run this program? a. The program will compile and run fine. b. The program will compile but produce an error when it runs. c. The program will not compile. 2. Which main() method will compile? a. static public void main(String args[]) {} b. public static void main(String args[]) {} 3 c. public static void main(String s[]) {} d. public static int main(String args[]) {} 3. Which of the following will declare an array of five integers: a. int a[] = {1, 2, 3, 4, 5} b. int a[]; c. int a [] = new int[5]; d. int a[] = new int(5); 4. What will be the result of the statement: System.out.println(0x001B + “ “ + 033); a. 21 23 b. 21 27 c. 27 27 d. 33 33 5. A table can be declared as 2-dimension array, such as int m[][] = new int[3][4]; Which of the following can be used to determine the number of columns of the table? a. m.length(); b. a.size(); c. m[0].length; d. m.length(3); e. m[].length; Section 5: Tips • Do not close the MS-DOS window during the lab, otherwise you must set up the Java environment again. When you close MS-DOS windows, all the values set in the path and classpath will be lost. • To name a Java source file, follow the following rules: If the Java source file contains only one class which has the main() method inside, the file name must be the same as the class name. If the Java source file contains only one class which does not have the main() method inside, the file name need not to be the same as the class name. If the Java source file contains more than one class, and each class is declared without public keyword, the file name of the Java source file must be the same as the name of the class containing the main() method. If there is no class containing the main() method, the name of Java source file can be any valid file name. If the Java source file contains more than one class, and there is one class declared with public keyword, the file name of the Java source file must be the same as the name of this public class. There can not be more than one public class in a Java source file. • To compile a Java program, you must specify the .java extension. 4 • To run a Java program, you must not specify the .class extension. • Every declaration and statement in Java (except import and package) must be written in some class! • There may be at most one public class in a Java source file!. CORE JAVA – LAB 1 INTRODUCTION TO OOP Objectives Set up environment Class declaration Naming convention of class files Compiling and running Java programs Display a string onto the screen Methods to accept strings and integers from keyboard Set up environments: • Check location of compiler and JVM on your computer. Open Windows Explorer, find the compiler on disk C: or D:. Remember this directory for further use. The location is: C:\jdk1.3\bin • Open DOS window One way to open DOS window is: Start Program MSDOS Prompt. 5 ANSWER OF THE EXERCISE • • • Type: path=C:\jdk1.3\bin (or another suitable path in your environment) Note: Before using this command, you should check the location of JDK and its version on the hard disks. Create a new Java folder to hold your Java programs. For example: type md D:\JavaProgs to create JavaProgs folder in the root directory D:\. Change to your Java programs folder. In this example, you change to drive D: (using D: command) and type cd D:\JavaProgs. Guide to save, compile and run Java programs: • • • When you save, the filename must be the same as the name of the class containing main method. To compile program test.java, type: javac test.java To run program test.class, type: java test CORE JAVA – LAB 2 INTRODUCTION TO JAVA Objectives Write simple methods Using mathematical functions in Math.class Access the arguments of a Java program Accept a sequence of numbers entered in one line from keyboard Section 1: Sample Programs 1. Factorial. Write program to calculate n!. class Fac { int factorial(int n) { int p = 1; for (int i=1; i<=n; i++) p *= i; return p; } public static void main(String s[]) { Fac a = new Fac(); System.out.println("The factorial of 5 is " + a.factorial(5)); } } Note: save as Fac.java, compile as javac Fac.java, and run as java Fac. 2. Mathematical functions. Write program to calculate values of mathematical functions in Math class. For example: max(5, 7), sin(10), cos (10), log(10), 10 , 1.23.4. class Functions { public static void main(String s[]) { System.out.println("The max of 5 and 7 is " + Math.max(5, 7)); 6 ANSWER OF THE EXERCISE System.out.println("The System.out.println("The System.out.println("The System.out.println("The value value value value of of of of sin(10) is " + Math.sin(10)); cos(10) is " + Math.cos(10)); log(10) is " + Math.log(10); sqrt(10) is " + Math.sqrt(10)); System.out.println("The value of 1.2 powered by 3.4 is " + Math.pow(1.2, 3.4)); } } 3. Arguments of Java programs. Write program to display the arguments of a Java program. class readArgs { public static void main(String s[]) { for (int i=0; i < s.length; i++) System.out.println(“The argument s[“+ i + “] is “ + s[i]); } } When you run, type: java readArgs Hello World, the program will display: The argument s[0] is Hello The argument s[1] is World If you type: java readArgs Hello “My World” “of Java”, the program will display: The argument s[0] is Hello The argument s[1] is My World The argument s[2] is of Java 4. The sum. Write program to calculate the sum S = 1 + 2 + 3 + … + n, n is an integer entered from keyboard. import java.io.*; class E { int sum(int n) { int S = 0; for (int i=1; i<=n; i++) S += i; return S; } int readInt() throws IOException, NumberFormatException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); int i = Integer.parseInt(s); return i; } public static void main(String s[]) { E e = new E(); int n=0; try { System.out.print("Enter a natural number: "); n = e.readInt(); } catch (NumberFormatException e1) {} catch (IOException e1) {} System.out.println("The sum is " + e.sum(n)); } 7 ANSWER OF THE EXERCISE } 5. Triangle. Write program to read 3 integers, which are entered in one line from keyboard, separated by one or more spaces. The program will validate if the three integers are the lengths of three edges of a triangle. If yes, calculate and display the area of this triangle, if not display appropriate message. If the program name is Triangle.java, when you run, it will prompt: Enter 3 integers: 3 4 5↵ The program will display: The 3 integer numbers are the lengths of three edges of a triangle. The area of this triangle is 6. import java.util.*; import java.io.*; class Triangle { int x, y, z; double area(int x, int y, int z) { double p = (x+y+z)/2; return Math.sqrt(p*(p-x)*(p-y)*(p-z)); } boolean isTriangle() { return ((x + y > z) && (x + z > y) && (y + z > x)) } void readInts() throws IOException, NumberFormatException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); StringTokenizer st = new StringTokenizer(s, “ “); int c=0; while (st.hasMoreElements()) { c++; if (c==1) x = Integer.parseInt(st.nextToken()); else if (c==2) y = Integer.parseInt(st.nextToken()); else if (c==3) z = Integer.parseInt(st.nextToken()); } } public static void main(String s[]) { Triangle b = new Triangle(); try { System.out.print("Enter 3 integers: "); b.readInts(); } catch (NumberFormatException e) {} catch (IOException e) {} if (b.isTriangle()) System.out.println("The area of this triangle is " + b.area(b.x, b.y, b.z)); else System.out.println(“The three numbers are not the” + “ lengths of a triangle”); } } 8 ANSWER OF THE EXERCISE Section 2: Do More 1. Modify program 1 in Section 1 so that you do not need to create an object of Fac class in the main method (i.e. without the line Fac a = new Fac();). 2. Modify program 1 in Section I, where n is a natural number entered as a command-line parameter. ↵, the program will display: Note. If the program Fac.java is run, you type: java Fac 5↵ The factorial of 5 is 120. 3. Modify program 1 in Section I, where n is a natural number entered from keyboard. 5. Write program to calculate log2(8) (which is 3), log2(1024) (which is 10), 1.22.1 (which is 1.466), floor(3.7) (which is 3), and ceil(3.7) (which is 4). Section 3: Do Yourself 1. Write program to find the maximum number of a sequence of numbers, entered as commandline arguments of the program. If the program name is FindMax, when you run, type: java FindMax 6 5 7 23 14, the program will display: The max number is 23 2. Write program to check if a given natural number is a perfect number. Perfect number n is a number, for which the sum of all of its divisors (except n) is n. For example: 6 is a perfect number, because 6 = 1 + 2 + 3, 28 is a perfect number, because 28 = 1 + 2 + 4 + 7 + 14. 3. Write program to display all perfect numbers in the range 1..1000. Section 4: Self Test 1. The following source file is given the name FirstClass.java import java.*; public class FirstClass { } public interface Second { } abstract class SecondClass { } What error will the compiler likely generate? A. B. C. D. E. Package java not found in import. Public class FirstClass must be defined in a file called FirstClass.java Public interface Second must be defined in a file called Second.java Class SecondClass may not be defined as abstract. None. The file will compile fine. 2. You have just entered some Java code into a source file. You now wish to save and compile it. Which of the following will work? (Choose all that apply) A. Save it in a file called MyClass.jav and compile it with javac MyClass.jav B. Save it in a file called 1999Work.java and compile it with javac 1999Work.java C. Save it in a file called MyClass.java and compile it with javac MyClass 9 ANSWER OF THE EXERCISE D. Save it in a file called MyClass.java and compile it with javac MyClass.java 3. Examine the following code : import java.util.Vector; public Vector v = new Vector (); class Test { public static void main (String[] args) { System.out.println (”Good luck”); } } What will happen if we try to compile and run this code? A. The code will compile and run fine. B. The code will compile fine, but an error will occur when the class is instantiated. C. The code won’t compile. 4. How to run Java codes? A. Java codes → run directly B. Java codes → compile → bytecode → interpret C. Java codes → compile → run D. Java codes → interpret → bytecode → run 5. What will you do to compile Java codes? A. java abc B. javac abc C. java abc.java D. javac abc.java 6. Which of the following will declare an array of five integers: A. int a[] = {1, 2, 3, 4, 5} B. int a[]; C. int a [] = new int[5]; D. int a[] = new int(5); 7. What will be the result of the statement: System.out.println(0x001B + “ “ + 033); A. 21 23 B. 21 27 C. 27 27 D. 33 33 8. A table can be declared as 2-dimension array, such as int m[][] = new int[3][4]; Which of the following can be used to determine the number of columns of the table? A. m.length(); B. a.size(); C. m[0].length; D. m.length(3); E. m[].length; Section 5: Tips • Do not close the MS-DOS window during the lab; otherwise you must set up the Java environment again. When you close MS-DOS windows, all the values set in the path and classpath will be lost. 10 ANSWER OF THE EXERCISE • To compile a Java program, you must specify the .java extension. • To run a Java program, you must not specify the .class extension. • Every declaration and statement in Java (except import and package) must be written in some class! • There may be at most one public class in a Java source file! • Use the optimizing options of the compilers. Sun’s Java Compiler has the –O option (javac –O YourClass.java) • Use some profiling tools to know where you need to optimize your code, such as : HyperProf, ProfileViewer. JAVA – LAB 3 JAVA FUNDAMENTALS Objectives Default value of un-initialized instance variables. Variable declaration and type casting Get class name of a given class String manipulation Section 1: Sample Programs 1. Default values. Program to determine default value of un-initialized instance variables. // Default values of basic type variables class Var { byte a; float b; char c; boolean d; String s; public static void main(String args[]) { Var v = new Var(); System.out.println("a = " + v.a); System.out.println("b = " + v.b); System.out.println("c is character with unicode value 0: " + (v.c=='\u0000')); System.out.println("d = " + v.d); System.out.println("s is null string: " + (v.s==null)); } } 2. Variable declaration and type casting. Program to test variable declaration and type casting. Find and correct all compile errors in the following program: class Test { 11 ANSWER OF THE EXERCISE byte a; byte b = 5; byte c = 200; byte d = -200; byte e = (a + b); byte f = 4 + 5; byte g = 4 + 126; byte h = 3*b; float h = b/2.0; } Note: this file can not run, it does not contain the main() method. Here you simply modify the code so that there will not be any compile errors. 3. Class name. Write program to display the current class name. class Test1 { public static void main(String s[]) { Test1 t = new Test1(); System.out.println("The current class is: " + t.getClass().getName()); } } Note: getClass() is a method in Object class, which is superclass of Test1 class. This method returns an object of Class class. And getName() is a method of Class class, it returns the class name. 4. Display vowels. Write program to accept a string, and display the vowels appeared in the string. For example: if the input string is “Hello”, the program will display: the vowels appeared in string “Hello” is e, o. import java.io.*; class Vowel { static String readStr() throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); return br.readLine(); } public static void main(String s[]) { String st = “”; String vowels = “aeiou”; System.out.print(“Enter a string: “); try { st = readStr(); } catch (IOException e) {} System.out.print("The vowels in string “+st+“ is: “); for (int i=0; i<st.length(); i++) if (vowels.indexOf(st.charAt(i)) >= 0) System.out.print(st.charAt(i) + “ “); System.out.println(); } } 12 ANSWER OF THE EXERCISE 5. Reverse string. Write program to accept a string, and display its reverse. The reverse of a string is a string, which is written in reverse order. For example: the reverse of “Hello” is “olleH”. import java.io.*; class Reverse { static String readStr() throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); return br.readLine(); } public static void main(String s[]) { String st = “”; String reverse = “”; System.out.print(“Enter a string: “); try { st = readStr(); } catch (IOException e) {} System.out.print("The reverse of string “+st+“ is: “); for (int i=st.length()-1; i>=0; i--) reverse += st.charAt(i); System.out.println(reverse); } } Section 2: Do More 1. Modify sample program 2 so that it can run and display the values of variables (properties) in the class. 2. Sample program 4 displays all appearance of vowels in the input string, so that the same vowel is displayed repeatedly. Modify sample program 4 so that it displays different vowels in the input string. 3. Modify sample program 5 so it can reverse a string using the reverse() method in StringBuffer class. Section 3: Do Your Self 1. Write program to accept a natural number (type int) representing a year, and display if that year is a leaf year or not. Leaf year is a year satisfying: • If it ends with 00, it must divided by 400 • If it does not end with 00, it must be divided by 4. For example: if the input number is 2000, the program will display: 2000 is a leaf year. 2. Write program to accept two natural numbers n (type int), and k (type byte), and display the kth bit of number n (counted from right to left, with the first index is 1). For example: if the input number is 26 and 4, the program will display: The 4-th bit of 26 is 1. 13 ANSWER OF THE EXERCISE 3. Write program to accept an integer number, and display its reverse. The reverse of an integer is an integer, which is written in reverse order. For example: the reverse of number 1234 is 4321. 4. Write program to read an integers, and display the number of its digits and sum of its digits. For example, if the number entered is 1234, the program will display: The number of its digits is 4. The sum of its digits is: 1 + 2 + 3 + 4 = 10 Section 4: Self-Test 1. Which of the following top-level class definitions are legal ? (Choose all that apply) A. private class A { } B. class B { } C. public class C { } D. final class Class { } E. abstract class E; F. final abstract class F { } 2. We would like to create a valid main () method that we can use to start a class from the command line. Which of these candidates will work ? (Choose all that apply) A. static public void main (String[] args) { } B. public static int main (String [] args) { } C. public static void main (String args []) { } D. public static void main (String [] contract) { } 3. A summer student has just finished creating a class and wants you to review it : class DataServer extends Server { public String serverName; public DataServer () { serverName = “Customer Service”; super (serverName); } } A. B. C. D. The code will compile and run fine. The code will compile fine, but an error will occur when the class is instantiated. The code won’t compile because the String serverName must be static. The code won’t compile because of something in the DataSever () method. 4. Which of the following variable definitions are legitimate if it is an instance variable? (Choose all that apply) A. protected int a; B. transient int b=3; C. public static final int c; D. volatile int d; E. private synchronized int d; 5. Which one of these contains only Java keywords? A. class, Thread, void, long, if, continue B. goto, instanceof, native, finally, default, throws C. try, redo, throw, final, volatile, transient 14 ANSWER OF THE EXERCISE D. true, throws, super, implements, do E. null, byte, break, switch 6. Study the following class definition carefully : public class Test { public int t=4; public static void main (String[] args) { new Test().NumberPlay(); } public void NumberPlay () { int t = 2; t = t + 5; this.t = this.t - 2; t = t - this.t; System.out.print(t + " "); System.out.println(this.t); } } A. B. C. D. E. F. 25 -9 0 0 -9 52 72 27 7. Examine the following code : public class LocalTest { public static void main (String[] args) { int i; System.out.print (“int i = “ + i); i=20; } } A. B. C. D. It will compile, but will produce an interpreter error when executed. It will compile and output ‘0’ to the screen. It will not compile and will give a compile error. None of the above. 8. What will be printed out if this code is run with the following command line ? C:\>java myprog good morning public class myprog{ public static void main(String argv[]) { System.out.println(argv[2]) } } A. B. C. D. myprog good morning Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2" 15 ANSWER OF THE EXERCISE Section 5: Tips • A convenient way to pause the dos program execution until user hits enter : try { System.in.read(); } catch (Exception e) • To know how many parameters your main (String args[]) method has received, use this property : args.length • Use int or float data type in your code to avoid Type Casting when use other methods (because most methods take parameters as int or float) Unnecessary variables should place locally in a method rather than in public area of a class. JAVA – LAB4 JAVA FUNDAMENTALS (Cont.) Objectives Call methods from Object class Call methods from super class Create random two-dimension arrays Sort an array Section 1: Sample Programs 1. Object class. Write program to call some methods of superclass Object. class Test2 { public static void main(String s[]) { Test2 t = new Test2(); Test2 u = new Test2(); Test2 v = t; System.out.println("The current object is: " + t.toString()); System.out.println("t=u?: " + (t.equals(u))); System.out.println("t=v?: " + (t.equals(v))); System.out.println("t==u?: " + (t==u)); System.out.println("t==v?: " + (t==v)); } } 2. Call methods from super class. Write two classes in which one class inherits from another, and call a method from its super class. class A { int add(int a, int b) { return (a+b); } } class Call extends A{ public static void main(String s[]) { 16 ANSWER OF THE EXERCISE Call c = new Call(); System.out.println("The sum of 3 and 7 is: ”+c.add(3,7)); } } 3. Random matrix. Write program to create a random matrix (two-dimension array), and display it on the screen. class RandomArray{ static int [][] createRandomArray(int row, int col) { int [][] a = new int[row][col]; for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) a[i][j] = (int)(Math.random()*100); return a; } static void displayArray(int [][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) System.out.print(a[i][j] + “\t”); System.out.println(); } } public static void main(String s[]) { int [][] a = createRandomArray(3, 4); System.out.println("The random array is:”); displayArray(a); } } 4. Sort an array. Write program to sort an array of integers in increasing order. import java.util.*; class SortArray { public static void main(String s[]) { int a[] = {4, 3, 6, 1, 9}; Arrays.sort(a); for (int i=0; i<a.length; i++) System.out.print(a[i] + "\t"); } } Section 2: Do More 1. Modify sample program 3 so that it creates a random array and check if this array contains the numbers in increasing order. 2. Modify sample program 3 so that it creates and displays an array containing students’ ages from 18 to 25 (i.e. the random numbers should be in the interval [18, 25]). 3. Combine sample programs 3 and 4 to write program to sort a random array, which is created in this program. 17 ANSWER OF THE EXERCISE Section 3: Do Yourself 1. What will be the output of the following program? class Test { static byte add(byte x, byte y) { return (byte)(x+y); } public static void main(String args[]) { System.out.println(add((byte)100, (byte)100)); } } 2. A string is said to be an anagram of another string if the first string is a permutation of the other. For example, the string “dare” is an anagram of “read”. Write program to read 2 strings, and check if they are anagrams of each other. 3. Write program to create 2 random matrices and calculate the sum of them. Create a new method (for instance, Add2Matrices(…)) to perform the addition operation. Hint: use method random() in Math class to create a random number. Section 4: Self-Test 1. What will be the value of code variable after the method convertCode() is run? class I { public static void main (String s[]) { int code = 237; convertCode(code); } public static void convertCode(int i) { i = i + 100000; } } A. B. C. D. The code will not compile 100237 237 Another value 2. What will be the output of the following program? class L { static int users = 0; public static void main(String s[]) { System.out.print(++users); System.out.print(users++); } } A. B. C. D. 11 10 01 00 3. What will be the output of the following program? class B{ public static void main(String s[]) { 18 ANSWER OF THE EXERCISE int x = 0x80000000; System.out.print(x + “ and ”); x = x >> 31; System.out.println(x); } } A. B. C. D. –2147483648 and 2147483647 –2147483648 and 1 –2147483648 and –1 Another values 4. What will be the output of the following program? class B{ public static void main(String s[]) { int x = 0x80000000; System.out.println(x + “and”); x = x >>> 31; System.out.println(x); } } A. B. C. D. –2147483648 and 2147483647 –2147483648 and 1 –2147483648 and –1 Another values 5. What will be the output of the following program? class B { public static void main(String s[]) { int x = 11 & 9; System.out.println(x); } } A. B. C. D. 8 9 10 11 6. What will be the output of the following program? class B { public static void main(String s[]) { int x = 10 | 5; System.out.println(x); } } A. B. C. D. 12 13 14 15 7. Which of the followings are legal lines of code: a. int a = (int) 888.8; b. byte b = (byte) 1000L; 19 ANSWER OF THE EXERCISE c. long c = (byte) 100; d. byte d = (byte) 100L; 8. What will be the output of the following program? class S { public static void main(String s[]) { String java = “Java”, va = “va”; System.out.print(java == “java”); System.out.print(java == (“Ja” + “va”)); System.out.print(java == “Ja” + va); System.out.print(java.equals(“Ja”+va)); } } A. B. C. D. truefalsetruefalse truetruefalsefalse falsetruefalsetrue falsefalsetruetrue 9. What will be the output of the following program? class R { public static void main(String s[]) { int a = 1; R t = new R(); System.out.println(a); t.modify(a); System.out.println(a); } void modify(int n) { n = n+1; } } A. B. C. D. 11 12 13 10 10. What will be the output of the following program? Import java.awt.Dimension; class R { public static void main(String s[]) { Dimension d = new Dimension(5,5); R r = new R(); System.out.println(d.height); r.modify(d); System.out.println(d.height); } void modify(Dimension d) { d.height = d.height + 1; } } A. 5 7 B. 5 6 C. 5 4 20 ANSWER OF THE EXERCISE D. 5 5 Section 5: Tips • Bitwise operators can make your program a bit faster. Instead of using (a*2) you should use (a<<2) • Whereever you can, use integer arithmetic instead of floating-point arithmetic. int is the data type you should use. Avoid using double or float, because integer operations are much faster than floating-point operations. Do not use short, because it needs often to be casted to int, most methods return int values. • Move loop-invariant code outside the loop and method-invariant calculations into the constructor or init () method, e.g: for (int i=0; i<360; i++) { x = i * (a / (180.0/3.14)); ... change to : aRad = a / (180.0/3.14); for (int i=0; i<360; i++) { x = i * aRad; ... • Make sure that the variable for the loop counter is a local int variable. You can optimize the compare operation as following codes : for (int i=0; i< max; i++) chang to : for (int i=max; --i >=0; ) The second loop will be faster than the first one ! JAVA – LAB 5 PACKAGES AND INTERFACES Objectives Create a package Add classes to the created package Using classes in the created package Using classes in java.lang package: String, StringBuffer, Runtime, Math, and System. Calculate statistical values from a data set. 21 ANSWER OF THE EXERCISE Section 1: Sample Programs 1. Package util. Create a package called util from current directory, and place some class into it. package util; public class A { public int add(int x, int y) { return (x+y); } } Note: • • • • • Create a new directory util from your current directory (ex. D:\JavaProgs). Name this file as A.java and save it in util directory. From current directory, compile it using: javac util\A.java. A class file A.class is created in the util directory. The class A and the add() method must be declared public, so that other classes from outside util package can access them. If this file is saved in current directory, you can still compile it by using: javac –d d:\JavaProgs A.java. The compiler will create a directory util (if it does not exist), and place the class file A.class into this directory. Write the following code: import util.*; class B extends A { public static void main(String args[]) { B b = new B(); System.out.println("The sum of 3 and 5 is: “ + b.add(3, 5)); } } Note: • • • Name this file as B.java and save it in the current directory. From current directory, compile the source file B.java using: javac B.java. A class file B.class is created in the current directory. Run the program using: java B 2. Add combination() method to the class A in sample program 1. This method calculates C(n, k) by applying the following recursive definition: C(n, 0) = C(n, n) = 1, C(n, 1) = n, C(n, k) = C(n-1, k) + C(n-1, k-1) package util; public class A { public int add(int x, int y) { return (x+y); } public int combination(int n, int k) { if ((k==0) || (k==n)) return 1; 22 ANSWER OF THE EXERCISE else if (k==1) return n; else return combination(n-1, k) + combination(n-1, k-1); } } Add the bold code below into B class: import util.*; class B extends A { public static void main(String args[]) { B b = new B(); System.out.println("The sum of 3 and 5 is: “ + b.add(3, 5)); System.out.println("The value of C(5, 3) is: “ + b.combination(5,3)); } } 3. Run application. Write program to run an application (ex. freecell.exe in C:\Windows). import java.io.*; class Test { public static void main(String args[]) { Runtime r = Runtime.getRuntime(); try { r.exec(“C:\\windows\\freecell.exe”); } catch (IOException e) {} } } 4. Write program to get the classpath, Java version, and Java virtual machine name of your current environment; and calculate the time elapsed of a for loop. class SystemDemo { public static void main(String args[]) { System.out.println("The classpath is: “ + System.getProperty(“java.class.path”)); System.out.println("The Java version is: “ + System.getProperty(“java.version”)); System.out.println("The JVM name is: “ + System.getProperty(“java.vm.name”)); double a[] = new double[100000]; long t1 = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) a[i] = Math.sqrt(i); long t2 = System.currentTimeMillis(); System.out.println("The time elapsed is: “ + (t2 – t1)); } } 5. Count characters. Write program to count a given character (ex. ‘a’) in a given string (ex. “Lambada”). 23 ANSWER OF THE EXERCISE class Count { public static void main(String args[]) { String s = “Lambada”; int count = 0; for (int i=0; i < s.length(); i++) if (s.charAt(i) == ‘a’) count++; System.out.println("The number of character \‘a\’ in the string is “ + count); } } 6. ReverseString. Write program to reverse a string, using reverse() method in StringBuffer class. class ReverseString { public static void main(String args[]) { String s = “Hello”; StringBuffer sb = new StringBuffer(s); sb.reverse(); System.out.println("The reverse string of “ + s + “ is “ + sb); } } 1. Which of the following are Java key words? (Choose all that apply) A. double B. Switch C. then D. instanceof 2. Which of the following are valid statements? A. public class MyCalc extends Math; B. Math.max(s); C. Math.round(9.99); D. Math.mod(4,10); 3. Which of the following are legal statements? (Choose all that apply) A. float f=1/3; B. int i=1/3; C. float f=1.01; D. double d = 999d; Section 5: Tips • Remember two important points: all methods in the interfaces have to be of type public, methods have to be defined in the class that implements this interface. • You can use interface for multiple inheritance. 24 ANSWER OF THE EXERCISE • Interfaces cannot extend classes, but they can extend other interfaces. If you implement and interface that extends an interface, you need to override methods in the new interface as well as in the old one. 25 ANSWER OF THE EXERCISE JAVA – LAB 6 PACKAGES AND INTERFACES (CONT.) Objectives Create a simple interface. Sorting an array of objects using Comparable interface. Using classes in java.util package: StringTokenizer, HashTable, and Stack. Section 1: Sample Programs 1. Simple interface. Write program to create a simple interface. interface Add { int add(int a, int b); } class A implements Add { public int add(int a, int b) { return (a+b); } } class B implements Add { public int add(int a, int b) { return (Math.abs(a)+Math.abs(b)); } } class Test { public static void main(String args[]) { Add a = new A(); System.out.println(“The sum of -3 and 7 is: “ + a.add(-3, 7)); a = new B(); System.out.println(“The sum of -3 and 7 is: “ + a.add(-3, 7)); } } 2. Sorting an array of students. Write program to create an array of students and sort them according to their ages. Class Student contains two properties: name (of type String) and age (of type int). import java.util.*; class StudentSort { public static void main(String args[]) { Student st[] = new Student[5]; st[0] = new Student(“Vy”, 27); st[1] = new Student(“Hoa”, 17); st[2] = new Student(“Nam”, 21); st[3] = new Student(“Loan”, 22); st[4] = new Student(“Anh”, 25); Arrays.sort(st); 26 ANSWER OF THE EXERCISE for (int i=0; i<st.length; i++) System.out.println(st[i].name + “\t” + st[i].age); } } class Student implements Comparable { String name; int age; Student (String name, int age) { this.name = name; this.age = age; } public int compareTo(Object o) { Student st = (Student) o; if (age < st.age) return –1; else if (age > st.age) return 1; else return 0; } } 3. Display operands. Write program to display operands in an expression. For example, if the expression is: (2 + 7) * 4 – (15 / 2), the program will display: The operands in this expression are: 2 7 4 15 2. import java.util.*; class DisplayOperands { public static void main(String args[]) { String s = “(2 + 7) * 4 – (15 / 2)”; StringTokenizer st = new StringTokenizer (s, “ +-*/()”); System.out.print("The operands in this expression are:“); while (st.hasMoreTokens()) { System.out.print(st.nextToken() + “ “); } System.out.println(); } } 4. Small dictionary. Write a small dictionary containing several words with their explaination (ex. apple, orange…), and display the explaination according to the word. import java.util.*; class SD { public static void main(String args[]) { Hashtable h = new Hashtable(); h.put(“apple”, “Fruit containing many vitamins.”); h.put(“orange”, “A kind of fruit with a lot of water.”); System.out.println(h.get(“apple”)); } } 5. Stack with different objects. Write program to create a stack and add different objects onto it. The program should display the object on the top of the stack. import java.util.*; class Student { 27 ANSWER OF THE EXERCISE String name; int age; Student( String name, int age) { this.name = name; this.age = age; } } class StackDemo{ public static void main(String args[]) { Stack st = new Stack(); st.push(new Integer(100)); st.push(“Hello”); st.push(new Student(“Loan”, 22)); st.push(new Double(3.14)); System.out.println("The object on the top of the stack is “ + st.pop()); } } Section 2: Do More 1. Modify sample program 2 so that it sorts the students according to their names. 2. Modify sample program 2 so that it creates an array of 10 random students and sorts them according to their names. 3. Modify sample program 3 so that it displays not only operands but also operators in the expression. 4. Modify sample program 4 so that it accepts a word entered from keyboard, and display the corresponding explanation. When you type a word that does not exist in the dictionary (for instance, computer), it will display: The word “computer” is not in the dictionary. 5. Modify sample program 5 so that it creates an empty stack (use Stack class in java.util package) and add the following objects onto it: • • • • Several integers Several strings Several objects of class Dog (with properties: sex, color) Several objects of class Cat (with properties: nationality, name) The program display the following information: • • • The number of objects in the stack. The number of Chinese cats in the stack. The sum of all numbers in the stack. Section 3: Do Yourself 1. Write program to accept a natural number (type int), and display its binary representation. For example: if the input number is 26, the program will display: 28 ANSWER OF THE EXERCISE Binary representation of 26 is 11010. 2. Given an array containing integers, write program to find the first number whose value is greater than the sum of all its predecessors. For example, if the input array is: 4, 3, 2, 10, 30, the program will display: The number found is 10, because it’s the first number satisfying 4 + 3 + 2 < 10. JAVA - LAB 7 - TEST 1. (1 mark) Write program to accept two positive integers a and b on the same line (separated by one or more blanks). The program then display their sum S=a+b and their product P = a*b, and if (S=P) it will display the message “The sum equals the product”; else it will display the message “The sum does not equal the product”. 2. (2 marks) Write program to accept a natural number n (n=1, 2…), and check if its binary representation is symmetric or not. For example, if n = 9, its binary representation will be 1001 (symmetric), so the program will display: “The binary representation of 9 is symmetric: 9 = 1001.”. If n = 10, its binary representation will be 1010 (not symmetric), so the program will display: “The binary representation of 10 is not symmetric: 10 = 1010.” 3. (2 marks) Write program to display all numbers n from 10 to 1000 having the following property: the sum of all digits of n equals the product of all digits of n. For example: the number 123 has this property, because 1+2+3 = 1*2*3. 4. (1 mark) Write program to calculate the square root of a (a ≥ 0), by applying the following algorithm: x = 1; e = 10-6; while (| x – a/x | >= e) x = (1/2)*(x + a/x); When the loop terminates, the value of x will be the square root of a. For comparison, also display the return value of method Math.sqrt(a) in java.lang package. 5. (3 marks) Write program to accept 1, 2 or 3 positive integers. If user enters 1 integer a, the program will display the area of the circle with radius a. If user enters 2 integers a and b, the program will display the area of the rectangle with the width a, and the height b. If user enters 3 integers a, b and c, the program will firstly check if the numbers are the lengths of a triangle. If yes, it will display the area of the triangle having a, b, c as the lengths of its edges; otherwise, it will display the message “The three numbers are not the lengths of a triangle”. 29