0% found this document useful (0 votes)
6 views

5- Java main file

Uploaded by

omkarmalap
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

5- Java main file

Uploaded by

omkarmalap
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 223

1. Java was designed by _________________.

A. Microsoft
B. Mozilla Corporation
C. Sun Microsystems
D. Amazon Inc.

View Answer

Ans : C

Explanation: Java Programming language was designed by Sun Microsystems.

2. Earlier name of Java Programming language was -

A. Eclipse
B. OAK
C. Netbean
D. D

View Answer

Ans : B

Explanation: Earlier name of Java Programming language was -OAK.

3. Which of the following personality is called as father of Java Programming language -

A. James Gosling
B. Larry Page
C. Bjarne Stroustrup
D. None of these

View Answer

Ans : A
Explanation: None

4. Why OAK was renamed to Java ?

A. because the language was unsuccessful , so they created another version and changed its name to
java.
B. because the name was not relevant to the language they created
C. because there was another language called Oak
D. None of these

View Answer

Ans : C

Explanation: OAK was renamed to Java because there was another language called Oak

5. Java was publicly released in _______________ .

A. 25-05-1995
B. 27-05-1995
C. 29-05-1995
D. 28-05-1995

View Answer

Ans : B

Explanation: Java was publicly released in May 27, 1995.

6. Which kind of language java is ?

A. Object Oriented
B. Procedural
C. Event Driven
D. None of these
View Answer

Ans : A

Explanation: Java is Object Oriented language.

7. In the beginning, Java was created in order to -

A. Perform Operations on the Internet


B. Connect many household machines
C. Create Strong Programming alternative to C++
D. ALL of the above

View Answer

Ans : B

Explanation: Basic aim of java was to solve the problem of connecting many household machines
together..

8. Java is a ________ programming language

A. high-level
B. Middle-level
C. Low-level
D. None of the above

View Answer

Ans : A

Explanation: Java is a high-level programming language originally developed by Sun Microsystems


and released in 1995.

9. Which of the following are correct advantage of java?


A. Java is Simple
B. Java is Secure
C. Java is Portable
D. All of the above

View Answer

Ans : D

Explanation: All of the above are correct advantage of java.

10. In which year, Sun Microsystems released much of its Java virtual machine?

A. 2005
B. 2006
C. 2007
D. 2008

View Answer

Ans : B

Explanation: On November 13, 2006, Sun released much of its Java virtual machine (JVM) as free and
open-source software (FOSS), under the terms of the GNU General Public License (GPL).

11. After first public release java was targeted at ______________________.

A. Internet development
B. Search Engine Development
C. Desktop Development
D. Operating System Development

View Answer

Ans : A

Explanation: After first public release java was targeted at Internet development.
12. First public implementation of java was _____________

A. Java 1.2
B. Java 1.0
C. Java 1.1
D. Java Premium 1.0

View Answer

Ans : B

Explanation: First public implementation of java was java 1.0.

13. Basic aim of java was to solve the problem of connecting many household machines together.

A. Java data kit


B. Java defination kit
C. Java design kit
D. Java development kit

View Answer

Ans : D

Explanation: None

14. Sun Microsystems released the first public implementation as Java 1.0 in?

A. 1994
B. 1995
C. 1996
D. 1997

View Answer
Ans : C

Explanation: Sun Microsystems released the first public implementation as Java 1.0 in 1996.

15. Java SE 15 version released on?

A. March 19, 2019


B. March 17, 2020
C. September 17, 2019
D. September 15, 2020

View Answer

Ans : D

Explanation: Java SE 15 version released on September 15, 2020.

1. Java Source Code is compiled into ______________.

A. .Obj
B. Source Code
C. Bytecode
D. .Exe

View Answer

Ans : C
Explanation: Java Source Code is compiled into Bytecode.

2. Enums were introduced in?

A. Java 4.0
B. Java 8.0
C. Java 5.0
D. Java 6.0

View Answer

Ans : C

Explanation: Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few
predefined values. The values in this enumerated list are called enums.

3. Which of the following is used to interpret and execute Java Applet Classes hosted by HTML.

A. appletviewer
B. appletwatcher
C. appletshow
D. appletscreen

View Answer

Ans : A

Explanation: appletviewer is used to interpret and execute Java Applet Classes hosted by HTML.

4. HTML based Java Documentary help can be accessed using ______________.

A. javahelp
B. javamanual
C. javadoc
D. None of these
View Answer

Ans : C

Explanation: HTML based Java Documentary help can be accessed using javadoc.

5. Single line comment starts with _________ in Java.

