Java Practice Questions MCQ


1. What is the output?



class point1
{
static void a (int x, int y)
{
this.x=x; //non-static variable this cannot be referenced from a static context
this.y=y;
System.out.println(x+ “,”+y);
}
}
class point
{
public static void main (String[] args)
{
point1 pp=new point1();
pp.a(4,3);
}
}


a. 4 ,3
b. 3 ,4
c. Compile Error
d. None of the above


-------------------------------------------------------------------------------------------------------
2. Local variables cannot be declared as final.(True / False) .... False


-----------------------------------------------------------------------------------------------------
3. What is the output?


class A
{
A(int x, int y)
{
this.x=x;
this.y=y;
}
A()
{
this(2,3);
}
public static void main(String[] args)
{
A a1 = new A();
System.out.println(“x=”+a1.x+”,y=”+a1.y); // cannot find symbol x and y
}
}


a. x=2 y=3
b. x=-1 y=-1
c. x=3 y=2
d.None of the above


-------------------------------------------------------------------------------------------------------
4. Find output:


class ArrTest
{
public static void main(String[] args)
{
int arr[]=new int[-2]; //Exception - NegativeArraySizeException
System.out.println("first element : " +arr[0]);
}}


a. first element : -2
b. first element :0
c. first element :
d. None of the above
-------------------------------------------------------------------------------------------------------


5.Which of the following is NOT True ?


a. Instance of class can be cast to instances of other classes.
b. Conversion of primitive types to objects can be done explicitly.
c. Casting does not affect the original object or value
d. None of the above


-------------------------------------------------------------------------------------------------------


6. Given the code:
String s1="yes";
String s2="yes";
String s3=new String(s1);
Which of the following would equate to Boolean true?
s1 == s2
s1 = s2
s3 == s1
s1.equals(s2)
s3.equals(s1)


-----------------------------------------------------------------------------------------------
7. What will be the content of array variable table after executing the following code?
Int table[][]=new int[3][3];
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++) {
if(j == i)
table[i][j] = 1;
else
table[i][j] = 0;
}
}
100010001
100110111
1010100


-------------------------------------------------------------------------------------------------------


8. package mypackage.compute.financial;
Referring to the above, where must Class files belonging to the package be stored?
*******


In any classpath directory
In directory mypackage under the current working directory
In mypackage/compute/financial directory.
In mypackage/compute/classpath under any directory
In any directory defined in the path of the java interpreter


-------------------------------------------------------------------------------------------------------

int j;
for(int i=0;i<14;i++)
{
if(i<10){
j=2+m;
}
System.out.println(“j: “+ j +”i: “+i);
}


9. What is wrong with the above code


m is not declared and initialized
Nothing.
You cannot declare integer i inside the for-loop declaration
The syntax of the "if" statement is incorrect
You cannot print integer values without converting them to strings.


-------------------------------------------------------------------------------------------------------


int values[] = {1,2,3,4,5,6,7,8};
for(int i=0;i<X;++i)
System.out.println(values[i]);


10. Referring to the above, what value for "X" will print all members of array "values"?
1
7
8
9
None, since there is a syntax error in array declaration


-----------------------------------------------------------------------------


class SwitchDemo
{
public static void main(String args[])
{
char ch1='x',ch2;
try {
ch1 = (char) System.in.read();
}
catch(Exception e) {}
switch(ch1)
{ case 'a': ch2 = '1';
case 'b': ch2 = '2';
case 'c': ch2 = '3';
default: ch2 = '4';
}
System.out.println(ch2);
}
}
11. Referring to the above, during execution the user presses "b", what is the ending value of "ch2"?
1
2
3
4 //because there is NO break
NULL


-----------------------------------------------------------------------------


try {
int values[] = {1,2,3,4,3,2,1};
for(int i = values.length-1; i >= 0; i++)
System.out.print( values[i] + " " );
}
catch (Exception e) { System.out.print("2" + " "); }
finally { System.out.print("3" + " "); }


12. What is the output of the program above?
  1. 1 2
  2. 1 3
  3. 1 2 3 4 3 2 1
  4. 1 2 3
  5. 1 2 3 4 3 2 1 3


-----------------------------------------------------------------------------


class Conversion
{
public static void main(String arg[])
{
float amount; int quantity = 99;
}
}
13. Referring to the above, what is the correct way to cast an integer to a float?
  1. amount = (float) quantity;
  2. amount (float) = quantity;
  3. amount = (float) %% quantity
  4. You cannot cast an integer to a float
-------------------------------------------------------------------------------------------------------


double x = 0,y = 5.4324;
try {
System.out.println( (y/x) );
}
catch (Exception e) { System.out.println("Exception"); }
catch (Throwable t) { System.out.println("Error"); }


14. What is the output of the above code?
  1. -1
  2. 0
  3. Error
  4. Infinity
  5. Exception


Java will not throw an exception if you divide by float zero. It will detect a run-time error only if you divide by integer zero not double zero. If you divide by 0.0, the result will be INFINITY.
-------------------------------------------------------------------------------------------------------


15. Given the following class definition
public class Upton{
public static void main(String argv[]){ }
public void amethod(int i){}
//Here
}


Which of the following would be legal to place after the comment //Here ?
public int amethod(int z){}
public int amethod(int i,int j){return 99;}
protected void amethod(long l){ }
private void anothermethod(){}
------------------------------------------------------------------------------------------------------------------------


