What is the process of defining a method in terms of itself that is a method that calls itself select one a encapsulation B polymorphism C Recursion D abstraction?

This Section has more than 300+ java MCQ's that covers all the topics in java

1. What is the range of short data type in Java?a) -128 to 127b) -32768 to 32767c) -2147483648 to 2147483647d) None of the mentioned

Answer: b

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

2. What is the range of byte data type in Java?a) -128 to 127b) -32768 to 32767c) -2147483648 to 2147483647d) None of the mentioned
Answer: aExplanation: Byte occupies 8 bits in memory. Its range is from -128 to 127.

3. 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

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.

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

a) int

b) long

c) byte

d) float

Answer: a

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

5. 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

Answer: b

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

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

a) int

b) float

c) double

d) long

Answer: c

Explanation: None.

7. What will be the output of the following Java code?

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.566666644

c) 16.46666666666667

d) 16.46666666666666

Answer: c

Explanation: None.

output:

$ javac average.java$ java average16.46666666666667

8. What will be the output of the following Java statement?

class output { public static void main(String args[]) { double a, b,c; a = 3.0/0; b = 0/4.0; c=0/0.0; System.out.println(a); System.out.println(b); System.out.println(c); } }

a) Infinity

b) 0.0

c) NaN

d) all of the mentioned

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.

9. What will be the output of the following Java code?

class increment { public static void main(String args[]) { int g = 3; System.out.print(++g * 8); } }

a) 25

b) 24

c) 32

d) 33

Answer: c

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

output:

$ javac increment.java$ java increment32

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

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.56560000

Answer: a

Explanation: None.

output:

$ javac area.java$ java area301.5656

11. This Section of our 1000+ Java MCQs focuses on Character and Boolean Datatypes of Java Programming Language.

1. 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

Answer: d

Explanation: Char occupies 16-bit in memory, so it supports 216 i:e from 0 to 65535.

12. 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

Answer: 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.

13. Which of these values can a boolean variable contain?

a) True & False

b) 0 & 1

c) Any integer value

d) true

Answer: a

Explanation: Boolean variable can contain only one of two possible values, true and false.

14. 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

Answer: d

Explanation: First 0 to 127 character set in Unicode are same as those of ISO-LATIN-1 and ASCII.

15. 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’

Answer: c

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

16. What will be the output of the following Java 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

Answer: a

Explanation: None.

output:

$ javac array_output.java$ java array_outputi i i i i

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

class mainclass { public static void main(String args[]) { char a = 'A'; a++; System.out.print((int)a); } }

a) 66

b) 67

c) 65

d) 64

Answer: a

Explanation: ASCII value of ‘A’ is 65, on using ++ operator character value increments by one.

output:

$ javac mainclass.java$ java mainclass 66

18. What will be the output of the following Java 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

Answer: c

Explanation: None.

output:

$ javac mainclass.java$ java mainclasstrue

19. What will be the output of the following Java code?

class booloperators { public static void main(String args[]) { boolean var1 = true; boolean var2 = false; System.out.println((var1 & var2)); } }

a) 0

b) 1

c) true

d) false

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 booloperatorsfalse

20. What will be the output of the following Java code?

class asciicodes { public static void main(String args[]) { char var1 = 'A'; char var2 = 'a'; System.out.println((int)var1 + " " + (int)var2); } }

a) 162

b) 65 97

c) 67 95

d) 66 98

Answer: b

Explanation: ASCII code for ‘A’ is 65 and for ‘a’ is 97.

output:

$ javac asciicodes.java$ java asciicodes65 9

21. Which of these is long data type literal?

a) 0x99fffL

b) ABCDEFG

c) 0x99fffa

d) 99671246

Answer: a

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

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

a) Integer

b) Boolean

c) Character

d) Integer or Boolean

Answer: d

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

Literals in java must be appended by which of these?

a) L

b) l

c) D

d) L and I

Answer: d

Explanation: Data type long literals are appended by an upper or lowercase L.

Literal can be of which of these data types?

a) integer

b) float

c) boolean

d) all of the mentioned

Answer: d

Explanation: None

Which of these can not be used for a variable name in Java?

a) identifier

b) keyword

c) identifier & keyword

d) none of the mentioned

Answer: b

Explanation: Keywords are specially reserved words which can not be used for naming a user defined variable, example: class, int, for etc.

What will be the output of the following Java program?

class evaluate { public static void main(String args[]) { int a[] = {1,2,3,4,5}; int d[] = a; int sum = 0; for (int j = 0; j < 3; ++j) sum += (a[j] * d[j + 1]) + (a[j + 1] * d[j]); System.out.println(sum); } }

a) 38

b) 39

c) 40

d) 41

Answer: c

Explanation: None.

output:

$ javac evaluate.java$ java evaluate40

What will be the output of the following Java program?

class array_output { public static void main(String args[]) { int array_variable [] = new int[10]; for (int i = 0; i < 10; ++i) { array_variable[i] = i/2; array_variable[i]++; System.out.print(array_variable[i] + " "); i++; } } }

a) 0 2 4 6 8

b) 1 2 3 4 5

c) 0 1 2 3 4 5 6 7 8 9

d) 1 2 3 4 5 6 7 8 9 10

Answer: b

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_output1 2 3 4 5

What will be the output of the following Java program?

class variable_scope { public static void main(String args[]) { int x; x = 5; { int y = 6; System.out.print(x + " " + y); } System.out.println(x + " " + y); } }

a) 5 6 5 6

b) 5 6 5

c) Runtime error

d) Compilation error

Answer: d

Explanation: Second print statement doesn’t have access to y , scope y was limited to the block defined after initialization of x.

output:

$ javac variable_scope.javaException in thread "main" java.lang.Error: Unresolved compilation problem: y cannot be resolved to a variable

Which of these is an incorrect string literal?

a) “Hello World”

b) “Hello\nWorld”

c) “\”Hello World\””

d)

Answer: d

Explanation: All string literals must begin and end in the same line.

What will be the output of the following Java program?

class dynamic_initialization { public static void main(String args[]) { double a, b; a = 3.0; b = 4.0; double c = Math.sqrt(a * a + b * b); System.out.println(c); } }

a) 5.0

b) 25.0

c) 7.0

d) Compilation Error

Answer: a

Explanation: Variable c has been dynamically initialized to square root of a * a + b * b, during run time.

output:

$ javac dynamic_initialization.java$ java dynamic_initialization5.0

What is the order of variables in Enum?