A. /**
B. //
C. /*
D. None of these

View Answer

Ans : B

Explanation: Single-line comments start with two forward slashes ( // ). Any text between // and the
end of the line is ignored by Java

6. How to compile java code in command prompt?

A. javac filename.java
B. java filename.java
C. javac filename
D. java filename

View Answer

Ans : A

Explanation: Type javac filename.java and press enter to compile your code. If there are no errors in
your code, the command prompt will take you to the next line.

7. How to run java program in command prompt?


A. javac filename.java
B. java filename.java
C. javac filename
D. java filename

View Answer

Ans : D

Explanation: Now, type java filename to run your program.

8. Java is case sensitive?

A. True
B. False
C. Depends On Complier
D. May be true or false

View Answer

Ans : A

Explanation: Case Sensitivity : Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.

9. What is true in Java?

A. For all class names the first letter should be in Upper Case.
B. All method names should start with a Lower Case letter.
C. Name of the program file should exactly match the class name.
D. All of the above

View Answer

Ans : D

Explanation: All of the above statement are true.


10. All Java components require names. Names used for classes, variables, and methods are called?

A. Variables
B. identifiers
C. Access Modifiers
D. Java Modifiers

View Answer

Ans : B

Explanation: All Java components require names. Names used for classes, variables, and methods
are called identifiers.

11. Default, public , protected, private are?

A. Access Modifier
B. Non-access Modifiers
C. Both A and B
D. It's variable

View Answer

Ans : A

Explanation: Access Modifiers : default, public , protected, private

12. jar stands for _____________.

A. Java Application Runner


B. Java Archive
C. Java Archive Runner
D. None of these
View Answer

Ans : B

Explanation: jar stands for Java Archive

13. Which of the following is not a keyword in Java.

A. transient
B. instanceof
C. emun
D. strictfp

View Answer

Ans : C

Explanation: Incorrect spelling of the word "enum",enum is a keyword in Java.

14. Which of the following is not a keyword in Java.

A. assert
B. boolean
C. abstract
D. finalize

View Answer

Ans : D

Explanation: Final class can't be inherited, final method can't be overridden and final variable value
can't be changed. Finally is used to place important code, it will be executed whether exception is
handled or not. Finalize is used to perform clean up processing just before object is garbage
collected.
15. What is JRE?

A. JRE is a java based GUI application.


B. JRE is an implementation of the Java Virtual Machine which executes Java programs.
C. JRE is an application development framework.
D. None of the above

View Answer

Ans : B

Explanation: Java Runtime Environment is an implementation of the Java Virtual Machine which
executes Java programs. It provides the minimum requirements for executing a Java application.

1. Which of the following is smallest integer data type ?

A. int
B. byte
C. short
D. long

View Answer

Ans : B

Explanation: smallest integer data type is Byte.

2. Which of the following is not a primitive data type ?

A. byte
B. enum
C. short
D. int
View Answer

Ans : B

Explanation: enum is not a primitve data type..

3. Integer Data type does not include following primitive data type ____________.

A. long
B. byte
C. short
D. double

View Answer

Ans : D

Explanation: Integers includes byte, short, int, and long.

4. Which of the following data types comes under floating data types ?

A. int
B. double
C. long
D. byte

View Answer

Ans : B

Explanation: Floating-point numbers includes float and double

5. Character data type cannot store following value.

A. Digit
B. Letter
C. Special Character
D. String

View Answer

6. Range of Byte Data Type is ____________.

A. -128 to 128
B. -127 to 127
C. -127 to 128
D. -128 to 127

View Answer

Ans : D

Explanation: Range of Byte Data Type is -128 to 127.

7. What is size of integer in Java Programming.

A. 1 Bytes
B. 2 Bytes
C. 4 Bytes
D. 8 Bytes

View Answer

Ans : C

Explanation: The size of integer in Java Programming is 4 Bytes.

8. Which of the following data type(s) can store 64 bit Value.

A. boolean
B. int
C. float
D. long

View Answer

Ans : D

Explanation: Long is following data type(s) can store 64 bit Value .

9. Short data type has a minimum value of _____________.

A. -32768
B. -32767
C. 32768
D. 32767

View Answer

Ans : A

Explanation: Short data type has a minimum value of -32,768.

10. Default value of variable having boolean data type is ___________.

A. TRUE
B. FALSE
C. null
D. garbage

View Answer

Ans : B

Explanation: Default value of variable having boolean data type is False.


11. What will be the output of the program?

class Main {

public static void main(String args[]) {

int t;

System.out.println(t);

A. 0
B. garbage value
C. compiler error
D. runtime error

View Answer

Ans : C

Explanation: Unlike class members, local variables of methods must be assigned a value to before
they are accessed, or it is a compile error.

12. What will be the output of the program?

class Test {

public static void main(String[] args) {

for(int i = 0; 0; i++)

System.out.println(""Hello"");
break;

A. Hello
B. Empty Output
C. Compiler error
D. Runtime error

View Answer

Ans : C

Explanation: The error is in for loop where 0 is used in place of boolean value. Unlike C++, use of non
boolean variables in place of bool is not allowed

13. What will be the output of the program?

class mainclass {

public static void main(String args[])

boolean var1 = true;

boolean var2 = false;

if (var1)

System.out.println(var1);

else

System.out.println(var2);

}
A. 0
B. 1
C. TRUE
D. FALSE

View Answer

Ans : C

Explanation: True.

14. Predict the output of the following program.

class LFC {

public static void main(String[] args)

Double object = new Double("2.4");

int a = object.intValue();

byte b = object.byteValue();

float d = object.floatValue();

double c = object.doubleValue();

System.out.println(a + b + c + d );

A. 8
B. 8.8
C. 8.800000095
D. 8

View Answer

Ans : C
Explanation: Arithmetic conversions are implicitly performed to cast the values to a common type.
The compiler first performs integer promotion. If the operands still have different types, then they
are converted to the type that appears highest in the hierarchy.

15. Which of the following are legal lines of Java code?


1. int w = (int)888.8;
2. byte x = (byte)100L;
3. long y = (byte)100;
4. byte z = (byte)100L;

A. 1 and 2
B. 2 and 3
C. 3 and 4
D. All statements are correct

View Answer

Ans : D

Explanation: Statements (1), (2), (3), and (4) are correct. (1) is correct because when a floating-point
number (a double in this case) is cast to an int, it simply loses the digits after the decimal. (2) and (4)
are correct because a long can be cast into a byte. If the long is over 127, it loses its most significant
(leftmost) bits. (3) actually works, even though a cast is not necessary, because a long can store a
byte.

16. What is the output of this program?

class average {

public static void main(String args[])

double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};

double result;

result = 0;
for (int i = 0; i<6; ++i)

result = result + num[i];

System.out.print(result/6);

A. 16.34
B. 16.56666664
C. 16.46666667
D. 16.76666667

View Answer

Ans : C

Explanation: No Explanation.

17. What is the output of this program?

class output {

public static void main(String args[])

double a, b,c;

a = 4.0/0;

b = 0/3.0;

c=0/0.0;

System.out.println(a);
System.out.println(b);

System.out.println(c);

A. Infinity
B. 0
C. NaN
D. all of the mentioned

View Answer

Ans : D

Explanation: For floating point literals, we have constant value to represent (10/0.0) infinity either
positive or negative and also have NaN (not a number for undefined like 0/0.0), but for the integral
type, we don't have any constant that's why we get an arithmetic exception.

18. What will be the output of the program?

class increment {

public static void main(String args[])

int g = 4;

System.out.print(++g * 8);

A. 32
B. 36
C. 40
D. 48

View Answer

Ans : C

Explanation: Operator ++ has more preference than *, thus g becomes 5 and when multiplied by 8
gives 40.

19. What will be the output of the program?

class area {

public static void main(String args[])

double r, pi, a;

r = 9.8;

pi = 3.14;

a = pi * r * r;

System.out.println(a);

A. 301.5656
B. 301
C. 301.56
D. 301.57

View Answer

Ans : A
Explanation: The output for the following code is 301.5656.

20. What will be the output of the program?

class increment {

public static void main(String args[])

int g = 6;

System.out.print(--g * 8);

A. 48
B. 40
C. 56
D. 44

View Answer

Ans : B

Explanation: Operator -- has more preference than *, thus g becomes 5 and when multiplied by 8
gives 40.
21. What is the range of short data type in Java?

A. -128 to 127
B. -32768 to 32767
C. -2147483648 to 2147483647
D. None of the mentioned

View Answer

Ans : B

Explanation: Short occupies 16 bits in memory. Its range is from -32768 to 32767.

22. Which of the following are legal lines of Java code? Â Â 1. int w = (int)888.8; Â Â 2. byte x =
(byte)100L; Â Â 3. long y = (byte)100; Â Â 4. byte z = (byte)100L;

A. 1 and 2
B. 2 and 3
C. 3 and 4
D. All statements are correct

View Answer

Ans : D

Explanation: Statements (1), (2), (3), and (4) are correct. (1) is correct because when a floating-point
number (a double in this case) is cast to an int, it simply loses the digits after the decimal. (2) and (4)
are correct because a long can be cast into a byte. If the long is over 127, it loses its most significant
(leftmost) bits. (3) actually works, even though a cast is not necessary, because a long can store a
byte.

23. An expression involving byte, int, and literal numbers is promoted to which of these?

A. int
B. byte
C. long
D. float

View Answer
Ans : A

Explanation: An expression involving bytes, ints, shorts, literal numbers, the entire expression is
promoted to int before any calculation is done.

24. Which of these literals can be contained in float data type variable?

A. -1.7e+308
B. -3.4E+38
C. +1.7e+308
D. -3.4E+50

View Answer

Ans : B

Explanation: Range of float data type is -(3.4e38) To +(3.4e38)

25. Which data type value is returned by all transcendental math functions?

A. int
B. float
C. double
D. long

View Answer

Ans : C

Explanation: None.

26. Which of these coding types is used for data type characters in Java?

A. ASCII
B. ISO-LATIN-1
C. UNICODE
D. None of the mentioned

View Answer

Ans : C

Explanation: Unicode defines fully international character set that can represent all the characters
found in all human languages. Its range is from 0 to 65536.

27. Which one is a valid declaration of a boolean?

A. boolean b1 = 1;
B. boolean b2 = false;
C. boolean b3 = false;
D. boolean b4 = true

View Answer

Ans : C

Explanation: Boolean can only be assigned true or false literals.

28. What is the output of this program?

class array_output {

public static void main(String args[])

char array_variable [] = new char[10];

for (int i = 0; i < 10; ++i) {

array_variable[i] = 'i';

System.out.print(array_variable[i] + """" );
i++;

A. i i i i i
B. 0 1 2 3 4
C. i j k l m
D. None of the mentioned

View Answer

Ans : A

Explanation: None. output: $ javac array_output.java $ java array_output i i i i i

29. Which of these is long data type literal?

A. 0x99fffL
B. ABCDEFG
C. 0x99fffa
D. 99671246

View Answer

Ans : A

Explanation: Data type long literals are appended by an upper or lowercase L. 0x99fffL is
hexadecimal long literal.

30. Which of these can be returned by the operator &?

A. Integer
B. Boolean
C. Character
D. Integer or Boolean
View Answer

Ans : D

Explanation: We can use binary ampersand operator on integers/chars (and it returns an integer) or
on booleans (and it returns a boolean).

1. A ________ provides us with named storage that our programs can manipulate.

A. data type
B. constants
C. operators
D. variable

View Answer

Ans : D

Explanation: A variable provides us with named storage that our programs can manipulate.

2. Each variable in Java has a specific type, which determines the size and layout of the variable's
memory.

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : A

Explanation: True, Each variable in Java has a specific type, which determines the size and layout of
the variable's memory.
3. To declare more than one variable of the specified type, we can use a __________ list.

A. colon-separated
B. bracket-separated
C. comma-separated
D. None of the above

View Answer

Ans : C

Explanation: To declare more than one variable of the specified type, you can use a comma-
separated list.

4. How many kinds of variables in Java?

A. 2
B. 3
C. 4
D. 5

View Answer

Ans : B

Explanation: There are three kinds of variables in Java : Local variables, Instance variables and
Class/Static variables

5. Local variables are declared in?

A. methods
B. constructors
C. blocks
D. All of the above

View Answer
6. What is true about Instance Variables in java?

A. Instance variables are declared in a class


B. When a space is allocated for an object in the heap, a slot for each instance variable value is
created.
C. Instance variables can be declared in class level before or after use
D. All of the above

View Answer

Ans : D

Explanation: All of the above are true about Instance Variables in java

7. Which variables have no default values?

A. Static Variables
B. Instance Variables
C. Local Variable
D. Both A and B

View Answer

Ans : C

Explanation: There is no default value for local variables, so local variables should be declared and an
initial value should be assigned before the first use.

8. Static variables can be accessed by calling with the?

A. Object name
B. Class name
C. Function name
D. Can not say

View Answer
9. Which of the following is an Example of variable initialization?

A. int a, b, c;
B. int a = 10, b = 10;
C. int 10 = a;
D. None of the above

View Answer

Ans : B

Explanation: int a = 10, b = 10; is an Example of initialization

10. Access modifiers cannot be used for local variables.

A. Yes
B. No
C. Can be yes or no
D. Can not say

View Answer

Ans : A

Explanation: Yes, Access modifiers cannot be used for local variables

1. Which of the following can be operands of arithmetic operators?

A. Characters
B. Boolean
C. Numeric
D. Both Numeric & Characters

View Answer
Ans : D

Explanation: The operand of arithmetic operators can be any of numeric or character type, But not
boolean.

2. Modulus operator, %, can be applied to which of these?

A. Both Integers and floating - point numbers


B. Integers
C. Floating - point numbers
D. None of the mentioned

View Answer

Ans : A

Explanation: Modulus operator can be applied to both integers and floating point numbers..

3. Decrement operator, −−, decreases the value of variable by what number?

A. 1
B. 2
C. 3
D. 4

View Answer

Ans : A

Explanation: Decrement operator, −−, decreases the value of variable by 1.

4. Which of these statements are incorrect?

A. Assignment operators can be used only with numeric and character data type
B. Assignment operators are more efficiently implemented by Java run-time system than their
equivalent long forms
C. Assignment operators run faster than their equivalent long forms
D. None of the mentioned

View Answer

Ans : D

Explanation: None of the mentioned.

5. Can 8 byte long data type be automatically type cast to 4 byte float data type?

A. TRUE
B. FALSE
C. Can be true or false
D. can not say

View Answer

Ans : A

Explanation: Both data types have different memory representation that is why 8-byte integral data
type can be stored to 4-byte floating point data type.

6. Evaluate the value of the expression?

6 - 2 + 10 % 4 + 7

A. 14
B. 12
C. 13
D. 10

View Answer

Ans : C
Explanation: Output of the expression is 13.

7. What is/are highest order precedence operator(s) in Java?

A. ( )
B. { }
C. Both A & B
D. None of these

View Answer

8. The && and || operators

A. Compare two boolean values


B. Compare two numeric values
C. Combine two boolean values
D. Combine two numeric values

View Answer

Ans : C

Explanation: Logical AND(&&) and Logical OR(||) combine two boolean values.

9. Which of the following is the correct expression that evaluates to true if the number x is between
1 and 100 or the number is negative?

A. ((x < 100) && (x > 1)) && (x < 0)


B. ((x < 100) && (x > 1)) || (x < 0)
C. (1 > x > 100) || (x < 0)
D. 1 < x < 100 || x < 0

View Answer

Ans : B
Explanation: No explanation.

10. Select from among the following character escape code which is not available in Java.

A. \\
B. \v
C. \a
D. \t

View Answer

Ans : C

Explanation: No explanation.

11. What will be the output of the program?

class Main {

public static void main(String [] args)

Main p = new Main();

p.start();

void start()

long [] a1 = {3,4,5};

long [] a2 = fix(a1);

System.out.print(a1[0] + a1[1] + a1[2] + " ");


System.out.println(a2[0] + a2[1] + a2[2]);

long [] fix(long [] a3)

a3[1] = 7;

return a3;

A. 12 15
B. 15 15
C. 3 7 5 3 7 5
D. 3 4 5 3 7 5

View Answer

Ans : B

Explanation: The reference variables a1 and a3 refer to the same long array object. When the [1]
element is updated in the fix() method, it is updating the array referred to by a1. The reference
variable a2 refers to the same array object. So Output: 3+7+5+"" ""3+7+5 Output: 15 15 Because
Numeric values will be added

12. What will be the output of the program?

class Main {

public static void main(String [] args)

Main p = new Main();

p.start();

void start()
{

boolean b1 = false;

boolean b2 = fix(b1);

System.out.println(b1 + " " + b2);

boolean fix(boolean b1)

b1 = true;

return b1;

A. true true
B. true false
C. false true
D. false false

View Answer

Ans : C

Explanation: The boolean b1 in the fix() method is a different boolean than the b1 in the start()
method. The b1 in the start() method is not updated by the fix() method.

13. What will be the output of the program?

class Main {

public static void main(String [] args)

Main p = new Main();

p.start();
}

void start()

String s1 = "s";

String s2 = fix(s1);

System.out.println(s1 + " " + s2);

String fix(String s1)

s1 = s1 + "st";

System.out.print(s1 + " ");

return "st";

A. s st
B. sst st
C. st s st
D. sst s st

View Answer

Ans : D

Explanation: When the fix() method is first entered, start()'s s1 and fix()'s s1 reference variables both
refer to the same String object (with a value of ""s""). Fix()'s s1 is reassigned to a new object that is
created when the concatenation occurs (this second String object has a value of ""sst""). When the
program returns to start(), another String object is created, referred to by s2 and with a value of
""st"".

14. Which of the following will produce an answer that is closest in value to a double, d, while not
being greater than d?
A. (int)Math.min(d);
B. (int)Math.abs(d);
C. (int)Math.max(d);
D. (int)Math.floor(d);

View Answer

Ans : D

Explanation: The casting to an int is a smokescreen.

15. Predict the output of following Java Program?

class Test {

public static void main(String args[]) {

int x = -4;

System.out.println(x>>1);

int y = 4;

System.out.println(y>>1);

A. Compiler Error: Operator >> cannot be applied to negative numbers


B. -2
2
C. 2
D. 2
2

View Answer

Ans : B

Explanation: No explantion.
16. With x = 0, which of the following are legal lines of Java code for changing the value of x to 1?
1. x++;
2. x = x + 1;
3. x += 1;
4. x =+ 1;

A. 1, 2 & 3
B. 1 & 4
C. 1, 2, 3 & 4
D. 3 & 2

View Answer

Ans : C

Explanation: Operator ++ increases value of variable by 1. x = x + 1 can also be written in shorthand


form as x += 1. Also x =+ 1 will set the value of x to 1.

17. What is the output of this program?

class Main {

public static void main(String args[])

double var1 = 2 + 4;

double var2 = var1 / 4;

int var3 = 2 + 4;

int var4 = var3 / 4;

System.out.print(var2 + " " + var4);

A. 0 1
B. 1 1
C. 1.5 1
D. 1.5 1.0

View Answer

Ans : C

Explanation: No Explanation.

18. What will be the output of the program?

class Main {

public static void main(String [] args)

int x=20;

String sup = (x < 15) ? "s" : (x < 22)? "t" : "h";

System.out.println(sup);

A. s
B. t
C. h
D. Compilation fails

View Answer

Ans : B

Explanation: This is an example of a nested ternary operator. The second evaluation (x < 22) is true,
so the ""t"" value is assigned to sup.

19. What will be the output of the program?


class Bitwise

public static void main(String [] args)

int x = 11 & 9;

int y = x ^ 3;

System.out.println( y | 12 );

A. 7
B. 0
C. 14
D. 8

View Answer

Ans : C

Explanation: The & operator produces a 1 bit when both bits are 1. The result of the & operation is 9.
The ^ operator produces a 1 bit when exactly one bit is 1; the result of this operation is 10. The |
operator produces a 1 bit when at least one bit is 1; the result of this operation is 14.

20. What is the output of this program?

class increment

public static void main(String args[])

int g = 5;
System.out.print(++g * 8);

A. 44
B. 56
C. 48
D. 40

View Answer

Ans : C

Explanation: Operator ++ has more preference than *, thus g becomes 4 and when multiplied by 8
gives 32.

21. What is the output of relational operators?

A. Integer
B. Boolean
C. Characters
D. Double

View Answer

Ans : B

Explanation: None.

22. Which of these is returned by "greater than", "less than" and "equal to" operators?

A. Integers
B. Floating - point numbers
C. Boolean
D. None of the mentioned

View Answer

Ans : C

Explanation: All relational operators return a boolean value ie. true and false.

23. Which of the following operators can operate on a boolean variable?

A. &&
B. ==
C. ?:
D. +=

View Answer

Ans : D

Explanation: Operator Short circuit AND, &&, equal to, == , ternary if-then-else, ?:, are boolean
logical operators. += is an arithmetic operator it can operate only on numeric values.

24. Which of these operators can skip evaluating right hand operand?

A. !
B. |
C. &
D. &&

View Answer

25. Which of these statements is correct?

A. true and false are numeric values 1 and 0


B. true and false are numeric values 0 and 1
C. true is any non zero value and false is 0
D. true and false are non numeric values

View Answer

Ans : D

Explanation: True and false are keywords, they are non numeric values which do not relate to zero
or non zero numbers. true and false are boolean values.

26. What is the output of this program?

class Relational_operator

public static void main(String args[])

int var1 = 5;

int var2 = 6;

System.out.print(var1 > var2);

A. 1
B. 0
C. TRUE
D. FALSE

View Answer

Ans : D

Explanation: Operator > returns a boolean value. 5 is not greater than 6 therefore false is returned.
output: $ javac Relational_operator.java $ java Relational_operator false
27. What is the output of this program?

class ternary_operator

public static void main(String args[])

int x = 3;

int y = ~ x;

int z;

z = x > y ? x : y;

System.out.print(z);

A. 0
B. 1
C. 3
D. -4

View Answer

Ans : C

Explanation: None. output: $ javac ternary_operator.java $ java ternary_operator 3

28. What is the output of this program?

class Output
{

public static void main(String args[])

int x , y = 1;

x = 10;

if (x != 10 && x / 0 == 0)

System.out.println(y);

else

System.out.println(++y);

A. 1
B. 2
C. Runtime error owing to division by zero in if condition
D. Unpredictable behavior of program

View Answer

Ans : B

Explanation: Operator short circuit and, &&, skips evaluating right hand operand if left hand operand
is false thus division by zero in if condition does not give an error. output: $ javac Output.java $ java
Output 2

29. What is the output of this program?

class Output

public static void main(String args[])

{
boolean a = true;

boolean b = false;

boolean c = a ^ b;

System.out.println(!c);

A. 0
B. 1
C. FALSE
D. TRUE

View Answer

Ans : C

Explanation: None. output: $ javac Output.java $ java Output false

30. Which of these have highest precedence?

A. ()
B. ++
C. *
D. >>

View Answer

Ans : A

Explanation: Order of precedence is (highest to lowest) a -> b -> c -> d.


31. What should be expression1 evaluate to in using ternary operator as in this line?

expression1 ? expression2 : expression3

A. Integer
B. Floating - point numbers
C. Boolean
D. None of the mentioned

View Answer

Ans : C

Explanation: The controlling condition of ternary operator must evaluate to boolean.

32. What is the value stored in x in following lines of code?

int x, y, z;

x = 0;

y = 1;

x = y = z = 8;

A. 0
B. 1
C. 9
D. 8

View Answer

Ans : D

Explanation: None.
33. What is the order of precedence (highest to lowest) of following operators?
1. &
2. ^
3. ?:

A. 1 -> 2 -> 3
B. 2 -> 1 -> 3
C. 3 -> 2 -> 1
D. 2 -> 3 -> 1

View Answer

Ans : A

Explanation: None.

34. What is the output of this program?

class operators

public static void main(String args[])

int var1 = 5;

int var2 = 6;

int var3;

var3 = ++ var2 * var1 / var2 + var2;

System.out.print(var3);

A. 10
B. 11
C. 12
D. 56

View Answer

Ans : C

Explanation: Operator ++ has the highest precedence than / , * and +. var2 is incremented to 7 and
then used in expression, var3 = 7 * 5 / 7 + 7, gives 12. output: $ javac operators.java $ java operators
12

35. What is the output of this program?

class Main

public static void main(String args[])

int x = 8;

System.out.println(++x * 3 + " " + x);

A. 24 8
B. 24 9
C. 27 8
D. 27 9

View Answer

Ans : D

Explanation: Operator ++ has higher precedence than multiplication operator, *, x is incremented to


9 than multiplied with 3 giving 27. output: $ javac operators.java $ java operators 27 9
1. _________ are a sequence of characters.

A. Character
B. Strings
C. Integer
D. Classes

View Answer

Ans : B

Explanation: Strings, which are widely used in Java programming, are a sequence of characters.

2. In Java programming language, strings are treated as objects.

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : A

Explanation: True, In Java programming language, strings are treated as objects.

3. The String class is?


A. mutable
B. immutable
C. Both A and B
D. None of the above

View Answer

Ans : B

Explanation: The String class is immutable, so that once it is created a String object cannot be
changed.

4. Methods used to obtain information about an object are known as?

A. string methods
B. class methods
C. object method
D. accessor methods

View Answer

Ans : D

Explanation: Methods used to obtain information about an object are known as accessor methods.
One accessor method that you can use with strings is the length() method, which returns the
number of characters contained in the string object.

5. Which methods to print output with formatted numbers?

A. printf()
B. format()
C. formatted()
D. Both A and B

View Answer

Ans : D
Explanation: You have printf() and format() methods to print output with formatted numbers. The
String class has an equivalent class method, format(), that returns a String object rather than a
PrintStream object.

6. Which method returns the character at the specified index?

A. int compareTo(Object o)
B. int compareTo(String anotherString)
C. char charAt(int index)
D. int compareToIgnoreCase(String str)

View Answer

Ans : C

Explanation: char charAt(int index) : Returns the character at the specified index.

7. Which method returns a String that represents the character sequence in the array specified?

A. int compareToIgnoreCase(String str)


B. String concat(String str)
C. boolean contentEquals(StringBuffer sb)
D. static String copyValueOf(char[] data)

View Answer

Ans : C

Explanation: boolean contentEquals(StringBuffer sb) : Returns true if and only if this String
represents the same sequence of characters as the specified StringBuffer.

8. Which of the following is true about boolean equals(Object anObject)?

A. Tests if this string ends with the specified suffix


B. Compares this string to the specified object
C. Compares this String to another String, ignoring case considerations
D. None of the above

View Answer

Ans : B

Explanation: boolean equals(Object anObject) : Compares this string to the specified object.

9. Which of these method of String class is used to obtain character at specified index?

A. char()
B. Charat()
C. charat()
D. charAt()

View Answer

Ans : D

Explanation: charAt() method of String class is used to obtain character at specified index.

10. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.

A. Yes
B. No
C. Can be yes or no
D. Can not say

View Answer

Ans : A

Explanation: Yes, Whenever a subclass needs to refer to its immediate superclass, it can do so by use
of the keyword super.
1. A __________ statement allows us to execute a statement or group of statements multiple times.

A. array
B. loop
C. function
D. exception

View Answer

Ans : B

Explanation: A loop statement allows us to execute a statement or group of statements multiple


times.

2. A __________ loop statement in Java programming language repeatedly executes a target


statement as long as a given condition is true.

A. for
B. do-while
C. while
D. None of the above

View Answer

Ans : C

Explanation: A while loop statement in Java programming language repeatedly executes a target
statement as long as a given condition is true.

3. Which loop guaranteed to execute at least one time?

A. for
B. do-while
C. while
D. All of the above

View Answer

Ans : B

Explanation: A do...while loop is similar to a while loop, except that a do...while loop is guaranteed
to execute at least one time.

4. A for loop is useful when you know how many times a task is to be repeated.

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : A

Explanation: True, A for loop is useful when you know how many times a task is to be repeated.

5. Which statement causes the loop to immediately jump to the next iteration of the loop?

A. Exit
B. Break
C. Jump
D. Continue

View Answer

Ans : D

Explanation: The continue keyword can be used in any of the loop control structures. It causes the
loop to immediately jump to the next iteration of the loop.
6. What is the syntax of a continue is a single statement inside any loop?

A. Jump
B. Continue
C. Con
D. State-Continue

View Answer

Ans : B

Explanation: The syntax of a continue is a single statement inside any loop : continue;

7. Choose a valid loop name in Java below.

A. For
B. While
C. Do-while
D. All of the above

View Answer

Ans : D

Explanation: All of the above are valid loop in java

8. A BREAK statement inside a Loop like WHILE, FOR, DO WHILE and Enhanced-FOR causes the
program execution ___ Loop

A. Exit
B. Continuation with next iteration
C. Never exit
D. Can not say

View Answer
9. An enhanced FOR loop work with only Collection type data. Examples of Collection are ___.

A. Array Class type or any regular array variable


B. ArrayList
C. HashMap, HashSet
D. All of the above

View Answer

Ans : D

Explanation: All of the above are examples of collection.

10. Break statement can be used to terminate a case in the switch statement?

A. Yes
B. No
C. Can be yes or no
D. Can not say

View Answer

Ans : A

Explanation: Yes, break can be used to terminate a case in the switch statement

1. Java array is a collection of ________.

A. similar type of elements


B. different type of element
C. heterogeneous data
D. Both A and C

View Answer
Ans : A

Explanation: An array is a collection of similar type of elements which has contiguous memory
location.

2. Array data access using _____.

A. Operator
B. Variable
C. index
D. Pointer

View Answer

Ans : C

Explanation: Array data access using index.

3. At time of array initialization which is necessary to specify?

A. Row
B. Column
C. Row and Column
D. None of the above

View Answer

Ans : A

Explanation: Row is necessary to specify at time of array initialization.

4. Java Array can allocate __________.

A. Dynamic Memory
B. Static Memory
C. Both A and B
D. None of the above

View Answer

Ans : B

Explanation: Arrays in java are static lists that can store a certain kind of variables. Therefore these
arrays need to be initialized at the compile time.

5. Which of the following is an incorrect array declaration?

A. int [] arr = new int[5].


B. int arr[] = new int[5].
C. int arr[] = new int[5].
D. int arr[] = int [5] new

View Answer

Ans : D

Explanation: int arr[] = int [5] is an incorrect array declaration because Operator new must be
succeeded by array type and array size.

6. Index in array start with ______.

A. -1
B. 0
C. 1
D. infinite

View Answer

Ans : B

Explanation: Index in array start with 0.


7. Which of the following is used to declare,construct, and initlaize an array?

A. int arr [] [] = {1, 2, 3, 4};


B. int [] arr = (1, 2, 3);
C. int [] arr = {};
D. int arr [] = {1, 2, 3};

View Answer

Ans : D

Explanation: int arr [] = {1, 2, 3}; is used to declare,construct, and initlaize an array becuase Option A
is wrong because it initializes an int array with String literals. Option B is wrong because it uses
something other than curly braces for the initialization. Option C is wrong because it provides initial
values for only one dimension, although the declared array is a two-dimensional array.

8. We can calculate the length of an array using ________.

A. sizeof(array)
B. array.len
C. array.length
D. array.sizeof()

View Answer

Ans : C

Explanation: We can calculate the length of an array using array.length.

9. Which of the following is advantage of java array?

A. Code Optimization
B. Random access
C. Size No-Limit
D. Both A and B

View Answer
Ans : A

Explanation: Code Optimization and Random access the following is advantage of java array.

10. In java, array elements are stored in ________ memory locations.

A. Random
B. Sequential
C. Sequential & Random
D. Binary search

View Answer

Ans : B

Explanation: Array elements are stored in contiguous memory. Linked List is stored in random
memory locations.

11. What will be the output of the program?

class Main

public static void main(String args[]) {

int arr[] = {10, 20, 30, 40, 50};

for(int i=0; i < arr.length; i++)

System.out.print(" " + arr[i]);

}
A. 10 20 30 40 50
B. Compiler Error
C. 10 20 30 40
D. None of the above

View Answer

Ans : A

Explanation: It is a simple program where an array is first created then traversed. The important
thing to note is, unlike C++, arrays are first class objects in Java. For example, in the following
program, size of array is accessed using length which is a member of arr[] object.

12. What will be the output of the program?

int arr[] = new int [5];

System.out.print(arr);

A. 0
B. value stored in arr[0].
C. 0
D. Class name@ hashcode in hexadecimal form

View Answer

Ans : D

Explanation: If we trying to print any reference variable internally, toString() will be called which is
implemented to return the String

13. What will be the output of the program?

class Main

public static void main(String args[])


{

int array_variable [] = new int[10];

for (int i = 0; i < 10; ++i)

array_variable[i] = i;

System.out.print(array_variable[i] + " ");

i++;

A. 0 2 4 6 8
B. 1 3 5 7 9
C. 0 1 2 3 4 5 6 7 8 9
D. 1 2 3 4 5 6 7 8 9 10

View Answer

Ans : A

Explanation: When an array is declared using new operator then all of its elements are initialized to 0
automatically. for loop body is executed 5 times as whenever controls comes in the loop i value is
incremented twice, first by i++ in body of loop then by ++i in increment condition of for loop.

14. What will be output for the following code?

class Main

public static void main(String args[])

int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};

int n = 6;
n = arr[arr[n] / 2];

System.out.print(n);

A. 3
B. 0
C. 6
D. 1

View Answer

Ans : A

Explanation: Array arr contains 10 elements. n contains 6 thus in next line n is given value 2 printing
arr[arr[6]/2] i:e arr[3] = 3.

15. Predict the output of following Java Program?

class Main

public static void main(String args[])

char array_variable [] = new char[10];

for (int i = 0; i < 10; ++i)

array_variable[i] = 'i';

System.out.print(array_variable[i] + " ");

}
A. 1 2 3 4 5 6 7 8 9 10
B. 0 1 2 3 4 5 6 7 8 9 10
C. i j k l m n o p q r
D. i i i i i i i i i i

View Answer

Ans : D

Explanation: No explantion.

16. What will be output for the following code?

class Test {

public static void main(String args[]) {

int arr[2];

System.out.println(arr[0]);

System.out.println(arr[1]);

A. 0 0
B. garbage value garbage value
C. Compiler Error
D. Exception

View Answer

Ans : C

Explanation: In Java, it is not allowed to put the size of the array in the declaration because an array
declaration specifies only the element type and the variable name. The size is specified when you
allocate space for the array. .
17. What will be output for the following code?

class Test {

public static void main(String args[]) {

int arr[] = new int[2];

System.out.println(arr[0]);

System.out.println(arr[1]);

A. 0 0
B. garbage value garbage value
C. Compiler Error
D. Exception

View Answer

Ans : A

Explanation: Java arrays are first class objects and all members of objects are initialized with default
values like o, null.

18. What will be output for the following code?

class array_output

public static void main(String args[])

int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}};

int sum = 0;
for (int i = 0; i < 3; ++i)

for (int j = 0; j < 3 ; ++j)

sum = sum + array_variable[i][j];

System.out.print(sum / 5);

A. 8
B. 9
C. 10
D. 11

View Answer

Ans : B

Explanation: No explanation.

19. What will be the output of the program?

class Main

public static void main (String[] args)

int arr1[] = {1, 2, 3};

int arr2[] = {1, 2, 3};

if (arr1 == arr2)

System.out.println("Same");

else

System.out.println("Not same");

}
}

A. Same
B. Not Same
C. Compiler error
D. None of the above

View Answer

Ans : B

Explanation: No explanation.

20. What is the output of this program?

class Main

public static void main (String[] args)

int arr1[] = {1, 2, 3};

int arr2[] = {1, 2, 3};

if (arr1.equals(arr2))

System.out.println("Same");

else

System.out.println("Not same");

A. Same
B. Not Same
C. Compiler error
D. None of the above

View Answer
Ans : B

Explanation: arr1.equals(arr2) is same as (arr1 == arr2)

21. Which of these is an incorrect Statement?

A. It is necessary to use new operator to initialize an array


B. Array can be initialized using comma separated expressions surrounded by curly braces
C. Array can be initialized when they are declared
D. None of the mentioned

View Answer

Ans : A

Explanation: Array can be initialized using both new and comma separated expressions surrounded
by curly braces example : int arr[5] = new int[5]; and int arr[] = { 0, 1, 2, 3, 4};

22. What is the type of variable "b" and "d" in the below snippet?

int a[], b;

int []c, d;

A. "b" and "d" are int


B. "b" and "d" are arrays of type int
C. "d" is int variable; and "b" is int array
D. "b" is int variable; and "d" is int array

View Answer

Ans : D

Explanation: If [] is declared after variable it is applicable only to one variable. If [] is declared before
variable it is applicable to all the variables.
23. Which of these is necessary to What is the output of below snippet?specify at time of array
initialization?

Object[] names = new String[3];

names[0] = new Integer(0);

A. ArrayIndexOutOfBoundsException
B. ArrayStoreException
C. Compilation Error
D. Code runs successfully

View Answer

Ans : B

Explanation: ArrayIndexOutOfBoundsException comes when code tries to access an invalid index for
a given array. ArrayStoreException comes when you have stored an element of type other than the
type of array..

24. How to sort an array?

A. Array.sort()
B. Arrays.sort()
C. Collection.sort()
D. System.sort()

View Answer

Ans : B

Explanation: Arrays class contains various methods for manipulating arrays (such as sorting and
searching). Array is not a valid class.
25. How to copy contents of array?

A. System.arrayCopy()
B. Array.copy()
C. Arrays.copy()
D. Collection.copy()

View Answer

Ans : A

Explanation: Arrays class contains various methods for manipulating arrays (such as sorting and
searching). Array is not a valid class.

Regular Expressions

1. Java provides the ______ package for pattern matching with regular expressions.

A. regex
B. java.regex
C. util.regex
D. java.util.regex

View Answer

Ans : D

Explanation: Java provides the java.util.regex package for pattern matching with regular expressions.

2. A __________ is a compiled representation of a regular expression.


A. Matcher Object
B. PatternSyntaxException
C. Pattern Object
D. None of the above

View Answer

Ans : C

Explanation: Pattern Class : A Pattern object is a compiled representation of a regular expression.


The Pattern class provides no public constructors.

3. Capturing groups are a way to treat multiple characters as a single unit.

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : A

Explanation: True, Capturing groups are a way to treat multiple characters as a single unit.

4. Which subexpression matches the beginning of the line.

A. $
B. ^
C. &
D. *

View Answer

Ans : B

Explanation: ^ : Matches the beginning of the line.


5. Subexpression $ is used for?

A. End of the entire string


B. Beginning of the entire string
C. Matches any single character not in brackets
D. Matches the end of the line

View Answer

Ans : D

Explanation: $ Matches the end of the line.

6. Which of the following matches the nonword characters?

A. w
B. W
C. C
D. c

View Answer

Ans : B

Explanation: W : Matches the nonword characters.

7. Subexpression S is used for?

A. Matches the word characters


B. Matches the whitespace
C. Matches the nonwhitespace
D. Matches the nondigits

View Answer
Ans : C

Explanation: S Matches the nonwhitespace.

8. Which method returns the start index of the previous match?

A. public int start(int group)


B. public int end()
C. public int end(int group)
D. public int start()

View Answer

Ans : D

Explanation: public int start() : Returns the start index of the previous match

9. What is the use of public boolean find()?

A. Attempts to find the next subsequence of the input sequence that matches the pattern.
B. Attempts to match the input sequence, starting at the beginning of the region, against the
pattern.
C. Attempts to match the entire region against the pattern.
D. None of the above

View Answer

Ans : A

Explanation: public boolean find() : Attempts to find the next subsequence of the input sequence
that matches the pattern.

10. E Ends quoting begun with Q.


A. Yes
B. No
C. Can be yes or no
D. Can not say

View Answer

Ans : A

Explanation: Yes, E Ends quoting begun with Q.

Interfaces

1. Which of these keywords is used to define interfaces in Java?

A. interface
B. Interface
C. intf
D. Intf

View Answer

Ans : A

Explanation: interface keywords is used to define interfaces in Java.

2. A java interface can contain _______.


A. Abstract methods(unimplemented) and implemented methods both
B. public Abstract methods
C. public static Final Variables only
D. public static Final Variables and abstract methods both

View Answer

Ans : D

Explanation: An interface can have both final variables and abstract methods.

3. Which of these access specifiers can be used for an interface?

A. Public
B. private
C. Protected
D. All of the mentioned

View Answer

Ans : A

Explanation: Access specifier of interface is either public or no specifier. When no access specifier is
used then default access specifier is used due to which interface is available only to other members
of the package in which it is declared, when declared public it can be used by any code.

4. Which of the following is a correct interface?

A. abstract interface A { abstract void print(); { }}


B. abstract interface A { print(); }
C. interface A { void print() { } }
D. interface A { void print(); }

View Answer

Ans : D

Explanation: No explanation.
5. Which of the following classes directly implement Set interface?

A. Vector
B. HashSet
C. HashTable
D. LinkedList

View Answer

Ans : B

Explanation: HashSet classes directly implement Set interface

6. Which of these can be used to fully abstract a class from its implementation?

A. Objects
B. Packages
C. Interfaces
D. None of the Mentioned

View Answer

Ans : C

Explanation: None.

7. What is the output of this program?

interface calculate

void cal(int item);

class display implements calculate


{

int x;

public void cal(int item)

x = item * item;

class Main

public static void main(String args[])

display arr = new display();

arr.x = 0;

arr.cal(2);

System.out.print(arr.x);

A. 0
B. 2
C. 4
D. None of the mentioned

View Answer

Ans : C

Explanation: None. Output: $ javac interfaces.java $ java interfaces 4

8. All methods must be implemented of an interface.


A. TRUE
B. FALSE
C. Can be true or false
D. can not say

View Answer

Ans : A

Explanation: Concrete classes must implement all methods in an interface. Through interface
multiple inheritance is possible.

9. What type of variable can be defined in an interface?

A. public static
B. private final
C. public final
D. static final

View Answer

Ans : D

Explanation: variable defined in an interface is implicitly final and static. They are usually written in
capital letters.

10. What does an interface contain?

A. Method definition
B. Method declaration
C. Method declaration and definition
D. Method name

View Answer

Ans : B

Explanation: Interface contains the only declaration of the method.


11. Which of these keywords is used by a class to use an interface defined previously?

A. Import
B. import
C. implements
D. Implements

View Answer

Ans : C

Explanation: interface is inherited by a class using implements.

12. Which is the correct way to inherit and implement the interface?

A. class Cat implements IAnimal{}


B. class Cat import IAnimal{}
C. class Cat extends IAnimal{}
D. None is correct

View Answer

Ans : A

Explanation: Classes always implements an interface. An interface can extends another interface or
multiple interfaces. Hence, answer would be A.

13. which of the following is true about methods in an interface in java?

A. An interface can contain only abstract method.


B. We can define a method in an interface
C. Private and protected access modifiers can also be used to declare methods in interface
D. None of the above
View Answer

Ans : A

Explanation: In java, an interface contains only abstract method that can be public and it does not
have any method implementation.

14. Which of the following is the correct way of implementing an interface salary by class manager?

A. class manager imports salary {}


B. class manager implements salary {}
C. class manager extends salary {}
D. none of the mentioned

View Answer

Ans : B

Explanation: No Explanation.

15. Which of the following is an incorrect statement about packages?

A. Interfaces are specified public if they are to be accessed by any code in the program
B. Interfaces specifies what class must do but not how it does
C. All variables in interface are implicitly final and static
D. All variables are static and methods are public if interface is defined pubic

View Answer

Ans : D

Explanation: All methods and variables are implicitly public if interface is declared public.

16. What type of methods an interface contain by default?


A. abstract
B. static
C. final
D. private

View Answer

Ans : A

Explanation: By default, interface contains abstract methods. The abstract methods need to be
implemented by concrete classes.

17. What will happen if we provide concrete implementation of method in interface?

A. The concrete class implementing that method need not provide implementation of that method
B. Runtime exception is thrown
C. Compilation failure
D. Method not found exception is thrown

View Answer

Ans : C

Explanation: The methods of interfaces are always abstract. They provide only method definition.
Output: $ javac interfaces.java $ java interfaces 4

18. What happens when a constructor is defined for an interface?

A. Compilation failure
B. Runtime Exception
C. The interface compiles successfully
D. The implementing class will throw exception

View Answer

Ans : A

Explanation: Constructor is not provided by interface as objects cannot be instantiated.


19. What happens when we access the same variable defined in two interfaces implemented by the
same class?

A. Compilation failure
B. Runtime Exception
C. The JVM is not able to identify the correct variable
D. The interfaceName.variableName needs to be defined

View Answer

Ans : D

Explanation: The JVM needs to distinctly know which value of variable it needs to use. To avoid
confusion to the JVM interfaceName.variableName is mandatory.

20. Can "abstract" keyword be used with constructor, Initialization Block, Instance Initialization and
Static Initialization Block.

A. TRUE
B. FALSE
C. Can be true or false
D. can not say

View Answer

Ans : B

Explanation: No, Constructor, Static Initialization Block, Instance Initialization Block and variables
cannot be abstract.

Garbage Collection
1. What allows the programmer to destroy an object x?

A. x.finalize()
B. x.delete()
C. Runtime.getRuntime().gc()
D. Only the garbage collection system can destroy an object.

View Answer

Ans : D

Explanation: When an object is no longer referenced, it may be reclaimed by the garbage collector. If
an object declares a finalizer, the finalizer is executed before the object is reclaimed to give the
object a last chance to clean up resources that would not otherwise be released. When a class is no
longer needed, it may be unloaded.

2. Which statement is true?

A. Programs will not run out of memory.


B. Objects that are referred to by other objects will never be garbage collected.
C. Objects that will never again be used are eligible for garbage collection.
D. Objects that can be reached from a live thread will never be garbage collected.

View Answer

Ans : D

Explanation: C See the note above on Islands of Isolation (An object is eligible for garbage collection
when no live thread can access it - even though there might be references to it). B is wrong. ""Never
again be used"" does not mean that there are no more references to the object. A is wrong. Even
though Java applications can run out of memory there another answer supplied that is more right.

3. Which of the below is not a memory leak solution?


A. GC parameter tuning
B. Code changes
C. Process restart
D. JVM parameter tuning

View Answer

Ans : C

Explanation: Process restart is not a permanent fix to memory leak problem. The problem will
resurge again..

4. Which of the below is not a Java Profiler?

A. JVM
B. JProfiler
C. JConsole
D. Eclipse Profiler

View Answer

Ans : A

Explanation: Memory leak is like holding a strong reference to an object although it would never be
needed anymore. Objects that are reachable but not live are considered memory leaks. Various tools
help us to identify memory leaks.

5. Which statement is true?

A. All objects that are eligible for garbage collection will be garbage collected by the garbage
collector.
B. Objects from a class with the finalize() method overridden will never be garbage collected.
C. Objects with at least one reference will never be garbage collected.
D. Objects instantiated within anonymous inner classes are placed in the garbage collectible heap.

View Answer

Ans : D
Explanation: All objects are placed in the garbage collectible heap.

6. How to get prints of shared object memory maps or heap memory maps for a given process?

A. jmap
B. jvmmap
C. memorymap
D. memorypath

View Answer

Ans : A

Explanation: We can use jmap as jmap -J-d64 -heap pid.

7. What is -Xms and -Xmx while starting jvm?

A. Initial; Maximum memory


B. Initial memory
C. Maximum memory
D. Maximum; Initial memory

View Answer

Ans : A

Explanation: JVM will be started with Xms amount of memory and will be able to use a maximum of
Xmx amount of memory. java -Xmx2048m -Xms256m.

8. Which of the following has the highest memory requirement?

A. Stack
B. Class
C. JVM
D. Heap
View Answer

Ans : C

Explanation: JVM is the super set which contains heap, stack, objects, pointers, etc.

9. Where is a new object allocated memory?

A. Young space
B. JVM
C. Young or Old space depending on space availability
D. Old space

View Answer

Ans : A

Explanation: A new object is always created in young space. Once young space is full, a special young
collection is run where objects which have lived long enough are moved to old space and memory is
freed up in young space for new objects..

10. Which of the following is a garbage collection technique?

A. Sweep model
B. Mark and sweep model
C. Space management model
D. Cleanup model

View Answer

Ans : B

Explanation: A mark and sweep garbage collection consists of two phases, the mark phase and the
sweep phase. I mark phase all the objects reachable by java threads, native handles and other root
sources are marked alive and others are garbage. In sweep phase, the heap is traversed to find gaps
between live objects and the gaps are marked free list used for allocating memory to new objects.
11. When is the B object, created in line 3, eligible for garbage collection?

void start() {

A a = new A();

B b = new B();

a.s(b);

b = null; /* Line 5 */