16. What will happen when you attempt to compile and run the following code ?
public class Kmlt{
public static void main(String argv[])
{
Kmlt kmlt = new Kmlt();
kmlt.ft();
}


public void ft(){
int iParm=1;
switch(iParm){
case 0: System.out.print("one");
case 1: System.out.print("two");
default: System.out.print("default");
}
}
}


  1. Compile time error
  2. Compilation and output of "one"
  3. Compilation and output of "two"
  4. Compilation and output of "twodefault"


-------------------------------------------------------------------------------------------------------


17. What is the correct declaration of an abstract method that is intended to be public


  1. public abstract void add();
  2. public abstract void add() {}
  3. public abstract add();
  4. public virtual add();
------------------------------------------------------------------------------------------------------------------------


18. Given the following code what is the effect of a being 5:


public class Test {
public void add(int a) {
loop: for (int i = 1; i < 3; i++)
{
for (int j = 1; j < 3; j++)
{
if (a == 5)
{ break loop; }
System.out.println(i * j);
}
}
}


public static void main(String arg[])
{
new Test().add(3);
}
}


  1. Generate a runtime error
  2. Throw an ArrayIndexOutOfBoundsException
  3. Print the values: 1, 2, 2, 4
  4. Produces no output
-------------------------------------------------------------------------------------------------------------------


public class Test {
public static void test() {
print();
}


public static void print()
{
System.out.println("Test");
}


public void print()
{
System.out.println("Another Test");
}
}


What is the result of compiling this class?
  1. successful compilation.
  2. warning stating that the class has no main method. 2nd
  3. An error stating that print() is already in Test. 1st
  4. An error stating that the method test() will call one or other of the print() methods.
------------------------------------------------------------------------------------------------------------------------


public double SquareRoot (double value) throws AirthmeticException
{
if (value >=0)
return Math.sqrt( value);
else
throw new ArithmeticException();
}


public double func(int x)
{
double y = (double)x;
try{
y=SquareRoot(y);
}
catch(ArithmeticException e)
{
y=0;
}
finally
{
y--;
}
return y;
}


19. Referring to the above, what value is returned when method func(4) is invoked.


  1. -2
  2. -1
  3. 0
  4. 1.0


-------------------------------------------------------------------------------------------------------


20. Which of the following is correct syntax for an Abstract class ?
(a) abstract double area() { }
(b) abstract double area()
(c) abstract double area();
(d) abstract double area(); { }


abstract double area{};    //abstract class
abstract double area();    //abstract method

-------------------------------------------------------------------------------------------------------


21. What is the output of following block of program ?
boolean var = false;
if(var = true) {    
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}


(a) TRUE   // because var=true is assignment statement not comparision.
(b) FALSE
(c) Compilation Error
(d) Run-time Error


-------------------------------------------------------------------------------------------------------


22. What is the output of following piece of code ?
int x = 2;
switch (x) {
case 1:System.out.println("1");
case 2:
case 3:System.out.println("3");
case 4:
case 5:System.out.println("5");
}


(a) No output
(b) 3 and 5
(c) 1, 3 and 5
(d) 3


-------------------------------------------------------------------------------------------------------


23. Which of the following 2 methods executes faster ?
class Trial {
String _member;
void method1() {
for(int i=0;i<2048;i++) {
_member += "test";
}
}

void method2() {
String temp;
for(int i=0;i<2048;i++) {
temp += "test";
}
_member = temp;
}
}


(a) method1()
(b) method2()
(c) Both method1() and method2() takes same time for execution


Accessing method variables requires less overhead than accessing class variables.


-------------------------------------------------------------------------------------------------------
24. What is the output of following program ?
class Test {
public static void main(String args[]) {
for(int i=0;i<2;i++) {
System.out.println(i--);
}
}
}


(a) Goes into infinite loop
(b) 0,1
(c) 0,1,2
(d) None
-------------------------------------------------------------------------------------------------------