a) Ascending order

b) Descending order

c) Random order

d) Depends on the order() method

Answer: a

Explanation: The compareTo() method is implemented to order the variable in ascending order.

Can we create an instance of Enum outside of Enum itself?

a) True

b) False

Answer: b

Explanation: Enum does not have a public constructor.

What will be the output of the following Java code?

enum Season { WINTER, SPRING, SUMMER, FALL }; System.out.println(Season.WINTER.ordinal());

a) 0

b) 1

c) 2

d) 3

Answer: a

Explanation: ordinal() method provides number to the variables defined in Enum.

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

Answer: a

Explanation: Tree Set will sort the values in the order in which Enum constants are declared.

What will be the output of the following Java code snippet?

class A{ } enum Enums extends A{ ABC, BCD, CDE, DEF;}

a) Runtime Error

b) Compilation Error

c) It runs successfully

d) EnumNotDefined Exception

Answer: b

Explanation: Enum types cannot extend class.

What will be the output of the following Java code snippet?

enum Levels { private TOP, public MEDIUM, protected BOTTOM;}

a) Runtime Error

b) EnumNotDefined Exception

c) It runs successfully

d) Compilation Error

Answer: d

Explanation: Enum cannot have any modifiers. They are public, static and final by default.

What will be the output of the following Java code snippet?

enum Enums{ A, B, C; private Enums() { System.out.println(10); }} public class MainClass{ public static void main(String[] args) { Enum en = Enums.B; }}

a)

b) Compilation Error

c)

d) Runtime Exception

Answer: a

Explanation: The constructor of Enums is called which prints 10

Which method returns the elements of Enum class?

a) getEnums()

b) getEnumConstants()

c) getEnumList()

d) getEnum()

Answer: b

Explanation: getEnumConstants() returns the elements of this enum class or null if this Class object does not represent an enum type.

Which class does all the Enums extend?

a) Object

b) Enums

c) Enum

d) EnumClass

Answer: c

Explanation: All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.

Are enums are type-safe?

a) True

b) False

Answer: a

Explanation: Enums are type-safe as they have own name-space

Which of the following is the advantage of BigDecimal over double?

a) Syntax

b) Memory usage

c) Garbage creation

d) Precision

Answer: d

Explanation: BigDecimal has unnatural syntax, needs more memory and creates a great amount of garbage. But it has a high precision which is useful for some calculations like money.

Which of the below data type doesn’t support overloaded methods for +,-,* and /?

a) int

b) float

c) double

d) BigDecimal

Answer: d

Explanation: int, float, double provide overloaded methods for +,-,* and /. BigDecimal does not provide these overloaded methods.

What will be the output of the following Java code snippet?

double a = 0.02; double b = 0.03; double c = b - a; System.out.println(c); BigDecimal _a = new BigDecimal("0.02"); BigDecimal _b = new BigDecimal("0.03"); BigDecimal _c = b.subtract(_a); System.out.println(_c);

a)

0.009999999999999998 0.01

b)

0.01 0.009999999999999998

c)

d)

0.009999999999999998 0.009999999999999998

Answer: a

Explanation: BigDecimal provides more precision as compared to double. Double is faster in terms of performance as compared to BigDecimal.

What is the base of BigDecimal data type?

a) Base 2

b) Base 8

c) Base 10

d) Base e

Answer: c

Explanation: A BigDecimal is n*10^scale where n is an arbitrary large signed integer. Scale can be thought of as the number of digits to move the decimal point to left or right.

What is the limitation of toString() method of BigDecimal?

a) There is no limitation

b) toString returns null

c) toString returns the number in expanded form

d) toString uses scientific notation

Answer: d

Explanation: toString() of BigDecimal uses scientific notation to represent numbers known as canonical representation. We must use toPlainString() to avoid scientific notation.

Which of the following is not provided by BigDecimal?

a) scale manipulation

b) + operator

c) rounding

d) hashing

Answer: b

Explanation: toBigInteger() converts BigDecimal to a BigInteger.toBigIntegerExact() converts this BigDecimal to a BigInteger by checking for lost information.

BigDecimal is a part of which package?

a) java.lang

b) java.math

c) java.util

d) java.io

Answer: b

Explanation: BigDecimal is a part of java.math. This package provides various classes for storing numbers and mathematical operations.

What is BigDecimal.ONE?

a) wrong statement

b) custom defined statement

c) static variable with value 1 on scale 10

d) static variable with value 1 on scale 0

Answer: d

Explanation: BigDecimal.ONE is a static variable of BigDecimal class with value 1 on scale 0.

Which class is a library of functions to perform arithmetic operations of BigInteger and BigDecimal?

a) MathContext

b) MathLib

c) BigLib

d) BigContext

Answer: a

Explanation: MathContext class is a library of functions to perform arithmetic operations of BigInteger and BigDecimal.

What will be the output of the following Java code snippet?

public class AddDemo { public static void main(String args[]) { BigDecimal b = new BigDecimal("23.43"); BigDecimal br = new BigDecimal("24"); BigDecimal bres = b.add(new BigDecimal("450.23")); System.out.println("Add: "+bres); MathContext mc = new MathContext(2, RoundingMode.DOWN); BigDecimal bdecMath = b.add(new BigDecimal("450.23"), mc); System.out.println("Add using MathContext: "+bdecMath); }}

a) Compilation failure

b)

Add: 684.66Add using MathContext: 6.8E+2

c)

Add 6.8E+2Add using MathContext: 684.66

d) Runtime exception

Answer: b

Explanation: add() adds the two numbers, MathContext provides library for carrying out various arithmetic operations

How to format date from one form to another?

a) SimpleDateFormat

b) DateFormat

c) SimpleFormat

d) DateConverter

Answer: a

Explanation: SimpleDateFormat can be used as

Date now = new Date();SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-mm-dd'T'hh:MM:ss");String nowStr = sdf.format(now);System.out.println("Current Date: " + );

How to convert Date object to String?

a)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");sdf.parse(new Date());

b)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");sdf.format(new Date());

c)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");new Date().parse();

d)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");new Date().format();

Answer: b

Explanation: SimpleDateFormat takes a string containing pattern. sdf.format converts the Date object to String.

How to convert a String to a Date object?

a)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");sdf.parse(new Date());

b)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");sdf.format(new Date());

c)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");new Date().parse();

d)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");new Date().format();

Answer: a

Explanation: SimpleDateFormat takes a string containing pattern. sdf.parse converts the String to Date object