a = null; /* Line 6 */

System.out.println(""start completed""); /* Line 7 */

A. after line 5
B. after line 6
C. after line 7
D. There is no way to be absolutely certain.

View Answer

Ans : D

Explanation: No explanation.

12. How many objects are eligible for garbage collection after execution of line ?

public class Test

public static void main(String[] args)


{

m1(); // Line

static void m1()

Test t1 = new Test();

Test t2 = new Test();

A. 0
B. 1
C. 2
D. 3

View Answer

Ans : C

Explanation: Since t1 and t2 are local objects of m1() method, so they become eligible for garbage
collection after complete execution of method unless any of them is returned.

13. After line 11 runs, how many objects are eligible for garbage collection?

class X2

public X2 x;

public static void main(String [] args)

X2 x2 = new X2(); /* Line 6 */


X2 x3 = new X2(); /* Line 7 */

x2.x = x3;

x3.x = x2;

x2 = new X2();

x3 = x2; /* Line 11 */

doComplexStuff();

A. 0
B. 1
C. 2
D. 3

View Answer

Ans : C

Explanation: This is an example of the islands of isolated objects. By the time line 11 has run, the
objects instantiated in lines 6 and 7 are referring to each other, but no live thread can reach either of
them..

14. When is the Demo object eligible for garbage collection?

class Test

private Demo d;

void start()

d = new Demo();

this.takeDemo(d); /* Line 7 */
} /* Line 8 */

void takeDemo(Demo demo)

demo = null;

demo = new Demo();

A. After line 7
B. After line 8
C. After the start() method completes
D. When the instance running this code is made eligible for garbage collection.

View Answer

Ans : D

Explanation: D is correct. By a process of elimination.

15. How many objects are eligible for garbage collection after execution of line 8?

public class Test

public static void main(String [] args)

Test t1 = new Test();

Test t2 = m1(t1); // line 6

Test t3 = new Test();

t2 = t3; // line 8

}
static Test m1(Test temp)

temp = new Test();

return temp;

A. 0
B. 1
C. 2
D. 3

View Answer

Ans : B

Explanation: By the time line 8 has executed, the only object without a reference is the one
generated i.e as a result of line 6. Remember that ""Java is strictly pass by value"" so the reference
variable t1 is not affected by the m1() method. We can check it using finalize() method. The
statement ""System.out.println(this.hashcode())"" in finalize() method print the object hashcode
value on which finalize() method is called,and then just compare the value with other objects
hashcode values created in main m

16. When is the Float object, created in line 3, eligible for garbage collection?

public Object m()

Object o = new Float(3.14F);

Object [] oa = new Object[l];

oa[0] = o; /* Line 5 */

o = null; /* Line 6 */

oa[0] = null; /* Line 7 */


return o; /* Line 8 */

A. just after line 5


B. just after line 6
C. just after line 7
D. just after line 8

View Answer

Ans : C

Explanation: No explnation.

Exception Handling

1. Which statement is true?

A. catch(X x) can catch subclasses of X where X is a subclass of Exception.


B. Any statement that can throw an Exception must be enclosed in a try block.
C. The Error class is a RuntimeException.
D. Any statement that can throw an Error must be enclosed in a try block.

View Answer

Ans : A

Explanation: Option A is correct. If the class specified in the catch clause does have subclasses, any
exception object that subclasses the specified class will be caught as well. Option B is wrong. The
error class is a subclass of Throwable and not Runtime Exception. Option C is wrong. You do not
catch this class of error. Option D is wrong. An exception can be thrown to the next method higher
up the call stack.
2. Which statement is true?

A. An Error that might be thrown in a method must be declared as thrown by that method, or be
handled within that method.
B. Multiple catch statements can catch the same class of exception more than once.
C. A try statement must have at least one corresponding catch block.
D. Except in case of VM shutdown, if a try block starts to execute, a corresponding finally block will
always start to execute.

View Answer

Ans : D