25. Cleaning operation in Java is done in the method
(a) finally()
(b) finalize()
(c) final()
-------------------------------------------------------------------------------------------------------
26. What code, if written, below the (//code here) will display 0.


class Test {
public static void main(String argv[]) {
int i=0;
//code here
}
}
(a) System.out.println(i++)
(b) System.out.println(i+'0')
(c) System.out.println(i--)
(d) System.out.println(i)
-------------------------------------------------------------------------------------------------------
class Conversion
{
Public static void main(String arg[])
{
Float amount;
Int quantity=99;
}
}


27. Referring to the above what is the correct way to cast an integer to a float


  1. Amount=(float)quantity;
  2. Amount(float)=quantity;
  3. Amount=(float)%%quantity
  4. You cannot cast an integer to a float
-------------------------------------------------------------------------------------------------------------------
28. Find output:
public class Test1 {
public static void main (String [] args)
{
int [] seq = {6,4,8,2,1};
int minVal = seq[0];
for (int i=1; i<seq.length; ++i)
minVal = checkMin(minVal, seq[i]);
System.out.println("Min Value:"+minVal);
}
public static int checkMin(int a, int b)
{
return (a <= b)? a:b;
}


}


Output:
  1. 6
  2. 4
  3. 2
  4. 1


------------------------------------------------------------------------------------------------------------------------
29. Find output
public class Test1 {
public Test1()
{
System.out.println("java Question");
}
public Test1(int w)
{
System.out.println("are very tricky");
}
public static void main(String[] args) {
Test1 test=new Test1();
}
}


Output:


  1. are very tricky gets printed
  2. java Question gets printed
  3. java Questions are very tricky gets printed
  4. are very tricky java Question gets printed
  5. compiles successfully but does not print anything
------------------------------------------------------------------------------------------------------------------------
30. Find Output
public class Test1 {
public static void main(String[] argv) {
System.out.println(argv[2]);
}
}


What will be the output if the code is run with the following command


Javac Test1.java
Java Test1 High Performance


Output:


  1. Test1
  2. High Performance
  3. High
  4. Performance
  5. Exception Raised: java.lang.ArrayIndexOutOfBoundException:2”
----------------------------------------------------------------------------------------------------------------------------
31. Find output
public class Test1 {
public Test1(){}
public int ext=0;
public Test1(String test)
{
ext=3;
}
}


public class Sub extends Test1
{
public Sub(){}
public Sub(String test)
{
ext=4;
}
public static void main(String[] args) {
Sub var=new Sub("Test");
System.out.println(var.ext);
}
}


Output:
  1. 4
  2. 2
  3. 3
  4. 0
------------------------------------------------------------------------------------------------------------------------
32. Methods declared as ________________cannot be overridden
Output:


  1. Private, static or final
  2. Public, static or abstract
  3. Final
  4. Public or final
------------------------------------------------------------------------------------------------------------------------
33. Which of the following are true?


1. null is java reserved word
2. null can be assigned to all primitive data types
3. If the package statement present, then it must be the first non-comment statement in Java source file
4. We can place same class in diff packages by defining different package statements in the same java source file
5. The argument following the new keyword must be a class name followed by a series of constructor arguments in req parenthesis


Output:
  1. 1,3,5
  2. 1,2,3,4,5
  3. 2,4
  4. 1,3,4
  5. 1,3
------------------------------------------------------------------------------------------------------------------------
34. Constructors are invoked starting with the Object Class up to the current class, then they are executed in reverse order. True or False


False– it’s the other way round
------------------------------------------------------------------------------------------------------------------------
35. Consider the following statement


int number[]=new int[5];


After execution which of the following are true. Select any 2


Output:
  1. Number[5] is undefined
  2. Number[4] is null
  3. Number[2] is 0
  4. Number[0] is undefined
------------------------------------------------------------------------------------------------------------------------
36. What happens when a constructor is not defined for a user defined class


  1. There is a default constructor, which takes arguments of the same type as the data members.
  2. There is a default constructor, which does not initialize the data members.
  3. There is a default constructor, which initializes data members that have basic types to false or 0 and the reference types to null.
  4. You cannot instantiate the class
------------------------------------------------------------------------------------------------------------------------
37. Which of the following statements are valid. Choose any two


  1. Local variables need to be initialized as compared to member variables which do not need initialization.
  2. Static methods or variables are public by default
  3. Import statement has to be the first line of any Java file
  4. Package statement has to be the first line of any Java file
-------------------------------------------------------------------------------------------------------------------
38. Find output:


public class Test1 {
public static void main(String[] args) {
double finalResult = captureResultA(37.5);
double finalValue= captureResultB(37.5);
System.out.println(finalResult + finalValue);
}


public static float captureResultA(double value)
{
float output=new Float(value);
return output;
}


public static double captureResultB(double value)
{
double output =new Float(value);
return output;
}
}


Output:
  1. 74
  2. 75
  3. 75.0
  4. 74.0
------------------------------------------------------------------------------------------------------------------------
39. What is the output?
public class Test1 {
static int num1=99;
protected static int num2=-101;
}


public class Sub extends Test1
{
public static void main(String[] args) {
num2--;
num1--;
System.out.println(num1 + " ");
System.out.println(num2);
}
}


Output:
  1. 98 102
  2. 98 -102
  3. 98        -101
  4. 98 -100
------------------------------------------------------------------------------------------------------------------------
40. What is the output?


public class Test1 {


void add(int a)
{
System.out.println("Int Method");
}
void add(float a)
{
System.out.println("Float Method");
}
void add(double a)
{
System.out.println("Double Method");
}
public static void main(String[] args) {
Test1 t=new Test1();
t.add(12.23);
}
}


Output:
  1. Int Method
  2. Float Method
  3. Double Method     // The default data type for 12.23 (decimal numbers is double and not float). To make it float you need to append with ‘f’ after the number e.g. 12.23f
  4. None of the above

------------------------------------------------------------------------------------------------------------------------


Java Questions


1.The Java interpreter is used for the execution of the source code.
a) True b) False
Ans: a.


2) On successful compilation a file with the class extension is created.
a) True b) False
Ans: a.
3) The Java source code can be created in a Notepad editor.
a) True b) False
Ans: a.


4) The Java Program is enclosed in a class definition.
a) True b) False
Ans: a.


5) What declarations are required for every Java application?
Ans: A class and the main( ) method declarations.


9) What output is displayed as the result of executing the following statement?
System.out.println("// Looks like a comment.");
a. // Looks like a comment
b. The statement results in a compilation error
c. Looks like a comment
d. No output is displayed
Ans : a.


10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?
  1. It must have a package statement
  2. It must be named Test.java
  3. It must import java.lang
  4. It must declare a public class named Test
Ans : b


12) What is the return type of program’s main( ) method?
Ans : void


13) What is the argument type of program’s main( ) method?
Ans : string array.


14) Which characters are as first characters of an identifier?
Ans : A – Z, a – z, _ ,$


15) What are different comments?
Ans : 1) // -- single line comment
2) /* --
*/ multiple line comment
3) /** --
*/ documentation


Data types, variables and Arrays


4) What are variable types?
Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array.


5) How do you assign values to variables?
Ans: Values are assigned to variables using the assignment operator =.


8) How do you declare an array?
Ans: Array variable indicates the type of object that the array holds.
Ex: int arr[];


9) Java supports multidimensional arrays.
a)True
b)False
Ans: a.


10) An array of arrays can be created.
a)True
b)False
Ans: a.