Is SimpleDateFormat thread safe?

a) True

b) False

Answer: b

Explanation: SimpleDateFormat is not thread safe. In the multithreaded environment, we need to manage threads explicitly.

How to identify if a timezone is eligible for DayLight Saving?

a) useDaylightTime() of Time class

b) useDaylightTime() of Date class

c) useDaylightTime() of TimeZone class

d) useDaylightTime() of DateTime class

Answer: c

Explanation: public abstract boolean useDaylightTime() is provided in TimeZone class.

What is the replacement of joda time library in java 8?

a) java.time (JSR-310)

b) java.date (JSR-310)

c) java.joda

d) java.jodaTime

Answer: a

Explanation: In java 8, we are asked to migrate to java.time (JSR-310) which is a core part of the JDK which replaces joda library project.

How is Date stored in database?

a) java.sql.Date

b) java.util.Date

c) java.sql.DateTime

d) java.util.DateTime

Answer: a

Explanation: java.sql.Date is the datatype of Date stored in database.

What does LocalTime represent?

a) Date without time

b) Time without Date

c) Date and Time

d) Date and Time with timezone

Answer: b

Explanation: LocalTime of joda library represents time without date

How to get difference between two dates?

a) long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();

b) long diffInMilli = java.time.difference(dateTime1, dateTime2).toMillis();

c) Date diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();

d) Time diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();

Answer: a

Explanation: Java 8 provides a method called between which provides Duration between two times.

How to get UTC time?

a) Time.getUTC();

b) Date.getUTC();

c) Instant.now();

d) TimeZone.getUTC();

Answer: c

Explanation: In java 8, Instant.now() provides current time in UTC/GMT.

Which of these is necessary condition for automatic type conversion in Java?

a) The destination type is smaller than source type

b) The destination type is larger than source type

c) The destination type can be larger or smaller than source type

d) None of the mentioned

Answer: b

Explanation: None.

What is the prototype of the default constructor of this Java class?

public class prototype { }

a) prototype( )

b) prototype(void)

c) public prototype(void)

d) public prototype( )

Answer: d

Explanation: None.

What will be the error in the following Java code?

a) b cannot contain value 100, limited by its range

b) * operator has converted b * 50 into int, which can not be converted to byte without casting

c) b cannot contain value 50

d) No error in this code

Answer: b

Explanation: While evaluating an expression containing int, bytes or shorts, the whole expression is converted to int then evaluated and the result is also of type int.

If an expression contains double, int, float, long, then the whole expression will be promoted into which of these data types?

a) long

b) int

c) double

d) float

Answer: c

Explanation: If any operand is double the result of an expression is double.

What is Truncation is Java?

a) Floating-point value assigned to an integer type

b) Integer value assigned to floating type

c) Floating-point value assigned to an Floating type

d) Integer value assigned to floating type

Answer: a

Explanation: None.

Explanation: None.

What will be the output of the following Java code?

class char_increment { public static void main(String args[]) { char c1 = 'D'; char c2 = 84; c2++; c1++; System.out.println(c1 + " " + c2); } }

a) E U

b) U E

c) V E

d) U F

Answer: a

Explanation: Operator ++ increments the value of character by 1. c1 and c2 are given values D and 84, when we use ++ operator their values increments by 1, c1 and c2 becomes E and U respectively.

output:

$ javac char_increment.java$ java char_incrementE U

What will be the output of the following Java code?

class conversion { public static void main(String args[]) { double a = 295.04; int b = 300; byte c = (byte) a; byte d = (byte) b; System.out.println(c + " " + d); } }

a) 38 43

b) 39 44

c) 295 300

d) 295.04 300

Answer: b

Explanation: Type casting a larger variable into a smaller variable results in modulo of larger variable by range of smaller variable. b contains 300 which is larger than byte’s range i:e -128 to 127 hence d contains 300 modulo 256 i:e 44.

output:

$ javac conversion.java$ java conversion39 44

What will be the output of the following Java code?

class A { final public int calculate(int a, int b) { return 1; } } class B extends A { public int calculate(int a, int b) { return 2; } } public class output { public static void main(String args[]) { B object = new B(); System.out.print("b is " + b.calculate(0, 1)); } }

a) b is : 2

b) b is : 1

c) Compilation Error

d) An exception is thrown at runtime

Answer: c

Explanation: The code does not compile because the method calculate() in class A is final and so cannot be overridden by method of class b.

What will be the output of the following Java program, if we run as “java main_arguments 1 2 3”?

class main_arguments { public static void main(String [] args) { String [][] argument = new String[2][2]; int x; argument[0] = args; x = argument[0].length; for (int y = 0; y < x; y++) System.out.print(" " + argument[0][y]); } }

a) 1 1

b) 1 0

c) 1 0 3

d) 1 2 3

Answer: d

Explanation: In argument[0] = args;, the reference variable arg[0], which was referring to an array with two elements, is reassigned to an array (args) with three elements.

Output:

$ javac main_arguments.java$ java main_arguments1 2 3

What will be the output of the following Java program?

class c { public void main( String[] args ) { System.out.println( "Hello" + args[0] ); } }

a) Hello c

b) Hello

c) Hello world

d) Runtime Error

Answer: d

Explanation: A runtime error will occur owning to the main method of the code fragment not being declared static.

Output:

$ javac c.javaException in thread "main" java.lang.NoSuchMethodError: main

Which of these operators is used to allocate memory to array variable in Java?

a) malloc

b) alloc

c) new

d) new malloc

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.

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

Answer: d

Explanation: Operator new must be succeeded by array type and array size.

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

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

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

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};

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

Explanation: None.

What will be the output of the following Java code?

class array_output { 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

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_output0 2 4 6 8

What will be the output of the following Java code?

class multidimention_array { public static void main(String args[]) { int arr[][] = new int[3][]; arr[0] = new int[1]; arr[1] = new int[2]; arr[2] = new int[3]; int sum = 0; for (int i = 0; i < 3; ++i) for (int j = 0; j < i + 1; ++j) arr[i][j] = j + 1; for (int i = 0; i < 3; ++i) for (int j = 0; j < i + 1; ++j) sum + = arr[i][j]; System.out.print(sum); } }

a) 11

b) 10

c) 13

d) 14

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_array10

What will be the output of the following Java code?

class evaluate { 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.println(arr[n] / 2); } }

a) 3

b) 0

c) 6

d) 1

Answer: d

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

output:

$ javac evaluate.java$ java evaluate1