Explanation: A is wrong. A try statement can exist without catch, but it must have a finally
statement. B is wrong. A try statement executes a block. If a value is thrown and the try statement
has one or more catch clauses that can catch it, then control will be transferred to the first such
catch clause. If that catch block completes normally, then the try statement completes normally. C is
wrong. Exceptions of type Error and RuntimeException do not have to be caught, only checked
exceptions (java.lan

3. When does Exceptions in Java arises in code sequence?

A. Run Time
B. Can Occur Any Time
C. Compilation Time
D. None of the mentioned

View Answer

Ans : A

Explanation: Exceptions in Java are run-time errors.

4. Which of these keywords is not a part of exception handling?

A. finally
B. thrown
C. catch
D. try
View Answer

Ans : B

Explanation: Exceptional handling is managed via 5 keywords – try, catch, throws, throw and
finally.

5. Which of these keywords must be used to monitor for exceptions?

A. finally
B. throw
C. catch
D. try

View Answer

Ans : D

Explanation: Try keywords must be used to monitor for exceptions

6. Which of these keywords must be used to handle the exception thrown by try block in some
rational manner?

A. finally
B. throw
C. catch
D. try

View Answer

Ans : C

Explanation: If an exception occurs within the try block, it is thrown and cached by catch block for
processing.
7. Which of these keywords is used to manually throw an exception?

A. finally
B. throw
C. catch
D. try

View Answer

Ans : B

Explanation: Throw keywords is used to manually throw an exception.

8. Which of these is a super class of all errors and exceptions in the Java language?

A. Catchable
B. Throwable
C. RunTimeExceptions
D. None of the above

View Answer

Ans : B

Explanation: Throwable is a super class of all errors and exceptions in the Java language

9. In which of the following package Exception class exist?

A. java.file
B. java.lang
C. java.io
D. java.util

View Answer

Ans : B

Explanation: No explanation.
10. Which exception is thrown when divide by zero statement executes?

A. NumberFormatException
B. NullPointerException
C. ArithmeticException
D. None of these

View Answer

Ans : C

Explanation: ArithmeticException is thrown when divide by zero statement executes.

Java Lang

1. Which of the following would compile without error?

A. int a = Math.abs(-5);
B. int b = Math.abs(5.0);
C. int d = Math.abs(5L);
D. int c = Math.abs(5.5F);

View Answer

Ans : A

Explanation: The return value of the Math.abs() method is always the same as the type of the
parameter passed into that method. In the case of A, an integer is passed in and so the result is also
an integer which is fine for assignment to ""int a"". The values used in B, C & D respectively are a
double, a float and a long. The compiler will complain about a possible loss of precision if we try to
assign the results to an ""int"".
2. Which of these classes encapsulate runtime state of an object?

A. Class
B. Runtime
C. System
D. Cache

View Answer

Ans : A

Explanation: Class encapsulate runtime state of an object.

3. Which of these classes is not included in java.lang?

A. Class
B. Integer
C. Array
D. Byte

View Answer

Ans : C

Explanation: Array class is a member of java.util..

4. Which of the following will produce an answer that is closest in value to a double, d, while not
being greater than d?

A. (int)Math.abs(d);
B. (int)Math.max(d);
C. (int)Math.min(d);
D. (int)Math.floor(d);

View Answer

Ans : D
Explanation: The casting to an int is a smokescreen.

5. Which of these methods returns the class of an object?

A. getClass()
B. WhoseObject()
C. Class()
D. WhoseClass()

View Answer

Ans : A

Explanation: getClass() methods returns the class of an object.

6. Which of these class have only one field "TYPE"?

A. Void
B. Process
C. System
D. Runtime

View Answer

Ans : A

Explanation: The Void class has one field, TYPE, which holds a reference to the Class object for the
type void. I

7. Which of the following method of Process class can terminate a process?

A. void kill()
B. void destroy()
C. void terminate()
D. void exit()
View Answer

Ans : B

Explanation: Kills the subprocess. The subprocess represented by this Process object is forcibly
terminated

8. Standard output variable "out" is defined in which class?

A. Void
B. Process
C. Runtime
D. System

View Answer

Ans : D

Explanation: Standard output variable "out" is defined in System class. out is usually used in print
statement i:e System.out.print().

9. Which of these class can encapsulate an entire executing program?

A. Void
B. Process
C. Runtime
D. System

View Answer

Ans : B

Explanation: None.
10. Which of the following is method of System class is used to find how long a program takes to
execute?

A. currenttime()
B. currentTime()
C. currentTimeMillis()
D. currenttimeMillis()

View Answer

Ans : C

Explanation: None.

11. Which of these is a process of converting a simple data type into a class?

A. type casting
B. type conversion
C. type wrapping
D. None of the Mentioned

View Answer

Ans : B

Explanation: type conversion is a process of converting a simple data type into a class

12. Which of the following is method of wrapper Float for converting the value of an object into
byte?

A. Bytevalue()
B. byte bytevalue()
C. bytevalue()
D. Byte Bytevalue()

View Answer
Ans : B

Explanation: byte bytevalue() is method of wrapper Float for converting the value of an object into
byte

13. Which of these methods is used to check for infinitely large and small values?

A. isInfinite()
B. Isinfinite()
C. isNaN()
D. IsNaN()

View Answer

Ans : A

Explanation: isinfinite() method returns true is the value being tested is infinitely large or small in
magnitude.

14. Which of the following methods is a method of wrapper Integer for obtaining hash code for the
invoking object?

A. Integer hashcode()
B. int hashcode()
C. int hashCode()
D. int hash()

View Answer

Ans : C

Explanation: int hashCode() methods is a method of wrapper Integer for obtaining hash code for the
invoking object

15. Which of the following method of Process class can terminate a process??
A. void terminate()
B. void destroy()
C. void exit()
D. void kill()

View Answer

Ans : B

Explanation: Kills the subprocess. The subprocess represented by this Process object is forcibly
terminated.

Threads

1. What is the name of the method used to start a thread execution?

A. run();
B. init();
C. start();
D. resume();

View Answer

Ans : C

Explanation: The start() method causes this thread to begin execution; the Java Virtual Machine calls
the run method of this thread.

2. Which cannot directly cause a thread to stop executing?

A. Calling the SetPriority() method on a Thread object.


B. Calling read() method on an InputStream object.
C. Calling notify() method on an object.
D. Calling the wait() method on an object.
View Answer

Ans : C

Explanation: notify() - wakes up a single thread that is waiting on this object's monitor.

3. Which of the following will directly stop the execution of a Thread?

A. notify()
B. notifyall()
C. wait()
D. exits synchronized code

View Answer

Ans : C

Explanation: . wait() causes the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.

4. Which function of pre defined class Thread is used to check weather current thread being checked
is still running?

A. isAlive()
B. Alive()
C. isRunning()
D. Join()

View Answer

Ans : A

Explanation: isAlive() function is defined in class Thread, it is used for implementing multithreading
and to check whether the thread called upon is still running or not.
5. Which method must be defined by a class implementing the java.lang.Runnable interface?

A. public void run()


B. void run()
C. void run(int priority)
D. public void start()

View Answer

Ans : A

Explanation: In an interface all methods are abstract by default therefore they must be overridden
by the implementing class. The Runnable interface only contains 1 method, the void run() method
therefore it must be implemented.

6. Assume the following method is properly synchronized and called from a thread A on an object B:
wait(2000); After calling this method, when will the thread A become a candidate to get another
turn at the CPU?

A. After thread A is notified, or after two seconds.


B. Two seconds after thread A is notified.
C. After the lock on B is released, or after two seconds.
D. Two seconds after lock B is released.

View Answer

Ans : A

Explanation: Either of the two events (notification or wait time expiration) will make the thread
become a candidate for running again.

7. Which will contain the body of the thread?

A. main();
B. stop();
C. start();
D. run();

View Answer
Ans : D

Explanation: The run() method to a thread is like the main() method to an application. Starting the
thread causes the object's run method to be called in that separately executing thread.

8. Which class or interface defines the wait(), notify(),and notifyAll() methods?

A. Object
B. Class
C. Runnable
D. Thread

View Answer

Ans : A

Explanation: The Object class defines these thread-specific methods.

9. Which of these method of Thread class is used to find out the priority given to a thread?

A. ThreadPriority()
B. get()
C. getPriority()
D. getThreadPriority()

View Answer

Ans : C

Explanation: getPriority() method of Thread class is used to find out the priority given to a thread.

10. Which of these method of Thread class is used to Suspend a thread for a period of time?

A. stop()
B. sleep()
C. terminate()
D. suspend()

View Answer

Ans : B

Explanation: sleep() method of Thread class is used to Suspend a thread for a period of time.

Control Flow Statements

1. What will be the output of the following code snippet?

int a=15;

int b=25;

if ((a < b ) || ( a = 5)>15)

system.out.println(a);

else

system.out.println(b);

A. Error
B. 15
C. 25
D. No output

View Answer
Ans : B

Explanation: No explanation

2. What will be the output of the program?

int x, y;

x=15; y=20;

if (x>15)

if(y>15)

system.ptintln("y is "+y);

else

system.out.ptintln("x is "+x);

A. Error
B. y is 20
C. x is 15
D. No output

View Answer

Ans : C

Explanation: No explanation.

3. Which two are acceptable types for x?

switch(x)

{
default:

System.out.println("Hello");

A. short
B. char
C. long
D. float

View Answer

Ans : A

Explanation: Switch statements are based on integer expressions and since both bytes and chars can
implicitly be widened to an integer, these can also be used. Also shorts can be used. Short and Long
are wrapper classes and reference types can not be used as variables.

4. Which statement is true?

public void test(int x)

int odd = 1;

if(odd) /* Line 4 */

System.out.println("odd");

else

System.out.println("even");

}
A. Compilation fails.
B. "odd" will always be output.
C. "even" will always be output.
D. "odd" will be output for odd values of x, and "even" for even values.

View Answer

Ans : A

Explanation: The compiler will complain because of incompatible types (line 4), the if expects a
boolean but it gets an integer.

5. Which statement is true?

public class While

public void loop()

int x= 0;

while ( 1 ) /* Line 6 */

System.out.print("x plus one is " + (x + 1)); /* Line 8 */

A. There is a syntax error on line 1.


B. There are syntax errors on lines 1 and 6.
C. There are syntax errors on lines 1, 6, and 8.
D. There is a syntax error on line 6.

View Answer

Ans : D
Explanation: Using the integer 1 in the while statement, or any other looping or conditional
construct for that matter, will result in a compiler error. This is old C Program syntax, not valid Java.
A, B and C are incorrect because line 1 is valid (Java is case sensitive so While is a valid class name).
Line 8 is also valid because an equation may be placed in a String operation as shown.

6. Which of the following for loop declaration is not valid?

A. for ( int i = 99; i >= 0; i / 9 )


B. for ( int i = 7; i <= 77; i += 7 )
C. for ( int i = 20; i >= 2; - -i )
D. for ( int i = 2; i <= 20; i = 2* i )

View Answer

Ans : A

Explanation: The first option is not a valid declaration as i/9 is not declared correctly.

7. _______ is not a flow control statement in Java.

A. break
B. continue
C. exit()
D. return

View Answer

Ans : C

Explanation: exit() is not a flow control statement in Java. exit() terminates the currently running
JVM.

8. The break statement causes an exit from ______ loop.

A. innermost
B. outermost
C. break statement causes an exit from program
D. Depends on program

View Answer

Ans : A

Explanation: The break statement causes an exit from innermost loop or switch.

9. Which of the following is an iteration statement?

A. switch
B. if-else
C. if
D. do-while

View Answer

Ans : D

Explanation: do-while is an iteration statement. Others are decision making statements.

10. What is the valid data type for variable "a" to print "Hello World"?

switch(a)

System.out.println("Hello World");

A. int and float


B. byte and short
C. char and long
D. byte and char

View Answer

Ans : D
Explanation: The switch condition would only meet if variable "a" is of type byte or char.

11. What is the output of this program?

class selection_statements

public static void main(String args[])

int var1 = 5;

int var2 = 6;

if ((var2 = 1) == var1)

System.out.print(var2);

else

System.out.print(++var2);

A. 1
B. 2
C. 3
D. 4

View Answer

Ans : B

Explanation: var2 is initialised to 1. The conditional statement returns false and the else part gets
executed.
12. What is the output of this program?

class comma_operator

public static void main(String args[])

int sum = 0;

for(int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1)

sum += i;

System.out.println(sum);

A. 5
B. 6
C. 14
D. compilation error

View Answer

Ans : B

Explanation: Using comma operator, we can include more than one statement in the initialization
and iteration portion of the for loop. Therefore both ++i and j = i + 1 is executed i gets the value –
0,1,2,3,4 & j gets the values -0,1,2,3,4,5.

13. What will be the output of the program?

int i = l, j = -1;

switch (i)
{

case 0, 1: j = 1; /* Line 4 */

case 2: j = 2;

default: j = 0;

System.out.println("j = " + j);

A. j = -1
B. j = 0
C. j = 1
D. Compilation fails.

View Answer

Ans : D

Explanation: The case statement takes only a single argument. The case statement on line 4 is given
two arguments so the compiler complains.

14. In the following code snippet, which lines of code contain error?

int j=0;

while (j < 10)

j++;

if (j==5) continue loop;

system.out.ptintln("j is " +j);

A. Line 2
B. Line 3
C. Line 4
D. Line 5

View Answer
Ans : A

Explanation: No explanation.

15. What is the output of this program?

int i = 1, j = 10;

do

{ if(i > j)

break;

j--;

} while (++i < 5);

System.out.println("i = " + i + " and j = " + j);

A. i = 6 and j = 5
B. i = 5 and j = 5
C. i = 6 and j = 4
D. i = 5 and j = 6

View Answer

Ans : D

Explanation: This loop is a do-while loop, which always executes the code block within the block at
least once, due to the testing condition being at the end of the loop, rather than at the beginning.
This particular loop is exited prematurely if i becomes greater than j.The order is, test i against j, if
bigger, it breaks from the loop, decrements j by one, and then tests the loop condition, where a pre-
incremented by one i is tested for being lower than 5.
Java Packages

1. Package in Java is a mechanism to encapsulate a ______________.

A. Classes
B. Sub Packages
C. Interfaces
D. All of the above

View Answer

Ans : D

Explanation: Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces.

2. Which of these keywords is used to define packages in Java?

A. pkg
B. Pkg
C. package
D. Package

View Answer

Ans : C

Explanation: package keywords is used to define packages in Java.


3. Package names and directory structure are closely related.

A. TRUE
B. FALSE
C. can be true or false
D. can not say

View Answer

Ans : A

Explanation: Package names and directory structure are closely related is true statement.

4. An _______________ statement can be used to access the classes and interface of a different
package from the current package.

A. instanceOf
B. import
C. extends
D. implement

View Answer

Ans : B

Explanation: This is the keyword which can be used to access the interface of a different package
from the current package.

5. Which of the following packages is used to includes classes to create user interface like Button and
Checkbox?

A. java.lang
B. java.net
C. java.awt
D. java.io

View Answer
6. Which of the following packages is used to includes utility classes like Calendar, Collection, Date?

A. java.lang
B. java.net
C. java.awt
D. java.util

View Answer

Ans : D

Explanation: java.util Includes utility classes like Calendar, Collection, Date.

7. Which of this access specifies can be used for a class so that its members can be accessed by a
different class in the same package?

A. Public
B. Protected
C. No Modifier
D. All of the mentioned

View Answer

Ans : D

Explanation: Either we can use public, protected or we can name the class without any specifier.

8. Which of the following is the correct way of importing an entire package "pkg"?

A. import pkg.
B. Import pkg.
C. import pkg.*
D. Import pkg.*

View Answer
Ans : C

Explanation: Operator * is used to import the entire package.

9. Which of the following is false statement about package in java?

A. Packages are used for preventing naming conflicts


B. Providing controlled access: protected and default have package level access control.
C. Packages cannot be considered as data encapsulation
D. Both B and C

View Answer

Ans : C

Explanation: Packages cannot be considered as data encapsulation is false statement about package
in java.

10. Packages that are inside another package are the _________

A. packages
B. nested packages
C. util subpackages
D. subpackages

View Answer

Ans : D

Explanation: Packages that are inside another package are the subpackages.
Inheritance

1. ____________ can be defined as the process where one class acquires the properties (methods
and fields) of another.

A. Overriding
B. Inheritance
C. Polymorphism
D. Abstraction

View Answer

Ans : B

Explanation: Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another

2. The class which inherits the properties of other is known as ________

A. superclass
B. parent class
C. subclass
D. None of the above

View Answer

Ans : C

Explanation: The class which inherits the properties of other is known as subclass

3. Subclass also known as ?


A. derived class
B. child class
C. base class
D. Both A and B

View Answer

Ans : D

Explanation: subclass also known as derived class, child class.

4. The class whose properties are inherited is known as superclass.

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : A

Explanation: True, the class whose properties are inherited is known as superclass

5. ___________ is the keyword used to inherit the properties of a class.

A. inherit
B. poly
C. extends
D. super

View Answer

Ans : C

Explanation: extends is the keyword used to inherit the properties of a class.


6. The super keyword is similar to _________ keyword.

A. construct
B. this
C. class
D. extends

View Answer

Ans : B

Explanation: The super keyword is similar to this keyword.

7. A class member declared protected becomes a member of subclass of which type?

A. public member
B. protected member
C. static member
D. private member

View Answer

Ans : D

Explanation: A class member declared protected becomes a private member of subclass.

8. Which of these is correct way of inheriting class A by class B?

A. class B + class A {}
B. class B inherits class A {}
C. class B extends A {}
D. class B extends class A {}

View Answer

Ans : C

Explanation: class B extends A {} correct way of inheritance.


9. ______ is a way of saying: This object is a type of that object.

A. IS-A
B. HAS-A
C. ARE-A
D. HAD-A

View Answer

Ans : A

Explanation: IS-A is a way of saying: This object is a type of that object.

10. A subclass inherits all the members (fields, methods, and nested classes) from its superclass

A. Yes
B. NO
C. Can be yes or no
D. Can not say

View Answer

Ans : A

Explanation: YES, A subclass inherits all the members (fields, methods, and nested classes) from its
superclass.

Java Abstract Class


1. A class which is declared with the ________ keyword is known as an abstract class in Java.

A. abstract
B. util
C. extends
D. None of the above

View Answer

Ans : A

Explanation: A class which is declared with the abstract keyword is known as an abstract class in
Java.

2. Abstract class can have constructors and static methods?

A. TRUE
B. FALSE
C. Abstract class can have constructors but can not have static methods.
D. Abstract class can not have constructors but can have static methods.

View Answer

Ans : A

Explanation: It can have constructors and static methods also.

3. What is the syntax of abstract class in java?

A. abstract A{}
B. abstract class A
C. abstract class A{}
D. abstract class A[]

View Answer
Ans : C

Explanation: The syntax of abstract class in java is abstract class A{}.

4. Which of these is not abstract?

A. Thread
B. AbstractList
C. List
D. None of the Mentioned

View Answer

Ans : A

Explanation: Thread is not an abstract class.

5. A method which is declared as abstract and does not have implementation is known as an
_____________?

A. Abstract Interface
B. Abstract Thread
C. Abstract List
D. abstract Method

View Answer

Ans : D

Explanation: A method which is declared as abstract and does not have implementation is known as
an abstract method.

6. Which of these packages contains abstract keyword?


A. java.lang
B. java.util
C. java.io
D. java.system

View Answer

Ans : A

Explanation: java.lang packages contains abstract keyword.

7. An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.

A. TRUE
B. FALSE
C. Can be true or false
D. can not say

View Answer

Ans : A

Explanation: Yes, An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method.

8. Which of these is not a correct statement?

A. Every class containing abstract method must be declared abstract


B. Abstract class defines only the structure of the class not its implementation
C. Abstract class can be initiated by new operator
D. Abstract class can be inherited

View Answer

Ans : C

Explanation: Abstract class cannot be directly initiated with new operator, Since abstract class does
not contain any definition of implementation it is not possible to create an abstract object.
9. What will be output for the folllowing code?

abstract class Bank {

private abstract void withdraw(); // Line 1

abstract void deposit();

public void balance(){} //Line 2

class office extends Bank{ // Line 3

void deposit() { // Line 4

// TODO Auto-generated method stub

A. Compilation error in Line 1(abstract method cannot be private)


B. Compilation error in Line 2(abstract class cannot have concrete method)
C. Compilation error in Line 3(abstract class cannot be extended)
D. Compilation error in Line 4(deposit method should have public access modifier)

View Answer

Ans : A

Explanation: Yes, you are right!! As private method can't be overridden and abstract method should
be overridden in child classes, so this line will give compilation error.
10. What will be output for the folllowing code?

abstract class Bank

private String bankName;

Bank(String bankName)

this.bankName = bankName;

public String getBankName()

return bankName;

class office extends Bank {

office() {

super("Axis Bank");

public static void main(String[] args) {

Bank bank = new office();

System.out.println(bank.getBankName());
}

A. Compilation error will occur because ""abstract class cannot have constructor""
B. Compilation error will occur because ""abstract class must have an abstract method""
C. Compilation error will occur while invoking the super class constructor
D. Code will be compiled successfully

View Answer

Ans : D

Explanation: As there is no syntax error, so the code will compile successfully.

Command Line Arguments

1. ____________method can be given parameters via using command line arguments.

A. main()
B. recursive()
C. System defined methods
D. Any method

View Answer

Ans : A

Explanation: Only main() method can be given parameters via using command line arguments.
2. Which of these data types is used to store command line arguments?

A. Array
B. Stack
C. String
D. Integer

View Answer

Ans : C

Explanation: String data types is used to store command line arguments.

3. Number of arguments can be passed to main() is?

A. 1
B. 2
C. 3
D. Infinite

View Answer

Ans : D

Explanation: Infinite number of arguments can be passed to main().

4. args in an array of String.

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : A

Explanation: True, args in an array of String.


5. What is the output for the following code, when you passed letsfindcourse at run time?

class CommandLineExample{

public static void main(String args[]){

System.out.println(""Your first argument is: ""+args[0]);

A. java
B. CommandLineExample{
C. arg[0]
D. letsfindcourse

View Answer

Ans : D

Explanation: letsfindcourse is the output for the following code.

6. What will be the output of the following Java program, Command line exceution is done as – “java
Output This is a command Line”?

class Output

public static void main(String args[])

System.out.print(""args[3]"");

A. java
B. this
C. is
D. command

View Answer

Ans : D

Explanation: command will be the output of the following Java program.

7. Which annotation is used to represent command line input and assigned to correct data type?

A. @Input
B. @Variable
C. @Command Line
D. @Parameter

View Answer

Ans : D

Explanation: @Parameter, @Parameter(names = { “-log”, “-verbose” }, description = “Level of


verbosity”), etc are various forms of using @Parameter

8. ___________ is a very small Java framework that makes it trivial to parse command line
parameters.

A. Command Line
B. Jcommander
C. Args
D. None of the above

View Answer

Ans : B

Explanation: JCommander is a very small Java framework that makes it trivial to parse command line
parameters.
9. Which tab is used to pass command line argument in eclipse?

A. Arguments
B. Variable
C. Both A and B
D. None of the above

View Answer

Ans : A

Explanation: Arguments tab is used to pass command line argument in eclipse.

10. What will be the output of the following Java program?

class abc

public static void main(String args[])

if(args.length>0)

System.out.println(args.length);

A. The snippet compiles, runs and prints 0


B. The snippet compiles, runs and prints 1
C. The snippet does not compile
D. The snippet compiles and runs but does not print anything

View Answer

Ans : D

Explanation: As no argument is passed to the code, the length of args is 0. So the code will not print.
Java.io

1. Java I/O is used to process the?

A. input
B. output
C. Both A and B
D. None of the above

View Answer

Ans : C

Explanation: Java I/O (Input and Output) is used to process the input and produce the output.

2. Can we perform file handling in Java by Java I/O API?

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : A

Explanation: Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations. We can perform file handling in
Java by Java I/O API.
3. In java, how many streams are created for us automatically?

A. 2
B. 3
C. 4
D. 5

View Answer

Ans : B

Explanation: In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
1. System.out
2. System.in
3. System.err

4. Which method is used to write a byte to the current output stream?

A. public void write(int)throws IOException


B. public void write(byte[])throws IOException
C. public void flush()throws IOException
D. public void close()throws IOException

View Answer

Ans : A

Explanation: public void write(int)throws IOException is used to write a byte to the current output
stream.

5. Which method is used to write an array of byte to the current output stream?

A. public void write(int)throws IOException


B. public void write(byte[])throws IOException
C. public void flush()throws IOException
D. public void close()throws IOException

View Answer

Ans : B

Explanation: public void write(byte[])throws IOException is used to write an array of byte to the
current output stream.

6. Which of these class is not a member class of java.io package?

A. File
B. StringReader
C. Writer
D. String

View Answer

Ans : D

Explanation: String class is not a member class of java.io package

7. ObjectFilter is a member of java.io package.

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : B

Explanation: ObjectFilter is not a member of java.io package.


8. ___________ returns true if called on a file and returns false when called on a directory.

A. IsFile()
B. Isfile()
C. isFile()
D. isfile()

View Answer

Ans : C

Explanation: isFile() returns true if called on a file and returns false when called on a directory.

9. What will be output for the following code?

import java.io.*;

class files

public static void main(String args[])

File obj = new File(""/java/system"");

System.out.print(obj.getName());

A. java
B. system
C. java/system
D. /java/system

View Answer

Ans : B

Explanation: obj.getName() returns the name of the file.


10. What will be output for the following code? Note: file is made in c drive

import java.io.*;

class files

public static void main(String args[])

File obj = new File(""/java/system"");

System.out.print(obj.canWrite());

System.out.print("" "" + obj.canRead());

A. true false
B. false true
C. true true
D. false false

View Answer

Ans : D

Explanation: false false will be output for the following code.

Applets
1. An applet is a Java class that extends the?

A. java.Applet class
B. java class
C. Applet class
D. java.applet.Applet class

View Answer

Ans : D

Explanation: An applet is a Java class that extends the java.applet.Applet class

2. Applets are designed to be embedded within an __________.

A. Javascript
B. Css
C. HTML
D. SQL

View Answer

Ans : C

Explanation: Applets are designed to be embedded within an HTML page.

3. Which of the following is required to view an applet?

A. JCM
B. JDM
C. JVM
D. Java class

View Answer
Ans : C

Explanation: A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.

4. Which method is automatically called after the browser calls the init method?

A. start
B. stop
C. destroy
D. paint

View Answer

Ans : A

Explanation: start : This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone off to
other pages.

5. Which method is only called when the browser shuts down normally?

A. start
B. stop
C. destroy
D. paint

View Answer

Ans : C

Explanation: destroy : This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
6. Which of these operators can be used to get run time information about an object?

A. getInfo
B. Info
C. instanceof
D. getinfoof

View Answer

Ans : C

Explanation: instanceof can be used to get run time information about an object

7. Which method causes the audio clip to replay continually?

A. public void play()


B. public void loop()
C. public void stop()
D. None of the above

View Answer

Ans : B

Explanation: public void loop() : Causes the audio clip to replay continually

8. paint() is an abstract method defined in AWT.

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

View Answer

Ans : A

Explanation: paint() is an abstract method defined in AWT.


9. ___________ method is defined in Graphics class, it is used to output a string in an applet.

A. display()
B. Print()
C. drawString()
D. transient()

View Answer

Ans : C

Explanation: drawString() method is defined in Graphics class, it is used to output a string in an


applet.

10. What will be output for the following code?

import java.awt.*;

import java.applet.*;

public class myapplet extends Applet

public void paint(Graphics g)

g.drawString(""A Simple Applet"", 20, 20);

A. A Simple Applet
B. A Simple Applet 20 20
C. Compilation Error
D. Runtime Error

View Answer
Ans : A

Explanation: A Simple Applet be output for the following code.

49. (i) Java is cohesive and logically not consistent Language. (ii) Java gives the programmer’s, full
control.
1. (i)False (ii)True
2. (i)True (ii)False
3. (i)False (ii)False
4. (i)True (ii)True

50. (i) Java is not a language with training wheels. It is a language for professional programmers
(ii) Java as simply the “Internet version of C++.”
1. (i)False (ii)True
2. (i)True (ii)False
3. (i)False (ii)False

1. Java is related to C++, which is a direct descendent of C.


1. true
2. false

2. Much of the character of Java is inherited from languages ___


1. C
2. C++
3. all of the above
4. none of the above
3. Java was conceived by ___ at Sun Microsystems, Inc. in 1991.
1. James Gosling
2. Patrick Naughton
3. Chris Warth and Ed Frank
4. all of the above

4. Java language was initially called “Oak” but was renamed “Java” in 1995.
1. Correct
2. Incorrect

5. Java can be used to create two types of programs: applications and ___
1. applets
2. servlets
3. both 1 and 2
4. none of the above

6. The output of a Java compiler is not executable code. Rather, it is byte code.
1. Valid statement
2. Invalid statement

7. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time
system, which is called the ___
1. JVM
2. IDE
3. working environment
4. all of the above

8. JVM stands for ___


1. Java Virtual Machine
2. Joint virtual machine
3. java virtual means
4. joint virtual minute

9. JIT stands for ___


1. Just In Temporary
2. Just In Time
3. Jump In Time
4. joke in Time

10. Java was not designed to be source-code compatible with any other language.
1. true
2. false

11. Java was designed to meet the real-world requirement of creating interactive, networked
Programs
1. correct
2. incorrect
12. Java enables the creation of cross-platform programs by compiling into an intermediate
representation called ___
1. code
2. intermediate code
3. Java byte code
4. none of the above

13. Remote Method Invocation (RMI). This feature brings an unparalleled level of abstraction to___
programming
1. socket
2. client/server
3. c++
4. C

14. ___programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time.
1. C++
2. C
3. Java
4. all of the above

15. JDBC stands for ___


1. Java Database Connectivity
2. Joint Database connection
3. Just Dependent component
4. none of the above

16. ___ which allows programs to access SQL databases


1. JVM
2. JDBC
3. JNI
4. IDE

17. JNI means ___


1. Java Native Immediate
2. Java Normal Interface
3. Java Native Interface
4. Joint Normal Interface

18. ___ is a set of user interface components that is implemented entirely in Java
1. intermediate code
2. Byte code
3. Swing
4. Servelets

19. Collections are groups of objects. Java 2 provides several types of collections, such as ___, for
your use. Collections offer a new way to solve several common programming problems.
1. linked lists
2. Dynamic arrays
3. Hash table
4. all of the above

20. Common Object Request Broker Architecture means CORBA


1. True
2. false

21. ORB stands for ___


1. Object Request Broker
2. On-Line response byte
3. Off-line request broker
4. Object response byte code

22. IDL means ___


1. Immediate Definition Language
2. Interface Digital Language
3. Interface Definition Language
4. Internet Dynamic Language

23. When Java source code is compiled, each individual class is put into its own output file named
after the class and using the .class extension.
1. True
2. False

24. Java is not case sensitive /portable language


1. Correct statement
2. Incorrect statement

25. Java allows two or more statements to be grouped into blocks of code, also called ___
1.code
2. blocks.
3. code blocks
4. none of the above

26. Java is a free-form language. This means that you do not need to follow any special indentation
rules.
1. valid
2. Invalid statement

27. The most commonly used separator in Java is the ___


1. comma
2. semicolon
3. single quotes
4. Double quotes

28. Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double,
and boolean.
1. True
2. False
29. Java allows variables to be initialized ___
1. statically
2. dynamically
3. both of the above
4. none of the above

30. each native method is ___-and operating-system-dependent


1. monitor
2. CPU
3. printer
4. webserver

31. The ability to create robust programs was given a ___ priority in the design of Java.
1. low
2. high
3. medium
4. all of the above

32. Java Virtual Machine is an attempt to the goal that was “write once; run anywhere, any time,
forever.”
1. True
2. False

Qs33. Java is designed for the distributed environment of the Internet because it handles ___
protocols
1. TCP
2. IP
3. HTTP
4. both 1 and 2

34. ___ is the mechanism that binds together code and the data it manipulates and keeps both safes
from outside interference and misuse.
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Multithreaded

35. A ___ defines the structure and behaviour (data and code) that will be shared by a set of objects.
1. Class
2. Objects
3. group of objects
4. Inheritance

36. The code that operates on that data is referred to as ___


1. member methods
2. methods.
3. both 1 and 2
4. none of the above
37. Inheritance interacts with encapsulation as well
1. True
2. False

38. Polymorphism allows you to create ___


1. clean
2. sensible
3. readable, and resilient code
4. all of the above

39. ___ allows you to migrate your implementations over time without breaking the code that
depends on the public interface of your classes.
1. Encapsulation
2. polymorphism
3. Portability
4. none of the above

40. In Java, a source file is officially called a ___


1. runtime unit
2. compilation unit
3. dynamic unit
4. static unit

41. Java was designed to meet the real-world requirement of creating ___ programs. To accomplish
this, Java supports ___ threaded programming, which allows you to write programs that do many
things simultaneously.
1. interactive, multi
2. networked, uni
3. interactive and networked, multi
4. web-enabled, dual

42. Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java___. This code can be interpreted on any system that provides a ___
1. bytecode, Java Virtual Machine.
2. code, IDE
3. intermediate code, JNI
4. bytecode, JNI

43. Java programs carry with them substantial amounts of ___ time type information that is used to
verify and resolve accesses to objects at ___ time
1. run, run
1. compile, run
2. run, compile
3. compile, compile

44. The concept of ___is often expressed by the phrase “one interface, multiple methods.” This
means that it is possible to design a generic interface to a group of related activities. This helps
reduce ___–by allowing the same interface to be used to specify a general class of action
1. polymorphism, simplicity
2. Inheritance, complexity
3. polymorphism, complexity
4. Multithreading, complexity

45. From ___, Java derives its syntax object-oriented features were influenced by___
1. C, C++
2. C#, C++
3. java script, C#
4. VB.net, C

46___and others began work on a portable, platform-independent language that could be used to
produce code that would run on a variety of CPUs under differing environments. This effort
ultimately led to the creation of ___
1. Gosling, Java.
2. Dennis, C++
3. Gosling, java
4. Dennis, C

47. OOP is a programming methodology that helps organize complex programs through the use of
inheritance,___ and ___
1. encapsulation, polymorphism
2. multithreading, data abstraction
3. Data hiding, encapsulation
4. polymorphism, data hiding

48. Java is also a ___ language. Java derives much of its character from ___and C++.
1. Programmer’s, C
2. system’s, C++
3. operating system, Visual Basic
4. programmer’s, Java

49. (i) Java is cohesive and logically not consistent Language. (ii) Java gives the programmer’s, full
control.
1. (i)False (ii)True
2. (i)True (ii)False
3. (i)False (ii)False
4. (i)True (ii)True

50. (i) Java is not a language with training wheels. It is a language for professional programmers
(ii) Java as simply the “Internet version of C++.”
1. (i)False (ii)True
2. (i)True (ii)False
3. (i)False (ii)False
4. (i)True (ii)True
1. The earlier name of Java was ____ ____.
Ans. Oak

2. The members of the Green Project were ____, ____ and ____.
Ans. Patrick Naughton, Mike Sheridan, James Gosling

3. ____ is the first graphical browser.


Ans. Mosaic

4. ____ is the process of converting typed code to machine code.


Ans. Compilation

5. Java code is ____ so that it can easily run on any systems.


Ans. Portable

6. Java is ____ than other interpreted language.


Ans. Secure

7. ____ is the ability of an application to perform multiple tasks at a time.


Ans. Multithreading

8. Java is tuned for ____.


Ans. Web

9. Java is both ____ and ____.


Ans. Compiled and Interpreted

10. ____ is used to create and manage public keys, private keys and security certificates.
Ans. Keytool

11. All information which is managed by the key tool is stored in a database called____.
Ans. Keystore

12. Sun Microsystems includes a default key store that uses a new file format called____.
Ans. JKS (Java Key Store)

13. Java archival tool used for packaging all java programs and resource files into a single archive file
is____.
Ans. Jar
14. ____ was the first programming language that could be used to send interactive programs over
the World Wide Web.
Ans. Java.

15. A ____ is an encrypted file or files that accompany a program, indicating exactly from whom the
file came.
Ans. Digital signature

16. The document that represents this digital signature is called a ____.
Ans. Certificate Ans

17. An applet provider must verify its identity using a group called a ____.
Ans. Certificate Authority.

18. A compiler converts the Java program into an intermediate language representation called ____.
Ans. bytecode

19. The concept of ____ is possible in Java.


Ans. write once, run anywhere

20. The third type of comment is used by a tool called ____ for automatic generation of
documentation.
Ans. Javadoc

21. Give the symbol for the modulus operator.


Ans. %

22. Give the symbol for logical AND operator.


Ans. &

23. If-else is a looping statement. (True or False)


Ans. False

24. String is a ____ data type in Java.


Ans. abstract / derived

25. Keywords can be used as a variable name. (True or False.)


Ans. false

26. A ____ access specifier allows the method to be executed from another class.
Ans. public

27. ____ operator is used to creating an object.


Ans. new

28. ____ is the extension for Java source code files.


Ans. java

29. ____ command is used to compile the Java source code.


Ans. Javac
30. ____ command is used to execute the Java class file.
Ans. java

31. The general form of a one-dimensional array declaration is ____.


Ans. type var-name [ ];

32. In Java, multidimensional arrays are actually arrays of ____.


Ans. arrays

33. Java implements strings as objects of type ____.


Ans. String

34. Both the String and StringBuffer classes are defined in ____ package.
Ans. java.lang

35. ____ represents a number of variables which occupy contiguous spaces in the memory.
Ans. array

36. Each element in the array is distinguished by its ____.


Ans. index

37. In Java, a ____ is a sequence of characters.


Ans. String

38. To extract a single character from a String, you can refer directly to an individual character via
the ____ method.
Ans. charAt( )

39. To extract more than one character at a time, you can use the ____ method.
Ans. getChars( )

40. To extract a single character from a String, you can use ____ method.
Ans. charAt()

41. To extract more than one character at a time, you can use ____ method.
Ans. getChars()

42. To compare two strings for equality, use ____ method.


Ans. equals()

43. While searching string ____ searches for the first occurrence of a character or substring.
Ans. indexOf( )

44. While searching string ____ Searches for the last occurrence of a character or substring.
Ans. lastIndexOf( )

45. ____ method searches for the first occurrence of a character or substring.
Ans. indexOf()
46. ____ method searches for the last occurrence of a character or substring.
Ans. lastIndexOf()

47. You can extract a substring using ____ method.


Ans. substring()

48. To set the length of the buffer within a StringBuffer object, use ____ method.
Ans. setLength()

49. The ____ method concatenates the string representation of any other type of data to the end of
the invoking StringBuffer object.
Ans. append()

50. You can reverse the characters within a StringBuffer object using ____ method.
Ans. reverse()

51. ____ is one of the features of object-oriented programming that allows the creation of
hierarchical classifications.
Ans. inheritance

52. A class that is inherited is called a ____.


Ans. superclass

53. The class that does the inheriting is called a ____.


Ans. subclass

54. Engine has a ____ relationship with the automobile.


Ans. part-of

55. ____, ____ and ____ are the three types of access specifiers in Java.
Ans. public, private, protected

56. ____ is the mechanism in Java through which the class namespace is partitioned into more
manageable chunks.
Ans. package

57. ____ keyword is used to define a package.


Ans. package

58. In Java, multi-leveled packages can be created. (True / False)


Ans. true

59. The specific location that the Java compiler will consider as the root of any package hierarchy is
controlled by ____.
Ans. CLASSPATH

60. ____ symbol denotes the current working directory.


Ans. . (dot)
61. ____ is the mechanism through which you can specify what a class must do, but not how it does
it.
Ans. Interface

62. Variables declared inside the interface declarations are implicit ____ and ____.
Ans. final, static

63. Do…While is a decision-making statement. (True or False)


Ans. False

64. ____ and ____ classes are derived from the Throwable class.
Ans. Error and Exception

65. Exception classes are available in the ____ package.


Ans. java.lang

66. ____ exception will be thrown when you divide by zero.


Ans. Arithmetic Exception

67. ____ exception will be thrown if you try to access the array element beyond its index value.
Ans. ArrayIndexOutOfBounds.

68. The term exception denotes a/an ____.


Ans. An exceptional event.

69. Java handles exceptions in a ____ way.


Ans. Object-oriented.

70. The class at the top of the exception classes hierarchy is ____.
Ans. Throwable.

1. ___ and ___ classes are derived from the Throwable class.
Ans. Error and Exception.
2. Exception classes are available in the ___ package.
Ans. java.lang

3. ___ exception will be thrown when you divide by zero.


Ans. Arithmetic Exception.

4. ___ exception will be thrown if you try to access the array element beyond its index value.
Ans. ArrayIndexOutOfBounds.

5. Java programs written to run on World Wide Web (WWW) are called ___.
Ans. applets.

6. Applets can be tested using the ___ tool included in the Java Development Kit.
Ans. applet viewer

7. When the user interacts with the application by pressing a key or clicking a mouse button, an ___
is generated.
Ans. event

8. The ___ class is at the top of the event class hierarchy.


Ans. EventObject

9. When the user clicks on the button, the ___ event is generated.
Ans. ActiionEvent

10. An ___ event is generated by a scroll bar.


Ans. AdjustmentEvent

11. An ___ event is generated when an item from a list, a choice, or a check box is selected.
Ans. ItemEvent.

12. The ___ method draws the graphics of the applet in the drawing area.
Ans. paint()

13. AWT stands for ___.


Ans. Abstract Windowing Toolkit

14. ___ defines how the components will be arranged in a container.


Ans. Layout Manager

15. The Applet tag is written in the ___ tag of an HTML document.
Ans. body

16. Parameters can be sent to the applet using ___ tag.


Ans. PARAM

17. JAVA API stands for ___.


Ans. Java DataBase Connectivity Application Program Interface
18. Give some examples for DBMS products.
Ans. MS-Access, SQL Server, MySQL, Oracle, Sybase etc.

19. <protocol> in a JDBC URL is always ___.


Ans. JDBC

20. <subprotocol> in JDBC URL must be ___.


Ans. odbc

21. ___ is used to identify the database in the JDBC URL.


Ans. <subname>

22. A ___ is a collection of related information and a ___ is the software that provides you with a
mechanism to manipulate data in the database.
Ans. Database, Database Management System (DBMS).

23. MS-Access stores the data in ___ file format whereas MS-SQL Server stores the data in a ___ file
format.
Ans. .MDB, .DAT

24. RMI stands for ___.


Ans. Remote Method Invocation

25. A ___ is a service that runs on a server and helps the objects on other hosts to remotely access
its registered objects.
Ans. Remote Registry Server.

26. Objects that are exported for remote access must implement the interface called ___.
Ans. remote interface.

27. JSP stands for ___.


Ans. Java Server Pages.

28. A ___ is a small pluggable extension to a server that enhances the server’s functionality.
Ans. Servlet.

29. CGI stands for ___.


Ans. Common Gateway Interface.

30. Middle tier of three-tier architecture contains ___.


Ans. Application Logic.

31. Servlet Life Cycle contains ___, ___ and ___ methods.
Ans. init(), service(), destroy().

32. CORBA stands for Common ___.


Ans. Common Object Request Broker Architecture.

33. IDL stands for ___.


Ans. Interface Definition Language.
34. CORBA and the IDL mappings are the work of an industry consortium known as the ___.
Ans. Object Management Group

35. The ___ is a very simple test container for JavaBeans.


Ans. BeanBox.

36. A Bean obtains all the benefits of Java’s “___” paradigm.


Ans. write-once, run-anywhere

37. The right-hand window of the bean box contains ___showing the properties for the currently
selected bean.
Ans. PropertySheet.

38. The Graphics class is a part of the ___ package.


Ans. java.awt

39. All the methods that are to be invoked remotely must throw the exception called ___.
Ans. RemoteException.

40. RMI uses the ___ protocol for transporting the information.
Ans. TCP

41. ___ is an abstract class that is used to create a format for opening a stream connection to a
specific URL.
Ans. URLStreamHandler

42. The ___ method is used to report that a thread has died.
Ans. threadDeathEvent()

43. ___ package contains all the network related classes and methods of Java.
Ans. java.net

44. ___ method opens a connection to an URL and enables to extract data from that connection.
Ans. getInputStream()

45. ___ class is used to read a stream of data that is generated by a network connection and produce
an object.
Ans. ContentHandler()

46. ___ is an abstract class that is used to create and control a connection to a platform- and
firewall-specific location.
Ans. URLConnection

47. The heart of the Java programming language is contained in a set of packages called ___, which is
a part of the Java API.
Ans. java.lang,

48. The JDK also includes a package called ___, which is designed to make the application-debugging
process easier.
Ans. sun.tools.debug,
49. ___ and ___ are two Java interpreters.
Ans. java, java_g

50. The various stacks in existence as a program runs are called the ___.
Ans. stack frame.

51. ___ method prints all object information.


Ans. dump.

52. ___ method frees all unused objects.


Ans. gc.

53. ___ was the first programming language that could be used to send interactive programs over
the World Wide Web.
Ans. Java

54. A ___ is an encrypted file or files that accompany a program, indicating exactly from whom the
file came.
Ans. Digital signature

55. The document that represents this digital signature is called a ___.
Ans. Certificate.

56. An applet provider must verify its identity using a group called a ___.
Ans. Certificate Authority

57. ___ is used to create and manage public keys, private keys and security certificates.
Ans. Keytool.

58. All information that is managed by a key tool is stored in a database called ___.
Ans. Keystore

59. Sun Microsystems includes a default key store that uses a new file format called ___.
Ans. JKS (Java Key Store)

60. The Java archival tool ___ is used to pack into a single archive file a Java program and all resource
files that it requires.
Ans. Jar
**********************************************************************************
********************************************************************

Rajput

Oops with java

1. Which of the following is an object encapsulated inside the System


class?
A) out
B) println
C) Both A and B
D) None of the above

2. Employee emp = ___ Employee (); Pick a suitable word from the list so
that an object of the class Employee is created.
A) object
B) class
C) run
D) new

3. What is the output for the following code: System.out.println (“Hello


World”);
A) Shows error
B) Hello World
C) “Hello World”
D) None of the above