12) Strings are instances of the class String.
a)True
b)False
Ans: a.


13) When a string literal is used in the program, Java automatically creates instances of the string class.
a)True
b)False
Ans: a.


14) Which operator is to create and concatenate string?
Ans: Addition operator(+).


15) Which of the following declare an array of string objects?
  1. String[ ] s;
  2. String [ ]s:
  3. String[ s]:
  4. String s[ ]:
Ans : a, b and d


16) What is the value of a[3] as the result of the following array declaration?
  1. 1
  2. 2
  3. 3
  4. 4
Ans : d


17) Which of the following are primitive types?
  1. byte
  2. String
  3. Integer
  4. Float
Ans : a.


18) What is the range of the char type
  1. 0 to 216
  2. 0 to 215
  3. 0 to 216-1
  4. 0 to 215-1
Ans. d


19) What are primitive data types?
Ans : byte, short, int, long
float, double
boolean
char


20) What are default values of different primitive types?
Ans : int - 0
short - 0
byte - 0
long - 0 l
float - 0.0 f
double - 0.0 d
boolean - false
char - null


21) Converting of primitive types to objects can be explicitly.
a)True
b)False
Ans: b.
Operators


1) What are operators and what are the various types of operators available in Java?
Ans: Operators are special symbols used in expressions.
The following are the types of operators:
Arithmetic operators,
Assignment operators,
Increment & Decrement operators,
Logical operators,
Bitwise operators,
Comparison/Relational operators and
Conditional operators


2) The ++ operator is used for incrementing and the -- operator is used for
decrementing.
a)True
b)False
Ans: a.


3) Comparison/Logical operators are used for testing and magnitude.
a)True b)False
Ans: a.


4) Character literals are stored as unicode characters.
a)True b)False
Ans: a.


5) What are the Logical operators?
Ans: OR(|), AND(&), XOR(^) AND NOT(~).


6) What is the % operator?
Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand.


7) What is the value of 111 % 13?
  1. 3
  2. 5
  3. 7
  4. 9
Ans : c.


8) Is &&= a valid operator?
Ans : No.


9) Can a double value be cast to a byte?
Ans : Yes


10) Can a byte object be cast to a double value ?
Ans : No. An object cannot be cast to a primitive value.


11) What are order of precedence and associativity?
Ans : Order of precedence the order in which operators are evaluated in expressions. Associativity determines whether an expression is evaluated left-right or right-left.
12) Which Java operator is right associativity?
Ans : = operator.


14) What is the result of expression 5.45 + "3,2"?
The double value 8.6
The string ""8.6"
The long value 8.
The String "5.453.2"
Ans : d
15) What are the values of x and y ?
x = 5; y = ++x;
Ans : x = 6; y = 6


16) What are the values of x and z?
x = 5; z = x++;
Ans : x = 6; z = 5
Control Statements
1) What are the programming constructs?
Ans: a) Sequential
b) Selection -- if and switch statements
c) Iteration -- for loop, while loop and do-while loop


2) class conditional {
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
z = i < j ? i : j; // ternary operator
System.out.println("The value assigned is " + z);} }
What is output of the above program?
Ans: The value assigned is 20


3) The switch statement does not require a break.
a)True
b)False
Ans: b.


4) The conditional operator is otherwise known as the ternary operator.
a)True
b)False
Ans: a.


5) The while loop repeats a set of code while the condition is false.
a)True
b)False
Ans: b.


6) The do-while loop repeats a set of code atleast once before the condition is tested.
a)True
b)False
Ans: a.


7) The for loop repeats a set of statements a certain number of times until a condition is matched.
a)True
b)False
Ans: a.


8) Can a for statement loop indefintely?
Ans : Yes.


9) What is the difference between while statement and a do statement/
Ans : A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.
A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
Introduction to Classes and Methods
1) Which is used to get the value of the instance variables?
Ans: Dot notation.


2) The new operator creates a single instance named class and returns a
reference to that object.
a)True
b)False
Ans: a.


3) A class is a template for multiple objects with similar features.
a)True
b)False
Ans: a.


4) What is mean by garbage collection?
Ans: When an object is no longer referred to by any variable, Java automatically
reclaims memory used by that object. This is known as garbage collection.


5) What are methods and how are they defined?
Ans: Methods are functions that operate on instances of classes in which they are defined.Objects can communicate with each other using methods and can call methods in other classes.
Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method.
A method's signature is a combination of the first three parts mentioned above.


6) What is calling method?
Ans: Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation.
Ex: obj.methodname(param1,param2)


7) Which method is used to determine the class of an object?
Ans: getClass ( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects.


8) All the classes in java.lang package are automatically imported when a program is compiled.
a)True b)False
Ans: a.


9) How can class be imported to a program?
Ans: To import a class, the import keyword should be used as shown.;
import classname;


10) How can class be imported from a package to a program?
Ans: import java . packagename . classname (or) import java.package name.*;


11) What is a constructor?
Ans: A constructor is a special kind of method that determines how an object is
initialized when created.
12) Which keyword is used to create an instance of a class?
Ans: new.


13) Which method is used to garbage collect an object?
Ans: finalize ().
14) Constructors can be overloaded like regular methods.
a)True
b)False
Ans: a.
15) What is casting?
Ans: Casting is used to convert the value of one type to another.
16) Casting between primitive types allows conversion of one primitive type to another.
a)True
b)False
Ans: a.


17) Casting occurs commonly between numeric types.
a)True
b)False
Ans: a.


18) Boolean values can be cast into any other primitive type.
a)True
b)False
Ans: b.


19) Casting does not affect the original object or value.
a)True
b)False
Ans: a.


