You are on page 1of 24

Final exam sample M255 Prepared By: Ms Samar Shilbayeh sshilbayeh@arabou.edu.

da

1. What will be the output of the following: for(int i = 0; i < 2; i++) { for(int j = 2; j>= 0; j--) { if(i == j) System.out.println("i=" + i + " j="+j); } }

Answer:

i=0j=0 i=1j=1 inti=1; intj=1; switch(i){ case0:System.out.println(0);break; case1:System.out.println(1); case2:System.out.println(2);break; case3:System.out.println(3);break; } Answer Nooutput inti=0,j=2; do{

i=++i; j; }while(j>0); System.out.println(i); Answer 2 inti=1,j=1; try{ i++; j; if(i/j>1) i++; } catch(ArithmeticExceptione){ System.out.println(0); } catch(ArrayIndexOutOfBoundsExceptione){ System.out.println(1);

} catch(Exceptione){ System.out.println(2); } Answer 0 inti=1,j=1; try{ i++; j; if(i==j) i++; } catch(ArithmeticExceptione){ System.out.println(0);

} catch(ArrayIndexOutOfBoundsExceptione){ System.out.println(1); } catch(Exceptione){ System.out.println(2); } finally{ System.out.println(3); } System.out.println(4); Answer 3 4

Strings1="abc"; Strings2="abc"; if(s1==s2) System.out.println(1); else System.out.println(2); if(s1.equals(s2)) System.out.println(3); else System.out.println(4); Answer 1 3

Stringr=newString("abc"); Strings=newString("abc"); r=r+1;//1 r=null;//2 s=s+r;//3 answer acbnull Writeaastatementthatdefinestwodimensional arraysandassign1234respectivelybyrowand printit Answer: int[][]ia={{1,2},{3,4}}; for(inti=0;i<2;i++) for(intj=0;j<2;j++) System.out.println(ia[i][j]);

Writeacodetodefinetwoonedimensionalarrays a1anda2,Withtwoelements,Writeamethodto swapbetweenthosearrays Answer: int[]a1={1,2}; int[]a2={3,4}; int[]a3=newint[2]; for(inti=0;i<2;i++) { a3[i]=a1[i]; a1[i]=a2[i]; a2[i]=a3[i]; } String[][]names={{"Mr.","Mrs.","Ms."}, {"Smith","Jones"}};

System.out.println(names[0][0]+names[1][0]);//Mr. Smith System.out.println(names[0][2]+names[1][1]);//Ms. Jones Answer Mr.Smith Ms.Jones Fillintheblank:


1. The term "instance variable" is another name for nonstatic field. 2. The term "class variable" is another name for static field. 3. A local variable stores temporary state; it is declared inside a method. 4. A variable declared within the opening and closing parenthesis of a method is called a parameter. 5. What are the eight primitive data types supported by the Java programming language? byte, short, int, long, float, double, boolean, char 6. Character strings are represented by the class java.lang.String. 7. An array is a container object that holds a fixed number of values of a single type.


Identify the following kinds of expression statements: aValue = 8933.234; aValue++; System.out.println("Hello World!"); Bicycle myBike = new Bicycle(); Answer: aValue = 8933.234; // assignment statement aValue++; // increment statement System.out.println("Hello World!"); // method invocation statement Bicycle myBike = new Bicycle(); // object creation statement

TreeMaptree=newTreeMap(); tree.put("aa",1); tree.put("bb",2); tree.put("cc",3); tree.put("dd",4); System.out.println("theelementis"+tree);

Answer: theelementis{aa=1,bb=2,cc=3,dd=4} Shortanswer:

Similaritiesanddifferencesbetweenvaluetype variables&referencetypevariables: Reference type variables are declared in the same way as value type variables Primitive data types are found by default in all programming languages. However, the reference type is programmer creation ones, so you need to create class then use it as a type.

Objects usually take up much more memory than values of primitive data types. This is simply because an object will have number of attributes each of which will be another value of primitive data type or object. In contrast to primitive data type, the space needed to store an object is also unpredictable at compilation time because we can not determine what class of object will actually be dynamically assigned to a variable at run time. (i.e. instances of sub-class can be assigned to variables declared for its supercalss, the super class and sub-class take different memory storage for their objects, because usually sub-class has extra attribute or message) A garbage collection process take place to remove from memory any reference variable that is not in use any more.
Example: int a = 5; int b = 5; a++; ++b;

// a is now 6 // b is now 6 int c = 5; int e = 5; int d = ++c; int f = e++; //c is 6, d is 6 // f is 5, e is 6

Example: Assume you have the following instances: Frog frog1 = new Frog; Account acc = new Account(); Write a Java code that will make frog1 hops one stone to the right. For each hop it makes, 10 pounds is credited to a bank account acc, which starts with balance zero. The frog continues hopping till either: It reaches stone 11 OR 80 pounds has accumulated in the account. Note that: hop means jump then move one step to the right or left. Solution: while ((frog1.getPosition() < 11) && (acc.getBalance() < 80)) { frog1.jump(); frog1.right(); acc.credit(10); }