4. ___ provides a standard interface to common system resources.


A) new
B) API
C) System
D) None of the above

5. Which of the following is also known as SDK:


A) devkit
B) JVM
C) JDK
D) None of the above

6. Which feature of Java is used to dynamically link code in a safe and


expedient manner:
A) Secure
B) Distributed
C) Dynamic
D) Robust

7. Which of the following additional package is included by JDK:


A) java.awt
B) sun.addtools.debug
C) java.util
D) sun.tools.debug

8. Which among the following is not a feature of Java:


A) Portable
B) Structured
C) Distributed
D) High Performance

9. ___ is a Java run-time system that chooses to execute the JAVA


Bytecode:
A) SDK
B) JDK
C) JVM
D) None of the above

10. Which of the following operators are used to compare two values and
give the results:
A) Increment and Decrement
B) Logical
C) Comparison
D) Arithmetic
11. What is the result of the expression: 10+5*8-15/5
A) 3
B) 47
C) 7
D) 21

12. ___ is a common programming construct that is based upon a


sequence of nested if:
A) switch
B) nested if
C) if-else-if ladder
D) None of the above

13. ___ statement is Java’s multi-way branch statement.


A) switch
B) nested if
C) break
D) if-else-if ladder

14. Which loop always executes its body at least once, even though the
condition is not true:
A) for
B) do-while
C) while
D) continue