20) Which cast must be used to convert a larger value into a smaller one?
Ans: Explicit cast.


21) Which cast must be used to cast an object to another class?
Ans: Specific cast.


22) Which of the following features are common to both Java & C++?
A.The class declaration
b.The access modifiers
c.The encapsulation of data & methods with in objects
d.The use of pointers
Ans: a,b,c.
23) Which of the following statements accurately describe the use of access modifiers within a class definition?
a.They can be applied to both data & methods
b.They must precede a class's data variables or methods
c.They can follow a class's data variables or methods
d.They can appear in any order
e.They must be applied to data variables first and then to methods
Ans: a,b,d.


24) Suppose a given instance variable has been declared private.
Can this instance variable be manipulated by methods out side its class?
a.yes
b.no
Ans: b.


25) Which of the following statements can be used to describe a public method?
a.It is accessible to all other classes in the hierarchy
b.It is accessablde only to subclasses of its parent class
c.It represents the public interface of its class
d.The only way to gain access to this method is by calling one of the public class
methods
Ans: a,c.


26) Which of the following types of class members can be part of the internal part of a class?
a.Public instance variables
b.Private instance variables
c.Public methods
d.Private methods
Ans: b,d.


27) You would use the ____ operator to create a single instance of a named class.
a.new
b.dot
Ans: a.


28) Which of the following statements correctly describes the relation between an object and the instance variable it stores?
a.Each new object has its own distinctive set of instance variables
b.Each object has a copy of the instance variables of its class
c.the instance variable of each object are seperate from the variables of other objects
d.The instance variables of each object are stored together with the variables of other objects
Ans: a,b,c.


29) If no input parameters are specified in a method declaration then the declaration will include __.
a.an empty set of parantheses
b.the term void
Ans: a.


30) What are the functions of the dot(.) operator?
a.It enables you to access instance variables of any objects within a class
b.It enables you to store values in instance variables of an object
c.It is used to call object methods
d.It is to create a new object
Ans: a,b,c.
31) Which of the following can be referenced by this variable?
a.The instance variables of a class only
b.The methods of a class only
c.The instance variables and methods of a class
Ans: c.


32) The this reference is used in conjunction with ___methods.
a.static
b.non-static
Ans: b.


33) Which of the following operators are used in conjunction with the this and super references?
a.The new operator
b.The instanceof operator
c.The dot operator
Ans: c.


34) A constructor is automatically called when an object is instantiated
a. true
b. false
Ans: a.


35) When may a constructor be called without specifying arguments?
a. When the default constructor is not called
b. When the name of the constructor differs from that of the class
c. When there are no constructors for the class
Ans: C.


36) Each class in java can have a finalizer method
a. true
b.false
Ans: a.


37) When an object is referenced, does this mean that it has been identified by the finalizer method for garbage collection?
a.yes
b.no
Ans: b.


38) Because finalize () belongs to the java.lang.Object class, it is present in all ___.
a.objects
b.classes
c.methods
Ans: b.


39) Identify the true statements about finalization.
a.A class may have only one finalize method
b.Finalizers are mostly used with simple classes
c.Finalizer overloading is not allowed
Ans: a,c.


40) When you write finalize() method for your class, you are overriding a finalizer
inherited from a super class.
a.true
b.false
Ans: a.


41) Java memory management mechanism garbage collects objects which are no longer referenced
a true
b.false
Ans: a.


42) are objects referenced by a variable candidates for garbage collection when the variable goes out of scope?
a yes
b. no
Ans: a.


43) Java's garbage collector runs as a ___ priority thread waiting for __priority threads to relinquish the processor.
a.high
b.low
Ans: a,b.


44) The garbage collector will run immediately when the system is out of memory
a.true
b.false
Ans: a.


45) You can explicitly drop a object reference by setting the value of a variable whose data type is a reference type to ___
Ans: null


46) When might your program wish to run the garbage collecter?
a. before it enters a compute-intense section of code
b. before it enters a memory-intense section of code
c. before objects are finalized
d. when it knows there will be some idle time
Ans: a,b,d


47) For externalizable objects the class is solely responsible for the external format of its contents
a.true
b.false
Ans: a


48) When an object is stored, are all of the objects that are reachable from that object stored as well?
a.true
b.false
Ans: a


49) The default__ of objects protects private and trancient data, and supports the __ of the classes
a.evolution
b.encoding
Ans: b,a.


50) Which are keywords in Java?
a) NULL
b) sizeof
c) friend
d) extends
e) synchronized
Ans : d and e
51) When must the main class and the file name coincide?
Ans :When class is declared public.


52) What are different modifiers?
Ans : public, private, protected, default, static, trancient, volatile, final, abstract.


53) What are access modifiers?
Ans : public, private, protected, default.


54) What is meant by "Passing by value" and " Passing by reference"?
Ans : objects – pass by reference Methods - pass by value


55) Is a class a subclass of itself?
Ans : A class is a subclass itself.
56) What modifiers may be used with top-level class?
Ans : public, abstract, final.


57) What is an example of polymorphism?
Inner class
Anonymous classes
Method overloading
Method overriding
Ans : c & d static and dynamic polymorphism

Packages and interface


1) What are packages ? what is use of packages ?
Ans :The package statement defines a name space in which classes are stored.If you omit the package, the classes are put into the default package.
Signature... package pkg;
Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism.


2) What is difference between importing "java.applet.Applet" and "java.applet.*;" ?
Ans :"java.applet.Applet" will import only the class Applet from the package java.applet Where as "java.applet.*" will import all the classes from java.applet package.