What will be the output of the following Java code?

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] + ""); } } }

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

Answer: d

Explanation: None.

output:

$ javac array_output.java$ java array_outputi i i i i i i i i i

What will be the output of the following Java 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

Answer: b

Explanation: None.

output:

$ javac array_output.java$ java array_output9

What is the type of variable ‘b’ and ‘d’ in the following Java snippet?

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

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.

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;

Answer: d

Explanation: Operator new must be succeeded by array type and array size. The order is important and determines the type of variable.

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) Garbage value

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].

What will be the output of the following Java code snippet?

Object[] names = new String[3];names[0] = new Integer(0);

a) ArrayIndexOutOfBoundsException

b) ArrayStoreException

c) Compilation Error

d) Code runs successfully

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.

Generics does not work with?

a) Set

b) List

c) Tree

d) Array

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.

How to sort an array?

a) Array.sort()

b) Arrays.sort()

c) Collection.sort()

d) System.sort()

Answer: b

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

How to copy contents of array?

a) System.arrayCopy()

b) Array.copy()

c) Arrays.copy()

d) Collection.copy()

Answer: a

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

Can you make an array volatile?

a) True

b) False

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.

Where is an array stored in memory?

a) heap space

b) stack space

c) heap space and stack space

d) first generation memory

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.

An array elements are always stored in ________ memory locations.

a) Sequential

b) Random

c) Sequential and Random

d) Binary search

Answer: a

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

Which of the following can be operands of arithmetic operators?

a) Numeric

b) Boolean

c) Characters

d) Both Numeric & Characters

Answer: d

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

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

a) Integers

b) Floating – point numbers

c) Both Integers and floating – point numbers

d) None of the mentioned

Answer: c

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

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

Answer: 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.

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

a) 1

b) 2

c) 3

d) 4

Answer: a

Explanation: None.

Which of these statements are incorrect?

a) Assignment operators are more efficiently implemented by Java run-time system than their equivalent long forms

b) Assignment operators run faster than their equivalent long forms

c) Assignment operators can be used only with numeric and character data type

d) None of the mentioned

Answer: d

Explanation: None.

What will be the output of the following Java program?

class increment { public static void main(String args[]) { double var1 = 1 + 5; double var2 = var1 / 4; int var3 = 1 + 5; int var4 = var3 / 4; System.out.print(var2 + " " + var4); } }

a) 1 1

b) 0 1

c) 1.5 1

d) 1.5 1.0

Answer: c

Explanation: None

output:

$ javac increment.java$ java increment1.5 1

What will be the output of the following Java program?

class Modulus { public static void main(String args[]) { double a = 25.64; int b = 25; a = a % 10; b = b % 10; System.out.println(a + " " + b); } }

a) 5.640000000000001 5

b) 5.640000000000001 5.0

c) 5 5

d) 5 5.640000000000001

Answer: a

Explanation: Modulus operator returns the remainder of a division operation on the operand. a = a % 10 returns 25.64 % 10 i:e 5.640000000000001. Similarly b = b % 10 returns 5.

output:

$ javac Modulus.java$ java Modulus5.640000000000001 5

What will be the output of the following Java program?

class increment { public static void main(String args[]) { int g = 3; System.out.print(++g * 8); } }

a) 25

b) 24

c) 32

d) 33

Answer: c

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

output:

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

a) True

b) False

Answer: a

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

What will be the output of the following Java program?

class Output { public static void main(String args[]) { int a = 1; int b = 2; int c; int d; c = ++b; d = a++; c++; b++; ++a; System.out.println(a + " " + b + " " + c); } }

a) 3 2 4

b) 3 2 3

c) 2 3 4

d) 3 4 4

Answer: d

Explanation: None.

output:

Which of these is not a bitwise operator?

a) &

b) &=

c) |=

d) <=

Answer: d

Explanation: <= is a relational operator.

Which operator is used to invert all the digits in a binary representation of a number?

a) ~

b) <<<

c) >>>

d) ^

Answer: a

Explanation: Unary not operator, ~, inverts all of the bits of its operand in binary representation.

On applying Left shift operator, <<, on integer bits are lost one they are shifted past which position bit?

a) 1

b) 32

c) 33

d) 31

Answer: d

Explanation: The left shift operator shifts all of the bits in a value to the left specified number of times. For each shift left, the high order bit is shifted out and lost, zero is brought in from the right. When a left shift is applied to an integer operand, bits are lost once they are shifted past the bit position 31.

Which right shift operator preserves the sign of the value?

a) <<

b) >>

c) <<=

d) >>=

Answer: b

Explanation: None.

Which of these statements are incorrect?

a) The left shift operator, <<, shifts all of the bits in a value to the left specified number of times

b) The right shift operator, >>, shifts all of the bits in a value to the right specified number of times

c) The left shift operator can be used as an alternative to multiplying by 2

d) The right shift operator automatically fills the higher order bits with 0

Answer: d

Explanation: The right shift operator automatically fills the higher order bit with its previous contents each time a shift occurs. This also preserves the sign of the value.

What will be the output of the following Java program?

class bitwise_operator { public static void main(String args[]) { int var1 = 42; int var2 = ~var1; System.out.print(var1 + " " + var2); } }

a) 42 42

b) 43 43

c) 42 -43

d) 42 43

Answer: c

Explanation: Unary not operator, ~, inverts all of the bits of its operand. 42 in binary is 00101010 in using ~ operator on var1 and assigning it to var2 we get inverted value of 42 i:e 11010101 which is -43 in decimal.

output:

What will be the output of the following Java program?

class bitwise_operator { public static void main(String args[]) { int a = 3; int b = 6; int c = a | b; int d = a & b; System.out.println(c + " " + d); } }

a) 7 2

b) 7 7

c) 7 5

d) 5 2

Answer: a

Explanation: And operator produces 1 bit if both operand are 1. Or operator produces 1 bit if any bit of the two operands in 1.

output:

What will be the output of the following Java program?

class leftshift_operator { public static void main(String args[]) { byte x = 64; int i; byte y; i = x << 2; y = (byte) (x << 2) System.out.print(i + " " + y); } }

a) 0 64

b) 64 0

c) 0 256

d) 256 0

Answer: d

Explanation: None.

output:

What will be the output of the following Java program?

class rightshift_operator { public static void main(String args[]) { int x; x = 10; x = x >> 1; System.out.println(x); } }

a) 10

b) 5

c) 2

d) 20

