Hi everyone,
I'm preparing for my Java module exam and I'm going through previous term papers. I have completed some of the questions and I need someone to check my answers and tell me if I have done it the correct way.
The questions are as below,
a) Briefly explain what byte code is.
Answer
Each java program is converted into one or more class files. The content of the class file is a set of instructions called bytecode to be executed by JVM. Java Virtual Machine (JVM) is an interpreter for the bytecode.
b) Briefly explain what is instance variable.
Answer
An instance variable is a variable defined in a class, for which each object in the class has a separate copy.
c) State the output for the below expression.
i) 9 && 33
I'm not too sure how to answer this but I know that the && logical AND operator evaluates both values to true
ii) 19 || 6
Same with one, the || logical OR operator evaluates either one of the value to true.
iii) 16 >> 2
Answer
The output is 4. Converting 16 to binary which is 10000 and shift right by 2 bits which is 100 then converting back to decimal gives 4.
iv) 9 << 1
Answer
The output is 18. Converting 9 to binary which is 1001 and shift left by 1 bit which is 10010 then converting back to decimal gives 18.
v) 34 % 6
Answer
The output is 4. The remainder operator will divide 34 by 6 and output 4 as its result.
d) Identify the mistakes found in the codes below.
public static void checkBigger(int no1, no2)
{ if (no1 > no2);
return no1;
else
return no2; }
}
Answer
Line 2: Return type for the second variable is not defined and there is no opening brace
Line 4: the opening brace should be after the if statement and the semi colon is not required
Line 6: void method cannot return a value
Line 8: if-else statement should be enclosed in braces
Line 10: void method cannot return a value
The above code should look like this
public static void checkBigger(int no1, int no2)
{
if (no1 > no2)
{
do something;
}
else
{
do something;
}
}
e i) Declare a class handphone with member brand of String and price of double type
Answer
class handPhone
{
String brand;
double price;
}
ii) Implement a constructor to initialize all the attributes belonging to handphone object
Answer
public handPhone(String phoneBrand, double phonePrice)
{
brand = phoneBrand;
price = phonePrice;
}
iii) Implement a method expensiveBrand which will return true if the price of it is above 500 otherwise return false.
Answer
double price;
public boolean expensiveBrand()
{
if (price > 500)
{
return true;
}
else
{
return false;
}
}
iv) Write statement to create an m2 object of handphone type and activate the expensiveBrand method
Not sure how to answer this
m2 handPhone = new m2();
m2.expensiveBrand();