3) What do you understand by package access specifier?
Ans : public: Anything declared as public can be accessed from anywhere
private: Anything declared in the private can’t be seen outside of its class.
default: It is visible to subclasses as well as to other classes in the same package.


4) What is interface? What is use of interface?
Ans : It is similar to class which may contain method’s signature only but not bodies.Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance.


5) Is it is necessary to implement all methods in an interface?
Ans : Yes. All the methods have to be implemented.


6) Which is the default access modifier for an interface method?
Ans : public.


7) Can we define a variable in an interface ?and what type it should be ?
Ans : Yes we can define a variable in an interface. They are implicitly final and static.


8) What is difference between interface and an abstract class?
Ans : All the methods declared inside an Interface are abstract. Where as abstract class must have at least one abstract method and others may be concrete or abstract.
In Interface we need not use the keyword abstract for the methods.


9) By default, all program import the java.lang package.
True/False
Ans : True


10) Java compiler stores the .class files in the path specified in CLASSPATH
environmental variable.
True/False
Ans : False

11) User-defined package can also be imported just like the standard packages.
True/False
Ans : True


12) When a program does not want to handle exception, the ______class is used.
Ans : Throws


13) The main subclass of the Exception class is _______ class.
Ans : RuntimeException


14) Only subclasses of ______class may be caught or thrown.
Ans : Throwable


15) Any user-defined exception class is a subclass of the _____ class.
Ans : Exception


16) The catch clause of the user-defined exception class should ______ its
Base class catch clause.
Ans : Exception


17) A _______ is used to separate the hierarchy of the class while declaring an
Import statement.
Ans : Package
18) All standard classes of Java are included within a package called _____.
Ans : java.lang


19) All the classes in a package can be simultaneously imported using ____.
Ans : *


20) Can you define a variable inside an Interface. If no, why? If yes, how?
Ans.: YES. final and static


21) How many concrete classes can you have inside an interface?
Ans.: None


22) Can you extend an interface?
Ans.: Yes


23) Is it necessary to implement all the methods of an interface while implementing the interface?
Ans.: No


24) If you do not implement all the methods of an interface while implementing , what specifier should you use for the class ?
Ans.: abstract


25) How do you achieve multiple inheritance in Java?
Ans: Using interfaces.


26) How to declare an interface example?
Ans : access class classname implements interface.
27) Can you achieve multiple interface through interface?
a)True
b) false
Ans : a.


28) Can variables be declared in an interface ? If so, what are the modifiers?
Ans : Yes. final and static are the modifiers can be declared in an interface.


29) What are the possible access modifiers when implementing interface methods?
Ans : public.


30) Can anonymous classes be implemented an interface?
Ans : Yes.


31) Interfaces can’t be extended.
a)True
b)False
Ans : b.


32) Name interfaces without a method?
Ans : Serializable, Cloneble & Remote.


33) Is it possible to use few methods of an interface in a class ? If so, how?
Ans : Yes. Declare the class as abstract.


Exception Handling
  1. What is the difference between ‘throw’ and ‘throws’ ?And it’s application?


Ans : Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not
handle, it must specify this behavior so the callers of the method can guard
against that exception.


  1. What is the difference between ‘Exception’ and ‘error’ in java?


Ans : Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception.
Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow.


  1. What is ‘Resource leak’?


Ans : Freeing up other resources that might have been allocated at the beginning of a method.



4)What is the ‘finally’ block?


Ans : Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.


  1. Can we have catch block with out try block? If so when?


Ans : No. Try/Catch or Try/finally form a unit.


6) What is the difference between the following statements?
Catch (Exception e),
Catch (Error err),
Catch (Throwable t)
Ans :
7) What will happen to the Exception object after exception handling?


Ans : It will go for Garbage Collector. And frees the memory.


8) How many Exceptions we can define in ‘throws’ clause?


Ans : We can define multiple exceptions in throws clause.
Signature is... type method-name (parameter-list) throws exception-list
9) The finally block is executed when an exception is thrown, even if no catch matches it.
True/False
Ans : True


10) The subclass exception should precede the base class exception when used within the catch clause.
True/False
Ans : True


11) Exceptions can be caught or rethrown to a calling method.
True/False
Ans : True


12) The statements following the throw keyword in a program are not executed.
True/False
Ans : True


13) The toString ( ) method in the user-defined exception class is overridden.
True/False
Ans : True
Inheritance


1) What is the difference between superclass & subclass?
Ans : A super class is a class that is inherited whereas subclass is a class that does the inheriting.


2) Which keyword is used to inherit a class?
Ans : extends


3) Subclasses methods can access superclass members/ attributes at all times?
True/False
Ans : False


4) When can subclasses not access superclass members?
Ans : When superclass is declared as private.


5) Which class does begin Java class hierarchy?
Ans : Object class


6) Object class is a superclass of all other classes?
True/False
Ans : True


7) Java supports multiple inheritance?
True/False
Ans : False


8) What is inheritance?
Ans : Deriving an object from an existing class. In the other words, Inheritance is the process of inheriting all the features from a class


9) What are the advantages of inheritance?
Ans : Reusability of code and accessibility of variables and methods of the superclass by subclasses.


10) Which method is used to call the constructors of the superclass from the subclass?
Ans : super(argument)


11) Which is used to execute any method of the superclass from the subclass?
Ans : super.method-name(arguments)


12) Which methods are used to destroy the objects created by the constructor methods?
Ans : finalize()


13) What are abstract classes?
Ans : Abstract classes are those for which instances can’t be created.


14) What must a class do to implement an interface?
Ans: It must provide all of the methods in the interface and identify the interface in its implements clause.