Answer: b

Explanation: Right shift operator, >>, devides the value by 2.

output:

What will be the output of the following Java program?

class Output { public static void main(String args[]) { int a = 1; int b = 2; int c = 3; a |= 4; b >>= 1; c <<= 1; a ^= c; System.out.println(a + " " + b + " " + c); } }

a) 3 1 6

b) 2 2 3

c) 2 3 4

d) 3 3 6

Answer: a

Explanation: None

What is the output of relational operators?

a) Integer

b) Boolean

c) Characters

d) Double

Answer: b

Explanation: None.

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

Answer: c

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

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

a) 3 & 2

b) 1 & 4

c) 1, 2 & 4

d) 1, 2 & 3

Answer: 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.

Which of these operators can skip evaluating right hand operand?

a) !

b) |

c) &

d) &&

Answer: d

Explanation: Operator short circuit and, &&, and short circuit or, ||, skip evaluating right hand operand when output can be determined by left operand alone.

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

Answer: 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.

What will be the output of the following Java code?

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

Answer: d

Explanation: Operator > returns a boolean value. 5 is not greater than 6 therefore false is returned.

output:

What will be the output of the following Java code?

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

Answer: d

Explanation: Operator > returns a boolean value. 5 is not greater than 6 therefore false is returned.

output:

$ javac Relational_operator.java$ java Relational_operatorfalse

This section of our 1000+ Java MCQs focuses on assignment operators and operator precedence in Java Programming Language.

1. Which of these have highest precedence?

a) ()

b) ++

c) *

Answer: a

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

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

Answer: c

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

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

int x, y, z; x = 0; y = 1; x = y = z = 8;

a) 0

b) 1

c) 9

d) 8

Answer: d

Explanation: None

What is the order of precedence (highest to lowest) of following operators?

a) 1 -> 2 -> 3

b) 2 -> 1 -> 3

c) 3 -> 2 -> 1

d) 2 -> 3 -> 1

Answer: a

Explanation: None.

Which of these statements are incorrect?

a) Equal to operator has least precedence

b) Brackets () have highest precedence

c) Division operator, /, has higher precedence than multiplication operator

d) Addition operator, +, and subtraction operator have equal precedence

Answer: c

Explanation: Division operator, /, has equal precedence as of multiplication operator. In expression involving multiplication and division evaluation of expression will begin from the right side when no brackets are used.

What will be the output of the following Java code?

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

Answer: 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.

Which of these have highest precedence?

a) ()

b) ++

c) *

d) >>

Answer: a

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

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

Answer: c

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

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

int x, y, z; x = 0; y = 1; x = y = z = 8;

a) 0

b) 1

c) 9

d) 8

Answer: d

Explanation: None.

What is the order of precedence (highest to lowest) of following operators?

a) 1 -> 2 -> 3

b) 2 -> 1 -> 3

c) 3 -> 2 -> 1

d) 2 -> 3 -> 1

Answer: a

Explanation: None.

Which of these statements are incorrect?

a) Equal to operator has least precedence

b) Brackets () have highest precedence

c) Division operator, /, has higher precedence than multiplication operator

d) Addition operator, +, and subtraction operator have equal precedence

Answer: c

Explanation: Division operator, /, has equal precedence as of multiplication operator. In expression involving multiplication and division evaluation of expression will begin from the right side when no brackets are used.

What will be the output of the following Java code?

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

Answer: 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.

Which of these selection statements test only for equality?

a) if

b) switch

c) if & switch

d) none of the mentioned

Answer: b

Explanation: Switch statements checks for equality between the controlling variable and its constant cases.

Which of these are selection statements in Java?

a) if()

b) for()

c) continue

d) break

Answer: a

Explanation: Continue and break are jump statements, and for is a looping statement.

Which of the following loops will execute the body of loop even when condition controlling the loop is initially false?

a) do-while

b) while

c) for

d) none of the mentioned

Answer: a

Explanation: None.

Which of these jump statements can skip processing the remainder of the code in its body for a particular iteration?

a) break

b) return

c) exit

d) continue

Answer: d

Explanation: None.

Which of this statement is incorrect?

a) switch statement is more efficient than a set of nested ifs

b) two case constants in the same switch can have identical values

c) switch statement can only test for equality, whereas if statement can evaluate any type of boolean expression

d) it is possible to create a nested switch statements

Answer: b

Explanation: No two case constants in the same switch can have identical values.

What will be the output of the following Java program?

class Output { public static void main(String args[]) { final int a=10,b=20; while(a<b) { System.out.println("Hello"); } System.out.println("World"); } }

a) Hello

b) run time error

c) Hello world

d) compile time error

Answer: d

What would be the output of the following code snippet if variable a=10?

if(a<=0){ if(a==0) { System.out.println("1 "); } else { System.out.println("2 "); }}System.out.println("3 ");

a) 1 2

b) 2 3

c) 1 3

d) 3

Answer: d

Explanation: Since the first if condition is not met, control would not go inside if statement and hence only statement after the entire if block will be executed.

The while loop repeats a set of code while the condition is not met?

a) True

b) False

Answer: b

Explanation: While loop repeats a set of code only until the condition is met.

What is true about a break?

a) Break stops the execution of entire program

b) Break halts the execution and forces the control out of the loop

c) Break forces the control out of the loop and starts the execution of next iteration

d) Break halts the execution of the loop for certain time frame

Answer: b

What is true about do statement?

a) do statement executes the code of a loop at least once

b) do statement does not get execute if condition is not matched in the first iteration

c) do statement checks the condition at the beginning of the loop

d) do statement executes the code more than once always

Answer: a

Explanation: Do statement checks the condition at the end of the loop. Hence, code gets executed at least once.

Which of the following is used with the switch statement?

a) Continue

b) Exit

c) break

d) do

Answer: c

Explanation: Break is used with a switch statement to shift control out of switch.

Which of the following is not OOPS concept in Java?

a) Inheritance

b) Encapsulation

c) Polymorphism

d) Compilation

Answer: d

Explanation: There are 4 OOPS concepts in Java. Inheritance, Encapsulation, Polymorphism and Abstraction.

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

Answer: a

Explanation: There are two types of polymorphism in Java. Compile time polymorphism (overloading) and runtime polymorphism (overriding).

When does method overloading is determined?

a) At run time

b) At compile time

c) At coding time

d) At execution time

Answer: b

Explanation: Overloading is determined at compile time. Hence, it is also known as compile time polymorphism.

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

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.