Define the class Bicycle and define three instance variables inside this class (gear,speed and ID ) Define one class variable for the number of Bicycle objects instantiated

Answer: public class Bicycle{ private int gear; private int speed; // add an instance variable for the object ID private int id; // add a class variable for the number of Bicycle objects instantiated private static int numberOfBicycles = 0; ...... }
Define the constructor Bicycle(int startCadence, int startSpeed) Notice that the ID should be increased by one each time a new bicycle created

Answer:
public Bicycle(int startCadence, int startSpeed, int startGear){ gear = startGear; cadence = startCadence; speed = startSpeed; // increment number of Bicycles and assign ID number id = ++numberOfBicycles; }

Define all accessories messages Answer: public int getID() { return id; } public static int getNumberOfBicycles() { return numberOfBicycles; } public int getCadence(){ return cadence; } public void setCadence(int newValue){ cadence = newValue; } public int getGear(){ return gear; } public void setGear(int newValue){ gear = newValue; }

public int getSpeed(){ return speed; }

Define the method applyBrake(int) and speedup(int) which decrease and increase the speed
Answer: public void applyBrake(int decrement){ speed -= decrement; } public void speedUp(int increment){ speed += increment; } }

The whole answer


public class Bicycle { /* instance variables */ private int gear; private int speed; private int id; private static int numberOfBicycle=0; // replace this example variable with your own

/** * Default constructor for objects of class Bicycle */ public Bicycle(int startGear,int startSpeed) { super(); this.gear=startGear; this.speed=startSpeed; this.id= ++ Bicycle.numberOfBicycle;

/* instance methods */

/** * An example of a method - replace this comment * and the method below with your own */ public int getID() { return this.id;

public static int getNumberOfBicycles() { return Bicycle.numberOfBicycle; } public int getGear() { return this.gear; } public void setGear(int x) { this.gear=x; } public int getSpeed() { return this.speed; } public void setSpeed(int y) { this.speed=y; } public void applyBrake(int decrement){ speed -= decrement; }

public void speedUp(int increment){ speed += increment; }

To test: Bicycle c=new Bicycle(10,200);

Read 5 characters from external file chosen by the user and print it in the reverse order

String pathname; pathname=OUFileChooser.getFilename(); File aFile=new File(pathname);

FileReader inFile1= new FileReader(aFile);

// Declare and instantiate an array char[] array1 = new char[5]; int s1=inFile1.read(); System.out.println("the value of s is"+s1); while(s1!=-1) { for (int i=0; i<5; i++) { array1[i]=(char)s1; System.out.println((char)s1); s1=inFile1.read(); } } for(int i=4;i>=0;i--) System.out.println(array1[i]);

inFile1.close();

This new6() method makes and returns a new int array of size N that is filled with the value 6.
public int[] new6(int n) { int[] result = new int[n]; for (int i=0; i<result.length; i++) { result[i] = 6; } return result; }


Write a method that returns true if an element x is found in an integer array anArray, and returns false otherwise. public Boolean seqsearch(int[] anArray) { int i = 0; boolean found = false; while ((i < anArray.length) && (! found)) { if (anArray[i] == x) found = true; else i++; } return found;

Write a code to find the summation of each row and print it. int sum; for (int i = 0; i < 4; i++) { sum = 0; for (int j = 0; j < 5; j++) { sum = sum + intTable [i][j]; } OUDialog.alert("Sum of row " + i + " is "+ sum); } Q5. Write a code to find the summation of each column and print it. int sum; for (int j = 0; j < 5; i++) { sum = 0; for (int i = 0; i < 4; j++) { sum = sum + intTable [i][j]; } OUDialog.alert("Sum of column " + j + " is "+ sum); } Write a code to find the summation of the diagonal from right to left and print it. int sum = 0; for (int k=0; k < 4; k++) sum = sum + intTable[k][3-k]; OUDialog.alert("Sum of diagonal is " + sum);
How to print the following array

int [][]array=new int [3][4]; for (int i=0;i<3;i++) for(int j=0;j<4;j++) array[i][j]=i;

0 1 2 3 Display for
leftandprintit.

0 1 2 3 the user the

0 1 2 3

0 1 2 3

summationofthediagonalfromrightto

int sum = 0; for (int k=0; k < 4; k++) sum = sum + array1[k][3-k]; OUDialog.alert("Sum of diagonal is " + sum);

Here'sawhileloopexamplethatusesalooptoseehowmantimesyoucandivideanumberby2:

String num1; int num; int count = 0; num1=OUDialog.request("enter any number"); num=Integer.parseInt(num1); while (num >= 1) { num = num / 2; count++; } return count; }

You might also like