15) Which methods in the Object class are declared as final?
Ans : getClass(), notify(), notifyAll(), and wait()


16) Final methods can be overridden.
True/False
Ans : False


17) Declaration of methods as final results in faster execution of the program?
True/False
Ans: True


18) Final variables should be declared in the beginning?
True/False
Ans : True


19) Can we declare variable inside a method as final variables? Why?
Ans : Cannot because, local variable cannot be declared as final variables.


20) Can an abstract class may be final?
Ans : An abstract class may not be declared as final.


21) Does a class inherit the constructors of it's super class?
Ans: A class does not inherit constructors from any of it's super classes.


22) What restrictions are placed on method overloading?
Ans: Two methods may not have the same name and argument list but different return types.


23) What restrictions are placed on method overriding?
Ans : Overridden methods must have the same name , argument list , and return type. The overriding method may not limit the access of the method it overridees.The overriding method may not throw any exceptions that may not be thrown by the overridden method.


24) What modifiers may be used with an inner class that is a member of an outer class?
Ans : a (non-local) inner class may be declared as public, protected, private, static, final or abstract.


25) How this() is used with constructors?
Ans: this() is used to invoke a constructor of the same class


26) How super() used with constructors?
Ans : super() is used to invoke a super class constructor


27) Which of the following statements correctly describes an interface?
a)It's a concrete class
b)It's a Superclass
c)It's a type of abstract class
Ans: c


28) An interface contains __ methods
a)Non-abstract
b)Implemented
c)unimplemented
Ans:c


69) What is the parameter specification for the public static void main method?
(multiple)
1) String args []
2) String [] args
3) Strings args []
4) String args
Answer : 1,2


70) What does the zeroth element of the string array passed to the public static void main method contain?
(multiple)
1) The name of the program
2) The number of arguments
3) The first argument if one is present
Answer :

71) Which of the following are Java keywords?
(multiple)
1) goto
2) malloc
3) extends
4) FALSE
Answer : 3


72) What will be the result of compiling the following code:
public class Test {
public static void main (String args []) {
int age;
age = age + 1;
System.out.println("The age is " + age);
}
}
1) Compiles and runs with no output
2) Compiles and runs printing out The age is 1
3) Compiles but generates a runtime error
4) Does not compile
5) Compiles but generates a compile time error
Answer : 4


73) Which of these is the correct format to use to create the literal char value a?
(multiple)
1) 'a'
2) "a"
3) new Character(a)
4) \000a
Answer : 1


74) What is the legal range of a byte integral type?
1) 0 - 65, 535
2) (-128) - 127
3) (-32,768) - 32,767
4) (-256) - 255
Answer : 2


75) Which of the following is illegal:
1) int i = 32;
2) float f = 45.0;
3) double d = 45.0;
Answer: 2


76) What will be the result of compiling the following code:
public class Test {
static int age;
public static void main (String args []) {
age = age + 1;
System.out.println("The age is " + age);
}
}
1) Compiles and runs with no output
2) Compiles and runs printing out The age is 1
3) Compiles but generates a runtime error
4) Does not compile
5) Compiles but generates a compile time error
Answer : 2


78) Which of the following return true?
(multiple)
1) "john" == new String("john")
2) "john".equals("john")
3) "john" = "john"


Answer : 2


79) Which of the following do not lead to a runtime error?
(multiple)
1) "john" + " was " + " here"
2) "john" + 3
3) 3 + 5
4) 5 + 5.5
answer 1,2,3,4


80) Which of the following are so called "short circuit" logical operators?
(multiple)
1) &
2) ||
3) &&
4) |
Answer : 2,3


82) What is the result of compiling and running the following code:
public class Test {
static int total = 10;
public static void main (String args []) {
new Test();
}
public Test () {
System.out.println("In test");
System.out.println(this);
int temp = this.total;
if (temp > 5) {
System.out.println(temp);
}
}
}
(Multiple)
1) The class will not compile
2) The compiler reports and error at line 2
3) The compiler reports an error at line 9
4) The value 10 is one of the elements printed to the standard output
5) The class compiles but generates a runtime error
Answer : 4


83) Which of the following is correct:
1) String temp [] = new String {"j" "a" "z"};
2) String temp [] = { "j " " b" "c"};
3) String temp = {"a", "b", "c"};
4) String temp [] = {"a", "b", "c"};
Answer 4


84) What is the correct declaration of an abstract method that is intended to be public:
1) public abstract void add();
2) public abstract void add() {}
3) public abstract add();
4) public virtual add();
Answer : 1


85) Under what situations do you obtain a default constructor?
1) When you define any class
2) When the class has no other constructors
3) When you define at least one constructor
Answer : 2


86) Which of the following can be used to define a constructor for this class, given the following code:
public class Test {
...
}
1) public void Test() {...}
2) public Test() {...}
3) public static Test() {...}
4) public static void Test() {...}
Answer : 2


87) Which of the following are acceptable to the Java compiler:
(multiple)
1) if (2 == 3) System.out.println("Hi");
2) if (2 = 3) System.out.println("Hi");
3) if (true) System.out.println("Hi");
4) if (2 != 3) System.out.println("Hi");
5) if (aString.equals("hello")) System.out.println("Hi");
Answer : 1,3,4,5


88) Assuming a method contains code which may raise an Exception (but not a Runtime Exception), what is the correct way for a method to indicate that it expects the caller to handle that exception:
1) throw Exception
2) throws Exception
3) new Exception
4) Don't need to specify anything
Answer : 2