Which concept of Java is a way of converting real world objects in terms of class?

a) Polymorphism

b) Encapsulation

c) Abstraction

d) Inheritance

Answer: c

Explanation: Abstraction is the concept of defining real world objects in terms of classes or interfaces.

Which concept of Java is achieved by combining methods and attribute into a class?

a) Encapsulation

b) Inheritance

c) Polymorphism

d) Abstraction

Answer: a

Explanation: Encapsulation is implemented by combining methods and attribute into a class. The class acts like a container of encapsulating properties.

What is it called if an object has its own lifecycle and there is no owner?

a) Aggregation

b) Composition

c) Encapsulation

d) Association

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.

What is it called where child object gets killed if parent object is killed?

a) Aggregation

b) Composition

c) Encapsulation

d) Association

Answer: b

Explanation: Composition occurs when child object gets killed if parent object gets killed. Aggregation is also known as strong Aggregation.

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

Answer: a

Explanation: Aggregation occurs when objects have their own life cycle and child object can associate with only one parent object.

Method overriding is combination of inheritance and polymorphism?

a) True

b) false

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.

Which component is used to compile, debug and execute java program?

a) JVM

b) JDK

c) JIT

d) JRE

Answer: b

Explanation: JDK is a core component of Java Environment and provides all the tools, executables and binaries required to compile, debug and execute a Java Program.

Which component is responsible for converting bytecode into machine specific code?

a) JVM

b) JDK

c) JIT

d) JRE

Answer: a

Explanation: JVM is responsible to converting bytecode to the machine specific code. JVM is also platform dependent and provides core java functions like garbage collection, memory management, security etc.

Which component is responsible to optimize bytecode to machine code?

a) JVM

b) JDK

c) JIT

d) JRE

Answer: c

Explanation: JIT optimizes bytecode to machine specific language code by compiling similar bytecodes at the same time.

What is the stored in the object obj in following lines of Java code?

a) Memory address of allocated memory of object

b) NULL

c) Any arbitrary pointer

d) Garbage

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.

Which of these keywords is used to make a class?

a) class

b) struct

c) int

d) none of the mentioned

Answer: a

Explanation: None.

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;

Answer: a

Explanation: None.

Which of these operators is used to allocate memory for an object?

a) malloc

b) alloc

c) new

d) give

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.

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

Answer: a

Explanation: Every class does not need to have a main() method, there can be only one main() method which is made public.

What will be the output of the following Java program?

class main_class { public static void main(String args[]) { int x = 9; if (x == 9) { int x = 8; System.out.println(x); } } }

a) 9

b) 8

c) Compilation error

d) Runtime error

Answer: c

Explanation: Two variables with the same name can’t be created in a class.

What is the return type of a method that does not return any value?

a) int

b) float

c) void

d) double

Answer: c

Explanation: Return type of a method must be made void if it is not returning any value

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

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.

Which of the following is a method having same name as that of it’s class?

a) finalize

b) delete

c) class

d) constructor

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.

Which method can be defined only once in a program?

a) main method

b) finalize method

c) static method

d) private method

Answer: a

Explanation: main() method can be defined only once in a program. Program execution begins from the main() method by java runtime system.

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

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.

What is the return type of Constructors?

a) int

b) float

c) void

d) none of the mentioned

Answer: d

Explanation: Constructors does not have any return type, not even void.

Which keyword is used by the method to refer to the object that invoked it?

a) import

b) catch

c) abstract

d) this

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.

Which of the following is a method having same name as that of its class?

a) finalize

b) delete

c) class

d) constructor

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.

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

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.

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

Answer: a

Explanation: None.

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

Answer: a

Explanation: Object of private constructor can only be created within class. Private constructor is used in singleton pattern.

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

Answer: c

Explanation: this() and super() cannot be used in a method. This throws compile time error.

What is false about constructor?

a) Constructors cannot be synchronized in Java

b) Java does not provide default copy constructor

c) Constructor can be overloaded

d) “this” and “super” can be used in a constructor

Answer: c

Explanation: Default, parameterised constructors can be defined.

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

Answer: d

Explanation: Class class provides list of methods for use like getInstance().

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

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.

Abstract class cannot have a constructor.

a) True

b) False

Answer: b

Explanation: No instance can be created of abstract class. Only pointer can hold instance of object.

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

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.

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

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.

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

Answer: d

Explanation: The class compiles successfully. But the object creation of that class gives a compilation error.

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

Answer: a

Explanation: The constructor cannot have a return type. It should create and return new object. Hence it would give compilation error.

Which of the following has the highest memory requirement?

a) Heap

b) Stack

c) JVM

d) Class

Answer: c

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

Where is a new object allocated memory?

a) Young space

b) Old space

c) Young or Old space depending on space availability

d) JVM

Answer: 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.

Which of the following is a garbage collection technique?

a) Cleanup model

b) Mark and sweep model

c) Space management model

d) Sweep model

Answer: 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.

What is -Xms and -Xmx while starting jvm?

a) Initial; Maximum memory

b) Maximum; Initial memory

c) Maximum memory

d) Initial memory

Answer: 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.

Which exception is thrown when java is out of memory?

a) MemoryFullException

b) MemoryOutOfBoundsException

c) OutOfMemoryError

d) MemoryError

Answer: c

Explanation: The Xms flag has no default value, and Xmx typically has a default value of 256MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.

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

a) jmap

b) memorymap

c) memorypath

d) jvmmap

Answer: a

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

What happens to the thread when garbage collection kicks off?

a) The thread continues its operation

b) Garbage collection cannot happen until the thread is running

c) The thread is paused while garbage collection runs

d) The thread and garbage collection do not interfere with each other

Answer: c

Explanation: The thread is paused when garbage collection runs which slows the application performance.

Which of the below is not a Java Profiler?

a) JVM

b) JConsole

c) JProfiler

d) Eclipse Profiler

Answer: 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.

Which of the below is not a memory leak solution?

a) Code changes

b) JVM parameter tuning

c) Process restart

d) GC parameter tuning

Answer: c

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

Garbage Collection can be controlled by a program?

a) True

b) False

Answer: b

Explanation: Garbage Collection cannot be controlled by a program.

What is the process of defining two or more methods within same class that have same name but different parameters declaration?

a) method overloading

b) method overriding

c) method hiding

d) none of the mentioned

Answer: a

Explanation: Two or more methods can have same name as long as their parameters declaration is different, the methods are said to be overloaded and process is called method overloading. Method overloading is a way by which Java implements polymorphism.