15. ___ is used to exit from a loop:


A) continue
B) quit
C) break
D) None of the above

16. Which of the following method can be used to set the size of the
buffer:
A) ensureCapacity( )
B) length( )
C) capacity( )
D) setLength( )

17. Which of the following method returns the reversed object on which
it is called:
A) insert( )
B) replace( )
C) delete( )
D) reverse( )

18. String indexes begin at:


A) 1
B) 3
C) 0
D) 2

19. Which of the following is a special operator to allocate memory:


A) New
B) Old
C) ++
D) –

20. Both the String and StringBuffer classes are defined in ____ package:
A) java.awt
B) java.io
C) java.lang
D) java.util

21. Method used to extract a single character from a String:


A) toCharArray( )
B) getChars( )
C) getBytes( )
D) charAt( )

22. Human Being and Elephant fall under which of the following
relationship:
A) Kind-Of
B) Is-A
C) Part-Of
D) Has-A

23. Which of the following allows the creation of hierarchical


classifications?
A) Interface
B) Inheritance
C) Package
D) Polymorphism

24. A class member that has been declared as private will be ___ to its
class.
A) Friendly
B) Public
C) Protected
D) Private

25. Which of the following keywords is used to prevent inheritance:


A) final
B) catch
C) extends
D) super
26. Java supports ___ access specifiers.
A) 1
B) 2
C) 3
D) 4

27. ___ is used as a base class to derive specific classes of the same kind.
A) private
B) friend class
C) abstract class
D) superclass

28. Writing the same code in different places, leading to unnecessary


replication of code:
A) Code extensibility
B) Code redundancy
C) Code reusability
D) None of the above

29. Which of the following blocks can be nested:


A) catch
B) finally
C) try
D) None of the above

30. Number of final blocks that are there for an exception-handler.


A) 1
B) 2
C) 3
D) 4

31. The ___ statement takes an object of an exception class as a


parameter.
A) try
B) if
C) catch
D) finally

32. DataInputStream and DataOutputStream classes are:


A) Abstract streams
B) Mode streams
C) Markable streams
D) Filter streams

33. Unicode is used to represent data such that each character is


represented by:
A) 8 bits
B) 16 bits
C) 64 bits
D) 32 bits

34. Java provides ___ to perform I/O operations at specified locations


within a file:
A) InputStreamReader
B) RandomAccessFile
C) DataInputStream
D) DataOutputStream

35. Which of the following is not a method of DataInputStream class:


A) void writeInt (int v )
B) int readInt ()
C) byte readByte ()
D) char readChar ()

36. Which of the following class lays the foundation for the output class
hierarchy:
A) Reader
B) InputStream
C) OutputStream
D) None of the above

37. InputStream class method is:


A) open( )
B) skip( )
C) flush( )
D) write( )

38. The streams that are read from or written to a specific place like a
disk file or memory:
A) Markable streams
B) ByteArray streams
C) Mode streams
D) Filter streams

39. Graphics class is a part of :


A) java.applet package
B) java.util package
C) java.io package
D) java.awt package

40. Which of the methods is called immediately after the init() is called:
A) destroy( )
B) start( )
C) paint( )
D) stop( )
41. Context can be retrieved using which of the following method:
A) getNum( )
B) getGraphics( )
C) getAppletContext( )
D) getText( )

42. Which of the following methods is defined by the AWT Component


class:
A) paint( )
B) init( )
C) stop( )
D) start( )

43. The argument temporaryFlag is set to true if the focus event is:
A) temporary
B) gained
C) lost
D) retrieved

44. ___ object is generated when the mouse is used.


A) AdjustmentEvent
B) MouseEvent
C) PaintEvent
D) TextEvent

45. Which of the following is at the top of the event class hierarchy:
A) java.awt.AWTEvent
B) java.awt.EventObject
C) java.util.EventObject
D) None of the above

46. In Java, events are represented by:


A) Objects
B) Anonymous classes
C) Inner classes
D) Classes

47. Which of the following class has empty methods:


A) Anonymous class
B) Adapter class
C) Nested class
D) None of the above

48. The method that returns the event ID that represents the nature of
the event:
A) getId( )
B) getNature( )
C) getName( )
D) getValue( )
49. Which of the following Swing Components hierarchically extends
AWT applet:
A) JTree
B) JToolTip
C) JApplet
D) JPanel

50. ___ components allow the editing of multiline plain text.


A) Tree
B) Text area
C) Text field
D) Toggle

1) The default value of a static integer variable of a class in Java is,

(a) 0 (b) 1 (c) Garbage value (d) Null (e) -1.

A) a

2) What will be printed as the output of the following program?

public class testincr


{
public static void main(String args[])
{
int i = 0;
i = i++ + i;
System.out.println(“I = ” +i);
}
}

(a) I = 0 (b) I = 1 (c) I = 2 (d) I = 3 (e) Compile-time Error.

A) b

3) Multiple inheritance means,

(a) one class inheriting from more super classes


(b) more classes inheriting from one super class
(c) more classes inheriting from more super classes
(d) None of the above
(e) (a) and (b) above.

A) a

4) Which statement is not true in java language?

(a) A public member of a class can be accessed in all the packages.


(b) A private member of a class cannot be accessed by the methods of the same
class.
(c) A private member of a class cannot be accessed from its derived class.
(d) A protected member of a class can be accessed from its derived class.
(e) None of the above.

A) b

5) To prevent any method from overriding, we declare the method as,

(a) static (b) const (c) final (d) abstract (e) none of the above.

A) c

6) Which one of the following is not true?

(a) A class containing abstract methods is called an abstract class.


(b) Abstract methods should be implemented in the derived class.
(c) An abstract class cannot have non-abstract methods.
(d) A class must be qualified as ‘abstract’ class, if it contains one abstract method.
(e) None of the above.

A) c

7) The fields in an interface are implicitly specified as,


(a) static only (b) protected (c) private
(d) both static and final (e) none of the above.

8) What is the output of the following program:

public class testmeth


{
static int i = 1;
public static void main(String args[])
{
System.out.println(i+” , “);
m(i);
System.out.println(i);
}
public void m(int i)
{
i += 2;
}
}

(a) 1 , 3 (b) 3 , 1 (c) 1 , 1 (d) 1 , 0 (e) none of the above.

A) c

9) Which of the following is not true?

(a) An interface can extend another interface.


(b) A class which is implementing an interface must implement all the methods of the
interface.
(c) An interface can implement another interface.
(d) An interface is a solution for multiple inheritance in java.
(e) None of the above.

A) c
10) Which of the following is true?

(a) A finally block is executed before the catch block but after the try block.
(b) A finally block is executed, only after the catch block is executed.
(c) A finally block is executed whether an exception is thrown or not.
(d) A finally block is executed, only if an exception occurs.
(e) None of the above.

A) c

Java Multiple Choice Questions And


Answers For Experienced
11) Among these expressions, which is(are) of type String?

(a) “0” (b) “ab” + “cd”


(c) ‘0’
(d) Both (A) and (B) above (e) (A), (B) and (C) above.

A) d

12) Consider the following code fragment


Rectangle r1 = new Rectangle();
r1.setColor(Color.blue);
Rectangle r2 = r1;
r2.setColor(Color.red);

After the above piece of code is executed, what are the colors of r1 and
r2 (in this order)?

(a) Color.blue
Color.red
(b) Color.blue
Color.blue
(c) Color.red
Color.red
(d) Color.red
Color.blue
(e) None of the above.

A) c

13) What is the type and value of the following expression? (Notice the integer
division)
-4 + 1/2 + 2*-3 + 5.0

(a) int -5 (b) double -4.5


(c) int -4
(d) double -5.0 (e) None of the above.

A) d

14) What is printed by the following statement?


System.out.print(“Hello,\nworld!”);

(a) Hello, \nworld! (b) Hello, world!


(c)
(d) “Hello, \nworld!” (e) None of the above.

A) c

15) Consider the two methods (within the same class)


public static int foo(int a, String s)
{
s = “Yellow”;
a=a+2;
return a;
}
public static void bar()
{
int a=3;
String s = “Blue”;
a = foo(a,s);
System.out.println(“a=”+a+” s=”+s);
}
public static void main(String args[])
{
bar();
}

What is printed on execution of these methods?

(a) a = 3 s = Blue (b) a = 5 s = Yellow (c) a = 3 s = Yellow


(d) a = 5 s = Blue (e) none of the above.

A) d

16) Which of the following variable declaration would NOT compile in a java
program?

(a) int var; (b) int VAR; (c) int var1; (d) int var_1; (e) int 1_var;.

A) e

17) Consider the following class definition:

public class MyClass


{
private int value;
public void setValue(int i){ / code / }
// Other methods…
}

The method setValue assigns the value of i to the instance field value. What could
you write for the implementation of setValue?
(a) value = i; (b) this.value = i; (c) value == i;
(d) Both (A) and (B) and above (e) (A), (B) and (C) above.

A) d

18) Which of the following is TRUE?

(a) In java, an instance field declared public generates a compilation error.


(b) int is the name of a class available in the package java.lang
(c) Instance variable names may only contain letters and digits.
(d) A class has always a constructor (possibly automatically supplied by the java
compiler).
(e) The more comments in a program, the faster the program runs.

A) d

19) A constructor

(a) Must have the same name as the class it is declared within.
(b) Is used to create objects.
(c) May be declared private
(d) Both (A) and (B) above
(e) (a), (b) and (c) above.

A) e

20) Consider,

public class MyClass


{
public MyClass(){/code/}
// more code…
}

To instantiate MyClass, you would write?


(a) MyClass mc = new MyClass();
(b) MyClass mc = MyClass();
(c) MyClass mc = MyClass;
(d) MyClass mc = new MyClass;
(e) The constructor of MyClass should be defined as, public void MyClass(){/code/}.

A) a

Java Programming Multiple Choice Questions


Java Multiple Choice Questions 21) What is byte code in the context of Java?

(a) The type of code generated by a Java compiler.


(b) The type of code generated by a Java Virtual Machine.
(c) It is another name for a Java source file.
(d) It is the code written within the instance methods of a class.
(e) It is another name for comments written within a program.

A) a

Java Multiple Choice Questions 22) What is garbage collection in the context
of Java?

(a) The operating system periodically deletes all the java files available on the
system.
(b) Any package imported in a program and not used is automatically deleted.
(c) When all references to an object are gone, the memory used by the object is
automatically reclaimed.
(d) The JVM checks the output of any Java program and deletes anything that
doesn’t make sense.
(e) Janitors working for Sun Micro Systems are required to throw away any Microsoft
documentation found in the employees’ offices.