89) What is the result of executing the following code, using the parameters 4 and 0:
public void divide(int a, int b) {
try {
int c = a / b;
} catch (Exception e) {
System.out.print("Exception ");
} finally {
System.out.println("Finally"); }
1) Prints out: Exception Finally
2) Prints out: Finally
3) Prints out: Exception
4) No output
Answer : 1


90) Which of the following is a legal return type of a method overloading the following method:
public void add(int a) {...}
1) void
2) int
3) Can be anything
Answer : 3


91) Which of the following statements is correct for a method which is overriding the following method:
public void add(int a) {...}
1) the overriding method must return void
2) the overriding method must return int
3) the overriding method can return whatever it likes
Answer : 1


92) Given the following classes defined in separate files, what will be the effect of compiling and running this class Test?
class Vehicle {
public void drive() {
System.out.println("Vehicle: drive");
}
}
class Car extends Vehicle {
public void drive() {
System.out.println("Car: drive");
}
}
public class Test {
public static void main (String args []) {
Vehicle v;
Car c;
v = new Vehicle();
c = new Car();
v.drive();
c.drive();
v = c;
v.drive();
} }
1) Generates a Compiler error on the statement v= c;
2) Generates runtime error on the statement v= c;
3) Prints out:
Vehicle: drive
Car: drive
Car: drive
4) Prints out:
Vehicle: drive
Car: drive
Vehicle: drive
Answer : 3


93) Where in a constructor, can you place a call to a constructor defined in the super class?
1) Anywhere
2) The first statement in the constructor
3) The last statement in the constructor
4) You can't call super in a constructor
Answer : 2


115) What is the result of executing the following code when the value of x is 2:
switch (x) {
case 1:
System.out.println(1);
case 2:
case 3:
System.out.println(3);
case 4:
System.out.println(4);
}
1) Nothing is printed out
2) The value 3 is printed out
3) The values 3 and 4 are printed out
4) The values 1, 3 and 4 are printed out
Answer : 3


116) What is the result of compiling and running the Second class?
Consider the following example:
class First {
public First (String s) {
System.out.println(s);
}
}
public class Second extends First {
public static void main(String args []) {
new Second();
} }
1) Nothing happens
2) A string is printed to the standard out
3) An instance of the class First is generated
4) An instance of the class Second is created
5) An exception is raised at runtime stating that there is no null parameter constructor in class First.
6) The class second will not compile as there is no null parameter constructor in the class First
Answer : 6


117) What is the result of executing the following fragment of code:
boolean flag = false;
if (flag = true) {
System.out.println("true");
} else {
System.out.println("false");
}
1) true is printed to standard out
2) false is printed to standard out
3) An exception is raised
4) Nothing happens
Answer : 1


118) Consider the following classes. What is the result of compiling and running this class?
public class Test {
public static void test() {
this.print();
}
public static void print() {
System.out.println("Test");
}
public static void main(String args []) {
test();
}
}
(multiple)
1) The string Test is printed to the standard out.
2) A runtime exception is raised stating that an object has not been created.
3) Nothing is printed to the standard output.
4) An exception is raised stating that the method test cannot be found.
5) An exception is raised stating that the variable this can only be used within an instance.
6) The class fails to compile stating that the variable this is undefined.
Answer : 6


125) Carefully examine the following code, When will the string "Hi there" be printed?
public class StaticTest {
static {
System.out.println("Hi there");
}
public void print() {
System.out.println("Hello");
}
public static void main(String args []) {
StaticTest st1 = new StaticTest();
st1.print();
StaticTest st2 = new StaticTest();
st2.print();
}
}
1) Never.
2) Each time a new instance is created.
3) Once when the class is first loaded into the Java virtual machine.
4) Only when the static method is called explicitly.
Answer : 3


126) What is the result of the following program:
public class Test {
public static void main (String args []) {
boolean a = false;
if (a = true)
System.out.println("Hello");
else
System.out.println("Goodbye");
}
}
1) Program produces no output but terminates correctly.
2) Program does not terminate.
3) Prints out "Hello"
4) Prints out "Goodbye"
Answer : 3


127) Examine the following code, it includes an inner class, what is the result:
public final class Test4 {
class Inner {
void test() {
if (Test4.this.flag); {
sample();
}
}
}
private boolean flag = true;
public void sample() {
System.out.println("Sample");
}
public Test4() {
(new Inner()).test();
}
public static void main(String args []) {
new Test4();
}
}
1) Prints out "Sample"
2) Program produces no output but terminates correctly.
3) Program does not terminate.
4) The program will not compile
Answer : 1


128) Carefully examine the following class:
public class Test5 {
public static void main (String args []) {
/* This is the start of a comment
if (true) {
Test5 = new test5();
System.out.println("Done the test");
}
/* This is another comment */
System.out.println ("The end");
}
}
1) Prints out "Done the test" and nothing else.
2) Program produces no output but terminates correctly.
3) Program does not terminate.
4) The program will not compile.
5) The program generates a runtime exception.
6) The program prints out "The end" and nothing else.
7) The program prints out "Done the test" and "The end"
Answer : 6


130) What is the effect of compiling and (if possible) running this class:
public class Calc {
public static void main (String args []) {
int total = 0;
for (int i = 0, j = 10; total > 30; ++i, --j) {
System.out.println(" i = " + i + " : j = " + j);
total += (i + j);
}
System.out.println("Total " + total);
}
}
1) Produce a runtime error
2) Produce a compile time error
3) Print out "Total 0"
4) Generate the following as output:
i = 0 : j = 10
i = 1 : j = 9
i = 2 : j = 8
Total 30
Answer : 3


Comments

Popular posts from this blog

HackerRank Introduction Challenges - Java

Linux Assignments - Practise