Which of these can be overloaded?

a) Methods

b) Constructors

c) All of the mentioned

d) None of the mentioned

Answer: c

Explanation: None.

Which of these is correct about passing an argument by call-by-value process?

a) Copy of argument is made into the formal parameter of the subroutine

b) Reference to original argument is passed to formal parameter of the subroutine

c) Copy of argument is made into the formal parameter of the subroutine and changes made on parameters of subroutine have effect on original argument

d) Reference to original argument is passed to formal parameter of the subroutine and changes made on parameters of subroutine have effect on original argument

Answer: a

Explanation: When we pass an argument by call-by-value a copy of argument is made into the formal parameter of the subroutine and changes made on parameters of subroutine have no effect on original argument, they remain the same.

What is the process of defining a method in terms of itself, that is a method that calls itself?

a) Polymorphism

b) Abstraction

c) Encapsulation

d) Recursion

Answer: d

Explanation: None.

Which of these access specifiers must be used for main() method?

a) private

b) public

c) protected

d) none of the mentioned

Answer: b

Explanation: main() method must be specified public as it called by Java run time system, outside of the program. If no access specifier is used then by default member is public within its own package & cannot be accessed by Java run time system.

Which of these is used to access a member of class before object of that class is created?

a) public

b) private

c) static

d) protected

Answer: c

Explanation: None.

Which of these is used as a default for a member of a class if no access specifier is used for it?

a) private

b) public

c) public, within its own package

d) protected

Answer: a

Explanation: When we pass an argument by call-by-value a copy of argument is made into the formal parameter of the subroutine and changes made on parameters of subroutine have no effect on original argument, they remain the same.

What is the process by which we can control what parts of a program can access the members of a class?

a) Polymorphism

b) Abstraction

c) Encapsulation

d) Recursion

Answer: c

Explanation: None.

Which of the following statements are incorrect?

a) public members of class can be accessed by any code in the program

b) private members of class can only be accessed by other members of the class

c) private members of class can be inherited by a subclass, and become protected members in subclass

d) protected members of a class can be inherited by a subclass, and become private members of the subclass

Answer: c

Explanation: private members of a class can not be inherited by a subclass.

Which one of the following is not an access modifier?

a) Public

b) Private

c) Protected

d) Void

Answer: d

Explanation: Public, private, protected and default are the access modifiers.

All the variables of class should be ideally declared as?

a) private

b) public

c) protected

d) default

Answer: a

Explanation: The variables should be private and should be accessed with get and set methods.

Which of the following modifier means a particular variable cannot be accessed within the package?

a) private

b) public

c) protected

d) default

Answer: a

Explanation: Private variables are accessible only within the class.

How can a protected modifier be accessed?

a) accessible only within the class

b) accessible only within package

c) accessible within package and outside the package but through inheritance only

d) accessible by all

Answer: c

Explanation: The protected access modifier is accessible within package and outside the package but only through inheritance. The protected access modifier can be used with data member, method and constructor. It cannot be applied in the class.

What happens if constructor of class A is made private?

a) Any class can instantiate objects of class A

b) Objects of class A can be instantiated only within the class where it is declared

c) Inherited class can instantiate objects of class A

d) classes within the same package as class A can instantiate objects of class A

Answer: b

Explanation: If we make any class constructor private, we cannot create the instance of that class from outside the class.

All the variables of interface should be?

a) default and final

b) default and static

c) public, static and final

d) protect, static and final

Answer: c

Explanation: Variables of an interface are public, static and final by default because the interfaces cannot be instantiated, final ensures the value assigned cannot be changed with the implementing class and public for it to be accessible by all the implementing classes.

What is true of final class?

a) Final class cause compilation failure

b) Final class cannot be instantiated

c) Final class cause runtime failure

d) Final class cannot be inherited

Answer: d

Explanation: Final class cannot be inherited. This helps when we do not want classes to provide extension to these classes.

How many copies of static and class variables are created when 10 objects are created of a class?

a) 1, 10

b) 10, 10

c) 10, 1

d) 1, 1

Answer: a

Explanation: Only one copy of static variables are created when a class is loaded. Each object instantiated has its own copy of instance variables.

Can a class be declared with a protected modifier.

a) True

b) False

Answer: b

Explanation: Protected class member (method or variable) is like package-private (default visibility), except that it also can be accessed from subclasses. Since there is no such concept as ‘subpackage’ or ‘package-inheritance’ in Java, declaring class protected or package-private would be the same thing.

Which is the modifier when there is none mentioned explicitly?

a) protected

b) private

c) public

d) default

Answer: d

Explanation: Default is the access modifier when none is defined explicitly. It means the member (method or variable) can be accessed within the same package.

Arrays in Java are implemented as?

a) class

b) object

c) variable

d) none of the mentioned

Answer: b

Explanation: None.

Which of these keywords is used to prevent content of a variable from being modified?

a) final

b) last

c) constant

d) static

Answer: a

Explanation: A variable can be declared final, doing so prevents its content from being modified. Final variables must be initialized when it is declared.

Which of these cannot be declared static?

a) class

b) object

c) variable

d) method

Answer: b

Explanation: static statements are run as soon as class containing then is loaded, prior to any object declaration.

Which of the following statements are incorrect?

a) static methods can call other static methods only

b) static methods must only access static data

c) static methods can not refer to this or super in any way

d) when object of class is declared, each object contains its own copy of static variables

Answer: d

Explanation: All objects of class share same static variable, when object of a class are declared, all the objects share same copy of static members, no copy of static variables are made.

Which of the following statements are incorrect?

a) Variables declared as final occupy memory

b) final variable must be initialized at the time of declaration

c) Arrays in java are implemented as an object

d) All arrays contain an attribute-length which contains the number of elements stored in the array

Answer: a

Explanation: None.

Which of these methods must be made static?

a) main()

b) delete()

c) run()

d) finalize()

Answer: a

Explanation: main() method must be declared static, main() method is called by Java runtime system before any object of any class exists.

What will be the output of the following Java program?

class Output { public static void main(String args[]) { int a1[] = new int[10]; int a2[] = {1, 2, 3, 4, 5}; System.out.println(a1.length + " " + a2.length); } }

a) 10 5

b) 5 10

c) 0 10

d) 0 5

Answer: a

String in Java is a?

a) class

b) object

c) variable

d) character array

Answer: a

Explanation: None.

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

a) char()

b) Charat()