A) c
Java Multiple Choice Questions 23) You read the following statement in a Java
program that compiles and executes.
submarine.dive(depth);

What can you say for sure?

(a) depth must be an int


(b) dive must be a method.
(c) dive must be the name of an instance field.
(d) submarine must be the name of a class
(e) submarine must be a method.

A) b

Java Multiple Choice Questions 24) The java run time system automatically
calls this method while garbage collection.

(a) finalizer() (b) finalize() (c) finally()


(d) finalized() (e) none of the above.

A) b

Java Multiple Choice Questions 25) The correct order of the declarations in a
Java program is,

(a) Package declaration, import statement, class declaration


(b) Import statement, package declaration, class declaration
(c) Import statement, class declaration, package declaration
(d) Class declaration, import statement, package declaration
(e) Class declaration, package declaration, import statement.

A) a

Java Multiple Choice Questions 26) An overloaded method consists of,


(a) The same method name with different types of parameters
(b) The same method name with different number of parameters
(c) The same method name and same number and type of parameters with different
return type
(d) Both (a) and (b) above
(e) (a), (b) and (c) above.

A) d

Java Multiple Choice Questions 27) A protected member can be accessed in,

(a) a subclass of the same package (b) a non-subclass of the same package
(c) a non-subclass of different package (d) a subclass of different package
(e) the same class.

Which is the false option?

A) c

Java Multiple Choice Questions 28) What is the output of the following code:

class eq
{
public static void main(String args[])
{
String s1 = “Hello”;
String s2 = new String(s1);
System.out.println(s1==s2);
}
}

(a) true (b) false (c) 0 (d) 1 (e) Hello.

A) b
Java Multiple Choice Questions 29) All exception types are subclasses of the
built-in class

(a) Exception (b) RuntimeException (c) Error


(d) Throwable (e) None of the above.

A) d

Java Multiple Choice Questions 30) When an overridden method is called from
within a subclass, it will always refer to the version of that method defined by
the

(a) Super class


(b) Subclass
(c) Compiler will choose randomly
(d) Interpreter will choose randomly
(e) None of the abvove.

A) b

**********************************************************************************
********************************************************************

Omkar

1.-concepts-oops/ 1-10
2.-floating-data-types/11-20
3. character-boolean-data-types/ 21-30
4.data-type-enums/ 31-40
5. https://www.sanfoundry.com/java-mcqs-arrays-2/ 41-50

1. Which of the following is not OOPS concept in Java?


a) Inheritance
b) Encapsulation
c) Polymorphism
d) Compilation
View Answer
Answer: d
Explanation: There are 4 OOPS concepts in Java. Inheritance, Encapsulation,
Polymorphism and Abstraction.
2. Which of the following is a type of polymorphism in Java?
a) Compile time polymorphism
b) Execution time polymorphism
c) Multiple polymorphism
d) Multilevel polymorphism
View Answer
Answer: a
Explanation: There are two types of polymorphism in Java. Compile time
polymorphism (overloading) and runtime polymorphism (overriding).

3. When does method overloading is determined?


a) At run time
b) At compile time
c) At coding time
d) At execution time
View Answer
Answer: b
4. When Overloading does not occur?
a) More than one method with same name but different method signature
and different number or type of parameters
b) More than one method with same name, same signature but different
number of signature
c) More than one method with same name, same signature, same number of
parameters but different type
d) More than one method with same name, same number of parameters and
type but different signature
View Answer
Answer: d
Explanation: Overloading occurs when more than one method with same
name but different constructor and also when same signature but different
number of parameters and/or parameter type.
5. Which concept of Java is a way of converting real world objects in terms of
class?
a) Polymorphism
b) Encapsulation
c) Abstraction
d) Inheritance
View Answer
Answer: c
Explanation: Abstraction is the concept of defining real world objects in terms
of classes or interfaces.

6. Which concept of Java is achieved by combining methods and attribute


into a class?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction
View Answer
Answer: a
Explanation: Encapsulation is implemented by combining methods and
attribute into a class. The class acts like a container of encapsulating
properties.

7. What is it called if an object has its own lifecycle and there is no owner?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
View Answer
Answer: d
Explanation: It is a relationship where all objects have their own lifecycle and
there is no owner. This occurs where many to many relationships are
available, instead of one to one or one to many.

8. What is it called where child object gets killed if parent object is killed?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
View Answer
Answer: b
Explanation: Composition occurs when child object gets killed if parent object
gets killed. Aggregation is also known as strong Aggregation.

9. What is it called where object has its own lifecycle and child object cannot
belong to another parent object?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
View Answer
Answer: a
Explanation: Aggregation occurs when objects have their own life cycle and
child object can associate with only one parent object.

10. Method overriding is combination of inheritance and polymorphism?


a) True
b) false
View Answer
Answer: a
Explanation: In order for method overriding, method with same signature in
both superclass and subclass is required with same signature. That satisfies
both concepts inheritance and polymorphism.

11. What is the range of short data type in Java?


a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
View Answer
Answer: b
Explanation: Short occupies 16 bits in memory. Its range is from -32768 to
32767.

12. What is the range of byte data type in Java?


a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
View Answer
Answer: a
Explanation: Byte occupies 8 bits in memory. Its range is from -128 to 127.

13. Which of the following are legal lines of Java code?

1. int w = (int)888.8;
2. byte x = (byte)100L;
3. long y = (byte)100;
4. byte z = (byte)100L;

a) 1 and 2
b) 2 and 3
c) 3 and 4
d) All statements are correct
View Answer
Answer: d
Explanation: Statements (1), (2), (3), and (4) are correct. (1) is correct
because when a floating-point number (a double in this case) is cast to an int,
it simply loses the digits after the decimal. (2) and (4) are correct because a
long can be cast into a byte. If the long is over 127, it loses its most
significant (leftmost) bits. (3) actually works, even though a cast is not
necessary, because a long can store a byte.

14. An expression involving byte, int, and literal numbers is promoted to


which of these?
a) int
b) long
c) byte
d) float
View Answer
Answer: a
Explanation: An expression involving bytes, ints, shorts, literal numbers, the
entire expression is promoted to int before any calculation is done.

15. Which of these literals can be contained in float data type variable?
a) -1.7e+308
b) -3.4e+038
c) +1.7e+308
d) -3.4e+050
View Answer
Answer: b
Explanation: Range of float data type is -(3.4e38) To +(3.4e38)

16. Which data type value is returned by all transcendental math functions?
a) int
b) float
c) double
d) long
View Answer
Answer: c

17. What will be the output of the following Java code?

1. class average {
2. public static void main(String args[])
3. {
4. double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
5. double result;
6. result = 0;
7. for (int i = 0; i < 6; ++i)
8. result = result + num[i];
9. System.out.print(result/6);
10.
11. }
12. }

a) 16.34
b) 16.566666644
c) 16.46666666666667
d) 16.46666666666666
View Answer
Answer: c

$ javac average.java
$ java average
16.46666666666667

18. What will be the output of the following Java statement?

1. class output {
2. public static void main(String args[])
3. {
4. double a, b,c;
5. a = 3.0/0;
6. b = 0/4.0;
7. c=0/0.0;
8.
9. System.out.println(a);
10. System.out.println(b);
11. System.out.println(c);
12. }
13. }

a) Infinity
b) 0.0
c) NaN
d) all of the mentioned
View Answer
Answer: d
Explanation: For floating point literals, we have constant value to represent
(10/0.0) infinity either positive or negative and also have NaN (not a number
for undefined like 0/0.0), but for the integral type, we don’t have any
constant that’s why we get an arithmetic exception.

19. What will be the output of the following Java code?

1. class increment {
2. public static void main(String args[])
3. {
4. int g = 3;
5. System.out.print(++g * 8);
6. }
7. }

a) 25
b) 24
c) 32
d) 33
View Answer
Answer: c
Explanation: Operator ++ has more preference than *, thus g becomes 4 and
when multiplied by 8 gives 32.
output:
$ javac increment.java
$ java increment
32

20. What will be the output of the following Java code?

1. class area {
2. public static void main(String args[])
3. {
4. double r, pi, a;
5. r = 9.8;
6. pi = 3.14;
7. a = pi * r * r;
8. System.out.println(a);
9. }
10. }

a) 301.5656
b) 301
c) 301.56
d) 301.56560000
View Answer
Answer: a
Explanation: None.
output:
$ javac area.java
$ java area
301.5656

21. What is the numerical range of a char data type in Java?


a) -128 to 127
b) 0 to 256
c) 0 to 32767
d) 0 to 65535
View Answer
Answer: d
Explanation: Char occupies 16-bit in memory, so it supports 2 16 i:e from 0 to
65535.

22. Which of these coding types is used for data type characters in Java?
a) ASCII
b) ISO-LATIN-1
c) UNICODE
d) None of the mentioned
View Answer
Answer: c

23. . Which of these values can a boolean variable contain?


a) True & False
b) 0 & 1
c) Any integer value
d) true
View Answer
Answer: a
Explanation: Boolean variable can contain only one of two possible values,
true and false.

24. Which of these occupy first 0 to 127 in Unicode character set used for
characters in Java?
a) ASCII
b) ISO-LATIN-1
c) None of the mentioned
d) ASCII and ISO-LATIN1
View Answer
Answer: d
Explanation: First 0 to 127 character set in Unicode are same as those of ISO-
LATIN-1 and ASCII.

25. Which one is a valid declaration of a boolean?


a) boolean b1 = 1;
b) boolean b2 = ‘false’;
c) boolean b3 = false;
d) boolean b4 = ‘true’
View Answer
Answer: c
Explanation: Boolean can only be assigned true or false literals.
26. What will be the output of the following Java program?

1. class array_output {
2. public static void main(String args[])
3. {
4. char array_variable [] = new char[10];
5. for (int i = 0; i < 10; ++i) {
6. array_variable[i] = 'i';
7. System.out.print(array_variable[i] + "" );
8. i++;
9. }
10. }
11. }

a) i i i i i
b) 0 1 2 3 4
c) i j k l m
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
output:
$ javac array_output.java
$ java array_output
i i i i i

27. What will be the output of the following Java program?

1. class mainclass {
2. public static void main(String args[])
3. {
4. char a = 'A';
5. a++;
6. System.out.print((int)a);
7. }
8. }

a) 66
b) 67
c) 65
d) 64
View Answer
Answer: a
Explanation: ASCII value of ‘A’ is 65, on using ++ operator character value
increments by one.
output:
$ javac mainclass.java
$ java mainclass
66

28. What will be the output of the following Java program?

1. class mainclass {
2. public static void main(String args[])
3. {
4. boolean var1 = true;
5. boolean var2 = false;
6. if (var1)
7. System.out.println(var1);
8. else
9. System.out.println(var2);
10. }
11. }

a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: None.
output:
$ javac mainclass.java
$ java mainclass
true

29. What will be the output of the following Java code?

1. class booloperators {
2. public static void main(String args[])
3. {
4. boolean var1 = true;
5. boolean var2 = false;
6. System.out.println((var1 & var2));
7. }
8. }

a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: boolean ‘&’ operator always returns true or false. var1 is defined
true and var2 is defined false hence their ‘&’ operator result is false.
output:
$ javac booloperators.java
$ java booloperators
false

30. What will be the output of the following Java code?

1. class asciicodes {
2. public static void main(String args[])
3. {
4. char var1 = 'A';
5. char var2 = 'a';
6. System.out.println((int)var1 + " " + (int)var2);
7. }
8. }

a) 162
b) 65 97
c) 67 95
d) 66 98
View Answer
Answer: b
Explanation: ASCII code for ‘A’ is 65 and for ‘a’ is 97.
output:
$ javac asciicodes.java
$ java asciicodes
65 97

31. What is the order of variables in Enum?


a) Ascending order
b) Descending order
c) Random order
d) Depends on the order() method
View Answer
Answer: a
Explanation: The compareTo() method is implemented to order the variable
in ascending order.

32. Can we create an instance of Enum outside of Enum itself?


a) True
b) False
View Answer
Answer: b
Explanation: Enum does not have a public constructor.

33. What will be the output of the following Java code?

1. enum Season
2. {
3. WINTER, SPRING, SUMMER, FALL
4. };
5. System.out.println(Season.WINTER.ordinal());

a) 0
b) 1
c) 2
d) 3
View Answer
Answer: a
Explanation: ordinal() method provides number to the variables defined in
Enum

34. If we try to add Enum constants to a TreeSet, what sorting order will it
use?
a) Sorted in the order of declaration of Enums
b) Sorted in alphabetical order of Enums
c) Sorted based on order() method
d) Sorted in descending order of names of Enums
View Answer
Answer: a
Explanation: Tree Set will sort the values in the order in which Enum
constants are declared.

35. What will be the output of the following Java code snippet?

1. class A
2. {
3.
4. }
5.
6. enum Enums extends A
7. {
8. ABC, BCD, CDE, DEF;
9. }
a) Runtime Error
b) Compilation Error
c) It runs successfully
d) EnumNotDefined Exception
View Answer
Answer: b
Explanation: Enum types cannot extend class.

36. What will be the output of the following Java code snippet?

1. enum Levels
2. {
3. private TOP,
4.
5. public MEDIUM,
6.
7. protected BOTTOM;
8. }

a) Runtime Error
b) EnumNotDefined Exception
c) It runs successfully
d) Compilation Error
View Answer
Answer: d
Explanation: Enum cannot have any modifiers. They are public, static and
final by default.

37. What will be the output of the following Java code snippet?

1. enum Enums
2. {
3. A, B, C;
4.
5. private Enums()
6. {
7. System.out.println(10);
8. }
9. }
10.
11. public class MainClass
12. {
13. public static void main(String[] args)
14. {
15. Enum en = Enums.B;
16. }
17. }

a)

10

10

10

b) Compilation Error
c)

10

10

d) Runtime Exception
View Answer
Answer: a
Explanation: The constructor of Enums is called which prints 10.

38. Which method returns the elements of Enum class?


a) getEnums()
b) getEnumConstants()
c) getEnumList()
d) getEnum()
View Answer
Answer: b
Explanation: getEnumConstants() returns the elements of this enum class or
null if this Class object does not represent an enum type.

39. Which class does all the Enums extend?


a) Object
b) Enums
c) Enum
d) EnumClass
View Answer
Answer: c
Explanation: All enums implicitly extend java.lang.Enum. Since Java does not
support multiple inheritance, an enum cannot extend anything else.
40. Are enums are type-safe?
a) True
b) False
View Answer
Answer: a
Explanation: Enums are type-safe as they have own name-space.

41. Which of these operators is used to allocate memory to array variable in


Java?
a) malloc
b) alloc
c) new
d) new malloc
View Answer
Answer: c
Explanation: Operator new allocates a block of memory specified by the size
of an array, and gives the reference of memory allocated to the array
variable.

42. Which of these is an incorrect array declaration?


a) int arr[] = new int[5]
b) int [] arr = new int[5]
c) int arr[] = new int[5]
d) int arr[] = int [5] new
View Answer
Answer: d
Explanation: Operator new must be succeeded by array type and array size.

43. What will be the output of the following Java code?

int arr[] = new int [5];


System.out.print(arr);

a) 0
b) value stored in arr[0]
c) 00000
d) Class name@ hashcode in hexadecimal form
View Answer
Answer: d
Explanation: If we trying to print any reference variable internally, toString()
will be called which is implemented to return the String in following form:
classname@hashcode in hexadecimal form

44. Which of these is an incorrect Statement?


a) It is necessary to use new operator to initialize an array
b) Array can be initialized using comma separated expressions surrounded by
curly braces
c) Array can be initialized when they are declared
d) None of the mentioned
View Answer
Answer: a
Explanation: Array can be initialized using both new and comma separated
expressions surrounded by curly braces example : int arr[5] = new int[5]; and
int arr[] = { 0, 1, 2, 3, 4};

45. Which of these is necessary to specify at time of array initialization?


a) Row
b) Column
c) Both Row and Column
d) None of the mentioned
Answer: a
46. What will be the output of the following Java code?

1. class array_output
2. {
3. public static void main(String args[])
4. {
5. int array_variable [] = new int[10];
6. for (int i = 0; i < 10; ++i)
7. {
8. array_variable[i] = i;
9. System.out.print(array_variable[i] + " ");
10. i++;
11. }
12. }
13. }

a) 0 2 4 6 8
b) 1 3 5 7 9
c) 0 1 2 3 4 5 6 7 8 9
d) 1 2 3 4 5 6 7 8 9 10
View Answer
Answer: a
Explanation: When an array is declared using new operator then all of its
elements are initialized to 0 automatically. for loop body is executed 5 times
as whenever controls comes in the loop i value is incremented twice, first by
i++ in body of loop then by ++i in increment condition of for loop.
output:
$ javac array_output.java
$ java array_output
0 2 4 6 8
47. What will be the output of the following Java code?

1. class multidimention_array
2. {
3. public static void main(String args[])
4. {
5. int arr[][] = new int[3][];
6. arr[0] = new int[1];
7. arr[1] = new int[2];
8. arr[2] = new int[3];
9. int sum = 0;
10. for (int i = 0; i < 3; ++i)
11. for (int j = 0; j < i + 1; ++j)
12. arr[i][j] = j + 1;
13. for (int i = 0; i < 3; ++i)
14. for (int j = 0; j < i + 1; ++j)
15. sum + = arr[i][j];
16. System.out.print(sum);
17. }
18. }

a) 11
b) 10
c) 13
d) 14
View Answer
Answer: b
Explanation: arr[][] is a 2D array, array has been allotted memory in parts.
1st row contains 1 element, 2nd row contains 2 elements and 3rd row
contains 3 elements. each element of array is given i + j value in loop. sum
contains addition of all the elements of the array.
output:

$ javac multidimention_array.java
$ java multidimention_array
10

48. What will be the output of the following Java code?

1. class evaluate
2. {
3. public static void main(String args[])
4. {
5. int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};
6. int n = 6;
7. n = arr[arr[n] / 2];
8. System.out.println(arr[n] / 2);
9. }
10. }

a) 3
b) 0
c) 6
d) 1
View Answer
Answer: d
Explanation: Array arr contains 10 elements. n contains 6 thus in next line n
is given value 3 printing arr[3]/2 i:e 3/2 = 1 because of int Value, by int
values there is no rest. If this values would be float the result would be 1.5.
output:
$ javac evaluate.java
$ java evaluate

49. . What will be the output of the following Java code?

1. class array_output
2. {
3. public static void main(String args[])
4. {
5. char array_variable [] = new char[10];
6. for (int i = 0; i < 10; ++i)
7. {
8. array_variable[i] = 'i';
9. System.out.print(array_variable[i] + "");
10. }
11. }
12. }

a) 1 2 3 4 5 6 7 8 9 10
b) 0 1 2 3 4 5 6 7 8 9 10
c) i j k l m n o p q r
d) i i i i i i i i i i
View Answer
Answer: d
Explanation: None.
output:
$ javac array_output.java
$ java array_output
i i i i i i i i i i

50. What will be the output of the following Java code?

1. class array_output
2. {
3. public static void main(String args[])
4. {
5. int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8,
9}};
6. int sum = 0;
7. for (int i = 0; i < 3; ++i)
8. for (int j = 0; j < 3 ; ++j)
9. sum = sum + array_variable[i][j];
10. System.out.print(sum / 5);
11. }
12. }

a) 8
b) 9
c) 10
d) 11
View Answer
Answer: b
Explanation: None.
output:
$ javac array_output.java
$ java array_output
9

https://www.sanfoundry.com/tricky-java-questions-answers/

51. What is the type of variable ‘b’ and ‘d’ in the following Java snippet?

int a[], b;
int []c, d;

a) ‘b’ and ‘d’ are int


b) ‘b’ and ‘d’ are arrays of type int
c) ‘b’ is int variable; ‘d’ is int array
d) ‘d’ is int variable; ‘b’ is int array
View Answer
Answer: c
Explanation: If [] is declared after variable it is applicable only to one
variable. If [] is declared before variable it is applicable to all the variables.
52. Which of these is an incorrect array declaration?
a) int arr[] = new int[5] ;
b) int [] arr = new int[5] ;
c)

int arr[];
arr = new int[5];

d) int arr[] = int [5] new;


View Answer
Answer: d
Explanation: Operator new must be succeeded by array type and array size.
The order is important and determines the type of variable.

53. What will be the output of the following Java code?

1. int arr[] = new int [5];


2. System.out.print(arr);

a) 0
b) value stored in arr[0].
c) 00000
d) Garbage value
View Answer
Answer: d
Explanation: arr is an array variable, it is pointing to array of integers.
Printing arr will print garbage value. It is not same as printing arr[0].

54. What will be the output of the following Java code snippet?

1. Object[] names = new String[3];


2. names[0] = new Integer(0);

a) ArrayIndexOutOfBoundsException
b) ArrayStoreException
c) Compilation Error
d) Code runs successfully
View Answer
Answer: b
Explanation: ArrayIndexOutOfBoundsException comes when code tries to
access an invalid index for a given array. ArrayStoreException comes when
you have stored an element of type other than the type of array.

55. Generics does not work with?


a) Set
b) List
c) Tree
d) Array
View Answer
Answer: d
Explanation: Generics gives the flexibility to strongly typecast collections.
Generics is applicable to Set, List and Tree. It is not applicable to Array.
56. How to sort an array?
a) Array.sort()
b) Arrays.sort()
c) Collection.sort()
d) System.sort()
View Answer
Answer: b
Explanation: Arrays class contains various methods for manipulating arrays
(such as sorting and searching). Array is not a valid class.

57. How to copy contents of array?


a) System.arrayCopy()
b) Array.copy()
c) Arrays.copy()
d) Collection.copy()
View Answer
Answer: a
Explanation: Arrays class contains various methods for manipulating arrays
(such as sorting and searching). Array is not a valid class.

58. Can you make an array volatile?


a) True
b) False
View Answer
Answer: a
Explanation: You can only make variable pointing to array volatile. If an array
is changed by replacing individual elements then guarantee provided by
volatile variable will not be held.

59. Where is an array stored in memory?


a) heap space
b) stack space
c) heap space and stack space
d) first generation memory
View Answer
Answer: a
Explanation: Array is stored in heap space. Whenever an object is created,
it’s always stored in the Heap space and stack memory contains the
reference to it.

60. An array elements are always stored in ________ memory locations.


a) Sequential
b) Random
c) Sequential and Random
d) Binary search
View Answer
Answer: a
Explanation: Array elements are stored in contiguous memory. Linked List is
stored in random memory locations.

61. What is the stored in the object obj in following lines of Java code?

box obj;

a) Memory address of allocated memory of object


b) NULL
c) Any arbitrary pointer
d) Garbage
View Answer
Answer: b
Explanation: Memory is allocated to an object using new operator. box obj;
just declares a reference to object, no memory is allocated to it hence it
points to NULL.

62. Which of these keywords is used to make a class?


a) class
b) struct
c) int
d) none of the mentioned
View Answer
Answer: a
Explanation: None.

63. Which of the following is a valid declaration of an object of class Box?


a) Box obj = new Box();
b) Box obj = new Box;
c) obj = new Box();
d) new Box obj;
View Answer
Answer: a

64. Which of these operators is used to allocate memory for an object?


a) malloc
b) alloc
c) new
d) give
View Answer
Answer: c
Explanation: Operator new dynamically allocates memory for an object and
returns a reference to it. This reference is address in memory of the object
allocated by new.

65. Which of these statement is incorrect?


a) Every class must contain a main() method
b) Applets do not require a main() method at all
c) There can be only one main() method in a program
d) main() method must be made public
View Answer
Answer: a
Explanation: Every class does not need to have a main() method, there can
be only one main() method which is made public.

66. What will be the output of the following Java program?

1. class main_class
2. {
3. public static void main(String args[])
4. {
5. int x = 9;
6. if (x == 9)
7. {
8. int x = 8;
9. System.out.println(x);
10. }
11. }
12. }

a) 9
b) 8
c) Compilation error
d) Runtime error
View Answer
Answer: c
Explanation: Two variables with the same name can’t be created in a class.
output:
$ javac main_class.java
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Duplicate local variable x

67. Which of the following statements is correct?


a) Public method is accessible to all other classes in the hierarchy
b) Public method is accessible only to subclasses of its parent class
c) Public method can only be called by object of its class
d) Public method can be accessed by calling object of the public class
View Answer
Answer: a

68. What will be the output of the following Java program?

1. class box
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
9. public static void main(String args[])
10. {
11. box obj = new box();
12. obj.width = 10;
13. obj.height = 2;
14. obj.length = 10;
15. int y = obj.width * obj.height * obj.length;
16. System.out.print(y);
17. }
18. }

a) 12
b) 200
c) 400
d) 100
View Answer
Answer: b
Explanation: None.
output:
$ javac mainclass.java
$ java mainclass
200

69. What will be the output of the following Java program?

1. class box
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
9. public static void main(String args[])
10. {
11. box obj1 = new box();
12. box obj2 = new box();
13. obj1.height = 1;
14. obj1.length = 2;
15. obj1.width = 1;
16. obj2 = obj1;
17. System.out.println(obj2.height);
18. }
19. }

a) 1
b) 2
c) Runtime error
d) Garbage value
View Answer
Answer: a
Explanation: When we assign an object to another object of same type, all
the elements of right side object gets copied to object on left side of equal to,
=, operator.
output:
$ javac mainclass.java
$ java mainclass
1

70. What will be the output of the following Java program?

1. class box
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
9. public static void main(String args[])
10. {
11. box obj = new box();
12. System.out.println(obj);
13. }
14. }

a) 0
b) 1
c) Runtime error
d) classname@hashcode in hexadecimal form
View Answer
Answer: d
Explanation: When we print object internally toString() will be called to return
string into this format classname@hashcode in hexadecimal form.
output:
$ javac mainclass.java
$ java mainclass
box@130671e

https://www.sanfoundry.com/java-mcqs-introduction-methods/

71. What is the return type of a method that does not return any value?
a) int
b) float
c) void
d) double
View Answer
Answer: c
Explanation: Return type of a method must be made void if it is not returning
any value.

72. What is the process of defining more than one method in a class
differentiated by method signature?
a) Function overriding
b) Function overloading
c) Function doubling
d) None of the mentioned
View Answer
Answer: b
Explanation: Function overloading is a process of defining more than one
method in a class with same name differentiated by function signature i:e
return type or parameters type and number. Example – int volume(int length,
int width) & int volume(int length , int width , int height) can be used to
calculate volume.

73. Which of the following is a method having same name as that of it’s
class?
a) finalize
b) delete
c) class
d) constructor
View Answer
Answer: d
Explanation: A constructor is a method that initializes an object immediately
upon creation. It has the same name as that of class in which it resides.

74. Which method can be defined only once in a program?


a) main method
b) finalize method
c) static method
d) private method
View Answer
Answer: a
Explanation: main() method can be defined only once in a program. Program
execution begins from the main() method by java runtime system.

75. Which of this statement is incorrect?


a) All object of a class are allotted memory for the all the variables defined in
the class
b) If a function is defined public it can be accessed by object of other class by
inheritation
c) main() method must be made public
d) All object of a class are allotted memory for the methods defined in the
class
View Answer
Answer: d
Explanation: All object of class share a single copy of methods defined in a
class, Methods are allotted memory only once. All the objects of the class
have access to methods of that class are allotted memory only for the
variables not for the methods

76. What will be the output of the following Java program?

1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. void volume(int height, int length, int width)
8. {
9. volume = width*height*length;
10. }
11. }
12. class Prameterized_method
13. {
14. public static void main(String args[])
15. {
16. box obj = new box();
17. obj.height = 1;
18. obj.length = 5;
19. obj.width = 5;
20. obj.volume(3,2,1);
21. System.out.println(obj.volume);
22. }
23. }

a) 0
b) 1
c) 6
d) 25
View Answer
Answer: c
Explanation: None.
output:
$ Prameterized_method.java
$ Prameterized_method
6

77. What will be the output of the following Java program?

1. class equality
2. {
3. int x;
4. int y;
5. boolean isequal()
6. {
7. return(x == y);
8. }
9. }
10. class Output
11. {
12. public static void main(String args[])
13. {
14. equality obj = new equality();
15. obj.x = 5;
16. obj.y = 5;
17. System.out.println(obj.isequal());
18. }
19. }

a) false
b) true
c) 0
d) 1
View Answer
Answer: b
Explanation: None.
output:
$ javac Output.java
$ java Output
true

78. What will be the output of the following Java program?

1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. void volume()
8. {
9. volume = width*height*length;
10. }
11. }
12. class Output
13. {
14. public static void main(String args[])
15. {
16. box obj = new box();
17. obj.height = 1;
18. obj.length = 5;
19. obj.width = 5;
20. obj.volume();
21. System.out.println(obj.volume);
22. }
23. }

a) 0
b) 1
c) 25
d) 26
View Answer
Answer: c
Explanation: None.
output:
$ javac Output.java
$ java Output
25
79. In the following Java code, which call to sum() method is appropriate?

1. class Output
2. {
3.
4. public static int sum(int ...x)
5. {
6. return;
7. }
8. static void main(String args[])
9. {
10. sum(10);
11. sum(10,20);
12. sum(10,20,30);
13. sum(10,20,30,40);
14. }
15. }

a) only sum(10)
b) only sum(10,20)
c) only sum(10) & sum(10,20)
d) all of the mentioned
View Answer
Answer: d
Explanation: sum is a variable argument method and hence it can take any
number as an argument.

80. What will be the output of the following Java program?

1. class area
2. {
3. int width;
4. int length;
5. int volume;
6. area()
7. {
8. width=5;
9. length=6;
10. }
11. void volume()
12. {
13. volume = width*length*height;
14. }
15. }
16. class cons_method
17. {
18. public static void main(String args[])
19. {
20. area obj = new area();
21. obj.volume();
22. System.out.println(obj.volume);
23. }
24. }

a) 0
b) 1
c) 30
d) error
View Answer
Answer: d
Explanation: Variable height is not defined.
output:
$ javac cons_method.java
$ java cons_method
error: cannot find symbol height

https://www.sanfoundry.com/java-mcqs-constructors-garbage-collection/

81. What is the return type of Constructors?


a) int
b) float
c) void
d) none of the mentioned
View Answer
Answer: d
Explanation: Constructors does not have any return type, not even void.

82. Which keyword is used by the method to refer to the object that invoked
it?
a) import
b) catch
c) abstract
d) this
View Answer
Answer: d
Explanation: this keyword can be used inside any method to refer to the
current object. this is always a reference to the object on which the method
was invoked.
83. Which of the following is a method having same name as that of its class?
a) finalize
b) delete
c) class
d) constructor
View Answer
Answer: d
Explanation: A constructor is a method that initializes an object immediately
upon creation. It has the same name as that of class in which it resides.

84. Which operator is used by Java run time implementations to free the
memory of an object when it is no longer needed?
a) delete
b) free
c) new
d) none of the mentioned
View Answer
Answer: d
Explanation: Java handles deallocation of memory automatically, we do not
need to explicitly delete an element. Garbage collection only occurs during
execution of the program. When no references to the object exist, that object
is assumed to be no longer needed, and the memory occupied by the object
can be reclaimed.

85. Which function is used to perform some action when the object is to be
destroyed?
a) finalize()
b) delete()
c) main()
d) none of the mentioned
View Answer
Answer: a

86. What will be the output of the following Java code?

1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. box()
8. {
9. width = 5;
10. height = 5;
11. length = 6;
12. }
13. void volume()
14. {
15. volume = width*height*length;
16. }
17. }
18. class constructor_output
19. {
20. public static void main(String args[])
21. {
22. box obj = new box();
23. obj.volume();
24. System.out.println(obj.volume);
25. }
26. }

a) 100
b) 150
c) 200
d) 250
View Answer
Answer: b
Explanation: None.
output:
$ constructor_output.java
$ constructor_output
150

87. What will be the output of the following Java code?

1. class San
2. {
3. San()throws IOException
4. {
5.
6. }
7.
8. }
9. class Foundry extends San
10. {
11. Foundry()
12. {
13.
14. }
15. public static void main(String[]args)
16. {
17.
18. }
19. }

a) compile time error


b) run time error
c) compile and runs fine
d) unreported exception java.io.IOException in default constructor
View Answer
Answer: a
Explanation: If parent class constructor throws any checked exception,
compulsory child class constructor should throw the same checked exception
as its parent, otherwise code won’t compile.

88. What will be the output of the following Java code?

1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. void finalize()
8. {
9. volume = width*height*length;
10. System.out.println(volume);
11. }
12. protected void volume()
13. {
14. volume = width*height*length;
15. System.out.println(volume);
16. }
17. }
18. class Output
19. {
20. public static void main(String args[])
21. {
22. box obj = new box();
23. obj.width=5;
24. obj.height=5;
25. obj.length=6;
26. obj.volume();
27. }
28. }

a) 150
b) 200
c) Run time error
d) Compilation error
View Answer
Answer: a
Explanation: None.
output:
$ javac Output.java
$ java Output
150

89. Which of the following statements are incorrect?


a) default constructor is called at the time of object declaration
b) constructor can be parameterized
c) finalize() method is called when a object goes out of scope and is no longer
needed
d) finalize() method must be declared protected
View Answer
Answer: c
Explanation: finalize() method is called just prior to garbage collection. it is
not called when object goes out of scope.

90. What will be the output of the following Java code?

1. class area
2. {
3. int width;
4. int length;
5. int area;
6. void area(int width, int length)
7. {
8. this.width = width;
9. this.length = length;
10. }
11.
12. }
13. class Output
14. {
15. public static void main(String args[])
16. {
17. area obj = new area();
18. obj.area(5 , 6);
19. System.out.println(obj.length + " " + obj.width);
20. }
21. }

a) 0 0
b) 5 6
c) 6 5
d) 5 5
View Answer
Answer: c
Explanation: this keyword can be used inside any method to refer to the
current object. this is always a reference to the object on which the method
was invoked.
output:
$ javac Output.java
$ java Output
6 5

https://www.sanfoundry.com/java-questions-answers-constructor/

91. What is true about private constructor?


a) Private constructor ensures only one instance of a class exist at any point
of time
b) Private constructor ensures multiple instances of a class exist at any point
of time
c) Private constructor eases the instantiation of a class
d) Private constructor allows creating objects in other classes
View Answer
Answer: a
Explanation: Object of private constructor can only be created within class.
Private constructor is used in singleton pattern.

92. What would be the behaviour if this() and super() used in a method?
a) Runtime error
b) Throws exception
c) compile time error
d) Runs successfully
View Answer
Answer: c
Explanation: this() and super() cannot be used in a method. This throws
compile time error.
93. What is false about constructor?
a) Constructors cannot be synchronized in Java
b) Java does not provide default copy constructor
c) Constructor can have a return type
d) “this” and “super” can be used in a constructor
View Answer
Answer: c
Explanation: The constructor cannot have a return type. It should create and
return new objects. Hence it would give a compilation error.
94. What is true about Class.getInstance()?
a) Class.getInstance calls the constructor
b) Class.getInstance is same as new operator
c) Class.getInstance needs to have matching constructor
d) Class.getInstance creates object if class does not have any constructor
View Answer
Answer: d
Explanation: Class class provides list of methods for use like getInstance().

95. What is true about constructor?


a) It can contain return type
b) It can take any number of parameters
c) It can have any non access modifiers
d) Constructor cannot throw an exception
View Answer
Answer: b
Explanation: Constructor returns a new object with variables defined as in the
class. Instance variables are newly created and only one copy of static
variables are created.

96. Abstract class cannot have a constructor.


a) True
b) False
View Answer
Answer: b
Explanation: No instance can be created of abstract class. Only pointer can
hold instance of object.

97. What is true about protected constructor?


a) Protected constructor can be called directly
b) Protected constructor can only be called using super()
c) Protected constructor can be used outside package
d) protected constructor can be instantiated even if child is in a different
package
View Answer
Answer: b
Explanation: Protected access modifier means that constructor can be
accessed by child classes of the parent class and classes in the same
package.

98. What is not the use of “this” keyword in Java?


a) Passing itself to another method
b) Calling another constructor in constructor chaining
c) Referring to the instance variable when local variable has the same name
d) Passing itself to method of the same class
View Answer
Answer: d
Explanation: “this” is an important keyword in java. It helps to distinguish
between local variable and variables passed in the method as parameters.

99. What would be the behaviour if one parameterized constructor is


explicitly defined?
a) Compilation error
b) Compilation succeeds
c) Runtime error
d) Compilation succeeds but at the time of creating object using default
constructor, it throws compilation error
View Answer
Answer: d
Explanation: The class compiles successfully. But the object creation of that
class gives a compilation error.

100. What would be behaviour if the constructor has a return type?


a) Compilation error
b) Runtime error
c) Compilation and runs successfully
d) Only String return type is allowed
View Answer
Answer: a
Explanation: The constructor cannot have a return type. It should create and
return new object. Hence it would give compilation error.

https://www.sanfoundry.com/java-questions-answers-heap-garbage-collection/

https://www.sanfoundry.com/java-mcqs-access-control/

https://www.sanfoundry.com/java-mcqs-overloading-methods-argument-passing/

https://www.sanfoundry.com/java-mcqs-access-control/

https://www.sanfoundry.com/java-interview-questions-answers/

https://www.sanfoundry.com/java-questions-bank/

https://www.sanfoundry.com/java-mcqs-string-class/
https://www.sanfoundry.com/java-questions-answers-entrance-exams/

https://www.sanfoundry.com/java-mcqs-command-line-arguments/

https://www.sanfoundry.com/java-questions-answers-freshers/

https://www.sanfoundry.com/java-mcqs-recursion/

https://www.sanfoundry.com/java-mcqs-method-overriding/

https://www.sanfoundry.com/java-mcqs-object-class/

https://www.sanfoundry.com/java-mcqs-inheritance-abstract-and-super/

https://www.sanfoundry.com/java-mcqs-inheritance/

https://www.sanfoundry.com/java-interview-questions-answers-freshers/

https://www.sanfoundry.com/java-mcqs-string-handling-basics/

https://www.sanfoundry.com/java-mcqs-character-extraction/

https://www.sanfoundry.com/java-mcqs-string-comparision/

https://www.sanfoundry.com/java-mcqs-seraching-modifying-string/

https://www.sanfoundry.com/java-mcqs-stringbuffer-class/

https://www.sanfoundry.com/java-mcqs-stringbuffer-methods/

and soo on…

You might also like