c) charat()

d) charAt()

Answer: d

Explanation: None.

Which of these keywords is used to refer to member of base class from a subclass?

a) upper

b) super

c) this

d) none of the mentioned

Answer: b

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

Which of these method of String class can be used to test to strings for equality?

a) isequal()

b) isequals()

c) equal()

d) equals()

Answer: d

Explanation: None.

Which of the following statements are incorrect?

a) String is a class

b) Strings in java are mutable

c) Every string is an object of class String

d) Java defines a peer class of String, called StringBuffer, which allows string to be altered

Answer: b

Explanation: Strings in Java are immutable that is they can not be modified.

What will be the output of the following Java program?

class string_demo { public static void main(String args[]) { String obj = "I" + "like" + "Java"; System.out.println(obj); } }

a) I

b) like

c) Java

d) IlikeJava

Answer: d

Which of these is the method which is executed first before execution of any other thing takes place in a program?

a) main method

b) finalize method

c) static method

d) private method

Answer: c

Explanation: If a static method is present in the program then it will be executed first, then main will be executed.

What is the process of defining more than one method in a class differentiated by parameters?

a) Function overriding

b) Function overloading

c) Function doubling

d) None of the mentioned

Answer: b

Which of these can be used to differentiate two or more methods having the same name?

a) Parameters data type

b) Number of parameters

c) Return type of method

d) All of the mentioned

Answer: d

Explanation: None.

Which of these data type can be used for a method having a return statement in it?

a) void

b) int

c) float

d) both int and float

Answer: d

Explanation: None

Which of these statement is incorrect?

a) Two or more methods with same name can be differentiated on the basis of their parameters data type

b) Two or more method having same name can be differentiated on basis of number of parameters

c) Any already defined method in java library can be defined again in the program with different data type of parameters

d) If a method is returning a value the calling statement must have a variable to store that value

Answer: d

Explanation: Even if a method is returning a value, it is not necessary to store that value.

What will be the output of the following Java program?

class box { int width; int height; int length; int volume; void volume(int height, int length, int width) { volume = width * height * length; } } class Prameterized_method{ public static void main(String args[]) { box obj = new box(); obj.height = 1; obj.length = 5; obj.width = 5; obj.volume(3, 2, 1); System.out.println(obj.volume); } }

a) 0

b) 1

c) 6

d) 25

Answer: c

Explanation: None

Which of this method is given parameter via command line arguments?

a) main()

b) recursive() method

c) Any method

d) System defined methods

Answer: a

Explanation: Only main() method can be given parameters via using command line arguments.

Which of these data types is used to store command line arguments?

a) Array

b) Stack

c) String

d) Integer

Answer: c

Explanation: None.

How many arguments can be passed to main()?

a) Infinite

b) Only 1

c) System Dependent

d) None of the mentioned

Answer: a

Explanation: None.

Which of these is a correct statement about args in the following line of code?

public static void main(String args[])

a) args is a String

b) args is a Character

c) args is an array of String

Answer: c

Explanation: args in an array of String.

Can command line arguments be converted into int automatically if required?

a) Yes

b) No

c) Compiler Dependent

d) Only ASCII characters can be converted

Answer: b

Explanation: All command Line arguments are passed as a string. We must convert numerical value to their internal forms manually.

What will be the output of the following Java program, Command line execution is done as – “javaOutput This is a command Line”?

class Output { public static void main(String args[]) { System.out.print("args[0]"); } }

a) java

b) Output

c) This

d) is

Answer: c

Explanation: None.

What will be the output of the following Java snippet, if attempted to compile and run this codewith command line argument “java abc Rakesh Sharma”?

public class abc{ int a=2000; public static void main(String argv[]) { System.out.println(argv[1]+" :-Please pay Rs."+a); }}

a) Compile time error

b) Compilation but runtime error

c) Compilation and output Rakesh :-Please pay Rs.2000

d) Compilation and output Sharma :-Please pay Rs.2000

Answer: a

Explanation: Main method is static and cannot access non static variable a.

What will be the output of the following Java snippet, if attempted to compile and execute?

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

Answer: d

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

What will be the output of the following Java snippet, if compiled and executed with command ine argument “java abc 1 2 3”?

public class abc{ static public void main(String [] xyz) { for(int n=1;n<xyz.length; n++) { System.out.println(xyz[n]+""); } }}

a) 1 2

b) 2 3

c) 1 2 3

d) Compilation error

Answer: b

What is Recursion in Java?

a) Recursion is a class

b) Recursion is a process of defining a method that calls other methods repeatedly

c) Recursion is a process of defining a method that calls itself repeatedly

d) Recursion is a process of defining a method that calls other methods which in turn call again this method

Answer: b

Explanation: Recursion is the process of defining something in terms of itself. It allows us to define a method that calls itself.

Which of these data types is used by operating system to manage the Recursion in Java?

a) Array

b) Stack

c) Queue

d) Tree

View Answer

Answer: b

Explanation: Recursions are always managed by using stack.

Which of these data types is used by operating system to manage the Recursion in Java?

a) Array

b) Stack

c) Queue

d) Tree

Answer: b

Explanation: Recursions are always managed by using stack.

Which of these will happen if recursive method does not have a base case?

a) An infinite loop occurs

b) System stops the program after some time

c) After 1000000 calls it will be automatically stopped

d) None of the mentioned

View Answer

Answer: a

Explanation: If a recursive method does not have a base case then an infinite loop occurs which results in Stack Overflow.

Which of these is not a correct statement?

a) A recursive method must have a base case

b) Recursion always uses stack

c) Recursive methods are faster that programmers written loop to call the function repeatedly using a stack

d) Recursion is managed by Java Runtime environment

Answer: d

Explanation: Recursion is always managed by operating system.

Which of these packages contains the exception Stack Overflow in Java?

a) java.lang

b) java.util

c) java.io

d) java.system

Answer: a

Explanation: None.

What is the process of defining a method in terms of itself?

The process of defining a method in terms of itself is called RECURSION. AND THE FUNCTIONS ARE CALLED AS 'RECURSIVE FUNCTIONS'.

What is a recursive method?

A method or algorithm that repeats steps by using one or more loops. recursive: A method or algorithm that invokes itself one or more times with different arguments. base case: A condition that causes a recursive method not to make another recursive call.

What is the process of defining a method in a subclass?

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

What is the process of defining two or more methods?

The practice of defining two or more methods within the same class that share the same name but have different parameters is called overloading methods.