Java Questions & Answers – Integer and Floating Data Types

Jio
By -
0
Text Example

Java Questions & Answers – Integer and Floating Data Types


1. What is the range of short data type in Java?

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?

b) -32768 to 32767

c) -2147483648 to 2147483647

Explanation:Byte occupies 8 bits in memory. Its range is from -128 to 127.

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

b) long

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

1. What is the numericalrange of a char data type in Java?

c) 0 to 32767

1. enum Season {

2. WINTER, SPRING, SUMMER, FALL

3. };

4. System.out.println(Season.WINTER.ordinal());

1. What is the order of variables in Enum?

a) Ascending order

b) Descending order

c) Random order

d) depends on the order() method

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

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

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

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

numericalrange of a char data type in Java?

a) -128 to 127

b) 0 to 256

c) 0 t o 32767

d) 0 to 65535

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

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

c) UNICODE

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.

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

a) True & False

c) Any integer value

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

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

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

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

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

a) i i i i i

b) 0 1 2 3 4

Java Questions & Answers – Character and Boolean Data Types

c) i j k l m

i i i i i

a) 66

b) 67

c) 65

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

66

Explanation: boolean ‘&’ operator always returns true or false. var1 is defined true and var2 is defined false hence their ‘&’ operator result is

$ javac booloperators.java

$ java booloperators

a) 162

b) 65 97

c) 67 95

d) 66 98

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

$ javac asciicodes.java

$ java asciicodes

65 97

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

Explanation: Enum does not have a public constructor.

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

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

3.

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

a) Syntax

b) Memory usage

c) Garbage creation

d) Precision

Explanation:BigDecimal has unnaturalsyntax, needs more memory and creates a great amount of garbage. But it has a high precision which is

usefulfor some calculations like money.

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

d) BigDecimal

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

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

4. What is the base of BigDecimal data type?

a) Base 2

b) Base 8

c) Base 10

d) Base e

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.

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

Explanation: toString() of BigDecimal uses scientific notation to represent numbers known as canonicalrepresentation. We must use

toPlainString() to avoid scientific notation.

6. Which of the following is not provided by BigDecimal?

a) scale manipulation

b) + operator

c) rounding

d) hashing

Java Questions & Answers – Data Type-BigDecimal

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

lost information.

7. BigDecimal is a part of which package?

b) java.math

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

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

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

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

a) MathContext

b) MathLib

c) BigLib

d) BigContext

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

d) Runtime exception

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

1. How to format date from one form to another?

a) SimpleDateFormat

b) DateFormat

c) SimpleFormat

d) DateConverter

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

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

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

4. Is SimpleDateFormat thread safe?

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

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

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

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

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.

7. How is Date stored in database?

a) java.sql.Date

b) java.util.Date

Java Questions & Answers – Data Type-Date, TimeZone

c) java.sql.DateTime

d) java.util.DateTime

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

8. What does LocalTime represent?

a) Date without time

b) Time without Date

c) Date and Time

d) Date and Time with timezone

Explanation: LocalTime of joda library represents time without date.

9. 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();

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

10. How to get UTC time?

a) Time.getUTC();

b) Date.getUTC();

c) Instant.now();

d) TimeZone.getUTC();

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

1. Which of these is long data type literal?

a) 0x99fffL

b) ABCDEFG

c) 0x99fffa

d) 99671246

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

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

c) Character

d) Integer or Boolean

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

3. Literals in java must be appended by which of these?

a) L

b) l

c) D

d) Land I

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

4. Literal can be of which of these data types?

a) integer

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

a) identifier

b) keyword

c) identifier & keyword

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

a) 38

b) 39

c) 40

Java Questions & Answers – Literals & Variables

d) 41

40

b) 1 2 3 4 5

1 2 3 4 5

a) 5 6 5 6

b) 5 6 5

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

$ javac variable_scope.java

Exception in thread "main" java.lang.Error: Unresolved compilation problem: y cannot be resolved to a variable

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

b) 25.0

c) 7.0

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

$ javac dynamic_initialization.java

$ java dynamic_initialization

5.0

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

a) prototype( )

b) prototype(void)

c) public prototype(void)

d) public prototype( )

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

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.

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

a) long

d) float

Java Questions & Answers – Type Conversions, Promotions and Castings

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

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

a) E U

b) U E

c) V E

d) U F

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.

$ javac char_increment.java

$ java char_increment

E U

a) 38 43

b) 39 44

c) 295 300

d) 295.04 300

Explanation: Type casting a larger variable into a smaller variable results in modulo of larger variable by range ofsmaller 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.

$ javac conversion.java

$ java conversion

39 44

a) b is : 2

b) b is : 1

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.

b) 1 0

c) 1 0 3

d) 1 2 3

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.

$ javac main_arguments.java

$ java main_arguments

3. What is the error in this code?

byte b = 50;

b = b * 50;

a) Hello c

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

$ javac c.java

Exception in thread "main" java.lang.NoSuchMethodError: main

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

d) new malloc

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.

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

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

d) Class [email protected] hashcode in hexadecimalform

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

form:

in hexadecimalform

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

Java Questions & Answers – Arrays

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

5. Which of these is necessary to specify at time of array initialization?

a) Row

b) Column

c) Both Row and Column

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

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

0 2 4 6 8

a) 11

c) 13

d) 14

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.

$ javac multidimention_array.java

$ java multidimention_array

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.

$ javac evaluate.java

$ java evaluate

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

i i i i i i i i i i

3. What will this code print?

int arr[] = new int [5];

System.out.print(arr);

b) 9

c) 10

d) 11

$ javac array_output.java

$ java array_output

9

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

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.

d) int arr[] = int [5] new;

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

b) value stored in arr[0].

c) 00000

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

a) ArrayIndexOutOfBoundsException

b) ArrayStoreException

d) Code runs successfully

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.

5. Generics does not work with?

Java Questions & Answers – Data Structures-Arrays

c) Tree

d) Array

Explanation: Generics gives the flexibility to strongly typecast collections. Generics is applicable to Set, List and Tree. It is not applicable to

Array.

6. How to sort an array?

a) Array.sort()

b) Arrays.sort()

c) Collection.sort()

d) System.sort()

7. How to copy contents of array?

a) System.arrayCopy()

b) Array.copy()

c) Arrays.copy()

d) Collection.copy()

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

8. Can you make an array volatile?

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.

9. Where is array stored in memory?

a) heap space

b) stack space

c) heap space and stack space

d) first generation memory

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.

1. int arr[] = new int [5];

2. System.out.print(arr);

10. An array elements are always stored in ________ memory locations?

a) Sequential

b) Random

c) Sequential and Random

d) Binary search

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

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

a) Numeric

d) Both Numeric & Characters

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?

c) Both Integers and floating – point numbers

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

a) 1, 2 & 3

c) 1, 2, 3 & 4

d) 3 & 2

Explanation: Operator ++ increases value of variable by 1. x = x + 1 can also be written in shorthand form as x += 1. Also x =+ 1 willset the

value of x to 1.

Java Questions & Answers – Arithmetic Operators

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

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

a) 1 1

b) 0 1

c) 1.5 1

d) 1.5 1.0

1.5 1

a) 5.640000000000001 5

b) 5.640000000000001 5.0

c) 5 5

d) 5 5.640000000000001

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.

$ javac Modulus.java

$ java Modulus

5.640000000000001 5

a) 25

b) 24

d) 33

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

$ javac increment.java

$ java increment

32

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

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.

3. With x = 0, which of the following are legal lines ofJava code for changing the value of x to 1?

1. x++;

2. x = x + 1;

3. x += 1;

4. x =+ 1;

a) 3 2 4

b) 3 2 3

d) 3 4 4

3 4 4

1. Which of these is not a bitwise operator?

a) &

b) &=

c) |=

d) <=

Explanation: <= is a relational operator.

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

a) ~

b) <<<

c) >>>

d) ^

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

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

b) 32

c) 33

d) 31

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.

4. Which right shift operator preserves the sign of the value?

a) <<

b) >>

c) <<=

d) >>=

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

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.

Java Questions & Answers – Bitwise Operators

a) 42 42

b) 43 43

c) 42 -43

d) 42 43

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.

42 -43

a) 7 2

b) 7 7

c) 7 5

d) 5 2

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.

$ javac bitwise_operator.java

$ java bitwise_operator

7 2

a) 0 64

b) 64 0

c) 0 256

d) 256 0

$ javac leftshift_operator.java

$ java leftshift_operator

256 0

d) 20

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

$ javac rightshift_operator.java

$ java rightshift_operator

a) 3 1 6

c) 2 3 4

d) 3 3 6

3 1 6

1. What is the output of relational operators?

c) Characters

2. Which of these is returned by “greater than”, “less than” and “equal to” operators?

a) Integers

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

a) 3 & 2

b) 1 & 4

c) 1, 2 & 4

d) 1, 2 & 3

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.

Java Questions & Answers – Relational Operators and Boolean Logic Operators

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

a) !

b) |

d) &&

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

operand alone.

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

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.

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

$ javac Relational_operator.java

$ java Relational_operator

b) true ture

Explanation: Operator | returns true if any one operand is true, thus ‘c = true | false’ is true. Operator & returns a true if both of the operand is

true thus d is false. Ternary operator ?: assigns left of ‘:’ if condition is true and right hand of ‘:’ if condition is false. d is false thus e = d ? b : c ,

assigns c to e , e contains true.

$ javac bool_operator.java

$ java bool_operator

d) -4

$ javac ternary_operator.java

$ java ternary_operator

c) Runtime error owing to division by zero in if condition

d) Unpredictable behavior of program

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.

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

1. &&

2. ==

3. ?:

4. +=

c) false

d) true

1. Which of these have highest precedence?

a) ()

b) ++

c) *

d) >>

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

b) Floating – point numbers

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

c) 9

a) 1 -> 2 -> 3

b) 2 -> 1 -> 3

Java Questions & Answers – Assignment Operators and Operator Precedence

c) 3 -> 2 -> 1

d) 2 -> 3 -> 1

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

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.

b) 11

c) 12

d) 56

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.

12

a) 24 8

b) 24 9

c) 27 8

d) 27 9

Explanation: Operator ++ has higher precedence than multiplication operator, *, x is incremented to 9 than multiplied with 3 giving 27.

$ javac operators.java

$ java operators

27 9

a) compile and runs fine

b) 20

c) run time error

a) 1 will give better performance as it has no parentheses

b) 2 will give better performance as it has parentheses

c) Both 1 & 2 will give equal performance

d) Dependent on the computer system

Explanation: Parentheses do not degrade the performance of the program. Adding parentheses to reduce ambiguity does not negatively affect

your system.

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

int x, y, z;

x = 0;

y = 1;

x = y = z = 8;

b) runtime error

c) a=20 b=0 c=20 d=1

Explanation: Expression will evaluate from right to left.

20 0 20 1

1. Which of these selection statements test only for equality?

b) switch

c) if & switch

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

2. Which of these are selection statements in Java?

a) if()

b) for()

d) break

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

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

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

b) return

c) exit

d) continue

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 ifstatement can evaluate any type of boolean expression

d) it is possible to create a nested switch statements

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

Java Questions & Answers – Control Statements – 1

Explanation: var2 is initialised to 1. The conditionalstatement returns false and the else part gets executed.

$ javac selection_statements.java

$ java selection_statements

c) 14

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.

$ javac comma_operator.java

$ java comma_operator

a) 1 3 5 7

b) 2 4 6 8

c) 1 3 5 7 9

d) 1 2 3 4 5 6 7 8 9

Explanation: Whenever y is divisible by x remainder body of loop is skipped by continue statement, therefore if condition y == 8 is never true as

when y is 8, remainder body of loop is skipped by continue statements of first if. Control comes to print statement only in cases when y is odd.

$ javac jump_statments.java

$ java jump_statments

1 3 5 7 9

d) compile time error

Explanation: Every final variable is compile time constant.

a) 5 10

b) 10 5

c) 5

d) 10

Explanation: b >> 1 in if returns 5 which is equal to a i:e 5, therefore body of if is executed and block second is exited. Control goes to end of

the block second executing the last print statement, printing 10.

10

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

be executed.

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

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

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

Explanation:Break halts the execution and forces the control out of the loop.

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

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

5. Which of the following is used with the switch statement?

a) Continue

b) Exit

c) break

d) do

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

a) int and float

b) byte and short

c) char and long

d) byte and char

Java Questions & Answers – Control Statements – 2

Explanation: The switch condition would only meet if variable “a” is of type byte or char.

7. Which of the following is not a decision making statement?

a) if

b) if-else

c) switch

d) do-while

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

8. Which of the following is not a valid jump statement?

a) break

b) goto

Explanation: break, continue and return transfer control to another part of the program and returns back to caller after execution. However,

goto is marked as not used in Java.

9. From where break statement causes an exit?

a) Only from innermost loop

b) Terminates a program

c) Only from innermost switch

d) From innermost loops or switches

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

10. Which of the following is not a valid flow controlstatement?

a) exit()

b) break

c) continue

d) return

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

1. Which of the following is not OOPS concept in Java?

a) Inheritance

d) Compilation

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

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

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

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 ofsignature

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

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 ofJava is a way of converting real world objects in terms of class?

c) Abstraction

d) Inheritance

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

6. Which concept ofJava is achieved by combining methods and attribute into a class?

a) Encapsulation

Java Questions & Answers – Concepts of OOPs

b) Inheritance

d) Abstraction

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?

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?

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

d) Association

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?

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.

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

Explanation:JDK is a core component ofJava Environment and provides all the tools, executables and binaries required to compile, debug and

execute a Java Program.

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

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.

3. Which component is responsible to run java program?

Explanation:JRE is the implementation ofJVM, it provides platform to execute java programs.

4. Which component is responsible to optimize bytecode to machine code?

b) JDK

c) JIT

d) JRE

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

time taken for compilation of bytecode to machine specific language.

5. Which statement is true about java?

a) Platform independent programming language

b) Platform dependent programming language

c) Code dependent programming language

d) Sequence dependent programming language

Explanation:Java is called ‘Platform Independent Language’ as it primarily works on the principle of ‘compile once, run everywhere’.

Java Questions & Answers – JDK-JRE-JIT-JVM

6. Which of the below is invalid identifier with the main method?

Explanation: main method cannot be private as it is invoked by external method. Other identifier are valid with main method.

7. What is the extension of java code files?

Explanation:Java files have .java extension.

8. What is the extension of compiled java classes?

a) .class

b) .java

c) .txt

d) .js

Explanation: The compiled java files have .class extension.

9. How can we identify whether a compilation unit is class or interface from a .class file?

a) Java source file header

b) Extension of compilation unit

c) We cannot differentiate between class and interface

d) The class or interface name should be postfixed with unit type

Explanation: The Java source file contains a header that declares the type of class or interface, its visibility with respect to other classes, its name

and any superclass it may extend, or interface it implements.

10. What is use of interpreter?

a) They convert bytecode to machine language code

b) They read high level code and execute them

c) They are intermediated between JIT and JVM

d) It is a synonym for JIT

Explanation:Interpreters read high level language (interprets it) and execute the program. Interpreters are normally not passing through bytecode and jit compilation.

a) Memory address of allocated memory of object

b) NULL

c) Any arbitrary pointer

d) Garbage

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.

2. Which of these keywords is used to make a class?

b) struct

c) int

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

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

a) malloc

d) give

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.

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

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

b) 8

Java Questions & Answers – Class Fundamentals & Declaring objects

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

$ javac main_class.java

Duplicate local variable x

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

a) 12

c) 400

d) 100

200

d) Garbage value

Explanation: When we assign an object to another object ofsame type, all the elements of right side object gets copied to object on left side of

equal to, =, operator.

d) [email protected] in hexadecimalform

Explanation: When we print object internally toString() will be called to return string into this format in hexadecimalform.

$ javac mainclass.java

$ java mainclass

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

d) double

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

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

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

4. Which method can be defined only once in a program?

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

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

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.

Java Questions & Answers – Introduction To Methods

25

a) only sum(10)

b) only sum(10,20)

c) only sum(10) & sum(10,20)

Explanation:sum is a variable argument method and hence it can take any number as argument.

c) 30

d) error

Explanation: Variable height is not defined.

error: cannot find symbol height

1. What is the return type of Constructors?

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

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

c) abstract

d) this

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

a) finalize

b) delete

d) constructor

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.

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

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.

5. Which function is used to perform some action when the object is to be destroyed?

a) finalize()

c) main()

Java Questions & Answers – Constructors & Garbage Collection

a) 100

b) 150

c) 200

d) 250

$ constructor_output.java

$ constructor_output

a) compile time error

b) run time error

c) compile and runs fine

d) unreported exception java.io.IOException in default constructor

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.

a) 150

b) 200

c) Run time error

150

9. 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 ofscope and is no longer needed

d) finalize() method must be declared protected

Explanation:finalize() method is called just prior to garbage collection. it is not called when object goes out ofscope.

b) 5 6

c) 6 5

d) 5 5

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.

6 5

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

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

2. What would be the behaviour if this() and super() used in a method?

b) Throws exception

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

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

Explanation: Default, parameterised constructors can be defined.

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

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

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

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.

6. Abstract class cannot have a constructor.

Java Questions & Answers – Constructor

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

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

Explanation: Protected access modifier means that constructor can be accessed by child classes of the parent class and classes in the same

package.

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

Explanation: “this” is an important keyword in java. It helps to distinguish between local variable and variables passed in the method as

parameters.

9. What would be the behaviour if one parameterized constructor is explicitly defined?

b) Compilation succeeds

c) Runtime error

d) Compilation succeeds but at the time of creating object using default constructor, it throws compilation error

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

10. What would be behaviour if the constructor has a return type?

b) Runtime error

c) Compilation and runs successfully

d) Only String return type is allowed

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

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

a) Heap

c) JVM

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

2. Where is a new object allocated memory?

a) Young space

b) Old space

c) Young or Old space depending on space availability

d) JVM

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.

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

a) Cleanup model

b) Mark and sweep model

c) Space management model

d) Sweep model

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.

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

a) Initial; Maximum memory

b) Maximum; Initial memory

c) Maximum memory

d) Initial memory

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.

5. Which exception is thrown when java is out of memory?

a) MemoryFullException

b) MemoryOutOfBoundsException

c) OutOfMemoryError

d) MemoryError

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

Java Questions & Answers – Heap and Garbage Collection

encounter a java.lang.OutOfMemoryError.

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

a) jmap

b) memorymap

c) memorypath

d) jvmmap

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

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

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

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

a) JVM

b) JConsole

c) JProfiler

d) Eclipse Profiler

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.

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

a) Code changes

b) JVM parameter tuning

c) Process restart

d) GC parameter tuning

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

10. Garbage Collection can be controlled by a program?

Explanation: Garbage Collection cannot be controlled by a program.

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

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.

2. Which of these can be overloaded?

a) Methods

b) Constructors

3. 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 ofsubroutine have effect on original

argument

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

original argument

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

a) int float method

b) float int method

d) run time error

Explanation: While resolving overloaded method, compiler automatically promotes if exact match is not found. But in this case, which one to

promote is an ambiguity.

Java Questions & Answers – Overloading Methods & Argument Passing

b) 6

7

a) 6

b) 7

c) 8

d) 9

8

a) 6 6

b) 6.4 6.4

c) 6.4 6

d) 4 6.4

Explanation: For obj.add(a,a); ,the function in line number 4 gets executed and value of x is 4. For the next function call, the function in line

number 7 gets executed and value of y is 6.4

$ javac Overload_methods.java

$ java Overload_methods

4 6.4

Explanation: Variables a & b are passed by value, copy of their values are made on formal parameters of function meth() that is i & j. Therefore

changes done on i & j are not reflected back on original arguments. a & b remain 10 & 20 respectively.

10 20

a) 10 20

b) 20 10

c) 20 40

d) 40 20

Explanation:Class objects are always passed by reference, therefore changes done are reflected back on original arguments. obj.meth(obj)

sends object obj as parameter whose variables a & b are multiplied and divided by 2 respectively by meth() function of class test. a & b

becomes 20 & 10 respectively.

20 10

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

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.

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

c) static

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

c) public, within its own package

d) protected

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 ofsubroutine have no effect on original argument, they remain the same.

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

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

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

a) 3 3

Java Questions & Answers – Access Control – 1

The field access.y is not visible

a) 2 3

$ javac access_specifier.java

$ java access_specifier

3 3

a) 7 7.4

b) 6 6.4

9. Which of these access specifier must be used for class so that it can be inherited by another subclass?

a) public

1. Which one of the following is not an access modifier?

c) Protected

d) Void

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

2. All the variables of class should be ideally declared as?

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

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

a) private

b) public

Explanation: Private variables are accessible only within the class.

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

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.

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

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

6. All the variables of interface should be?

a) default and final

Java Questions & Answers – Access Control – 2

b) default and static

c) public, static and final

d) protect, static and final

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.

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

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

8. How many copies ofstatic 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

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

variables.

9. Can a class be declared with a protected modifier.

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.

10. Which is the modifier when there is none mentioned explicitly?

a) protected

b) private

c) public

d) default

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.

1. Arrays in Java are implemented as?

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

a) final

b) last

c) constant

d) static

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

declared.

3. Which of these cannot be declared static?

d) method

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

4. 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 ofstatic variables

Explanation: All objects of class share same static variable, when object of a class are declared, all the objects share same copy ofstatic

members, no copy ofstatic variables are made.

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

6. Which of these methods must be made static?

Java Questions & Answers – Arrays Revisited & Keyword static

c) run()

d) finalize()

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

c) 3 2

d) 1 5

$ javac static_specifier.java

$ java static_specifier

1 5

b) 1 1

c) 2 2

Explanation: All objects of class share same static variable, all the objects share same copy ofstatic members, obj1.x and obj2.x refer to same

element of class which has been incremented twice and its value is 2.

2 2

a) 7 7

b) 6 6

c) 7 9

d) 9 7

$ javac static_use.java

$ java static_use

7 9

b) 1 2 3

c) 1 2 3 4

d) 1 2 3 4 5

Explanation: arr.length() is 5, so the loop is executed for three times.

1 2 3

a) 10 5

b) 5 10

c) 0 10

d) 0 5

Explanation: Arrays in java are implemented as objects, they contain an attribute that is length which contains the number of elements that can

be stored in the array. Hence a1.length gives 10 and a2.length gives 5.

10 5

1. String in Java is a?

a) class

b) object

c) variable

d) character array

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

a) char()

b) Charat()

c) charat()

d) charAt()

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

a) upper

c) this

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

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

a) isequal()

b) isequals()

c) equal()

d) equals()

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

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

b) like

c) Java

Java Questions & Answers – String Class

d) IlikeJava

Explanation:Java defines an operator +, it is used to concatenate strings.

$ javac string_demo.java

$ java string_demo

IlikeJava

a) I

b) L

c) K

d) E

Explanation: charAt() is a method of class String which gives the character specified by the index. obj.charAt(3) gives 4th character i:e I.

I

a) 9

c) 11

d) 12

11

a) hello hello

b) world world

c) hello world

d) world hello

hello world

a) false false

b) true true

Explanation: equals() is method of class String, it is used to check equality of two String objects, if they are equal, true is retuned else false.

$ javac string_class.java

$ java string_class

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

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

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

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.

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

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

a) void

c) float

d) both int and float

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

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

Java Questions & Answers – Methods Taking Parameters

d) 25

$ Prameterized_method.java

$ Prameterized_method

6

d) 26

Explanation: main() method must be made public. Without main() being public java run time system will not be able to access main() and will not

be able to execute the code.

Error: Main method not found in class Output, please define the main method as:

public static void main(String[] args)

c) 25

d) 30

$ javac cons_method.java

$ java cons_method

30

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

a) main()

b) recursive() method

c) Any method

d) System defined methods

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?

3. How many arguments can be passed to main()?

a) Infinite

b) Only 1

4. Which of these is a correct statement about args in this 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

d) args in an array of Character

Explanation: args in an array of String.

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

d) Only ASCII characters can be converted

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

b) Output

Java Questions & Answers – Command Line Arguments – 1

d) is

This

b) is

c) This

d) command

command

a) This

b) java Output This is a command Line

c) This is a command Line

java Output This is a command Line

This is a command Line

c) 20

20

b) 10

c) b

d) N

java Output command Line 10 A b 4 N

N

b) Compilation but runtime error

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

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

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

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

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

Java Questions & Answers – Command Line Arguments – 2

b) 2 3

c) 1 2 3

d) Compilation error

Explanation: The index of array starts with 0. Since the loop is starting with 1 it will print 2 3.

a) The snippet compiles, runs and prints “java demo”

b) The snippet compiles, runs and prints “java code”

c) The snippet compiles, runs and prints “demo code”

d) The snippet compiles, runs and prints “I code”

Explanation: The index of array starts with 0 till length – 1. Hence it would print “I code”.

a) Compile time error

b) Output would be “hello”

c) Output would be “there”

d) Output would be “hello there”

Explanation: Error would be “Cannot make static reference to a non static variable”. Even if main method was not static, the array argv is local

to the main method and would not be visible within runMethod.

6. How do we pass command line argument in Eclipse?

a) Arguments tab

b) Variable tab

c) Cannot pass command line argument in eclipse

d) Environment variable tab

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

7. Which class allows parsing of command line arguments?

a) Args

b) JCommander

c) Command Line

d) Input

Explanation:JCommander is a very smallJava framework that makes it trivial to parse command line parameters.

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

a) @Input

c) @Command Line

d) @Parameter

Explanation: @Parameter, @Parameter(names = { “-log”, “-verbose” }, description = “Level of verbosity”), etc are various forms of using

@Parameter

a) 2 512 3

b) 2 2 3

c) 512 2 3

d) 512 512 3

Explanation:JCommander helps easily pass command line arguments. @Parameter assigns input to desired parameter.

3. What would be the output of following snippet, if compiled and executed with command line argument “java abc 1 2 3”?

1. public class abc

3. static public void main(String [] xyz)

5. for(int n=1;n.length="" n="" p="">

7. System.out.println(xyz[n]+"");

9. }

10. What is the use of @syntax?

a) Allows multiple parameters to be passed

b) Allows one to put all your options into a file and pass this file as a parameter

c) Allows one to pass only one parameter

d) Allows one to pass one file containing only one parameter

Explanation:JCommander supports the @syntax, which allows us to put all our options into a file and pass this file as a parameter.

/tmp/parameters

-verbose

file1

file2

$ java Main @/tmp/parameters

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

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

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

c) Queue

d) Tree

Explanation:Recursions are always managed by using stack.

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

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

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

Explanation:Recursion is always managed by operating system.

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

Java Questions & Answers – Recursion

Explanation: Since the base case of the recursive function func() is not defined hence infinite loop occurs and results in Stack Overflow.

Exception in thread "main" java.lang.StackOverflowError

a) 24

120

Explanation:fact() method recursively calculates factorial of a number, when value of n reaches 1, base case is excuted and 1 is returned.

b) 30

c) 120

d) 720

720

1. Which of this keyword can be used in a subclass to call the constructor ofsuperclass?

2. What is the process of defining a method in a subclass having same name & type signature as a method in its superclass?

a) Method overloading

b) Method overriding

c) Method hiding

3. Which of these keywords can be used to prevent Method overriding?

a) static

c) protected

Explanation: To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final

cannot be overridden.

4. Which of these is correct way of calling a constructor having no parameters, ofsuperclass A by subclass B?

a) super(void);

b) superclass.();

c) super.A();

d) super();

a) final, native, private

b) final, static, protected

c) final, private, abstract

d) final, static, public

Explanation: Every interface variable is implicitly public static and final.

6. Which of these is supported by method overriding in Java?

a) Abstraction

b) Encapsulation

Java Questions & Answers – Method overriding

c) Polymorphism

c) 7

Explanation:Both x,and y are pointing to the same array.

Explanation: class A has been declared final hence it cannot be inherited by any other class. Hence class B does not have member i, giving

i cannot be resolved or is not a field

a) Compilation error

b) An exception is thrown at run time

c) The variable first is set to null

d) The variable first is set to elements[0].

Explanation: The value at the 0th position will be assigned to the variable first.

Explanation:r is reference of type A, the program assigns a reference of object obj2 to r and uses that reference to callfunction display() of

class B.

$ javac Dynamic_dispatch.java

$ java Dynamic_dispatch

1. Which of these class is superclass of every class in Java?

a) String class

b) Object class

c) Abstract class

d) ArrayList class

Explanation: Object class is superclass of every class in Java.

2. Which of these method of Object class can clone an object?

a) Objectcopy()

c) Object clone()

d) clone()

3. Which of these method of Object class is used to obtain class of an object at run time?

b) void getclass()

c) Class getclass()

4. Which of these keywords can be used to prevent inheritance of a class?

b) constant

d) final

Explanation: Declaring a class final implicitly declared all of its methods final, and makes the class inheritable.

5. Which of these keywords cannot be used for a class which has been declared final?

b) extends

c) abstract and extends

Explanation: A abstract class is incomplete by itself and relies upon its subclasses to provide complete implementation. If we declare a class final

then no class can inherit that class, an abstract class needs its subclasses hence both final and abstract cannot be used for a same class.

6. Which of these class relies upon its subclasses for complete implementation of its methods?

a) Object class

Java Questions & Answers – The Object Class

b) abstract class

c) ArrayList class

Explanation: class A is an abstract class, it contains a abstract function display(), the full implementation of display() method is given in its

subclass B, Both the display functions are the same. Prototype of display() is defined in class A and its implementation is given in class B.

$ javac Abstract_demo.java

$ java Abstract_demo

a) false

b) true

Explanation: obj1 and obj2 are two different objects. equals() is a method of Object class, Since Object class is superclass of every class it is

available to every object.

b) class Object

c) class java.lang.Object

class java.lang.Object

c) String associated with obj1

Explanation: toString() is method of class Object, since it is superclass of every class, every object has this method. toString() returns the string

associated with the calling object.

1. Which of these keywords are used to define an abstract class?

a) abst

b) abstract

d) abstract class

2. Which of these is not abstract?

b) AbstractList

Explanation: Thread is not an abstract class.

3. If a class inheriting an abstract class does not define all of its function then it will be known as?

a) Abstract

b) A simple class

c) Static class

Explanation: Any subclass of an abstract class must either implement all of the abstract method in the superclass or be itself declared abstract.

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

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.

5. Which of these packages contains abstract keyword?

d) java.system

Java Questions & Answers – Inheritance – Abstract Class and Super

Explanation:Class contains a private member variable j, this cannot be inherited by subclass B and does not have access to it.

The field A.j is not visible

Explanation: class A & class B both contain display() method, class B inherits class A, when display() method is called by object of class B,

$ javac method_overriding.java

$ java method_overriding

c) 1 3

d) 3 1

Explanation:Both class A & B have member with same name that is j, member of class B will be called by default if no specifier is used. I

contains 1 & j contains 2, printing 1 2.

1. Which of this keyword must be used to inherit a class?

c) extent

d) extends

2. A class member declared protected becomes a member ofsubclass of which type?

a) public member

b) private member

c) protected member

d) static member

Explanation: A class member declared protected becomes a private member ofsubclass.

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

a) B,E

b) A,C

c) C,E

d) T,H

Explanation:If one is extending any class, then they should use extends keyword not implements.

Explanation:Class A & class B both contain display() method, class B inherits class A, when display() method is called by object of class B,

display() method of class B is executed rather than that of Class A.

$ javac inheritance_demo.java

$ java inheritance_demo

Java Questions & Answers – Inheritance – 1

a) 2 2

b) 3 3

c) 2 3

d) 3 2

$ javac inheritance.java

$ java inheritance

2 3

a) 1 2

b) 2 1

Explanation: Keyword super is used to call constructor of class A by constructor of class B. Constructor of a initializes i & j to 1 & 2

respectively.

$ javac super_use.java

$ java super_use

1 2

1. What is not type of inheritance?

a) Single inheritance

b) Double inheritance

c) Hierarchical inheritance

d) Multiple inheritance

Explanation:Inheritance is way of acquiring attributes and methods of parent class. Java supports hierarchical inheritance directly.

2. Using which of the following, multiple inheritance in Java can be implemented?

a) Interfaces

b) Multithreading

c) Protected methods

d) Private methods

Explanation: Multiple inheritance in java is implemented using interfaces. Multiple interfaces can be implemented by a class.

3. All classes in Java are inherited from which class?

a) java.lang.class

b) java.class.inherited

c) java.class.object

d) java.lang.Object

Explanation: All classes in java are inherited from Object class. Interfaces are not inherited from Object Class.

4. In order to restrict a variable of a class from inheriting to subclass, how variable should be declared?

d) Static

Explanation:By declaring variable private, the variable will not be available in inherited to subclass.

5. Ifsuper class and subclass have same variable name, which keyword should be used to use super class?

a) super

b) this

c) upper

d) classname

Explanation: Super keyword is used to access hidden super class variable in subclass.

6. Static members are not inherited to subclass.

Java Questions & Answers – Inheritance – 2

Explanation: Static members are also inherited to subclasses.

7. Which of the following is used for implementing inheritance through an interface?

Explanation:Interface is implemented using implements keyword. A concrete class must implement all the methods of an interface, else it must

be declared abstract.

8. Which of the following is used for implementing inheritance through class?

a) inherited

b) using

Explanation:Class can be extended using extends keyword. One class can extend only one class. A final class cannot be extended.

9. What would be the result if a class extends two interfaces and both have a method with same name and signature? Lets assume that the class

is not implementing that method.

a) Runtime error

b) Compile time error

c) Code runs successfully

d) First called method is executed successfully

Explanation:In case ofsuch conflict, compiler will not be able to link a method call due to ambiguity. It will throw compile time error.

10. Does Java support multiple level inheritance?

Explanation:Java supports multiple level inheritance through implementing multiple interfaces.

1. Which of these class is superclass of String and StringBuffer class?

2. Which of these operators can be used to concatenate two or more String objects?

a) +

b) +=

c) &

d) ||

Explanation: Operator + is used to concatenate strings, Example String s = “i ” + “like ” + “java”; String s contains “I like java”.

3. Which of this method of class String is used to obtain a length of String object?

b) Sizeof()

c) lengthof()

d) length()

Explanation: Method length() ofstring class is used to get the length of the object which invoked method length().

4. Which of these method of class String is used to extract a single character from a String object?

a) CHARAT()

b) chatat()

c) charAt()

d) ChatAt()

5. Which of these constructors is used to create an empty String object?

b) String(void)

c) String(0)

6. Which of these is an incorrect statement?

a) String objects are immutable, they cannot be changed

b) String object can point to some other reference of String variable

Java Questions & Answers – String Handling Basics

c) StringBuffer class is used to store string in a buffer for later use

Explanation: StringBuffer class is used to create strings that can be modified after they are created.

d) abc

Explanation: String(chars) is a constructor of class string, it initializes string s with the values stored in character array chars, therefore s contains

“abc”.

a) ABC

b) BCD

c) CDA

d) ABCD

Explanation: ascii is an array of integers which contains ascii codes of Characters A, B, C, D. String(ascii, 1, 3) is an constructor which

initializes s with Characters corresponding to ascii codes stored in array ascii, starting position being given by 1 & ending position by 3, Thus s

stores BCD.

BCD

a) 3 0

b) 0 3

c) 3 4

d) 4 3

$ javac String_demo.java

$ java String_demo

4 3

1. Which of these method of class String is used to extract more than one character at a time a String object?

a) getchars()

b) GetChars()

c) Getchars()

d) getChars()

2. Which of these methods is an alternative to getChars() that stores the characters in an array of bytes?

a) getBytes()

b) GetByte()

c) giveByte()

d) Give Bytes()

Explanation: getBytes() stores the character in an array of bytes. It uses default character to byte conversions provided by the platform.

a) any class

b) only the Target class

c) any class in the test package

Java Questions & Answers – Character Extraction

d) any class that extends Target

Explanation: Any class in the test package can access and change name.

a) The value “4” is printed at the command line

b) Compilation fails because of an error in line

c) A NullPointerException occurs at runtime

d) An IllegalStateException occurs at runtime

Explanation:Because we are performing operation on reference variable which is null.

5. Which of these methods can be used to convert all characters in a String into a character array?

a) charAt()

b) both getChars() & charAt()

c) both toCharArray() & getChars()

Explanation: charAt() return one character only not array of character.

a) Hello, i love java

b) i love ja

c) lo i lo

d) llo i l

Explanation: getChars(start,end,s,0) returns an array from the string c, starting index of array is pointed by start and ending index is pointed by

end. s is the target character array where the new string of letters is going to be stored and the new string will be stored from 0th position in s.

llo i l

Explanation:Character.isDigit(c[i]),Character.isUpperCase(c[i]),Character.isWhitespace(c[i]) are the function of library java.lang. They are

used to find weather the given character is ofspecified type or not. They return true or false i:e Boolean variable.

A is an Upper Case Letter

3. In below code, what can directly access and change the value of the variable name?

1. package test;

2. class Target

4. public String name = "hello";

a) h

b) e

c) l

d) o

Explanation: “hello” is a String literal, method charAt() returns the character specified at the index position. Character at index position 1 is e of

hello, hence ch contains e.

e

1. Which of these method of class String is used to compare two String objects for their equality?

a) equals()

b) Equals()

c) isequal()

d) Isequal()

2. Which of these methods is used to compare a specific region inside a string with another specific region in another string?

a) regionMatch()

b) match()

c) RegionMatches()

d) regionMatches()

3. Which of these methods of class String is used to check whether a given object starts with a particular string literal?

b) endsWith()

c) Starts()

d) ends()

Explanation: Method startsWith() ofstring class is used to check whether the String in question starts with a specified string. It is a specialized

form of method regionMatches().

4. What is the value returned by function compareTo() if the invoking string is less than the string compared?

5. Which of these data type value is returned by equals() method of String class?

a) char

b) int

c) boolean

Explanation: equals() method ofstring class returns boolean value true if both the string are equal and false if they are unequal.

Java Questions & Answers – String Comparison

Explanation:startsWith() method is case sensitive “hello” and “Hello” are treated differently, hence false is stored in var.

Explanation: The == operator compares two object references to see whether they refer to the same instance, where as equals() compares the

content of the two objects.

false true

a) true true

b) false false

c) true false

d) false true

true false

a) sb1.append(“abc”); s1.append(“abc”);

b) sb1.append(“abc”); s1.concat(“abc”);

c) sb1.concat(“abc”); s1.append(“abc”);

d) sb1.append(“abc”); s1 = s1.concat(“abc”);

Explanation: append() is stringbuffer method and concat is String class method.

append() is stringbuffer method and concat is String class method.

a) ab

b) bc

c) ca

d) ac

Explanation: compareTo() function returns zero when both the strings are equal, it returns a value less than zero if the invoking string is less than

the other string being compared and value greater than zero when invoking string is greater than the string compared to.

ac

1. Which of this method of class String is used to extract a substring from a String object?

Explanation: Two strings can be concatenated by using concat() method.

3. Which of these method of class String is used to remove leading and trailing whitespaces?

a) startsWith()

b) trim()

c) Trim()

d) doTrim()

4. What is the value returned by function compareTo() if the invoking string is greater than the string compared?

a) zero

b) value less than zero

c) value greater than zero

if (s1 == s2) then 0, if(s1 > s2) > 0, if (s1 < s2) then < 0.

a) replace() method replaces all occurrences of one character in invoking string with another character

b) replace() method replaces only first occurrences of a character in invoking string with another character

c) replace() method replaces all the characters in invoking string with another character

d) replace() replace() method replaces last occurrence of a character in invoking string with another character

Explanation:replace() method replaces all occurrences of one character in invoking string with another character.

a) “”Hello World””

b) “”Hello World”

Java Questions & Answers – Searching & Modifying a String

c) “Hello World”

d) Hello world

Explanation: trim() method is used to remove leading and trailing whitespaces in a string.

"Hello World"

c) one two

d) compilation error

one two

b) helwo

c) hewlo

d) hewwo

Explanation:replace() method replaces all occurrences of one character in invoking string with another character. s1.replace(‘l’,’w’) replaces

every occurrence of ‘l’ in hello by ‘w’, giving hewwo.

hewwo

c) Worl

d) World

Explanation:substring(0,4) returns the character from 0 th position to 3 rd position.

Hell

a) 4 8

b) 5 9

c) 4 9

d) 5 8

Explanation: indexOf() method returns the index of first occurrence of the character where as lastIndexOf() returns the index of last occurrence

of the character.

4 9

1. Which of these class is used to create an object whose character sequence is mutable?

a) String()

b) StringBuffer()

c) String() & StringBuffer()

Explanation: StringBuffer represents growable and writable character sequence.

2. Which of this method of class StringBuffer is used to concatenate the string representation to the end of invoking string?

a) concat()

b) append()

d) concatenate()

3. Which of these method of class StringBuffer is used to find the length of current character sequence?

b) Length()

c) capacity()

a) Hell

b) ello

c) Hel

Explanation: deleteCharAt() method deletes the character at the specified index location and returns the resulting StringBuffer object.

5. Which of the following statement is correct?

a) reverse() method reverses all characters

b) reverseall() method reverses all characters

c) replace() method replaces first occurrence of a character in invoking string with another character

d) replace() method replaces last occurrence of a character in invoking string with another character

d) 1 14 8 15

Java Questions & Answers – StringBuffer Class

1 14 8 15

a) He

b) Hel

c) lo

d) llo

Explanation: delete(0,2) is used to delete the characters from 0 th position to 1 st position.

llo

Explanation:Character.isDigit(c[i]),Character.isUpperCase(c[i]),Character.isWhitespace(c[i]) are the function of library java.lang they are used

to find whether the given character is ofspecified type or not. They return true or false i:e Boolean variable.

1 is a digit

1. Which of these methods of class StringBuffer is used to extract a substring from a String object?

a) substring()

b) Substring()

c) SubString()

a) one

b) two

c) onetwo

d) twoone

Explanation: Two strings can be concatenated by using append() method.

3. Which of this method of class StringBuffer is used to reverse sequence of characters?

a) reverse()

b) reverseall()

c) Reverse()

d) reverseAll()

4. Which of this method of class StringBuffer is used to get the length of the sequence of characters?

a) length()

b) capacity()

d) Capacity()

Explanation: length()- returns the length of String the StringBuffer would create whereas capacity() returns a total number of characters that can

be supported before it is grown.

5. Which of the following are incorrect form of StringBuffer class constructor?

a) StringBuffer()

b) StringBuffer(int size)

c) StringBuffer(String str)

d) StringBuffer(int size , String str)

Java Questions & Answers – StringBuffer Methods

a) Hello java

b) Hellojava

c) HJavalo

d) Hjava

Explanation: The replace() method replaces the given string from the specified beginIndex and endIndex.

HJavalo

c) HellGood oWorld

d) Hello Good World

Explanation: The insert() method inserts one string into another. It is overloaded to accept values of allsimple types, plus String and Objects.

Sting is inserted into invoking object at specified position. “Good ” is inserted in “Hello World” T index 6 giving “Hello Good World”.

Hello Good World

a) hello

c) Hello Java

d) HJavaello

Explanation:Insert method will insert string at a specified position

HJavaello

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

a) Byte

b) Integer

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

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

a) type wrapping

b) type conversion

c) type casting

d) none of the Mentioned

3. Which of these is a super class of wrappers Double & Integer?

4. Which of these is a wrapper for simple data type float?

a) float

b) double

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

b) byte byteValue()

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

a) isInfinite()

b) isNaN()

Java Questions & Answers – Java.lang Introduction

c) Isinfinite()

d) IsNaN()

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

7. Which of the following package stores all the simple data types in java?

Explanation: isInfinite() method returns true is the value being tested is infinitely large or small in magnitude. 1/0. is infinitely large in magnitude

hence true is stored in x.

$ javac isinfinite_output.java

$ java isinfinite_output

Explanation: isisNaN() method returns true is the value being tested is a number. 1/0. is infinitely large in magnitude, which cannot be defined as

a number hence false is stored in x.

$ javac isNaN_output.java

$ java isNaN_output

a) 1001

b) 10011

c) 11011

d) 10001

$ javac binary.java

$ java binary

10001

1. Which of these is a wrapper for data type int?

b) Long

d) Double

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

a) int hash()

b) int hashcode()

c) int hashCode()

d) Integer hashcode()

3. Which of these is a super class of wrappers Long, Character & Integer?

4. Which of these is a wrapper for simple data type char?

a) Float

b) Character

d) Integer

5. Which of the following is method of wrapper Integer for converting the value of an object into int?

a) bytevalue()

b) int intValue();

c) Bytevalue()

d) Byte Bytevalue()

6. Which of these methods is used to obtain value of invoking object as a long?

a) long value()

b) long longValue()

Java Questions & Answers – Java.lang – Integer, Long & Character Wrappers

c) Long longvalue()

d) Long Longvalue()

Explanation: long longValue() is used to obtain value of invoking object as a long.

Explanation: i.byteValue() method returns the value of wrapper i as a byte value. i is 257, range of byte is 256 therefore i value exceeds byte

range by 1 hence 1 is returned and stored in x.

c) 257

d) 257.0

257.0

a) 256

b) 256.0

c) 256.00

d) 257.00

256

1. Which of these class have only one field ‘TYPE’?

d) Runtime

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

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

a) void kill()

b) void destroy()

c) void terminate()

d) void exit()

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

3. Standard output variable ‘out’ is defined in which class?

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

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

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

6. Which of these class holds a collection ofstatic methods and variables?

a) Void

Java Questions & Answers – Java.lang – Void, Process & System Class

Explanation: System class holds a collection ofstatic methods and variables. The standard input, output and error output of java runtime is

stored in the in, out and err variables of System class.

Explanation: end time is the time taken by loop to execute it can be any non zero value depending on the System.

ABCDEF GCDEFL

a) ABCDEF GHIJKL

b) ABCDEF GCDEFL

d) GCDEFL GHIJKL

Explanation: Since last parameter of System.arraycopy(a,1,b,3,0) is 0 nothing is copied from array a to array b, hence b remains as it is.

ABCDEF GHIJKL

1. Which of these class is a superclass of all other classes?

Explanation: The object class class is a superclass of all other classes.

2. Which of these method of Object class can generate duplicate copy of the object on which it is called?

a) clone()

b) copy()

c) duplicate()

d) dito()

3. What is the value of double consonant ‘E’ defined in Math class?

a) approximately 3

b) approximately 3.14

c) approximately 2.72

d) approximately 0

4. Which of these method is a rounding function of Math class?

a) max()

b) min()

c) abs()

Explanation: max(), min() and abs() are allrounding functions.

5. Which of these class contains only floating point functions?

Explanation: Math class contains all the floating point functions that are used for geometry, trigonometry, as well as several general purpose

methods. Example :sin(), cos(), exp(), sqrt() etc.

6. Which of these class encapsulate the runtime state of an object or an interface?

Java Questions & Answers – Java.lang – Object & Math Class

d) 2.5

Explanation: The Math.random() method returns a number greater than or equal to 0 and less than 1. so 2.5 will be greater than or equal to 2.5

and less than 3.5, we can be sure that Math.round() willround that number to 3.

b) flase

c) 3.1

d) 4.5

4.5

a) 2.0

b) 4.0

d) 9.0

Explanation: Math.pow(x, y) methods returns value of y to the power x, i:e x ^ y, 2.0 ^ 3.0 = 8.0.

8.0

1. Which of these exceptions is thrown by methods of System class?

d) InputOutputException

Explanation: System class methods throw SecurityException.

2. Which of these methods initiates garbage collection?

a) gc()

b) garbage()

c) garbagecollection()

d) Systemgarbagecollection()

3. Which of these methods loads the specified dynamic library?

b) library()

c) loadlib()

d) loadlibrary()

Explanation: load() methods loads the dynamic library whose name is specified.

4. Which of these method can set the out stream to OutputStream?

a) setStream()

b) setosteam()

c) setOut()

d) streamtoOstream()

5. Which of these values are returns under the case of normal termination of a program?

c) 1000

Java Questions & Answers – Java.lang – System Class Advance

Explanation: End time is the time taken by loop to execute it can be any non zero value depending on the System.

78

c) GHIJKL ABCDEF

ABCDEF ABCDEF

d) GHIJKL GHIJKL

ABCDEF GHIABC

a) ABCDEF ABCDEF

b) ABCDEF GHIJKL

c) ABCDEF GHIABC

d) ABCDEF GHICDL

Explanation: System.arraycopy() is a method of class System which is used to copy a string into another string.

ABCDEF GHICDL

1. Which of these is a super class of wrappers Double and Float?

2. Which of the following methods return the value as a double?

3. Which of these methods can be used to check whether the given value is a number or not?

a) isNaN()

b) isNumber()

c) checkNaN()

d) checkNumber()

Explanation: isNaN() methods returns true if num specified is not a number, otherwise it returns false.

4. Which of these method of Double wrapper can be used to check whether a given value is infinite or not?

a) Infinite()

c) checkInfinite()

Explanation: isInfinite() methods returns true if the specified value is an infinite value otherwise it returns false.

5. Which of these exceptions is thrown by compareTo() method defined in a double wrapper?

c) CastException

d) ClassCastException

Explanation: compareTo() methods compare the specified object to be double, if it is not then ClassCastException is thrown.

Java Questions & Answers – Java.lang – Double & Float Wrappers

Explanation: i.isNaN() method returns returns true if i is not a number and false when i is a number. Here false is returned because i is a number

i:e 257.5.

c) 256

d) 257

Explanation: i.intValue() method returns the value of wrapper i as a Integer. i is 257.578 is double number when converted to an integer data

type its value is 257.

257

Explanation: i.compareTo() methods two double values, if they are equal then 0 is returned and if not equal then 1 is returned, here 257.57812

and 257.578123456789 are not equal hence 1 is returned and stored in x.

1. Which of these packages contain classes and interfaces used for input & output operations of a program?

a) java.util

Explanation: java.io provides support for input and output operations.

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

d) File

3. Which of these interface is not a member of java.io package?

a) DataInput

b) ObjectInput

c) ObjectFilter

d) FileFilter

4. Which of these class is not related to input and output stream in terms of functioning?

a) File

c) InputStream

Explanation: A File describes properties of a file, a File object is used to obtain or manipulate the information associated with a disk file, such as

the permissions, time date, and directories path, and to navigate subdirectories.

5. Which of these is specified by a File object?

a) a file in disk

b) directory path

c) directory in disk

6. Which of these is method for testing whether the specified element is a file or a directory?

a) IsFile()

Java Questions & Answers – Java.io Introduction

b) isFile()

c) Isfile()

d) isfile()

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

d) /java/system

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

system

a) java

b) system

c) java/system

d) \java\system

\java\system

a) true false

b) false true

c) true true

d) false false

false false

Note:file is made in c drive.

a) java true

b) java false

c) \java false

d) \java true

Explanation: getparent() giver the parent directory of the file and isfile() checks weather the present file is a directory or a file in the disk

$ javac files.java

$ java files

\java false

1. Which of these classes is used for input and output operation when working with bytes?

b) Reader

c) Writer

Explanation:InputStream & OutputStream are designed for byte stream. Reader and writer are designed for character stream.

2. Which of these class is used to read and write bytes in a file?

3. Which of these method of InputStream is used to read integer representation of next available byte input?

4. Which of these data type is returned by every method of OutputStream?

a) int

b) float

c) byte

Explanation: Every method of OutputStream returns void and throws an IOExeption in case of errors.

5. Which of these is a method to clear all the data present in output buffers?

6. Which of these method(s) is/are used for writing bytes to an outputstream?

b) print() and write()

Java Questions & Answers – Java.io Byte Streams

c) printf()

d) write() and read()

Explanation: write() and print() are the two methods of OutputStream that are used for printing the byte data.

b) ABC

c) ab

d) AB

ABC

1. Which of these stream contains the classes which can work on character stream?

b) OutputStream

c) Character Stream

Explanation:InputStream & OutputStream classes under byte stream they are not streams. Character Stream contains all the classes which can

work with Unicode.

2. Which of these class is used to read characters in a file?

a) FileReader

b) FileWriter

3. Which of these method of FileReader class is used to read characters from a file?

a) read()

b) scanf()

d) getInteger()

4. Which of these class can be used to implement the input stream that uses a character array as the source?

b) FileReader

c) CharArrayReader

d) FileArrayReader

Explanation:CharArrayReader is an implementation of an input stream that uses character array as a source. Here array is the input source.

5. Which of these classes can return more than one character to be returned to input stream?

b) Bufferedwriter

c) PushbachReader

d) CharArrayReader

Explanation: PushbackReader class allows one or more characters to be returned to the input stream. This allows looking ahead in input stream

and performing action accordingly.

Java Questions & Answers – Java.io Character Streams

abcdef

1. Which of the following is not a segment of memory in java?

a) Stack Segment

b) Heap Segment

c) Code Segment

d) Register Segment

Explanation: There are only 3 types of memory segment. Stack Segment, Heap Segment and Code Segment.

2. Does code Segment loads the java code?

Explanation:Code Segment loads compiled java bytecode. Bytecode is platform independent.

3. What is JVM?

b) Interpreter

c) Extension

d) Compiler

Explanation:JVM is Interpreter. It reads .class files which is the byte code generated by compiler line by line and converts it into native OS

code.

4. Which one of the following is a class loader?

b) Compiler

c) Heap

d) Interpreter

Explanation:Bootstrap is a class loader. It loads the classes into memory.

5. Which class loader loads jar files from JDK directory?

a) Bootstrap

b) Extension

d) Heap

Explanation: Extension loads jar files from lib/ext directory of the JRE. This gives the basic functionality available.

6. Which of the following is not a memory classification in java?

a) Young

b) Old

c) Permanent

Java Questions & Answers – Memory Management

d) Temporary

Explanation: Young generation is further classified into Eden space and Survivor space. Old generation is also the tenured space. The permanent

generation is the non heap space.

7. What is the Java 8 update of PermGen?

a) Code Cache

b) Tenured Space

c) Metaspace

d) Eden space

Explanation: Metaspace is the replacement of PermGen in Java 8. It is very similar to PermGen except that it resizes itself dynamically. Thus, it

is unbounded.

8. Classes and Methods are stored in which space?

a) Eden space

b) Survivor space

c) Tenured space

d) Permanent space

Explanation: The permanent generation holds objects which JVM finds convenient to have the garbage collector. Objects describing classes and

methods, as well as the classes and methods themselves, are a part of Permanent generation.

9. Where is String Poolstored?

a) Java Stack

b) Java Heap

c) Permanent Generation

d) Metaspace

Explanation: When a string is created; if the string already exists in the pool, the reference of the existing string will be returned, else a new

object is created and its reference is returned.

10. The same import package/class be called twice in java?

Explanation: We can import the same package or same class multiple times. Neither compiler nor JVM complains will complain about it. JVM

will internally load the class only once no matter how many times we import the same class or package.

1. Which of these exceptions handles the situations when an illegal argument is used to invoke a method?

a) IllegalException

b) Argument Exception

c) IllegalArgumentException

d) IllegalMethodArgumentExcepetion

2. Which of these exceptions will be thrown if we declare an array with negative size?

a) IllegalArrayException

b) IllegalArraySizeExeption

c) NegativeArrayException

d) NegativeArraySizeExeption

Explanation: Array size must always be positive if we declare an array with negative size then built in exception “NegativeArraySizeException”

is thrown by the java’s run time system.

3. Which of these packages contain all the Java’s built in exceptions?

c) java.lang

d) java.net

4. Which of these exceptions will be thrown if we use nullreference for an arithmetic operation?

d) IllegalOperationException

Explanation:If we use nullreference anywhere in the code where the value stored in that reference is used then NullPointerException occurs.

5. Which of these class is used to create user defined exception?

Explanation: Exception class contains all the methods necessary for defining an exception. The class contains the Throwable class.

b) 123450

Java Questions & Answers – Java’s Built in Exceptions

c) 1234500

Explanation: When array index goes out of bound then ArrayIndexOutOfBoundsException exception is thrown by the system.

123450

b) 12345A

c) 12345B

Explanation: There can be more than one catch of a single try block. Here Arithmetic exception occurs instead of Array index out of bound

exception hence B is printed after 12345

12345B

c) 0A

d) Exception

0A

prints ‘A’ the outer try block does have catch for NullPointerException exception but no such exception occurs in it hence its catch is never

executed and only ‘A’ is printed.

c) 0TypeA

Explanation: Execution command line is “$ java exception_ handling one two” hence there are two input making args.length = 2, hence “c[8] =

9” in second try block is executing which throws ArrayIndexOutOfBoundException which is caught by catch of nested try block. Hence

0TypeB is printed

0TypeB

1. Which of these class provides various types of rounding functions?

a) Math

d) Object

2. Which of these methods return a smallest whole number greater than or equal to variable X?

Explanation: ceil(double X) returns the smallest whole number greater than or equal to variable X.

3. Which of these method returns a largest whole number less than or equal to variable X?

a) double ceil(double X)

Explanation: double floor(double X) returns a largest whole number less than or equal to variable X.

4. Which of function return absolute value of a variable?

a) abs()

b) absolute()

c) absolutevariable()

Explanation: abs() returns the absolute value of a variable.

a) 1 2 0 0

b) 1 2 1 2

c) 0 0 0 0

d) System Dependent

Explanation: clone() method of object class is used to generate duplicate copy of the object on which it is called. Copy of obj1 is generated and

stored in obj2.

1 2 1 2

Java Questions & Answers – Java.lang – Rounding Functions

Explanation: ciel(double X) returns the smallest whole number greater than or equal to variable x.

Explanation: double floor(double X) returns a largest whole number less than or equal to variable X. Here the smallest whole number less than

3.14 is 3.

1. Which of these methods of Byte wrapper can be used to obtain Byte object from a string?

a) toString()

b) getString()

c) decode()

d) encode()

Explanation: decode() methods returns a Byte object that contains the value specified by string.

2. Which of the following methods Byte wrapper return the value as a double?

a) doubleValue()

b) converDouble()

c) getDouble()

d) getDoubleValue()

Explanation: doubleValue() returns the value of invoking object as double.

3. Which of these is a super class of wrappers Byte and short wrappers?

Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Integer and Long.

4. Which of these methods is not defined in both Byte and Short wrappers?

a) intValue()

b) isInfinite()

c) toString()

d) hashCode()

Explanation: isInfinite() methods is defined in Integer and Long Wrappers, returns true ifspecified value is an infinite value otherwise it returns

false.

b) 1.7976931348623157E308

c) 1.7976931348623157E30

Explanation: The super class of Double class defines a constant MAX_VALUE above which a number is considered to be infinity.

MAX_VALUE is 1.7976931348623157E308.

Java Questions & Answers – Java.lang – Byte & Short Wrappers

1.7976931348623157E308

b) 4.9E-324

c) 1.7976931348623157E308

Explanation: The super class of Byte class defines a constant MIN_VALUE below which a number is considered to be negative infinity.

MIN_VALUE is 4.9E-324.

4.9E-324

b) 257.0

c) 257.57812

d) 257.578123456789

Explanation:floatValue() converts the value of wrapper i into float, since float can measure till 5 places after decimal hence 257.57812 is stored

in floating point variable x.

257.57812

1. Which of these methods of Character wrapper can be used to obtain the char value contained in Character object.

b) getVhar()

c) charValue()

d) getCharacter()

Explanation: To obtain the char value contained in a Character object, we use charValue() method.

2. Which of the following constant are defined in Character wrapper?

a) MAX_RADIX

b) MAX_VALUE

Explanation:Character wrapper defines 5 constants – MAX_RADIX, MIN_RADIX, MAX_VALUE, MIN_VALUE & TYPE.

3. Which of these is a super class of Character wrapper?

a) Long

b) Digits

c) Float

d) Number

Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Character, Integer and Long.

4. Which of these methods is used to know whether a given Character object is part ofJava’s Identifiers?

a) isIdentifier()

b) isJavaIdentifier()

c) isJavaIdentifierPart()

5. Which of these coding techniques is used by method isDefined()?

a) Latin

b) ASCII

c) ANSI

d) UNICODE

Explanation: isDefined() returns true if ch is defined by Unicode. Otherwise, it returns false.

b) >

c) ?

Java Questions & Answers – Java.lang – Character Wrapper Advance

d) $

Explanation:Character.MAX_VALUE returns the largest character value, which is of character ‘?’.

?

a) <

d) Space

Explanation:Character.MIN_VALUE returns the smallest character value, which is ofspace character ‘ ‘.

a) true false true

b) false true true

c) true true false

d) false false false

Explanation:Character.isDigit(a[0]) checks for a[0], whether it is a digit or not, since a[0] i:e ‘a’ is a character false is returned. a[3] is a

whitespace hence Character.isWhitespace(a[3]) returns a true. a[2] is an uppercase letter i:e ‘A’ hence Character.isUpperCase(a[2]) returns

false true true

a) b

b) c

c) B

d) C

c) @

d) B

1. Which of these methods of Boolean wrapper returns boolean equivalent of an object.

a) getBool()

b) booleanValue()

c) getbooleanValue()

d) getboolValue()

2. Which of the following constant are defined in Boolean wrapper?

a) TRUE

b) FALSE

c) TYPE

Explanation:Boolean wrapper defines 3 constants – TRUE, FALSE & TYPE.

3. Which of these methods return string equivalent of Boolean object?

a) getString()

c) converString()

d) getStringObject()

4. Which of these methods is used to know whether a string contains “true”?

a) valueOf()

b) valueOfString()

5. Which of these class have only one field?

a) Character

b) Boolean

c) Byte

d) void

Explanation: Void class has only one field – TYPE, which holds a reference to the Class object for type void. We do not create an instance of

this class.

Java Questions & Answers – Java.lang – Boolean Wrapper Advance

Explanation: valueOf() returns true if the specified string contains “true” in lower or uppercase and false otherwise.

Explanation: valueOf() returns a Boolean instance representing the specified boolean value. If the specified boolean value is true, this method

returns Boolean.TRUE; if it is false, this method returns Boolean.FALSE. If a new Boolean instance is not required, this method should

generally be used in preference to the constructor Boolean(boolean), as this method is likely to yield significantly better space and time.

Explanation: parseBoolean() Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not

null and is equal, ignoring case, to the string “true”.

Example:Boolean.parseBoolean(“True”) returns true.

Example:Boolean.parseBoolean(“yes”) returns false.

c) System Dependent

Explanation: toString() Returns a String object representing the specified boolean. If the specified boolean is true, then the string “true” will be

returned, otherwise the string “false” will be returned

1. Which of these class contains all the methods present in Math class?

a) SystemMath

b) StrictMath

c) Compiler

Explanation: SystemMath class defines a complete set of mathematical methods that are parallel those in Math class. The difference is that the

StrictMath version is guaranteed to generate precisely identicalresults across allJava implementations.

2. Which of these method return a pseudorandom number?

b) random()

c) randomNumber()

d) randGenerator()

3. Which of these method returns the remainder of dividend / divisor?

a) remainder()

b) getRemainder()

c) CSIremainder()

d) IEEEremainder()

Explanation:IEEEremainder() returns the remainder of dividend / divisor.

4. Which of these method converts radians to degrees?

a) toRadian()

b) toDegree()

c) convertRadian()

d) converDegree()

5. toRadian() and toDegree() methods were added by which version ofJava?

a) Java 1.0

b) Java 1.5

c) Java 2.0

d) Java 3.0

Explanation: toRadian() and toDegree() methods were added by Java 2.0 before that there was no method which could directly convert degree

into radians and vice versa.

6. Which of these method returns a smallest whole number greater than or equal to variable X?

Java Questions & Answers – Java.lang – Miscellaneous Math Methods & StrictMath Class

a) double ciel(double X)

b) double floor(double X)

c) double max(double X)

d) double min(double X)

Explanation: ciel(double X) returns the smallest whole number greater than or equal to variable X.

b) 179

c) 180

d) 360

Explanation: 3.14 in degree 179.9087. We usually take it to be 180. Buts here we have type casted it to integer data type hence 179.

179

c) 3.0

d) 3.1

Explanation:IEEEremainder() returns the remainder of dividend / divisor. Here dividend is 102 and divisor is 5 therefore remainder is 2. It is

similar to modulus – ‘%’ operator of C/C++ language.

a) Yes

b) No

c) Compiler Dependent

d) Operating System Dependent

Explanation: There is no relation between random numbers generated previously in Java.

1. Which of these classes encapsulate runtime environment?

2. Which of the following exceptions is thrown by every method of Runtime class?

c) SecurityException

Explanation: Every method of Runtime class throws SecurityException.

3. Which of these methods returns the total number of bytes of memory available to the program?

a) getMemory()

b) TotalMemory()

c) SystemMemory()

d) getProcessMemory()

Explanation: TotalMemory() returns the total number of bytes available to the program.

4. Which of these Exceptions is thrown by loadClass() method of ClassLoader class?

c) ClassFormatError

d) ClassNotFoundException

Explanation: getSuperClass() returns the super class of an object. b is an object of class Y which extends class X , Hence Super class of b is X.

Java Questions & Answers – Java.lang – Runtime & ClassLoader Classes

Explanation: Although class Y extends class X but still a is not considered related to Y. hence isInstance() returns false.

1. Which of these classes encapsulate runtime state of an object?

d) Cache

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

b) Class()

c) WhoseClass()

d) WhoseObject()

3. Which of these methods return a class object given its name?

a) getClass()

b) findClass()

c) getSystemClass()

d) findSystemClass()

Explanation:findSystemClass() returns a class object given its name.

4. Which of these class defines how the classes are loaded?

c) Runtime

d) ClassLoader

c) a

d) b

Explanation: getClass() is used to obtain the class of an object, here ‘a’ is an object of class ‘X’. hence a.getClass() returns ‘X’ which is stored

in class Class object obj.

X

Java Questions & Answers – Java.lang – Class

a) X

b) Y

c) class X

d) class Y

Explanation: getSuperClass() returns the super class of an object. b is an object of class Y which extends class X, Hence Super class of b is X.

therefore class X is printed.

class X

1. Which of the interface contains all the methods used for handling thread related operations in Java?

a) Runnable interface

b) Math interface

c) System interface

d) ThreadHandling interface

Explanation:Runnable interface defines all the methods for handling thread operations in Java.

2. Which of these class is used to make a thread?

d) Runnable

Explanation: Thread class is used to make threads in java, Thread encapsulates a thread of execution. To create a new thread the program will

either extend Thread or implement the Runnable interface.

3. Which of this interface is implemented by Thread class?

b) Connections

c) Set

d) MapConnections

4. Which of these methods of a Thread class is used to suspend a thread for a period of time?

Java Questions & Answers – Java.lang – ThreadGroup class & Runnable Interface

1. Which object Java application uses to create a new process?

b) Builder

c) ProcessBuilder

d) CreateBuilder

Explanation:Java application uses ProcessBuilder object to create a new process. By default, same set of environment variables passed which

are set in application’s virtual machine process.

2. Which of the following is true about Java system properties?

a) Java system properties are accessible by any process

b) Java system properties are accessible by processes they are added to

c) Java system properties are retrieved by System.getenv()

d) Java system properties are set by System.setenv()

Explanation:Java system properties are only used and accessible by the processes they are added.

3. Java system properties can be set at runtime.

Explanation:Java system properties can be set at runtime using System.setProperty(name, value) or using System.getProperties().load()

methods.

4. Which system property stores installation directory ofJRE?

a) user.home

b) java.class.path

c) java.home

d) user.dir

Explanation: java.home is the installation directory ofJava Runtime Environment.

5. What does System.getProperty(“variable”) return?

a) compilation error

b) value stored in variable

c) runtime error

Explanation: System.getProperty(“variable”) returns null value. Because, variable is not a property and if property does not exist, this method

returns null value.

6. What is true about the setProperties method?

a) setProperties method changes the set ofJava Properties which are persistent

Java Questions & Answers – Environment Properties

b) Changing the system properties within an application will affect future invocations

c) setProperties method changes the set ofJava Properties which are not persistent

d) setProperties writes the values directly into the file which stores all the properties

Explanation: The changes made by the setProperties method are not persistent. Hence, it does not affect future invocation.

7. How to use environment properties in the class?

a) @Environment

b) @Variable

c) @Property

d) @Autowired

Explanation:

@Autowired

private Environment env;

This is how environment variables are injected in the class where they can be used.

Explanation: @Value are used to inject the properties and assign them to variables.

9. Which environment variable is used to set java path?

a) JAVA

b) JAVA_HOME

c) CLASSPATH

d) MAVEN_HOME

Explanation:JAVA_HOME is used to store a path to the java installation.

10. How to read a classpath file?

a) InputStream in =this.getClass().getResource(“SomeTextFile.txt”);

b) InputStream in =this.getClass().getResourceClasspath(“SomeTextFile.txt”);

c) InputStream in =this.getClass().getResourceAsStream(“SomeTextFile.txt”);

d) InputStream in =this.getClass().getResource(“classpath:/SomeTextFile.txt”);

Explanation: This method can be used to load files using relative path to the package of the class.

1. Which of these is a process of writing the state of an object to a byte stream?

Explanation: Serialization is the process of writing the state of an object to a byte stream. This is used when you want to save the state of your

program to a persistent storage area.

2. Which of these process occur automatically by the java runtime system?

b) Garbage collection

Explanation: Serialization and deserialization occur automatically by java runtime system, Garbage collection also occur automatically but is

done by CPU or the operating system not by the java runtime system.

3. Which of these is an interface for control over serialization and deserialization?

c) FileFilter

4. Which of these interface extends DataOutput interface?

Explanation: ObjectOutput interface extends the DataOutput interface and supports object serialization.

5. Which of these is a method of ObjectOutput interface used to finalize the output state so that any buffers are cleared?

b) flush()

c) fflush()

d) close()

6. Which of these is method of ObjectOutput interface used to write the object to input or output stream as required?

Java Questions & Answers – Serialization – 1

a) write()

b) Write()

c) StreamWrite()

Explanation: writeObject() is used to write an object into invoking stream, it can be input stream or output stream.

a) s=Hello; i=-7; d=2.1E10

b) Hello; -7; 2.1E10

c) s; i; 2.1E10

s=Hello; i=-7; d=2.1E10

b) 3.5

Explanation: oos.writeFloat(3.5); writes in output stream which is extracted by x = ois.readInt(); and stored in x hence x contains 3.5.

3.5

1. How an object can become serializable?

a) If a class implements java.io.Serializable class

b) If a class or any superclass implements java.io.Serializable interface

c) Any object is serializable

d) No object is serializable

Explanation: A Java object is serializable if class or any its superclass implements java.io.Serializable or its subinterface java.io.Externalizable.

2. What is serialization?

Explanation: Serialization in Java is the process of turning object in memory into stream of bytes.

3. What is deserialization?

a) Turning object in memory into stream of bytes

b) Turning stream of bytes into an object in memory

c) Turning object in memory into stream of bits

d) Turning stream of bits into an object in memory

Explanation: Deserialization is the reverse process ofserialization which is turning stream of bytes into an object in memory.

4. How many methods Serializable has?

Explanation: Serializable interface does not have any method. It is also called a marker interface.

5. What type of members are not serialized?

a) Private

c) Static

Explanation: Allstatic and transient variables are not serialized.

6. If member does not implement serialization, which exception would be thrown?

b) SerializableException

Java Questions & Answers – Serialization – 2

c) NotSerializableException

d) UnSerializedException

Explanation:If member of a class does not implement serialization, NotSerializationException will be thrown.

7. Default Serialization process cannot be overridden.

Explanation: Default serialization process can be overridden.

8. Which of the following methods is used to avoid serialization of new class whose super class already implements Serialization?

a) writeObject()

b) readWriteObject()

c) writeReadObject()

d) unSerializaedObject()

Explanation: writeObject() and readObject() methods should be implemented to avoid Java serialization.

9. Which of the following methods is not used while Serialization and DeSerialization?

a) readObject()

b) readExternal()

c) readWriteObject()

d) writeObject()

Explanation: Using readObject(), writeObject(), readExternal() and writeExternal() methods Serialization and DeSerialization are implemented.

10. Serializaed object can be transferred via network.

Explanation: Serialized object can be transferred via network because Java serialized object remains in form of bytes which can be transmitted

over network.

1. Which of these is a process of extracting/removing the state of an object from a stream?

c) File Filtering

d) Deserialization

Explanation: Deserialization is a process by which the data written in the stream can be extracted out from the stream.

2. Which of these process occur automatically by java run time system?

a) Serialization

b) Memory allocation

c) Deserialization

Explanation: Serialization, deserialization and Memory allocation occur automatically by java run time system.

3. Which of these interface extends DataInput interface?

b) Externalization

Explanation: ObjectInput interface extends the DataInput interface and supports object serialization.

4. Which of these is a method of ObjectInput interface used to deserialize an object from a stream?

a) int read()

b) void close()

c) Object readObject()

d) Object WriteObject()

5. Which of these class extend InputStream class?

a) ObjectStream

b) ObjectInputStream

c) ObjectOutput

d) ObjectInput

Explanation: ObjectInputStream class extends the InputStream class and implements the ObjectInput interface.

a) 5

b) void

c) serialization

Java Questions & Answers – Serialization & Deserialization

Explanation: oos.writeInt(5); writes integer 5 in the Output stream which is extracted by z = ois.readInt(); and stored in z hence z contains 5.

a) -7

c) 2.1E10

d) deserialization

Explanation: x = ois.readInt(); will try to read an integer value from the stream ‘serial’ created before, since stream contains an object of

Myclass hence error will occur and it will be catched by catch printing deserialization.

$ javac serialization.java

$ java serialization

deserialization

d) 0

Explanation: New input stream is linked to steal‘serials’, an object ‘ois’ of ObjectInputStream is used to access this newly created stream,

ois.close(); closes the stream hence we can’t access the stream and ois.available() returns 0.

Explanation: oos.writeFloat(3.5); writes 3.5 in output stream. A new input stream is linked to stream ‘serials’, an object ‘ois’ of

ObjectInputStream is used to access this newly created stream, ois.available() gives the total number of byte in the input stream since a float

was written in the stream thus the stream contains 4 byte, hence 4 is returned and printed.

$ javac streams.java

$ java streams

a) “Success” to the output and “Welcome to Sanfoundry” to the file

b) only “Welcome to Sanfoundry” to the file

c) compile time error

d) No Output

Explanation: First, it will print “Success” and besides that it will write “Welcome to Sanfoundry” to the file sanfoundry.txt.

1. Which of these package contains classes and interfaces for networking?

d) java.network

2. Which of these is a protocolfor breaking and sending packets to an address across a network?

a) TCP/IP

b) DNS

c) Socket

d) Proxy Server

Explanation: TCP/IP – Transfer control protocol/Internet Protocol is used to break data into small packets an send them to an address across a

network.

3. How many ports of TCP/IP are reserved for specific protocols?

b) 1024

c) 2048

d) 512

4. How many bits are in a single IP address?

a) 8

b) 16

c) 32

d) 64

5. Which of these is a fullform of DNS?

a) Data Network Service

b) Data Name Service

c) Domain Network Service

d) Domain Name Service

6. Which of these class is used to encapsulate IP address and DNS?

Java Questions & Answers – Networking Basics

b) URL

d) ContentHandler

Explanation:InetAddress class encapsulate both IP address and DNS, we can interact with this class by using name of an IP host.

Explanation:InetAddress obj1 = InetAddress.getByName(“cisco.com”); creates object obj1 having DNS and IP address of cisco.com,

InetAddress obj2 = InetAddress.getByName(“sanfoundry.com”); creates obj2 having DNS and IP address ofsanfoundry.com, since both

these address point to two different locations false is returned by obj1.equals(obj2);.

a) Protocol: http

b) Host Name: www.sanfoundry.com

c) Port Number:-1

Explanation: getProtocol() give protocol which is http

getUrl() give name domain name

getPort() Since we have not explicitly set the port, default value that is -1 is printed.

a) cisco

b) cisco.com

c) www.cisco.com

cisco.com

1. Which of these interface abstractes the output of messages from httpd?

a) LogMessage

b) LogResponse

c) Httpdserver

d) httpdResponse

Explanation: LogMessage is a simple interface that is used to abstract the output of messages from the httpd.

2. Which of these class is used to create servers that listen for either local or remote client programs?

a) httpServer

b) ServerSockets

c) MimeHeader

d) HttpResponse

3. Which of these is a standard for communicating multimedia content over email?

c) Mime

Explanation: MIME is an internet standard for communicating multimedia content over email. The HTTP protocol uses and extends the notion of

MIME headers to pass attribute pairs between HTTP client and server.

4. Which of these methods is used to make raw MIME formatted string?

a) parse()

c) getString()

d) parseString()

5. Which of these class is used for operating on request from the client to the server?

b) httpDecoder

c) httpConnection

d) httpd

6. Which of these method of MimeHeader is used to return the string equivalent of the values stores on MimeHeader?

a) string()

Java Questions & Answers – Networking – Server, Sockets & httpd Class

b) toString()

c) convertString()

d) getString()

Explanation: toString() does the reverse of parse() method, it is used to return the string equivalent of the values stores on MimeHeader.

8. Which of these is an instance variable of class httpd?

a) port

b) cache

c) log

Explanation: There are 5 instance variables: port, docRoot, log, cache and stopFlag. All of them are private.

1. Which of these methods of httpd class is used to read data from the stream?

a) getDta()

b) GetResponse()

c) getStream()

d) getRawRequest()

Explanation: The getRawRequest() method reads data from a stream until it gets two consecutive newline characters.

2. Which of these method of httpd class is used to get report on each hit to HTTP server?

a) log()

b) logEntry()

c) logHttpd()

d) logResponse()

3. Which of these methods are used to find a URLfrom the cache of httpd?

a) findfromCache()

b) findFromCache()

c) serveFromCache()

d) getFromCache()

Explanation:serveFromCatche() is a boolean method that attempts to find a particular URLin the cache. If it is successful then the content of

that cache entry are written to the client, otherwise it returns false.

4. Which of these variables stores the number of hits that are successfully served out of cache?

a) hits

b) hitstocache

c) hits_to_cache

d) hits.to.cache

5. Which of these method of httpd class is used to write UrlCacheEntry object into local disk?

a) writeDiskCache()

b) writetoDisk()

c) writeCache()

d) writeDiskEntry()

Explanation: The writeDiskCache() method takes an UrlCacheEntry object and writes it persistently into the local disk. It constructs directory

names out of URL, making sure to replace the slash(/) characters with system dependent seperatorChar.

Java Questions & Answers – Networking – httpd.java Class

7. Which of these method is used to start a server thread?

Explanation:run() method is called when the server thread is started.

8. Which of these method is called when http daemon is acting like a normal web server?

a) Handle()

b) HandleGet()

c) handleGet()

d) Handleget()

1. What does URLstands for?

a) Uniform Resource Locator

b) Uniform Resource Latch

c) UniversalResource Locator

d) UniversalResource Latch

Explanation: URLis Uniform Resource Locator.

2. Which of these exceptions is thrown by URLclass’s constructors?

a) URLNotFound

b) URLSourceNotFound

c) MalformedURLException

d) URLNotFoundException

3. Which of these methods is used to know host of an URL?

a) host()

c) GetHost()

d) gethost()

4. Which of these methods is used to know the full URLof an URLobject?

a) fullHost()

b) getHost()

c) ExternalForm()

d) toExternalForm()

5. Which of these class is used to access actual bits or content information of a URL?

a) URL

b) URLDecoder

c) URLConnection

Explanation: URL, URLDecoder and URLConnection all there are used to access information stored in a URL.

c) www

Java Questions & Answers – URL Class

d) com

Explanation: obj.getProtocol() is used to know the protocol used by the host. http stands for hypertext transfer protocol, usually 2 types of

protocols are used http and https, where s in https stands for secured.

http

d) garbage value

Explanation: Since we have not explicitly set the port default value that is -1 is printed.

-1

www.sanfoundry.com

a) sanfoundry

b) sanfoundry.com

c) www.sanfoundry.com

d) https://www.sanfoundry.com/javamcq

Explanation: toExternalForm() is used to know the full URLof an URLobject.

https://www.sanfoundry.com/javamcq

1. Which of these is a wrapper around everything associated with a reply from an http server?

b) HttpResponse

c) HttpRequest

d) httpserver

Explanation: HttpResponse is wrapper around everything associated with a reply from an http server.

2. Which of these transfer protocol must be used so that URLcan be accessed by URLConnection class object?

a) http

b) https

c) Any Protocol can be used

Explanation: For a URLto be accessed from remote location http protocol must be used.

3. Which of these methods is used to know when was the URLlast modified?

a) LastModified()

b) getLastModified()

c) GetLastModified()

d) getlastModified()()

4. Which of these methods is used to know the type of content used in the URL?

a) ContentType()

b) contentType()

c) getContentType()

d) GetContentType()

5. Which of these data member of HttpResponse class is used to store the response from an http server?

a) status

b) address

c) statusResponse

d) statusCode

Explanation: When we send a request to an http server it responds with a status code this status code is stored in statusCode and a textual

equivalent which is stored in reasonPhrase.

Note: Host URLis written in html and simple text.

a) html

Java Questions & Answers – HttpResponse & URLConnection Class

b) text

c) html/text

d) text/html

text/html

Note: Host URLis having length of content 127.

a) 126

b) 127

127

Note: Host URL was last modified on july 18 tuesday 2013 .

a) july

b) 18-6-2013

c) Tue 18 Jun 2013

d) Tue Jun 18 2013

$ javac networking.java

$ java networking

Tue Jun 18 2013

1. Which of these is a bundle of information passed between machines?

a) Mime

b) Cache

c) Datagrams

d) DatagramSocket

Explanation: The Datagrams are the bundle of information passed between machines.

2. Which of these class is necessary to implement datagrams?

c) All of the mentioned

3. Which of these method of DatagramPacket is used to find the port number?

a) port()

b) getPort()

c) findPort()

d) recievePort()

4. Which of these method of DatagramPacket is used to obtain the byte array of data contained in a datagram?

a) getData()

b) getBytes()

c) getArray()

d) recieveBytes()

5. Which of these methods of DatagramPacket is used to find the length of byte array?

a) getnumber()

c) Length()

d) getLength()

Explanation: getLength returns the length of the valid data contained in the byte array that would be returned from the getData () method. This

typically is not equal to length of whole byte array.

6. Which of these class must be used to send a datagram packets over a connection?

a) InetAdress

Java Questions & Answers – Networking – Datagrams

b) DatagramPacket

c) DatagramSocket

Explanation:By using 5 classes we can send and receive data between client and server, these are InetAddress, Socket, ServerSocket,

DatagramSocket, and DatagramPacket.

7. Which of these method of DatagramPacket class is used to find the destination address?

a) findAddress()

c) Address()

d) whois()

8. Which of these is a return type of getAddress() method of DatagramPacket class?

a) DatagramPacket

b) DatagramSocket

c) InetAddress

d) ServerSocket

9. Which API gets the SocketAddress (usually IP address + port number) of the remote host that this packet is being sent to or is coming from.

a) getSocketAddress()

b) getAddress()

c) address()

Explanation: getSocketAddress() is used to get the socket address.

1. Which of these standard collection classes implements a dynamic array?

c) ArrayList

Explanation: ArrayList class implements a dynamic array by extending AbstractList class.

2. Which of these class can generate an array which can increase and decrease in size automatically?

a) ArrayList()

b) DynamicList()

c) LinkedList()

d) MallocList()

3. Which of these method can be used to increase the capacity of ArrayList object manually?

a) Capacity()

b) increaseCapacity()

c) increasecapacity()

d) ensureCapacity()

Explanation: When we add an element, the capacity of ArrayList object increases automatically, but we can increase it manually to specified

length x by using function ensureCapacity(x);

4. Which of these method of ArrayList class is used to obtain present size of an object?

c) index()

d) capacity()

5. Which of these methods can be used to obtain a static array from an ArrayList object?

a) Array()

b) covertArray()

c) toArray()

d) covertoArray()

6. Which of these method is used to reduce the capacity of an ArrayList object?

a) trim()

Java Questions & Answers – Java.util – ArrayList Class

b) trimSize()

c) trimTosize()

d) trimToSize()

a) [A, B, C, D].

b) [A, D, B, C].

c) [A, D, C].

Explanation: obj is an object of class ArrayList hence it is an dynamic array which can increase and decrease its size. obj.add(“X”) adds to the

array element X and obj.add(1,”X”) adds element x at index position 1 in the list, Hence obj.add(1,”D”) stores D at index position 1 of obj and

shifts the previous value stored at that position by 1.

[A, D, B, C].

d) Any Garbage Value

Explanation: Although obj.ensureCapacity(3); has manually increased the capacity of obj to 3 but the value is stored only at index 0, therefore

obj.size() returns the total number of elements stored in the obj i:e 1, it has nothing to do with ensureCapacity().

d) 4

Explanation: trimTosize() is used to reduce the size of the array that underlines an ArrayList object.

1. Map implements collection interface?

Explanation:Collection interface provides add, remove, search or iterate while map has clear, get, put, remove, etc.

2. Which of the below does not implement Map interface?

a) HashMap

c) EnumMap

d) Vector

Explanation: Vector implements AbstractList which internally implements Collection. Others come from implementing the Map interface.

3. What is the premise of equality for IdentityHashMap?

a) Reference equality

b) Name equality

c) Hashcode equality

d) Length equality

Explanation:IdentityHashMap is rarely used as it violates the basic contract of implementing equals() and hashcode() method.

4. What happens if we put a key object in a HashMap which exists?

a) The new object replaces the older object

b) The new object is discarded

c) The old object is removed from the map

d) It throws an exception as the key already exists in the map

Explanation: HashMap always contains unique keys. Ifsame key is inserted again, the new object replaces the previous object.

5. While finding the correct location for saving key value pair, how many times the key is hashed?

d) unlimited till bucket is found

Explanation: The key is hashed twice; first by hashCode() of Object class and then by internal hashing method of HashMap class.

6. Is hashmap an ordered collection.

Java Questions & Answers – Data Structures-HashMap

Explanation: Hashmap outputs in the order of hashcode of the keys. So it is unordered but will always have same result for same set of keys.

7. If two threads access the same hashmap at the same time, what would happen?

a) ConcurrentModificationException

b) NullPointerException

c) ClassNotFoundException

d) RuntimeException

Explanation: The code will throw ConcurrentModificationException if two threads access the same hashmap at the same time.

c) Collections.synchronizedMap(new HashMap());

d) Collections.synchronize(new HashMap());

Explanation:Collections.synchronizedMap() synchronizes entire map. ConcurrentHashMap provides thread safety without synchronizing entire

a) {1=null, 2=null, 3=null, 4=null, 5=null}

b) {5=null}

c) Exception is thrown

d) {1=null, 5=null, 3=null, 2=null, 4=null}

Explanation: HashMap needs unique keys. TreeMap sorts the keys while storing objects.

10. If large number of items are stored in hash bucket, what happens to the internalstructure?

a) The bucket willswitch from LinkedList to BalancedTree

b) The bucket will increase its size by a factor of load size defined

c) The LinkedList will be replaced by another hashmap

d) Any further addition throws Overflow exception

Explanation:BalancedTree will improve performance from O(n) to O(log n) by reducing hash collisions.

1. How can we remove an object from ArrayList?

a) remove() method

b) using Iterator

c) remove() method and using Iterator

d) delete() method

Explanation: There are 2 ways to remove an object from ArrayList. We can use overloaded method remove(int index) or remove(Object obj).

We can also use an Iterator to remove the object.

2. How to remove duplicates from List?

a) HashSet listToSet = new HashSet(duplicateList);

b) HashSet listToSet = duplicateList.toSet();

c) HashSet listToSet = Collections.convertToSet(duplicateList);

d) HashSet listToSet = duplicateList.getSet();

Explanation: Duplicate elements are allowed in List. Set contains unique objects.

3. How to sort elements of ArrayList?

a) Collection.sort(listObj);

b) Collections.sort(listObj);

c) listObj.sort();

d) Sorter.sortAsc(listObj);

Explanation:Collections provides a method to sort the list. The order ofsorting can be defined using Comparator.

4. When two threads access the same ArrayList object what is the outcome of the program?

a) Both are able to access the object

b) ConcurrentModificationException is thrown

c) One thread is able to access the object and second thread gets Null Pointer exception

d) One thread is able to access the object and second thread will wait till control is passed to the second one

Explanation: ArrayList is not synchronized. Vector is the synchronized data structure.

5. How is Arrays.asList() different than the standard way of initialising List?

a) Both are same

b) Arrays.asList() throws compilation error

c) Arrays.asList() returns a fixed length list and doesn’t allow to add or remove elements

d) We cannot access the list returned using Arrays.asList()

Explanation: List returned by Arrays.asList() is a fixed length list which doesn’t allow us to add or remove element from it.add() and remove()

method will throw UnSupportedOperationException if used.

6. What is the difference between length() and size() of ArrayList?

Java Questions & Answers – Data Structures-List

a) length() and size() return the same value

b) length() is not defined in ArrayList

c) size() is not defined in ArrayList

d) length() returns the capacity of ArrayList and size() returns the actual number of elements stored in the list

Explanation: length() returns the capacity of ArrayList and size() returns the actual number of elements stored in the list which is always less than

or equal to capacity.

7. Which class provides thread safe implementation of List?

b) CopyOnWriteArrayList

c) HashList

d) List

Explanation:CopyOnWriteArrayList is a concurrent collection class. Its very efficient if ArrayList is mostly used for reading purpose because it

allows multiple threads to read data without locking, which was not possible with synchronized ArrayList.

8. Which of the below is not an implementation of List interface?

a) RoleUnresolvedList

b) Stack

c) AttibuteList

d) SessionList

Explanation: SessionList is not an implementation of List interface. The others are concrete classes of List.

9. What is the worst case complexity of accessing an element in ArrayList?

a) O(n)

b) O(1)

c) O(nlogn)

d) O(2)

Explanation: ArrayList has O(1) complexity for accessing an element in ArrayList. O(n) is the complexity for accessing an element from

LinkedList.

10. When an array is passed to a method, will the content of the array undergo changes with the actions carried within the function?

Explanation:If we make a copy of array before any changes to the array the content will not change. Else the content of the array will undergo

changes.

1. public void setMyArray(String[] myArray)

3. if(myArray == null)

5. this.myArray = new String[0];

7. else

9. this.myArray = Arrays.copyOf(newArray, newArray.length);

1. What is the default clone of HashSet?

a) Deep clone

b) Shallow clone

c) Plain clone

d) Hollow clone

Explanation: Default clone() method uses shallow copy. The internal elements are not cloned. A shallow copy only copies the reference object.

2. Do we have get(Object o) method in HashSet.

Explanation: get(Object o) method is useful when we want to compare objects based on the comparison of values. HashSet does not provide

any way to compare objects. It just guarantees unique objects stored in the collection.

3. What does Collections.emptySet() return?

a) Immutable Set

b) Mutable Set

c) The type of Set depends on the parameter passed to the emptySet() method

d) Null object

Explanation:Immutable Set is useful in multithreaded environment. One does not need to declare generic type collection. It is inferred by the

context of method call.

4. What are the initial capacity and load factor of HashSet?

a) 10, 1.0

b) 32, 0.75

c) 16, 0.75

d) 32, 1.0

Explanation: We should not set the initial capacity too high and load factor too low if iteration performance is needed.

5. What is the relation between hashset and hashmap?

a) HashSet internally implements HashMap

b) HashMap internally implements HashSet

c) HashMap is the interface; HashSet is the concrete class

d) HashSet is the interface; HashMap is the concrete class

Explanation: HashSet is implemented to provide uniqueness feature which is not provided by HashMap. This also reduces code duplication and

provides the memory efficient behavior of HashMap.

b) Test – 10

Java Questions & Answers – Data Structures-Set

d) Compilation Failure

Explanation:Integer and Long are two different data types and different objects. So they will be treated as unique elements and not overridden.

7. Set has contains(Object o) method.

Explanation: Set has contains(Object o) method instead of get(Object o) method as get is needed for comparing object and getting

corresponding value.

8. What is the difference between TreeSet and SortedSet?

a) TreeSet is more efficient than SortedSet

b) SortedSet is more efficient than TreeSet

c) TreeSet is an interface; SortedSet is a concrete class

d) SortedSet is an interface; TreeSet is a concrete class

Explanation: SortedSet is an interface. It maintains an ordered set of elements. TreeSet is an implementation of SortedSet.

9. What happens if two threads simultaneously modify TreeSet?

a) ConcurrentModificationException is thrown

b) Both threads can perform action successfully

c) FailFastException is thrown

d) IteratorModificationException is thrown

Explanation: TreeSet provides fail-fast iterator. Hence when concurrently modifying TreeSet it throws ConcurrentModificationException.

10. What is the unique feature of LinkedHashSet?

a) It is not a valid class

b) It maintains the insertion order and guarantees uniqueness

c) It provides a way to store key values with uniqueness

d) The elements in the collection are linked to each other

Explanation: Set is a collection of unique elements.HashSet has the behavior of Set and stores key value pairs. The LinkedHashSet stores the

key value pairs in the order of insertion.

1. Which of these standard collection classes implements a linked list data structure?

a) AbstractList

2. Which of these classes implements Set interface?

b) HashSet

Explanation: HashSet and TreeSet implements Set interface where as LinkedList and ArrayList implements List interface.

3. Which of these method is used to add an element to the start of a LinkedList object?

b) first()

c) AddFirst()

d) addFirst()

4. Which of these method of HashSet class is used to add elements to its object?

b) Add()

c) addFirst()

5. Which of these methods can be used to delete the last element in a LinkedList object?

a) remove()

b) delete()

c) removeLast()

d) deleteLast()

Explanation:removeLast() and removeFirst() methods are used to remove elements in end and beginning of a linked list.

6. Which of this method is used to change an element in a LinkedList Object?

a) change()

Java Questions & Answers – Java.util – LinkedList, HashSet & TreeSet Class

Explanation: An element in a LinkedList object can be changed by first using get() to obtain the index or location of that object and the passing

that location to method set() along with its new value.

b) [D, B, C].

d) [D, A, B, C].

Explanation: obj.addFirst(“D”) method is used to add ‘D’ to the start of a LinkedList object obj.

[D, A, B, C].

a) [A, B].

b) [B, C].

c) [A, B, C, D].

d) [A, B, C].

$ javac Linkedlist.java

$ java Linkedlist

[B, C]

a) ABC 3

b) [A, B, C] 3

c) ABC 2

d) [A, B, C] 2

Explanation: HashSet obj creates an hash object which implements Set interface, obj.size() gives the number of elements stored in the object

obj which in this case is 3.

[A, B, C] 3

a) [1, 3, 5, 8, 9].

b) [3, 4, 1, 8, 9].

c) [9, 8, 4, 3, 1].

d) [1, 3, 4, 8, 9].

Explanation:TreeSet class uses set to store the values added by function add in ascending order using tree for storage

[1, 3, 4, 8, 9].

1. Which of these object stores association between keys and values?

a) Hash table

d) String

2. Which of these classes provide implementation of map interface?

b) HashMap

c) LinkedList

d) DynamicList

Explanation: AbstractMap, WeakHashMap, HashMap and TreeMap provide implementation of map interface.

3. Which of these method is used to remove all keys/values pair from the invoking map?

a) delete()

b) remove()

c) clear()

d) removeAll()

4. Which of these method Map class is used to obtain an element in the map having specified key?

a) search()

b) get()

c) set()

d) look()

5. Which of these methods can be used to obtain set of all keys in a map?

a) getAll()

b) getKeys()

c) keyall()

d) keySet()

Explanation: keySet() methods is used to get a set containing all the keys used in a map. This method provides set view of the keys in the

invoking map.

6. Which of these method is used add an element and corresponding key to a map?

Java Questions & Answers – Java.util – Maps

c) redo()

Explanation: Maps revolve around two basic operations – get() and put(). to put a value into a map, use put(), specifying the key and the value.

To obtain a value, call get() , passing the key as an argument. The value is returned.

a) {A 1, B 1, C 1}

c) {A-1, B-1, C-1}

d) {A=1, B=2, C=3}

{A=1, B=2, C=3}

b) {A, B, C}

c) {1, 2, 3}

d) [1, 2, 3].

Explanation: keySet() method returns a set containing all the keys used in the invoking map. Here keys are characters A, B & C. 1, 2, 3 are the

values given to these keys.

[A, B, C].

d) null

Explanation: obj.get(“B”) method is used to obtain the value associated with key “B”, which is 2.

a) [A, B, C].

b) [1, 2, 3].

c) {A=1, B=2, C=3}

d) [A=1, B=2, C=3].

Explanation: obj.entrySet() method is used to obtain a set that contains the entries in the map. This method provides set view of the invoking

map.

$ javac Maps.java

$ java Maps

[A=1, B=2, C=3].

1. Which of these class object can be used to form a dynamic array?

a) ArrayList

d) ArrayList & Vector

Explanation: Vectors are dynamic arrays, it contains many legacy methods that are not part of collection framework, and hence these methods

are not present in ArrayList. But both are used to form dynamic arrays.

2. Which of these are legacy classes?

a) Stack

b) Hashtable

Explanation: Stack, Hashtable, Vector, Properties and Dictionary are legacy classes.

3. Which of these is the interface of legacy?

4. What is the name of a data member of class Vector which is used to store a number of elements in the vector?

a) length

b) elements

c) elementCount

d) capacity

5. Which of these methods is used to add elements in vector at specific location?

c) AddElement()

Explanation: addElement() is used to add data in the vector, to obtain the data we use elementAt() and to first and last element we use

firstElement() and lastElement() respectively.

Java Questions & Answers – Java.util – Vectors & Stack

Explanation: obj.elementAt(1) returns the value stored at index 1, which is 2.

a) [3, 2, 6].

b) [3, 2, 8].

c) [3, 2, 6, 8].

d) [3, 2, 8, 6].

[3, 2, 8, 6].

Explanation:firstly elements 3, 2, 5 are entered in the vector obj, but when obj.removeAll(obj); is executed all the elements are deleted and

vector is empty, hence obj.isEmpty() returns true.

$ javac vector.java

$ java vector

a) [3, 5].

b) [3, 2].

c) [3, 2, 5].

d) [3, 5, 2].

Explanation: push() and pop() are standard functions of the class stack, push() inserts in the stack and pop removes from the stack. 3 & 2 are

inserted using push() the pop() is used which removes 2 from the stack then again push is used to insert 5 hence stack contains elements 3 & 5.

$ javac stack.java

$ java stack

[3, 5].

1. Which of these class object uses the key to store value?

a) Dictionary

2. Which of these method is used to insert value and its key?

c) insertElement()

d) addElement()

3. Which of these is the interface of legacy is implemented by Hashtable and Dictionary classes?

a) Map

b) Enumeration

c) HashMap

d) Hashtable

Explanation: Dictionary, Map & Hashtable all implement Map interface hence all of them uses keys to store value in the object.

4. Which of these is a class which uses String as a key to store the value in object?

b) ArrayList

c) Dictionary

d) Properties

5. Which of these methods is used to retrieve the elements in properties object at specific location?

Java Questions & Answers – Java.util – Dictionary, Hashtable & Properties

Explanation: Hashtable object obj contains values 3, 2, 8 when obj.contains(new Integer(5)) is executed it searches for 5 in the hashtable since

it is not present false is returned.

d) 3

0

{C=8, B=2}

a) {C=8, B=2}

b) [C=8, B=2].

c) {A=3, C=8, B=2}

d) [A=3, C=8, B=2].

Explanation: obj.toString returns String equivalent of the hashtable, which can also be obtained by simply writing System.out.print(obj); as print

system automatically converts the obj tostring equivalent.

$ javac hashtable.java

$ java hashtable

{A=3, C=8, B=2}

a) {AB, BC, CD}

b) [AB, BC, CD].

c) [3, 2, 8].

d) {3, 2, 8}

Explanation: obj.keySet() returns a set containing all the keys used in properties object, here obj contains keys AB, BC, CD therefore

obj.keySet() returns [AB, BC, CD].

$ javac properties.java

$ java properties

[AB, BC, CD].

1. Which of these class object has an architecture similar to that of array?

a) Bitset

b) Map

c) Hashtable

Explanation:Bitset class creates a special type of array that holds bit values. This array can increase in size as needed.

2. Which of these method is used to make a bit zero specified by the index?

b) set()

c) remove()

d) clear()

3. Which of these method is used to calculate number of bits required to hold the BitSet object?

a) size()

b) length()

c) indexes()

d) numberofBits()

4. Which of these is a method of class Date which is used to search whether object contains a date before the specified date?

a) after()

b) contains()

c) before()

d) compareTo()

Explanation: before() returns true if the invoking Date object contains a date that is earlier than one specified by date, otherwise it returns false.

5. Which of these methods is used to retrieve elements in BitSet object at specific location?

b) Elementat()

c) ElementAt()

d) getProperty()

Java Questions & Answers – Java.util – BitSet & Date class

a) 4 64

b) 5 64

c) 5 128

d) 4 128

Explanation: obj.length() returns the length allotted to object obj at time of initialization and obj.size() returns the size of current object obj, each

BitSet element is given 16 bits therefore the size is 4 * 16 = 64, whereas length is still 5.

5 64

a) Prints Present Date

b) Runtime Error

c) Any Garbage Value

d) Prints Present Time & Date

$ javac date.java

$ java date

Tue Jun 11 11:29:57 PDT 2013

a) {0, 1}

b) {2, 4}

c) {3, 4}

d) {3, 4, 5}

Explanation: obj1.and(obj2) returns an BitSet object which contains elements common to both the object obj1 and obj2 and stores this BitSet

in invoking object that is obj1. Hence obj1 contains 3 & 4.

{3, 4}

1. What is Remote method invocation (RMI)?

a) RMI allows us to invoke a method of java object that executes on another machine

b) RMI allows us to invoke a method of java object that executes on another Thread in multithreaded programming

c) RMI allows us to invoke a method of java object that executes parallely in same machine

Explanation:Remote method invocation RMI allows us to invoke a method of java object that executes on another machine.

2. Which of these package is used for remote method invocation?

b) java.rmi

c) java.lang.rmi

3. Which of these methods are member of Remote class?

a) checkIP()

b) addLocation()

c) AddServer()

Explanation:Remote class does not define any methods, its purpose is simply to indicate that an interface uses remote methods.

4. Which of these Exceptions is thrown by remote method?

a) RemoteException

b) InputOutputException

c) RemoteAccessException

d) RemoteInputOutputException

Explanation: Allremote methods throw RemoteException.

5. Which of these class is used for creating a client for a server-client operations?

a) serverClientjava

b) Client.java

c) AddClient.java

d) ServerClient.java

6. Which of these package is used for all the text related modifications?

Java Questions & Answers – Remote Method Invocation (RMI)

c) java.lang.text

d) java.text.modify

Explanation: java.text provides capabilities for formatting, searching and manipulating text.

1. Which of these packages contain all the collection classes?

b) java.util

d) java.awt

2. Which of these classes is not part ofJava’s collection framework?

a) Maps

c) Stack

d) Queue

Explanation: Maps is not a part of collection framework.

3. Which of this interface is not a part ofJava’s collection framework?

b) Set

c) SortedMap

d) SortedList

Explanation: SortedList is not a part of collection framework.

4. Which of these methods deletes all the elements from invoking collection?

a) clear()

b) reset()

c) delete()

d) refresh()

Explanation: clear() method removes all the elements from invoking collection.

5. What is Collection in Java?

a) A group of objects

b) A group of classes

c) A group of interfaces

Explanation: A collection is a group of objects, it is similar to String Template Library (STL) of C++ programming language.

a) 12885

b) 12845

c) 58881

Java Questions & Answers – Collection Framework Overview

d) 54881

Explanation: array was containing 5,4,3,2,1 but when method Arrays.fill(array, 1, 4, 8) is called it fills the index location starting with 1 to 4 by

value 8 hence array becomes 5,8,8,8,1.

58881

a) {0, 1, 3, 4}

b) {0, 1, 2, 4}

c) {0, 1, 2, 3, 4}

d) {0, 0, 0, 3, 4}

$ javac Bitset.java

$ java Bitset

{0, 1, 3, 4}

1. Which of these return type of hasNext() method of an iterator?

c) Boolean

d) Collections Object

Explanation: hasNext() returns boolean values true or false.

2. Which of these methods is used to obtain an iterator to the start of collection?

a) start()

b) begin()

c) iteratorSet()

d) iterator()

Explanation: To obtain an iterator to the start of the start of the collection we use iterator() method.

3. Which of these methods can be used to move to next element in a collection?

a) next()

b) move()

d) hasNext()

4. Which of these iterators can be used only with List?

a) Setiterator

b) ListIterator

c) Literator

5. Which of these is a method of ListIterator used to obtain index of previous element?

a) previous()

b) previousIndex()

c) back()

d) goBack()

Explanation: previousIndex() returns index of previous element. if there is no previous element then -1 is returned.

6. Which of these exceptions is thrown by remover() method?

b) SystemException

Java Questions & Answers – Iterators

c) ObjectNotFoundExeception

d) IllegalStateException

d) EMPTY

EMPTY

a) 2 8 5

b) 2 1 8

c) 2 5 8

d) 8 5 1

Explanation: i.next() returns the next element in the iteration. i.remove() removes from the underlying collection the last element returned by this

iterator (optional operation). This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying

collection is modified while the iteration is in progress in any way other than by calling this method.

$ javac Collection_iterators.java

$ java Collection_iterators

2 1 8

1. Which of these standard collection classes implements all the standard functions on list data structure?

b) LinkedList

c) HashSet

d) AbstractSet

2. Which of this method is used to make all elements of an equal to specified value?

a) add()

c) all()

d) set()

Explanation:fill() method assigns a value to all the elements in an array, in other words, it fills the array with specified value.

3. Which of these method of Array class is used sort an array or its subset?

a) binarysort()

b) bubblesort()

c) sort()

d) insert()

4. Which of these methods can be used to search an element in a list?

a) find()

b) sort()

c) get()

d) binaryserach()

Explanation: binaryserach() method uses binary search to find a specified value. This method must be applied to sorted arrays.

Explanation: obj1 and obj2 are an object of class ArrayList hence it is a dynamic array which can increase and decrease its size. obj.add(“X”)

adds to the array element X and obj.add(1,”X”) adds element x at index position 1 in the list, Both the objects obj1 and obj2 contain same

elements i:e A & B thus obj1.equals(obj2) method returns true.

$ javac Arraylist.java

$ java Arraylist

Java Questions & Answers – Java.util – Array Class

a) 2

3

1. Which of these interface declares core method that all collections will have?

a) set

b) EventListner

Explanation:Collection interfaces defines core methods that all the collections like set, map, arrays etc will have.

2. Which of these interface handle sequences?

c) Comparator

3. Which of this interface must contain a unique element?

c) Array

Explanation: Set interface extends collection interface to handle sets, which must contain unique elements.

4. Which of these is a Basic interface that all other interface inherits?

a) Set

b) Array

c) List

d) Collection

Explanation:Collection interface is inherited by all other interfaces like Set, Array, Map etc. It defines core methods that all the collections like

set, map, arrays etc will have

5. Which of these is static variable defined in Collections?

a) EMPTY_SET

b) EMPTY_LIST

c) EMPTY_MAP

a) 12345

b) 54321

Java Questions & Answers – Collections Interface

c) 1234

d) 5432

Explanation: Arrays.sort(array) method sorts the array into 1,2,3,4,5.

$ javac Array.java

$ java Array

12345

Explanation:Collections.sort(list) sorts the given list, the list was 2->8->5->1 after sorting it became 1->2->5->8.

1 2 5 8

c) 1 2 5 8

d) Any random order

1 5 2 8

(output will be different on your system)

1. Which of these is an incorrect form of using method max() to obtain a maximum element?

a) max(Collection c)

b) max(Collection c, Comparator comp)

c) max(Comparator comp)

d) max(List c)

Explanation:Its illegal to call max() only with comparator, we need to give the collection to be searched into.

2. Which of these methods sets every element of a List to a specified object?

b) fill()

c) Complete()

d) add()

3. Which of these methods can randomize all elements in a list?

a) rand()

b) randomize()

c) shuffle()

d) ambiguous()

Explanation:shuffle – randomizes all the elements in a list.

4. Which of these methods can convert an object into a List?

a) SetList()

b) ConvertList()

c) singletonList()

d) CopyList()

Explanation:singletonList() returns the object as an immutable List. This is an easy way to convert a single object into a list. This was added by

Java 2.0.

5. Which of these is true about unmodifiableCollection() method?

a) unmodifiableCollection() returns a collection that cannot be modified

b) unmodifiableCollection() method is available only for List and Set

c) unmodifiableCollection() is defined in Collection class

Explanation: unmodifiableCollection() is available for al collections, Set, Map, List etc.

Java Questions & Answers – Collection Algorithms

2 8 5 1

a) 2 8 5 1

b) 1 5 8 2

d) 2 1 8 5

Explanation:Collections.reverse(list) reverses the given list, the list was 2->8->5->1 after reversing it became 1->5->8->2.

$ javac Collection_Algos.java

$ java Collection_Algos

1 5 8 2

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

a) Run Time

b) Compilation Time

c) Can Occur Any Time

Explanation: Exceptions in Java are run-time errors.

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

c) thrown

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

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

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

Explanation:If an exception occurs within the try block, it is thrown and cached by catch block for processing.

5. Which of these keywords is used to manually throw an exception?

c) HelloWorld

Java Questions & Answers – Exceptional Handling Basics

Explanation: System.ou.print() function first converts the whole parameters into a string and then prints, before “Hello” goes to output stream 1 /

0 error is encountered which is cached by catch block printing just “World”.

B

c) AC

d) BC

Explanation:finally keyword is used to execute the code before try and catch block end.

BC

b) 05

Explanation: Value of variable sum is printed outside of try block, sum is declared only in try block, outside try block it is undefined.

sum cannot be resolved to a variable

1. Which of the following keywords is used for throwing exception manually?

Explanation: “throw’ keyword is used for throwing exception manually in java program. User defined exceptions can be thrown too.

2. Which of the following classes can catch all exceptions which cannot be caught?

a) RuntimeException

b) Error

d) ParentException

Explanation:Runtime errors cannot be caught generally. Error class is used to catch such errors/exceptions.

3. Which of the following is a super class of all exception type classes?

a) Catchable

d) Throwable

Explanation: Throwable is built in class and all exception types are subclass of this class. It is the super class of all exceptions.

4. Which of the following operators is used to generate instance of an exception which can be thrown using throw?

a) thrown

b) alloc

c) malloc

d) new

Explanation: new operator is used to create instance of an exception. Exceptions may have parameter as a String or have no parameter.

5. Which of the following keyword is used by calling function to handle exception thrown by called function?

c) try

Explanation: A method specifies behaviour of being capable of causing exception. Throws clause in the method declaration guards caller of the

method from exception.

6. Which of the following handles the exception when a catch is not used?

Java Questions & Answers – Exception Handling

b) throw handler

c) default handler

d) java run time system

Explanation: Default handler is used to handle all the exceptions if catch is not used to handle exception. Finally is called in any case.

7. Which part of code gets executed whether exception is caught or not?

b) try

c) catch

d) throw

Explanation: Finally block of the code gets executed regardless exception is caught or not. File close, database connection close, etc are usually

done in finally.

8. Which of the following should be true of the object thrown by a thrown statement?

a) Should be assignable to String type

b) Should be assignable to Exception type

c) Should be assignable to Throwable type

d) Should be assignable to Error type

Explanation: The throw statement should be assignable to the throwable type. Throwable is the super class of all exceptions.

9. At runtime, error is recoverable.

Explanation: Error is not recoverable at runtime. The control is lost from the application.

1. Which of these is a super class of all exceptional type classes?

b) RuntimeExceptions

d) Cacheable

Explanation: All the exception types are subclasses of the built in class Throwable.

2. Which of these class is related to all the exceptions that can be caught by using catch?

3. Which of these class is related to all the exceptions that cannot be caught?

c) RuntimeExecption

Explanation: Error class is related to java run time error that can’t be caught usually, RuntimeExecption is subclass of Exception class which

contains all the exceptions that can be caught.

4. Which of these handles the exception when no catch is used?

a) Default handler

c) throw handler

d) Java run time system

5. What exception thrown by parseInt() method?

b) ClassNotFoundException

c) NullPointerException

d) NumberFormatException

Explanation: parseInt() method parses input into integer. The exception thrown by this method is NumberFormatException.

Java Questions & Answers – Exceptions Types

d) First Exception then World

Exception in thread "main" java.lang.ArithmeticException: / by zero

a) -1

b) 0

c) -10

d) -101

Explanation: For the 1st iteration -1 is displayed. The 2nd exception is caught in catch block and 0 is displayed.

-10

1. Which of these keywords is used to generate an exception explicitly?

2. Which of these class is related to all the exceptions that are explicitly thrown?

c) Throwable

d) Throw

3. Which of these operator is used to generate an instance of an exception than can be thrown by using throw?

a) new

b) malloc

c) alloc

d) thrown

Explanation: new is used to create an instance of an exception. All of java’s built in run-time exceptions have two constructors: one with no

parameters and one that takes a string parameter.

4. Which of these keywords is used to by the calling function to guard against the exception that is thrown by called function?

Explanation:If a method is capable of causing an exception that it does not handle. It must specify this behaviour the behaviour so that callers of

the method can guard themselves against that exception. This is done by using throws clause in methods declaration.

c) Compile Time Error

d) 0TypeB

Explanation:Because we can’t go beyond array limit

Java Questions & Answers – Throw, Throws & Nested Try

c) Hello

d) Runtime Exception

at exception_handling.main

a) Finally

b) Compilation fails

c) The code runs with no output

d) An exception is thrown at runtime

Explanation:Because finally will execute always.

a) The program will not compile because no exceptions are specified

b) The program will not compile because no catch clauses are specified

c) Hello world

d) Hello world Finally executing

Explanation: None

1. Which of these clause will be executed even if no exceptions are found?

a) throws

b) finally

d) catch

Explanation:finally keyword is used to define a set of instructions that will be executed irrespective of the exception found or not.

2. A single try block must be followed by which of these?

a) finally

c) finally & catch

Explanation: try block can be followed by any of finally or catch block, try block checks for exceptions and work is performed by finally and

catch block as per the exception.

3. Which of these exceptions handles the divide by zero error?

b) MathException

c) IllegalAccessException

d) IllegarException

4. Which of these exceptions will occur if we try to access the index of an array beyond its length?

a) ArithmeticException

b) ArrayException

c) ArrayIndexException

d) ArrayIndexOutOfBoundsException

Explanation: ArrayIndexOutOfBoundsException is a built in exception that is caused when we try to access an index location which is beyond

the length of an array.

Note : Execution command line : $ java exception_handling

Java Questions & Answers – Finally & Built in Exceptions

Explanation: Try block is throwing NullPointerException but the catch block is used to counter Arithmetic Exception. Hence

c) AB

d) BA

Explanation: The inner try block does not have a catch which can tackle ArrayIndexOutOfBoundException hence finally is executed which

prints ‘A’ the outer try block does have catch for ArrayIndexOutOfBoundException exception but no such exception occurs in it hence its catch

is never executed and only ‘A’ is printed.

A

Note: Execution command line: $ java exception_handling one two

Main.java:9: error: 'try' without 'catch', 'finally' or resource declarations

1. What is the use of try & catch?

a) It allows us to manually handle the exception

b) It allows to fix errors

c) It prevents automatic terminating of the program in cases when an exception occurs

2. Which of these keywords are used for the block to be examined for exceptions?

Explanation: try is used for the block that needs to checked for exception.

3. Which of these keywords are used for the block to handle the exceptions generated by try block?

4. Which of these keywords are used for generating an exception manually?

a) try

b) catch

c) throw

d) check

a) try block need not to be followed by catch block

b) try block can be followed by finally block instead of catch block

c) try can be followed by both catch and finally block

d) try need not to be followed by anything

Explanation: try must be followed by either catch or finally block.

Java Questions & Answers – Try & Catch

World

Explanation: try must be followed by either catch or finally

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

Syntax error, insert "Finally" to complete BlockStatements

Explanation:finally block is always executed after try block, no matter exception is found or not.

HelloWorld

c) HelloWOrld

d) WorldWorld

Explanation:finally block is always executed after tryblock, no matter exception is found or not. catch block is executed only when exception is

found. Here divide by zero exception is found hence both catch and finally are executed.

WorldWorld

1. Which of these classes is used to define exceptions?

a) Exception

b) Throwable

c) Abstract

d) System

2. Which of these methods return description of an exception?

a) getException()

c) obtainDescription()

d) obtainException()

Explanation: getMessage() returns a description of the exception.

3. Which of these methods is used to print stack trace?

a) obtainStackTrace()

b) printStackTrace()

c) getStackTrace()

d) displayStackTrace()

4. Which of these methods return localized description of an exception?

a) getLocalizedMessage()

b) getMessage()

c) obtainLocalizedMessage()

d) printLocalizedMessage()

5. Which of these classes is super class of Exception class?

a) Throwable

b) System

c) RunTime

d) Class

Java Questions & Answers – Creating Exceptions

Explanation: Mexception is self defined exception, we are generating Myexception but catching DevideByZeroException which causes error.

a) A

b) B

Explanation: try block is throwing NullPointerException but the catch block is used to counter Arithmetic Exception. Hence

NullPointerException occurs since no catch is there which can handle it, runtime error occurs.

Exception in thread "main" java.lang.NullPointerException: Hello

a) 3

b) Exception

Explanation: Myexception is self defined exception.

java Output

Exception

Note : Execution command line : $ java exception_handling one

a) TypeA

b) TypeB

Explanation: try without catch or finally

$ javac exception_handling.java

$ java exception_handling

error: 'try' without 'catch', 'finally' or resource declarations

1. Which of this method can be used to make the main thread to be executed last among all the threads?

b) sleep()

d) call()

Explanation:By calling sleep() within main(), with long enough delay to ensure that all child threads terminate prior to the main thread.

2. Which of this method is used to find out that a thread is stillrunning or not?

b) Alive()

c) isAlive()

d) checkRun()

Explanation: The isAlive( ) method returns true if the thread upon which it is called is stillrunning. It returns false otherwise.

3. What is the default value of priority variable MIN_PRIORITY AND MAX_PRIORITY?

a) 0 & 256

b) 0 & 1

c) 1 & 10

d) 1 & 256

4. Which of these method waits for the thread to terminate?

b) isAlive()

c) join()

5. Which of these method is used to explicitly set the priority of a thread?

a) set()

b) make()

c) setPriority()

d) makePriority()

Explanation: The default value of priority given to a thread is 5 but we can explicitly change that value between the permitted values 1 & 10, this

is done by using the method setPriority().

Java Questions & Answers – isAlive(), Join() & Thread Synchronization

d) It’s a method that allow too many threads to access any information require

Explanation: Although we have not created any object of thread class still we can make a thread pointing to main method, we can refer it by

using this.

Thread[My Thread,5,main].

c) Exception

Explanation: join() method of Thread class waits for thread being called to finish or terminate, but here we have no condition which can

terminate the thread, hence code ‘t.join()’ leads to runtime error and nothing will be printed on the screen.

Explanation: isAlive() method is used to check whether the thread being called is running or not, here thread is the main() method which is

running till the program is terminated hence it returns true.

1. Which of these method is used to implement Runnable interface?

a) stop()

b) run()

d) stopThread()

Explanation: To implement Runnable interface, a class needs only to implement a single method called run().

2. Which of these method is used to begin the execution of a thread?

a) run()

b) start()

c) runThread()

d) startThread()

3. Which of these statement is incorrect?

a) A thread can be formed by implementing Runnable interface only

b) A thread can be formed by a class that extends Thread class

c) start() method is used to begin execution of the thread

d) run() method is used to begin execution of a thread before start() method in special cases

Explanation:run() method is used to define the code that constitutes the new thread, it contains the code to be executed. start() method is used

to begin execution of the thread that is execution of run(). run() itself is never used for starting execution of the thread.

My Thread

Java Questions & Answers – Implementing Runnable interface for Threads

Thread[My Thread,5,main]

a) My Thread

b) Thread[My Thread,5,main].

Explanation: Thread t has been made by using Runnable interface, hence it is necessary to use inherited abstract method run() method to specify

instructions to be implemented on the thread, since no run() method is used it gives a compilation error.

The type newthread must implement the inherited abstract method Runnable.run()

a) Thread[New Thread,0,main].

b) Thread[New Thread,1,main].

c) Thread[New Thread,5,main].

d) Thread[New Thread,10,main].

Explanation: Thread t has been made with default priority value 5 but in run method the priority has been explicitly changed to

MAX_PRIORITY of class thread, that is 10 by code ‘t.setPriority(Thread.MAX_PRIORITY);’ using the setPriority function of thread t.

Thread[New Thread,10,main]

Explanation: Threads t1 & t2 are created by class newthread that is implementing runnable interface, hence both the threads are provided their

own run() method specifying the actions to be taken. When constructor of newthread class is called first the run() method of t1 executes than

the run method of t2 printing 2 times “false” as both the threads are not equal one is having different priority than other, hence falsefalse is

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

b) ThreadPriority()

c) getPriority()

d) getThreadPriority()

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

a) sleep()

b) terminate()

c) suspend()

d) stop()

3. Which function of pre defined class Thread is used to check weather current thread being checked is stillrunning?

a) isAlive()

b) Join()

c) isRunning()

d) Alive()

Explanation:isAlive() function is defined in class Thread, it is used for implementing multithreading and to check whether the thread called upon

is stillrunning or not.

b) Thread[New Thread,5].

c) Thread[main,5,main].

Thread[New Thread,5,main]

c) New Thread

d) Thread[New Thread,5,main].

Explanation: The getName() function is used to obtain the name of the thread, in this code the name given to thread is ‘New Thread’.

Java Questions & Answers – Thread class

New Thread

d) 5

Explanation: The default priority given to a thread is 5.

c) true

d) false

Explanation: Thread t is seeded to currently program, hence when you run the program the thread becomes active & code ‘t.isAlive’ returns

true.

true

1. What is multithreaded programming?

a) It’s a process in which two different processes run simultaneously

b) It’s a process in which two or more parts ofsame process run simultaneously

c) It’s a process in which many different process are able to access same information

d) It’s a process in which a single process can access information from many sources

Explanation: Multithreaded programming a process in which two or more parts of the same process run simultaneously.

2. Which of these are types of multitasking?

a) Process based

b) Thread based

c) Process and Thread based

Explanation: There are two types of multitasking: Process based multitasking and Thread based multitasking.

3. Thread priority in Java is?

b) Float

c) double

d) long

Explanation:Java assigns to each thread a priority that determines hoe that thread should be treated with respect to others. Thread priority is

integers that specify relative priority of one thread to another.

4. What will happen if two thread of the same priority are called to be processed simultaneously?

a) Anyone will be executed first lexographically

b) Both of them will be executed simultaneously

c) None of them will be executed

d) It is dependent on the operating system

Explanation:In cases where two or more thread with same priority are competing for CPU cycles, different operating system handle this

situation differently. Some execute them in time sliced manner some depending on the thread they call.

5. Which of these statements is incorrect?

a) By multithreading CPU idle time is minimized, and we can take maximum use of it

b) By multitasking CPU idle time is minimized, and we can take maximum use of it

c) Two thread in Java can have the same priority

d) A thread can exist only in two states, running and blocked

Explanation: Thread exist in severalstates, a thread can be running, suspended, blocked, terminated & ready to run.

a) Thread[5,main].

Java Questions & Answers – Multithreading Basics

b) Thread[main,5].

c) Thread[main,0].

d) Thread[main,5,main].

c) 0

d) 1

Explanation: The output of program is Thread[main,5,main], in this priority assigned to the thread is 5. It’s the default value. Since we have not

named the thread they are named by the group to they belong i:e main method.

a) main

Explanation: The output of program is Thread[main,5,main], Since we have not explicitly named the thread they are named by the group to they

belong i:e main method. Hence they are named ‘main’.

Thread[main,5,main]

1. What requires less resources?

b) Process

c) Thread and Process

d) Neither Thread nor Process

Explanation: Thread is a lightweight and requires less resources to create and exist in the process. Thread shares the process resources.

2. What does not prevent JVM from terminating?

b) Daemon Thread

c) User Thread

d) JVM Thread

Explanation: Daemon thread runs in the background and does not prevent JVM from terminating. Child of daemon thread is also daemon

thread.

3. What decides thread priority?

a) Process

b) Process scheduler

c) Thread

d) Thread scheduler

Explanation: Thread scheduler decides the priority of the thread execution. This cannot guarantee that higher priority thread will be executed

first, it depends on thread scheduler implementation that is OS dependent.

4. What is true about time slicing?

a) Time slicing is OS service that allocates CPU time to available runnable thread

b) Time slicing is the process to divide the available CPU time to available runnable thread

c) Time slicing depends on its implementation in OS

d) Time slicing allocates more resources to thread

Explanation: Time slicing is the process to divide the available CPU time to available runnable thread.

5. Deadlock is a situation when thread is waiting for other thread to release acquired object.

Explanation: Deadlock is java programming situation where one thread waits for an object lock that is acquired by other thread and vice-versa.

6. What should not be done to avoid deadlock?

a) Avoid using multiple threads

b) Avoid hold several locks at once

Java Questions & Answers – Multithreading

c) Execute foreign code while holding a lock

d) Use interruptible locks

Explanation: To avoid deadlock situation in Java programming do not execute foreign code while holding a lock.

7. What is true about threading?

a) run() method calls start() method and runs the code

b) run() method creates new thread

c) run() method can be called directly without start() method being called

d) start() method creates new thread and calls code written in run() method

Explanation:start() eventually calls run() method. Start() method creates thread and calls the code written inside run method.

8. Which of the following is a correct constructor for thread?

a) Thread(Runnable a, String str)

b) Thread(int priority)

c) Thread(Runnable a, int priority)

d) Thread(Runnable a, ThreadGroup t)

Explanation: Thread(Runnable a, String str) is a valid constructor for thread. Thread() is also a valid constructor.

9. Which of the following stops execution of a thread?

a) Calling SetPriority() method on a Thread object

b) Calling notify() method on an object

c) Calling wait() method on an object

d) Calling read() method on an InputStream object

Explanation: notify() wakes up a single thread which is waiting for this object.

10. Which of the following will ensure the thread will be in running state?

a) yield()

c) wait()

d) Thread.killThread()

Explanation: wait() always causes the current thread to go into the object’s wait pool. Hence, using this in a thread will keep it in running state.

1. Which of these keywords are used to implement synchronization?

a) synchronize

b) syn

c) synch

d) synchronized

2. Which of this method is used to avoid polling in Java?

Explanation: Polling is a usually implemented by looping in CPU is wastes CPU time, one thread being executed depends on other thread output

and the other thread depends on the response on the data given to the first thread. In such situation CPU time is wasted, in Java this is avoided

by using methods wait(), notify() and notifyAll().

3. Which of these method is used to tell the calling thread to give up a monitor and go to sleep untilsome other thread enters the same monitor?

a) wait()

c) notifyAll()

d) sleep()

Explanation: wait() method is used to tell the calling thread to give up a monitor and go to sleep untilsome other thread enters the same monitor.

This helps in avoiding polling and minimizes CPU idle time.

4. Which of these method wakes up the first thread that called wait()?

a) wake()

5. Which of these method wakes up all the threads?

a) wakeAll()

c) start()

d) notifyAll()

Explanation: notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread willrun first.

Java Questions & Answers – Creating Threads

6. What is synchronization in reference to a thread?

a) It’s a process of handling situations when two or more threads need access to a shared resource

b) It’s a process by which many thread are able to access same shared resource simultaneously

c) It’s a process by which a method is able to access many different threads simultaneously

d) It’s a method that allow too many threads to access any information the require

Explanation: When two or more threads need to access the same shared resource, they need some way to ensure that the resource will be used

by only one thread at a time, the process by which this is achieved is called synchronization

Explanation: obj1.t.wait() causes main thread to go out of processing in sleep state hence causes exception and “Main thread interrupted” is

printed.

Main thread interrupted

Explanation: Thread.sleep(1000) has caused all the threads to be suspended for some time, hence onj1.t.isAlive() returns false.

c) Main thread interrupted

Explanation:Both obj1 and obj2 have threads with different name that is “one” and “two” hence obj1.t.equals(obj2.t) returns false.

false

c) truetrue

d) falsefalse

Explanation: This program was previously done by using Runnable interface, here we have used Thread class. This shows both the method are

equivalent, we can use any of them to create a thread.

$ javac multithreaded_programing.java

$ java multithreaded_programing

falsefalse

1. What does AWT stands for?

a) All Window Tools

b) All Writing Tools

c) Abstract Window Toolkit

d) Abstract Writing Toolkit

Explanation: AWT stands for Abstract Window Toolkit, it is used by applets to interact with the user.

2. Which of these is used to perform all input & output operations in Java?

a) streams

b) Variables

c) classes

d) Methods

Explanation: Like in any other language, streams are used for input and output operations.

3. Which of these is a type ofstream in Java?

a) Integer stream

b) Short stream

c) Byte stream

d) Long stream

Explanation:Java defines only two types ofstreams – Byte stream and character stream.

4. Which of these classes are used by Byte streams for input and output operation?

c) Reader

Explanation:Byte stream uses InputStream and OutputStream classes for input and output operation.

5. Which of these classes are used by character streams for input and output operations?

6. Which of these class is used to read from byte array?

Java Questions & Answers – Input & Output Basics

c) ArrayInputStream

d) ByteArrayInputStream

a) abcqfgh

b) abc

c) abcq

abcq

a) 4

b) 5

c) 6

d) 7

Explanation: length() method is used to obtain length of StringBuffer object, length of “Hello” is 5.

5

1. Which exception is thrown by read() method?

b) InterruptedException

c) SystemException

d) SystemInputException

Explanation:read method throws IOException.

2. Which of these is used to read a string from the input stream?

b) getLine()

c) read()

d) readLine()

3. Which of these class is used to read characters and strings in Java from console?

a) BufferedReader

b) StringReader

c) BufferedStreamReader

d) InputStreamReader

4. Which of these class is implemented by FilterInputStream class?

b) InputOutputStream

c) BufferedInputStream

d) SequenceInputStream

Explanation: FileInputStream implements InputStream.

b) Hello stop

c) World

d) Hello stop World

Explanation: “stop” will be able to terminate the do-while loop only when it occurs singly in a line. “Hello stop World” does not terminate the

loop.

Hello stop World

Java Questions & Answers – Reading Console Input

b) World

c) Helloworld

d) Hello World

Explanation: append() method of class StringBuffer is used to concatenate the string representation to the end of invoking string.

Hello World

a) abc’

b) abcdef/’

c) abc’def/’egh

d) abcqfghq

Explanation: \’ is used for single quotes that is for representing ‘ .

$ javac Input_Output.java

$ java Input_Output

abc'

1. Which of these class contains the methods print() & println()?

a) System

b) System.out

d) PrintStream

Explanation: print() and println() are defined under the class PrintStream, System.out is the byte stream used by these methods .

2. Which of these methods can be used to writing console output?

a) print()

b) println()

3. Which of these classes are used by character streams output operations?

b) Writer

c) ReadStream

d) InputOutputStream

Explanation:Character streams uses Writer and Reader classes for input & output operations.

4. Which of these class is used to read from a file?

a) InputStream

b) BufferedInputStream

c) FileInputStream

d) BufferedFileInputStream

a) 6 4 6 9

b) 5 4 5 9

c) 7 8 8 9

d) 4 3 6 9

Explanation: indexof(‘c’) and lastIndexof(‘c’) are pre defined function which are used to get the index of first and last occurrence of

the character pointed by c in the given array.

6 4 6 9

Java Questions & Answers – Writing Console Output

Explanation:Character.isDigit(c[i]),Character.isUpperCase(c[i]),Character.isWhitespace(c[i]) are the function of library java.lang

they are used to find weather the given character is ofspecified type or not. They return true or false i:e Boolean variable.

a is a lower case Letter

is White space character

a) Hello

b) olleH

c) HelloolleH

d) olleHHello

Explanation:reverse() method reverses all characters. It returns the reversed object on which it was called.

olleH

1. Which of these class contains the methods used to write in a file?

a) FileStream

b) FileInputStream

c) BUfferedOutputStream

d) FileBufferStream

2. Which of these exception is thrown in cases when the file specified for writing is not found?

d) FileInputException

Explanation:In cases when the file specified is not found, then FileNotFoundException is thrown by java run-time system, earlier versions of

java used to throw IOException but after Java 2.0 they throw FileNotFoundException.

3. Which of these methods are used to read in from file?

a) get()

b) read()

c) scan()

d) readFileInput()

4. Which of these values is returned by read() method is end of file (EOF) is encountered?

c) -1

d) Null

Explanation: Each time read() is called, it reads a single byte from the file and returns the byte as an integer value. read() returns -1 when the

end of the file is encountered.

5. Which of these exception is thrown by close() and read() methods?

b) FileException

c) FileNotFoundException

d) FileInputOutputException

Explanation:Both close() and read() method throw IOException.

Java Questions & Answers – Reading & Writing Files

6. Which of these methods is used to write() into a file?

a) put()

b) putFile()

c) write()

d) writeFile()

Note: inputoutput.java is stored in the disk.

c) prints number of bytes in file

d) prints number of characters in the file

Explanation: obj.available() returns the number of bytes.

1422

(Output will be different in your case)

a) AaBaCa

b) ABCaaa

c) AaaBaaCaa

d) AaBaaCaaa

$ javac filesinputoutput.java

$ java filesinputoutput

AaBaaCaaa

d) abcdef

abc

1. Which of these functions is called to display the output of an applet?

c) displayApplet()

d) PrintApplet()

Explanation: Whenever the applet requires to redraw its output, it is done by using method paint().

2. Which of these methods can be used to output a string in an applet?

b) print()

Explanation: drawString() method is defined in Graphics class, it is used to output a string in an applet.

3. Which of these methods is a part of Abstract Window Toolkit (AWT) ?

a) display()

b) paint()

c) drawString()

d) transient()

Explanation: paint() is an abstract method defined in AWT.

4. Which of these modifiers can be used for a variable so that it can be accessed from any thread or parts of a program?

a) transient

b) volatile

c) global

d) No modifier is needed

Explanation: The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other part of the

program. Specially used in situations involving multithreading.

5. Which of these operators can be used to get run time information about an object?

a) getInfo

b) Info

c) instanceof

d) getinfoof

a) A Simple Applet

b) A Simple Applet 20 20

Java Questions & Answers – Applets Fundamentals

A Simple Applet

(Output comes in a new java application)

b) 50

c) 100

d) System dependent

Explanation: the code in pain() method – g.drawString(“A Simple Applet”,20,20); draws a applet box of length 20 and width 20.

method we can not define and use drawString or any Graphic class methods.

a) abc

b) abcd

c) abcde

Explanation: No output is printed. CharArrayReader object input1 contains string “abcdefgh” whereas object input2 contains string “bcde”,

when while((i=input1.read())==(j=input2.read())) is executed the starting character of each object is compared since they are unequal control

comes out of loop and nothing is printed on the screen.

$ javac Chararrayinput.java

$ java Chararrayinput

1. Which of these package is used for text formatting in Java programming language?

a) java.text

c) java.awt.text

Explanation: java.text allows formatting, searching and manipulating text.

2. Which of this class can be used to format dates and times?

a) Date

b) SimpleDate

c) DateFormat

d) textFormat

Explanation: DateFormat is an abstract class that provides the ability to format and parse dates and times.

3. Which of these method returns an instance of DateFormat that can format time information?

a) getTime()

b) getTimeInstance()

c) getTimeDateinstance()

d) getDateFormatinstance()

Explanation: getTimeInstance() method returns an instance of DateFormat that can format time information.

4. Which of these class allows us to define our own formatting pattern for dates and time?

a) DefinedDateFormat

b) SimpleDateFormat

c) ComplexDateFormat

d) UsersDateFormat

Explanation: The DateFormat is a concrete subclass of DateFormat. It allows you to define your own formatting patterns that are used to

display date and time information.

5. Which of these formatting strings of SimpleDateFormat class is used to print AM or PM in time?

a) a

b) b

c) c

d) d

Explanation:By using format string “a” we can print AM/PM in time.

6. Which of these formatting strings of SimpleDateFormat class is used to print week of the year?

a) w

Java Questions & Answers – Text Formatting

b) W

c) s

d) S

Explanation:By using format string “w” we can print week in a year whereas by using ‘W’ we can print week of a month.

55:03:04

Note : The program is executed at 3 hour 55 minutes and 4 sec (24 hours time).

a) 3:55:4

b) 3.55.4

c) 55:03:04

d) 03:55:04

Explanation: The code “sdf = new SimpleDateFormat(“hh:mm:ss”);” create a SimpleDataFormat class with format hh:mm:ss where h is hours, m

is month and s is seconds.

03:55:04

Note: The program is executed at 3 hour 55 minutes and 4 sec on Monday, 15 July(24 hours time).

a) Mon Jul 15 2013

b) Jul 15 2013

c) 55:03:04 Mon Jul 15 2013

d) 03:55:04 Jul 15 2013

Mon Jul 15 2013

Note : The program is executed at 3 hour 55 minutes and 4 sec on Monday, 15 July(24 hours time).

a) z

b) Jul

c) Mon

d) PDT

Explanation:format string “z” is used to print time zone.

$ javac Date_formatting.java

$ java Date_formatting

PDT

1. Which of the following is not a class of java.util.regex?

b) matcher class

d) Regex class

Explanation: java.util.regex consists 3 classes. PatternSyntaxException indicates syntax error in regex.

2. What is the significance of Matcher class for regular expression in java?

a) interpretes pattern in the string

b) Performs match in the string

c) interpreted both pattern and performs match operations in the string

d) None of the mentioned.

Explanation: macther() method is invoked using matcher object which interpretes pattern and performs match operations in the input string.

3. Object of which class is used to compile regular expression?

a) Pattern class

b) Matcher class

c) PatternSyntaxException

Explanation: object of Pattern class can represent compiled regular expression.

4. Which capturing group can represent the entire expression?

a) group *

b) group 0

c) group * or group 0

d) Noe of the mentioned

Explanation: Group 0 is a special group which represents the entire expression.

5. groupCount reports a total number of Capturing groups.

Explanation: groupCount reports total number of Capturing groups. this does not include special group, group 0.

6. Which of the following matches nonword character using regular expression in java?

a) \w

b) \W

c) \s

d) \S

Java Questions & Answers – Regular Expression

Explanation: \W matches nonword characters. [0-9], [A-Z] and _ (underscore) are word characters. All other than these characters are

nonword characters.

7. Which of the following matches end of the string using regular expression in java?

a) \z

b) \\

c) \*

d) \Z

Explanation: \z is used to match end of the entire string in regular expression in java.

8. What does public int end(int group) return?

a) offset from last character of the subsequent group

b) offset from first character of the subsequent group

c) offset from last character matched

d) offset from first character matched

Explanation: public int end(int group) returns offset from the last character of the subsequent group.

9. what does public String replaceAll(string replace) do?

a) Replace all characters that matches pattern with a replacement string

b) Replace first subsequence that matches pattern with a replacement string

c) Replace all other than first subsequence of that matches pattern with a replacement string

d) Replace every subsequence of the input sequence that matches pattern with a replacement string

Explanation:replaceAll method replaces every subsequence of the sequence that matches pattern with a replacement string.

10. What does public int start() return?

a) returns start index of the input string

b) returns start index of the current match

c) returns start index of the previous match

Explanation: public int start() returns index of the previous match in the input string.

1. Which of these packages contains all the classes and methods required for even handling in Java?

c) java.event

d) java.awt.event

Explanation: Most of the event to which an applet response is generated by a user. Hence they are in Abstract Window Kit package,

java.awt.event.

2. What is an event in delegation event model used by Java programming language?

a) An event is an object that describes a state change in a source

b) An event is an object that describes a state change in processing

c) An event is an object that describes any change by the user and system

d) An event is a class used for defining object, to create events

Explanation: An event is an object that describes a state change in a source.

3. Which of these methods are used to register a keyboard event listener?

a) KeyListener()

b) addKistener()

c) addKeyListener()

d) eventKeyboardListener()

4. Which of these methods are used to register a mouse motion listener?

a) addMouse()

b) addMouseListener()

c) addMouseMotionListner()

d) eventMouseMotionListener()

5. What is a listener in context to event handling?

a) A listener is a variable that is notified when an event occurs

b) A listener is a object that is notified when an event occurs

c) A listener is a method that is notified when an event occurs

Explanation: A listener is a object that is notified when an event occurs. It has two major requirements first, it must have been registered with

one or more sources to receive notification about specific event types, and secondly it must implement methods to receive and process these

notifications.

Java Questions & Answers – Event Handling Basics

6. Event class is defined in which of these libraries?

b) java.lang

c) java.net

d) java.util

7. Which of these methods can be used to determine the type of event?

a) getID()

b) getSource()

c) getEvent()

d) getEventObject()

Explanation: getID() can be used to determine the type of an event.

8. Which of these class is super class of all the events?

a) EventObject

b) EventClass

c) ActionEvent

d) ItemEvent

Explanation: EventObject class is a super class of all the events and is defined in java.util package.

9. Which of these events will be notified ifscroll bar is manipulated?

Explanation: AdjustmentEvent is generated when a scroll bar is manipulated.

10. Which of these events will be generated if we close an applet’s window?

c) AdjustmentEvent

Explanation: WindowEvent is generated when a window is activated, closed, deactivated, deiconfied, iconfied, opened or quit.

1. Which of these events is generated when a button is pressed?

Explanation: Action event is generated when a button is pressed, a list item is double-clicked or a menu item is selected.

2. Which of these methods can be used to obtain the command name for invoking ActionEvent object?

a) getCommand()

b) getActionCommand()

d) getActionEventCommand()

3. Which of these are integer constants defined in ActionEvent class?

a) ALT_MASK

b) CTRL_MASK

c) SHIFT_MASK

Explanation: Action event defines 4 integer constants ALT_MASK, CTRL_MASK, SHIFT_MASK and ACTION_PERFORMED

4. Which of these methods can be used to know which key is pressed?

a) getKey()

b) getModifier()

c) getActionKey()

d) getActionEvent()

Explanation: The getModifiers() methods returns a value that indicates which modifiers keys (ALT, CTRL, META, SHIFT) were pressed when

the event was generated.

5. Which of these events is generated by scroll bar?

a) ActionEvent

b) KeyEvent

c) WindowEvent

d) AdjustmentEvent

6. Which of these methods can be used to determine the type of adjustment event?

a) getType()

Java Questions & Answers – ActionEvent & AdjustmentEvent Class

b) getEventType()

c) getAdjustmentType()

d) getEventObjectType()

7. Which of these methods can be used to know the degree of adjustment made by the user?

a) getValue()

b) getAdjustmentType()

c) getAdjustmentValue()

d) getAdjustmentAmount()

Explanation: The amount of the adjustment can be obtained from the getvalue() method, it returns an integer value corresponding to the amount

of adjustment made.

8. Which of these constant value will change when the button at the end ofscroll bar was clicked to increase its value?

a) BLOCK_DECREMENT

b) BLOCK_INCREMENT

c) UNIT_DECREMENT

d) UNIT_INCREMENT

Explanation: UNIT_INCREMENT VALUE will change when the button at the end ofscroll bar was clicked to increase its value.

1. Which of these events is generated when the size of an event is changed?

Explanation: A ComponentEvent is generated when the size, position or visibility of a component is changed.

2. Which of these events is generated when the component is added or removed?

Explanation: A ContainerEvent is generated when a component is added to or removed from a container. It has two integer constants

COMPONENT_ADDED & COMPONENT_REMOVED.

3. Which of these methods can be used to obtain the reference to the container that generated a ContainerEvent?

a) getContainer()

b) getContainerCommand()

c) getActionEvent()

d) getContainerEvent()

4. Which of these methods can be used to get reference to a component that was removed from a container?

a) getComponent()

b) getchild()

c) getContainerComponent()

d) getComponentChild()

Explanation: The getChild() method returns a reference to the component that was added to or removed from the container.

5. Which of these are integer constants of ComponentEvent class?

a) COMPONENT_HIDDEN

b) COMPONENT_MOVED

c) COMPONENT_RESIZE

Explanation: The component event class defines 4 constants COMPONENT_HIDDEN, COMPONENT-MOVED, COMPONENT-RESIZE

and COMPONENT-SHOWN.

6. Which of these events is generated when computer gains or loses input focus?

Java Questions & Answers – ComponentEvent, ContainerEvent & FocusEvent Class

7. FocusEvent is subclass of which of these classes?

8. Which of these methods can be used to know the type of focus change?

a) typeFocus()

b) typeEventFocus()

c) isTemporary()

d) isPermanent()

Explanation: There are two types of focus events – permanent and temporary. The isTemporary() method indicates if this focus change is

temporary, it returns a Boolean value.

9. Which of these is superclass of ContainerEvent class?

Explanation:ContainerEvent is superclass of ContainerEvent, FocusEvent, KeyEvent, MouseEvent and WindowEvent.

1. Which of these events is generated when the window is closed?

a) TextEvent

b) MouseEvent

c) FocusEvent

d) WindowEvent

Explanation: A WindowEvent is generated when a window is opened, close, activated or deactivated.

2. Which of these methods can be used to obtain the coordinates of a mouse?

a) getPoint()

b) getCoordinates()

c) getMouseXY()

d) getMouseCordinates()

Explanation: getPoint() method can be used to obtain coordinates of a mouse, alternatively we can use getX() and getY() methods for x and y

coordinates of mouse respectively.

3. Which of these methods can be used to change location of an event?

a) ChangePoint()

b) TranslatePoint()

c) ChangeCordinates()

d) TranslateCordinates()

4. Which of these are integer constants of TextEvent class?

a) TEXT_CHANGED

b) TEXT_FORMAT_CHANGED

c) TEXT_VALUE_CHANGED

d) TEXT_sIZE_CHANGED

Explanation: TextEvent defines a single integer constant TEXT_VALUE_CHANGED.

5. Which of these methods is used to obtain the object that generated a WindowEvent?

a) getMethod()

b) getWindow()

c) getWindowEvent()

d) getWindowObject()

6. MouseEvent is subclass of which of these classes?

a) ComponentEvent

Java Questions & Answers – MouseEvent, TextEvent & WindowEvent Class

b) ContainerEvent

7. Which of these methods is used to get x coordinate of the mouse?

a) getX()

b) getXCoordinate()

c) getCoordinateX()

d) getPointX()

Explanation: getX() and getY() are used to obtain X AND Y coordinates of the mouse.

8. Which of these are constants defined in WindowEvent class?

a) WINDOW_ACTIVATED

b) WINDOW_CLOSED

c) WINDOW_DEICONIFIED

Explanation: WindowEvent class defines 7 constants – WINDOW_ACTIVATED, WINDOW_CLOSED, WINDOW_OPENED,

WINDOW_DECONIFIED, WINDOW_CLOSING, WINDOW_DEACTIVATED, WINDOW_ICONIFIED.

9. Which of these is superclass of WindowEvent class?

a) WindowEvent

c) ItemEvent

Explanation:ComponentEvent is superclass of ContainerEvent, FocusEvent, KeyEvent, MouseEvent and WindowEvent.

1. Which of these packages contains all the event handling interfaces?

c) java.awt.event

d) java.event

2. Which of these interfaces handles the event when a component is added to a container?

c) FocusListener

Explanation: The ContainerListener defines methods to recognize when a component is added to or removed from a container.

3. Which of these interfaces define a method actionPerformed()?

Explanation: ActionListener defines the actionPerformed() method that is invoked when an adjustment event occurs.

4. Which of these interfaces define four methods?

d) InputListener

Explanation:ComponentListener defines four methods componentResized(), componentMoved(), componentShown() and

componentHidden().

5. Which of these interfaces define a method itemStateChanged()?

a) ComponentListener

b) ContainerListener

c) ActionListener

d) ItemListener

6. Which of these methods willrespond when you click any button by mouse?

a) mouseClicked()

Java Questions & Answers – Event Listeners Interfaces

b) mouseEntered()

c) mousePressed()

Explanation: when we click a button, first we enter the region of button hence mouseEntered() method responds then we press the button which

leads to respond from mouseClicked() and mousePressed().

7. Which of these methods will be invoked if a character is entered?

a) keyPressed()

b) keyReleased()

c) keyTyped()

d) keyEntered()

8. Which of these methods is defined in MouseMotionAdapter class?

a) mouseDragged()

b) mousePressed()

c) mouseReleased()

d) mouseClicked()

Explanation: The MouseMotionAdapter class defines 2 methods – mouseDragged() and mouseMoved.

9. Which of these is a superclass of all Adapter classes?

a) Applet

b) ComponentEvent

c) Event

d) InputEvent

Explanation: All Adapter classes extend Applet class.

1. Which class is used to generate random number?

a) java.lang.Object

b) java.util.randomNumber

c) java.util.Random

d) java.util.Object

Explanation: java.util.random class is used to generate random numbers in java program.

2. Which method is used to generate boolean random values in java?

a) nextBoolean()

b) randomBoolean()

c) previousBoolean()

d) generateBoolean()

Explanation: nextBoolean() method of java.util.Random class is used to generate random numbers.

3. What is the return type of Math.random() method?

a) Integer

b) Double

c) String

d) Boolean

Explanation: Math.random() method returns floating point number or precisely a double.

4. Random is a final class?

Explanation:Random is not a final class and can be extended to implement the algorithm as per requirement.

5. What is the range of numbers returned by Math.random() method?

a) -1.0 to 1.0

b) -1 to 1

c) 0 to 100

d) 0.0 to 1.0

Explanation: Math.random() returns only double value greater than or equal to 0.0 and less than 1.0.

6. How many bits are used for generating random numbers?

a) 32

b) 64

c) 48

d) 8

Java Questions & Answers – Random Number

Explanation:Random number can accept 64 bits but it only uses 48 bits for generating random numbers.

a) Random number between 1 to 15, including 1 and 15

b) Random number between 1 to 15, excluding 15

c) Random number between 1 to 15, excluding 1

d) Random number between 1 to 15, excluding 1 and 15

Explanation:random.nextInt(15) + 1; returns random numbers between 1 to 15 including 1 and 15.

a) Random number between 4 to 7, including 4 and 7

b) Random number between 4 to 7, excluding 4 and 7

c) Random number between 4 to 10, excluding 4 and 10

d) Random number between 4 to 10, including 4 and 10

Explanation:random.nextInd(7) + 4; returns random numbers between 4 to 10 including 4 and 10. it follows “nextInt(max – min +1) + min”

formula.

9. Math.random() guarantees uniqueness?

Explanation: Math.random() doesn’t guarantee uniqueness. To guarantee uniqueness we must store the generated value in the database and

compare against already generated values.

10. What is the signature of Math.random() method?

a) public static double random()

b) public void double random()

c) public static int random()

d) public void int random()

Explanation: public static double random() is the utility method provided by Math class which returns double.

1. Which of these class produce objects with respect to geographical locations?

a) TimeZone

b) Locale

c) Date

d) SimpleTimeZone

Explanation: The Locale class isinstantiated to produce objects that each describe a geographical or culturalregion.

2. Which of these methods is not a Locale class?

a) UK

b) US

c) INDIA

d) KOREA

Explanation:INDIA is not a Locale class.

3. Which of these class can generate pseudorandom numbers?

a) Locale

b) Rand

c) Random

4. Which of these method of Locale class can be used to obtain country of operation?

a) getCountry()

b) whichCountry()

c) DisplayCountry()

d) getDisplayCountry()

5. Which of these is a method can generate a boolean output?

a) retbool()

b) getBool()

c) nextBool()

d) nextBoolean()

Java Questions & Answers – Locale & Random Classes

INDIA

a) India

b) INDIA

c) HINDI

d) Nothing is displayed

$ javac LOCALE_CLASS.java

$ java LOCALE_CLASS

HINDI

1. What is the use of Observable class?

a) It is used to create globalsubclasses

b) It is used to create classes that other part of the program can observe

c) It is used to create classes that can be accessed by other parts of program

d) It is used to create methods that can be accessed by other parts of program

Explanation: The Observable class is used to create subclasses that other part of program can observe.

2. Which of these methods is used to notify observer the change in observed object?

a) update()

b) notify()

c) check()

d) observed()

3. Which of these methods calls update() method?

a) notify()

b) observeObject()

c) updateObserver()

d) notifyObserver()

Explanation: notifyObserver() notifies all the observers of the invoking object that it has changed by calling update(). A null is passed as the

second argument to update().

4. Which of these methods is called when observed object has changed?

a) setChanged()

c) notifyObserver()

5. Which of these classes can schedule task for execution in future?

a) Thread

b) Timer

c) System

d) Observer

Explanation: Timer and TimerTask are the classes that support the ability to schedule tasks for execution at some future time.

6. Which of these interfaces is implemented by TimerTask class?

a) Runnable

Java Questions & Answers – Observable & Timer Class

b) Thread

c) Observer

d) ThreadCount

7. Which of these package provides the ability to read and write in Zip format?

a) java.lang

b) java.io

c) java.util.zip

d) java.util.zar

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

a) pkg

b) Pkg

c) package

d) Package

2. Which of these is a mechanism for naming and visibility control of a class and its content?

a) Object

d) None of the Mentioned.

Explanation: Packages are both naming and visibility control mechanism. We can define a class inside a package which is not accessible by code

outside the package.

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

c) No Modifier

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

4. Which of these access specifiers can be used for a class so that its members can be accessed by a different class in the different package?

c) Private

d) No Modifier

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

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

a) Package defines a namespace in which classes are stored

Java Questions & Answers – Packages

b) A package can contain other package within it

c) Java uses file system directories to store packages

d) A package can be renamed without renaming the directory in which the classes are stored

Explanation: A package can be renamed only after renaming the directory in which the classes are stored.

7. Which of the following package stores all the standard java classes?

a) lang

b) java

c) util

d) java.packages

Note : packages.class file is in directory pkg;

c) 2

d) 0 1 2

$ javac packages.java

$ java packages

2

a) xello

b) xxxxx

c) Hxllo

d) Hexlo

Hxllo

Note : Output.class file is not in directory pkg.

a) HelloGoodWorld

b) HellGoodoWorld

c) Compilation error

d) Runtime error

Explanation: Since output.class file is not in the directory pkg in which class output is defined, program will not be able to run.

$ javac output.java

$ java output

can not find file output.class

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

a) interface

c) intf

d) Intf

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

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

a) Public

b) Protected

c) private

Explanation: Access specifier of an 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 these keywords is used by a class to use an interface defined previously?

a) import

b) Import

c) implements

d) Implements

Explanation: interface is inherited by a class using implements.

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

a) class manager extends salary {}

b) class manager implements salary {}

c) class manager imports salary {}

d) none of the mentioned

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

Java Questions & Answers – Interfaces – 1

a) Interfaces specifies what class must do but not how it does

b) Interfaces are specified public if they are to be accessed by any code in the program

c) All variables in interface are implicitly final and static

d) All variables are static and methods are public if interface is defined pubic

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

c) 4

4

a) 0 0

b) 2 2

c) 4 1

d) 1 4

Explanation: class displayA implements the interface calculate by doubling the value of item, where as class displayB implements the interface by

dividing item by item, therefore variable x of class displayA stores 4 and variable x of class displayB stores 1.

4 1

a) 0 1 2

b) 0 2 4

c) 0 0 4

d) 0 1 4

output:

$ javac interfaces.java

$ java interfaces

0 0 4

1. Which of the following access specifiers can be used for an interface?

a) Protected

b) Private

c) Public

d) Public, protected, private

Explanation:Interface can have either public access specifier or no specifier. The reason is they need to be implemented by other classes.

2. Which of the following is the correct way of implementing an interface A by class B?

a) class B extends A{}

b) class B implements A{}

c) class B imports A{}

d) None of the mentioned

Explanation:Concrete class implements an interface. They can be instantiated.

3. All methods must be implemented of an interface.

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

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

a) public static

b) private final

c) public final

d) static final

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

5. What does an interface contain?

a) Method definition

b) Method declaration

c) Method declaration and definition

d) Method name

Explanation:Interface contains the only declaration of the method.

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

a) abstract

b) static

c) final

d) private

Java Questions & Answers – Interfaces – 2

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

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

Explanation: The methods of interfaces are always abstract. They provide only method definition.

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

c) The interface compiles successfully

d) The implementing class will throw exception

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

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

b) Runtime Exception

c) The JVM is not able to identify the correct variable

d) The interfaceName.variableName needs to be defined

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.

10. Can “abstract” keyword be used with constructor, Initialization Block, Instance Initialization and Static Initialization Block.

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

1. Which of these package is used for graphical user interface?

d) java.io

Explanation: java.awt provides capabilities for graphical user interface.

2. Which of this package is used for analyzing code during run-time?

a) java.applet

c) java.io

d) java.lang.reflect

Explanation:Reflection is the ability of a software to analyze itself. This is provided by java.lang.reflect package.

3. Which of this package is used for handling security related issues in a program?

a) java.security

b) java.lang.security

c) java.awt.image

d) java.io.security

Explanation: java.security handles certificates, keys, digests, signatures, and other security functions.

4. Which of these class allows us to get real time data about private and protected member of a class?

a) java.io

b) GetInformation

c) ReflectPermission

d) MembersPermission

Explanation: The ReflectPermission class allows reflection of private or protected members of a class. This was added after java 2.0 .

5. Which of this package is used for invoking a method remotely?

a) java.rmi

b) java.awt

c) java.util

d) java.applet

Explanation: java.rmi provides capabilities for remote method invocation.

b) Program prints all the possible constructors of class ‘Class’

c) Program prints “Exception”

Java Questions & Answers – Core Java API Packages

public java.awt.Dimension(java.awt.Dimension)

public java.awt.Dimension()

public java.awt.Dimension(int,int)

public int java.awt.Dimension.width

public int java.awt.Dimension.height

a) 20

b) Default value

d) Runtime Error

Explanation: To implement the method drawString we need first need to define abstract method of AWT that is paint() method. Without paint()

method we cannot define and use drawString or any Graphic class methods.

a) Program prints all the constructors of ‘java.awt.Dimension’ package

b) Program prints all the methods of ‘java.awt.Dimension’ package

c) Program prints all the data members of ‘java.awt.Dimension’ package

d) program prints all the methods and data member of ‘java.awt.Dimension’ package

$ javac Additional_packages.java

$ java Additional_packages

public int java.awt.Dimension.hashCode()

public boolean java.awt.Dimension.equals(java.lang.Object)

public java.lang.String java.awt.Dimension.toString()

public java.awt.Dimension java.awt.Dimension.getSize()

public void java.awt.Dimension.setSize(double,double)

public void java.awt.Dimension.setSize(int,int)

public void java.awt.Dimension.setSize(java.awt.Dimension)

public double java.awt.Dimension.getHeight()

public double java.awt.Dimension.getWidth()

public java.lang.Object java.awt.geom.Dimension2D.clone()

public void java.awt.geom.Dimension2D.setSize(java.awt.geom.Dimension2D)

public final native java.lang.Class java.lang.Object.getClass()

public final native void java.lang.Object.notify()

public final native void java.lang.Object.notifyAll()

public final native void java.lang.Object.wait(long)

public final void java.lang.Object.wait(long,int)

public final void java.lang.Object.wait()

1. Why are generics used?

a) Generics make code more fast

b) Generics make code more optimised and readable

c) Generics add stability to your code by making more of your bugs detectable at compile time

d) Generics add stability to your code by making more of your bugs detectable at runtime

Explanation: Generics add stability to your code by making more of your bugs detectable at compile time.

2. Which of these type parameters is used for a generic class to return and accept any type of object?

even another type variable.

3. Which of these type parameters is used for a generic class to return and accept a number?

4. Which of these is an correct way of defining generic class?

a) class name(T1, T2, …, Tn) { /* … */ }

b) class name { /* … */ }

d) class name{T1, T2, …, Tn} { /* … */ }

Explanation: The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called

type variables) T1, T2, …, and Tn.

5. Which of the following is an incorrect statement regarding the use of generics and parameterized types in Java?

a) Generics provide type safety by shifting more type checking responsibilities to the compiler

b) Generics and parameterized types eliminate the need for down casts when using Java Collections

c) When designing your own collections class (say, a linked list), generics and parameterized types allow you to achieve type safety with just a

single class definition as opposed to defining multiple classes

Java Questions & Answers – Type Interface

6. Which of the following reference types cannot be generic?

a) Anonymous inner class

b) 1

c) [1].

d) [0].

[0]

Box #0 contains [10].

1. JUnits are used for which type of testing?

a) Unit Testing

b) Integration Testing

c) System Testing

d) Blackbox Testing

Explanation:JUnit is a testing framework for unit testing. It uses java as a programming platform. It is managed by junit.org community.

2. Which of the below statement about JUnit is false?

a) It is an open source framework

b) It provides an annotation to identify test methods

c) It provides test runners for running test

d) They cannot be run automatically

Explanation:JUnits test can be run automatically and they check their own results and provide immediate feedback.

3. Which of the below is an incorrect annotation with respect to JUnits?

c) @Junit

d) @AfterEach

Explanation: @Test is used to annotate method under test, @BeforeEach and @AfterEach are called before and after each method

respectively. @BeforeClass and @AfterClass are called only once for each class.

4. Which of these is not a mocking framework?

a) EasyMock

b) Mockito

c) PowerMock

d) MockJava

Explanation: EasyMock, jMock, Mockito, Unitils Mock, PowerMock and JMockit are a various mocking framework.

5. Which method is used to verify the actual and expected results in Junits?

a) assert()

b) equals()

d) isEqual()

Explanation: assert method is used to compare actual and expected results in Junit. It has various implementation like assertEquals,

assertArrayEquals, assertFalse, assertNotNull, etc.

6. What does assertSame() method use for assertion?

Java Questions & Answers – JUnits

a) equals() method

b) isEqual() method

c) ==

d) compare() method

Explanation: == is used to compare the objects not the content. assertSame() method compares to check if actual and expected are the same

objects. It does not compare their content.

7. How to let junits know that they need to be run using PowerMock?

a) @PowerMock

b) @RunWith(PowerMock)

c) @RunWith(Junits)

d) @RunWith(PowerMockRunner.class)

Explanation: @RunWith(PowerMockRunner.class) signifies to use PowerMock JUnit runner. Along with that @PrepareForTest(User.class) is

used to declare the class being tested. mockStatic(Resource.class) is used to mock the static methods.

8. How can we simulate if then behavior in Junits?

a) if{..} else{..}

b) if(..){..} else{..}

c) Mockito.when(…).thenReturn(…);

d) Mockito.if(..).then(..);

Explanation: Mockito.when(mockList.size()).thenReturn(100); assertEquals(100, mockList.size()); is the usage to implement if and then

behavior.

9. What is used to inject mock fields into the tested object automatically?

a) @InjectMocks

b) @Inject

c) @InjectMockObject

d) @Mock

Explanation: @InjectMocks annotation is used to inject mock fields into the tested object automatically.

@InjectMocks

MyDictionary dic = new MyDictionary();

Explanation:JUnits can be used using dependency tag in maven in pom.xml. The version as desired and available in repository can be used.

1. Which of the following is not introduced with Java 8?

a) Stream API

b) Serialization

c) Spliterator

d) Lambda Expression

Explanation: Serialization is not introduced with Java 8. It was introduced with an earlier version ofJava.

2. What is the purpose of BooleanSupplier function interface?

a) represents supplier of Boolean-valued results

b) returns Boolean-valued result

c) There is no such function interface

d) returns null if Boolean is passed as argument

Explanation:BooleanSupplier function interface represents supplier of Boolean-valued results.

3. What is the return type of lambda expression?

a) String

c) void

d) Function

Explanation: Lambda expression enables us to pass functionality as an argument to another method, such as what action should be taken when

someone clicks a button.

4. Which is the new method introduced in java 8 to iterate over a collection?

a) for (String i : StringList)

b) foreach (String i : StringList)

c) StringList.forEach()

d) List.for()

Explanation: Traversing through forEach method of Iterable with anonymous class.

1. StringList.forEach(new Consumer()

3. public void accept(Integer t)

5. }

6. });

7. //Traversing with Consumer interface implementation

8. MyConsumer action = new MyConsumer();

Java Questions & Answers – Java 8 Features

9. StringList.forEach(action);

5. What are the two types of Streams offered by java 8?

a) sequential and parallel

b) sequential and random

c) parallel and random

d) random and synchronized

Explanation: Sequentialstream and parallelstream are two types ofstream provided by java.

1. Stream sequentialStream = myList.stream();

2. Stream parallelStream = myList.parallelStream();

6. Which feature of java 8 enables us to create a work stealing thread pool using all available processors at its target?

a) workPool

b) newWorkStealingPool

c) threadPool

d) workThreadPool

Explanation: Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target

parallelism level.

7. What does Files.lines(Path path) do?

a) It reads all the files at the path specified as a String

b) It reads all the lines from a file as a Stream

c) It reads the filenames at the path specified

d) It counts the number of lines for files at the path specified

Explanation: Files.lines(Path path) that reads all lines from a file as a Stream.

8. What is Optional object used for?

a) Optional is used for optionalruntime argument

b) Optional is used for optionalspring profile

c) Optional is used to represent null with absent value

d) Optional means it’s not mandatory for method to return object

Explanation: Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values

as ‘available’ or ‘not available’ instead of checking null values.

9. What is the substitute of Rhino javascript engine in Java 8?

a) Nashorn

b) V8

c) Inscript

d) Narcissus

Explanation: Nashorn provides 2 to 10 times faster in terms of performance, as it directly compiles the code in memory and passes the

bytecode to JVM. Nashorn uses invoke dynamic feature.

10. What does SAM stand for in the context of FunctionalInterface?

a) Single Ambivalue Method

b) Single Abstract Method

c) Simple Active Markup

d) Simple Abstract Markup

Explanation: SAM Interface stands for Single Abstract Method Interface. FunctionalInterface is also known as SAM Interface because it

contains only one abstract method.

1. Which method is used to create a directory with fileattributes?

a) Path.create()

b) Path.createDirectory()

c) Files.createDirectory(path, fileAttributes)

d) Files.create(fileAttributes)

Explanation: New directory can be created using Files.createDirectory(path, fileAttribute).

2. Which method can be used to check fileAccessiblity?

a) isReadable(path)

b) isWritable(path)

c) isExecutable(path)

d) isReadable(path), isWritable(path), and isExecutable(path)

Explanation: File accessibilty can be checked using isReadable(Path), isWritable(Path), and isExecutable(Path).

3. How can we delete allfiles in a directory?

a) Files.delete(path)

b) Files.deleteDir()

c) Directory.delete()

d) Directory.delete(path)

Explanation: The delete(Path) method deletes the file or throws an exception if the deletion fails. If file does not exist a NoSuchFileException is

thrown.

4. How to copy the file from one location to other?

a) Files.copy(source, target)

b) Path.copy(source, target)

c) source.copy(target)

d) Files.createCopy(target)

Explanation: Files.copy(source, target) is used to copy a file from one location to another. There are various options available like

REPLACE_EXISTING, COPY_ATTRIBUTES and NOFOLLOW_LINKS.

5. How can we get the size ofspecified file?

a) capacity(path)

b) size(path)

c) length(path)

d) Path.size()

Explanation:size(Path) returns the size of the specified file in bytes.

6. How to read entire file in one line using java 8?

Java Questions & Answers – File and Directory

a) Files.readAllLines()

b) Files.read()

c) Files.readFile()

d) Files.lines()

Explanation:Java 8 provides Files.readAllLines() which allows us to read entire file in one task. We do not need to worry about readers and

writers.

7. How can we create a symbolic link to file?

a) createLink()

b) createSymLink()

c) createSymbolicLink()

d) createTempLink()

Explanation: createSymbolicLink() creates a symbolic link to a target.

8. How can we filter lines based on content?

a) lines.filter()

b) filter(lines)

c) lines.contains(filter)

d) lines.select()

Explanation: lines.filter(line -> line.contains(“===—> Loaded package”)) can be used to filter out.

9. Which jar provides FileUtils which contains methods for file operations?

a) file

b) apache commons

c) file commons

d) dir

Explanation: FileUtils is a part of apache commons which provides various methods for file operations like writeStringToFile.

10. Which feature of java 7 allows to not explicitly close IO resource?

a) try catch finally

c) AutoCloseable

d) Streams

Explanation: Any class that has implemented Autocloseable releases the I/O resources.

1. Which of the following is not a core interface of Hibernate?

a) Configuration

b) Criteria

c) SessionManagement

d) Session

Explanation: SessionManagement is not a core interface of Hibernate. Configuration, Criteria, SessionFactory, Session, Query and Transaction

are the core interfaces of Hibernate.

2. SessionFactory is a thread-safe object.

Explanation: SessionFactory is a thread-safe object. Multiple threads can access it simultaneously.

3. Which of the following methods returns proxy object?

a) loadDatabase()

b) getDatabase()

c) load()

Explanation: load() method returns proxy object. load() method should be used if it is sure that instance exists.

4. Which of the following methods hits database always?

a) load()

b) loadDatabase()

c) getDatabase()

d) get()

Explanation: get() method hits database always. Also, get() method does not return proxy object.

5. Which of the following method is used inside session only?

a) merge()

b) update()

c) end()

d) kill()

Explanation: update() method can only be used inside session. update() should be used ifsession does not contain persistent object.

6. Which of the following is not a state of object in Hibernate?

a) Attached()

b) Detached()

c) Persistent()

Java Questions & Answers – Hibernate

d) Transient()

Explanation: Attached() is not a state of object in Hibernate. Detached(), Persistent() and Transient() are the only states in Hibernate.

7. Which of the following is not an inheritance mapping strategies?

a) Table per hierarchy

b) Table per concrete class

c) Table per subclass

d) Table per class

Explanation: Table per class is not an inheritance mapping strategies.

8. Which of the following is not an advantage of using Hibernate Query Language?

a) Database independent

b) Easy to write query

c) No need to learn SQL

d) Difficult to implement

Explanation: HQLis easy to implement. Also, to implement it HQLit is not dependent on a database platform.

9. In which file database table configuration is stored?

a) .dbm

b) .hbm

c) .ora

d) .sql

Explanation: Database table configuration is stored in .hbm file.

10. Which of the following is not an advantage of Hibernate Criteria API?

a) Allows to use aggregate functions

b) Cannot order the result set

c) Allows to fetch only selected columns of result

d) Can add conditions while fetching results

Explanation: addOrder() can be used for ordering the results.

1. What does Liskov substitution principle specify?

a) parent class can be substituted by child class

b) child class can be substituted by parent class

c) parent class cannot be substituted by child class

d) No classes can be replaced by each other

Explanation: Liskov substitution principle states that Objects in a program should be replaceable with instances of their sub types without

altering the correctness of that program.

Java Questions & Answers – Liskov’s Principle

a) ICust can be replaced with RegularCustomer

b) RegularCustomer can be replaced with OneTimeCustomer

c) OneTimeCustomer can be replaced with RegularCustomer

d) We can instantiate objects of ICust

Explanation: According to Liskov substitution principle we can replace ICust with RegularCustomer or OneTimeCustomer without affecting

functionality.

b) Runtime failure

Explanation:Child object can be assigned to parent variable without change in behaviour.

c) 1

Explanation: Parent object cannot be assigned to child class.

Explanation:ClassCastException is thrown as we cannot assign parent object to child variable.

Explanation: We cannot assign one child class object to another child class variable.

1. interface Shape

3. public int area();

4. }

5. public class Square implements Shape

7. public int area()

8. {

9. return 2;

10. }

11. }

12. public class Rectangle implements Shape

13. {

14. public int area()

15. {

16. return 3;

17. }

18. }

Explanation:Interface cannot be instantiated. So we cannot create instances ofshape.

Explanation: With parent class variable we can access methods declared in parent class. If the parent class variable is assigned child class object

than it accesses the method of child class.

3. What is the outcome of below Main class?

1. public class Shape

2. {

3. public int area()

4. {

5. return 1;

6. }

7. }

8. public class Square extends Shape

9. {

10. public int area()

11. {

12. return 2;

15. class Main()

17. public static void main(String[] args)

19. Shape shape = new Shape();

20. Square square = new Square();

21. shape = square;

22. System.out.println(shape.area());

23. }

24. }

a) Compilation failure

b) 3

c) Runtime Exception

d) 2

Explanation: The method of the child class object is accessed. When we reassign objects, the methods of the latest assigned object are

accessed.

1. What should the return type of method where there is no return value?

a) Null

b) Empty collection

c) Singleton collection

d) Empty String

Explanation:Returning Empty collection is a good practice. It eliminates chances of unhandled null pointer exceptions.

2. What data structure should be used when number of elements is fixed?

b) Array list

c) Vector

Explanation: Array list has variable size. Array is stored in contiguous memory. Hence, reading is faster. Also, array is memory efficient.

3. What causes the program to exit abruptly and hence its usage should be minimalistic?

a) Try

b) Finally

c) Exit

d) Catch

Explanation:In case of exit, the program exits abruptly hence would never be able to debug the root cause of the issue.

a) i

b) ii

c) option (i) causes compilation error

d) option (ii) causes compilation error

Explanation: Arithmetic and logical operations are much faster than division and multiplication.

5. Which one of the following causes memory leak?

a) Release database connection when querying is complete

b) Use Finally block as much as possible

c) Release instances stored in static tables

d) Not using Finally block often

Explanation: Finally block is called in successful as well exception scenarios. Hence, all the connections are closed properly which avoids

memory leak.

6. Which of the following is a best practice to measure time taken by a process for execution?

a) System.currentTimeMillis()

b) System.nanoTime()

Java Questions & Answers – Coding best practices

c) System.getCurrentTime()

d) System.getProcessingTime()

Explanation: System.nanoTime takes around 1/100000 th of a second whereas System.currentTimeMillis takes around 1/1000th of a second.

a) Option (i)

b) Option (ii)

d) Option (ii) gives incorrect result

Explanation: Null check must be done while dealing with nested structures to avoid null pointer exceptions.

8. Which of the below is true about java class structure?

a) The class name should start with lowercase

b) The class should have thousands of lines of code

c) The class should only contain those attribute and functionality which it should; hence keeping it short

d) The class attributes and methods should be public

Explanation:Class name should always start with upper case and contain those attribute and functionality which it should (Single Responsibility

Principle); hence keeping it short. The attributes should be usually private with get and set methods.

9. Which of the below is false about java coding?

a) variable names should be short

b) variable names should be such that they avoid ambiguity

c) test case method names should be created as english sentences without spaces

d) class constants should be used when we want to share data between class methods

Explanation: variable names like i, a, abc, etc should be avoided. They should be real world names which avoid ambiguity. Test case name

should explain its significance.

10. Which is better in terms of performance for iterating an array?

a) for(int i=0; i

b) for(int i=99; i>=0; i–)

c) for(int i=100; i

d) for(int i=99; i>0; i++)

Explanation:reverse traversal of array take half number cycles as compared to forward traversal. The other for loops will go in infinite loop.

Java Questions & Answers – Generics

Explanation: genericstack’s object gs is defined to contain a string parameter but we are sending an integer parameter, which results in

6. Which of these Exception handlers cannot be type parameterized?

a) catch

b) throw

c) throws

d) all of the mentioned

Explanation: we cannot Create, Catch, or Throw Objects of Parameterized Types as generic class cannot extend the Throwable class directly

or indirectly.

3. What is the output of this program?

1. import java.util.*;

2. public class genericstack

3. {

4. Stack stk = new Stack ();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. genericstack gs = new genericstack();

20. gs.push("Hello");

21. System.out.print(gs.pop() + " ");

22. genericstack gs = new genericstack();

23. gs.push(36);

24. System.out.println(gs.pop());

25. }

26. }

7. Which of the following cannot be Type parameterized?

a) Overloaded Methods

b) Generic methods

c) Class methods

d) Overriding methods

Explanation:Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.

1. What are generic methods?

a) Generic methods are the methods defined in a generic class

b) Generic methods are the methods that extend generic class methods

c) Generic methods are methods that introduce their own type parameters

d) Generic methods are methods that take void parameters

Explanation: Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type

parameter scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class

constructors.

2. Which of these type parameters is used for a generic methods to return and accept any type of object?

Explanation: T is used for type, A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or

even another type variable..

3. Which of these type parameters is used for a generic methods to return and accept a number?

a) K

b) N

c) T

d) V

Explanation: N is used for Number.

4. Which of these is an correct way of defining generic method?

a) name(T1, T2, …, Tn) { /* … */ }

b) public name { /* … */ }

c) class name[T1, T2, …, Tn] { /* … */ }

d) name{T1, T2, …, Tn} { /* … */ }

Explanation: The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method’s return type.

For static generic methods, the type parameter section must appear before the method’s return type.

5. Which of the following allows us to call generic methods as a normal method?

a) Type Interface

b) Interface

c) Inner class

d) All of the mentioned

Explanation: Type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets.

Java Questions & Answers – Generic Methods

Hello

b) 36

36

1. Which of these types cannot be used to initiate a generic type?

a) Integer class

b) Float class

c) Primitive Types

d) Collections

2. Which of these instance cannot be created?

a) Integer instance

b) Generic class instance

c) Generic type instance

d) Collection instances

Explanation:It is not possible to create generic type instances. Example – “E obj = new E()” will give a compilation error.

3. Which of these data type cannot be type parameterized?

a) Array

c) Map

d) Set

a) 10

b) Box #0 [10].

c) Box contains [10].

d) Box #0 contains [10].

Box #0 contains [10]

a) Error

c) 36

d) Hello 36

Java Questions & Answers – Restrictions on Generics

Hello 36

a) 1

b) 2

c) 3

d) 6

1

$ javac Output.java

1. Which of these is wildcard symbol?

a) ?

b) !

c) %

d) &

Explanation:In generic code, the question mark (?), called the wildcard, represents an unknown type.

2. What is use of wildcards?

a) It is used in cases when type being operated upon is not known

b) It is used to make code more readable

c) It is used to access members ofsuper class

d) It is used for type argument of generic method

Explanation: The wildcard can be used in a variety ofsituations: as the type of a parameter, field, or local variable; sometimes as a return type

(though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a

generic class instance creation, or a supertype.

3. Which of these keywords is used to upper bound a wildcard?

a) stop

b) bound

c) extends

d) implements

4. Which of these is an correct way making a list that is upper bounded by class Number?

a) List

b) List

c) List(? extends Number)

d) List(? UpperBounds Number)

5. Which of the following keywords are used for lower bounding a wild card?

a) extends

b) super

c) class

d) lower

Explanation: A lower bounded wildcard is expressed using the wildcard character (‘?’), following by the super keyword, followed by its lower

bound: .

Java Questions & Answers – Wildcards

a) 0

b) 4

c) 5.0

6.0

a) 5.0

b) 7.0

c) 8.0

d) 6.0

Explanation: None.

7.0

a) H

b) Hello

c) Runtime Error

d) Compilation Error

Explanation: generic stack object gs is defined to contain a string parameter but we are sending an integer parameter, which results in

compilation error.

Output:

$ javac Output.javac

$ java Output

1. Which of the following is not an Enterprise Beans type?

a) Doubleton

b) Singleton

c) Stateful

d) Stateless

Explanation: Stateful, Stateless and Singleton are session beans.

2. Which of the following is not true about Java beans?

a) Implements java.io.Serializable interface

b) Extends java.io.Serializable class

c) Provides no argument constructor

d) Provides setter and getter methods for its properties

Explanation: java.io.Serializable is not a class. Instead it is an interface. Hence it cannot be extended.

3. Which file separator should be used by MANIFEST file?

a) /

b) \

c) –

d) //

Explanation: MANIFEST file uses classes using / file separator.

4. Which of the following is correct error when loading JAR file with duplicate name?

a) java.io.NullPointerException

b) java.lang.ClassNotFound

c) java.lang.ClassFormatError

d) java.lang.DuplicateClassError

Explanation: java.lang.ClassFormatError: Duplicate Name error is thrown when .class file in the JAR contains a class whose class name is

different from the expected name.

5. Java Beans are extremely secured?

Explanation:JavaBeans do not add any security features to the Java platform.

6. Which of the following is not a feature of Beans?

a) Introspection

b) Events

c) Persistence

Advanced Java Questions & Answers – Java Beans

d) Serialization

Explanation: Serialization is not the feature ofJava Beans. Introspection, Customization, Events, Properties and Persistence are the features.

7. What is the attribute of java bean to specify scope of bean to have single instance per Spring IOC?

a) prototype

b) singleton

c) request

d) session

Explanation: Singleton scope of bean specifies only one instance per spring IOC container. This is the default scope.

8. Which attribute is used to specify initialization method?

a) init

b) init-method

c) initialization

d) initialization-method

Explanation: init-method is used to specify the initialization method.

.bean.HelloWorld" id="helloWorld" init-method="init">

9. Which attribute is used to specify destroy method?

a) destroy

b) destroy-method

c) destruction

d) destruction-method

Explanation: destroy-method is used to specify the destruction method.

advertisement

.tutorialspoint.HelloWorld" destroy-method="destroy" id="helloWorld">

10. How to specify autowiring by name?

a) @Qualifier

b) @Type

c) @Constructor

d) @Name

Explanation: Different beans of the same class are identified by name.

1. @Qualifier("student1")

2. @Autowired

3. Student student1;

1. Which of the following contains both date and time?

a) java.io.date

b) java.sql.date

c) java.util.date

d) java.util.dateTime

Explanation: java.util.date contains both date and time. Whereas, java.sql.date contains only date.

2. Which of the following is advantage of using JDBC connection pool?

b) Using more memory

c) Using less memory

d) Better performance

Explanation: Since the JDBC connection takes time to establish. Creating connection at the application start-up and reusing at the time of

requirement, helps performance of the application.

3. Which of the following is advantage of using PreparedStatement in Java?

a) Slow performance

b) Encourages SQLinjection

c) Prevents SQLinjection

d) More memory usage

Explanation: PreparedStatement in Java improves performance and also prevents from SQLinjection.

4. Which one of the following contains date information?

a) java.sql.TimeStamp

b) java.sql.Time

c) java.io.Time

d) java.io.TimeStamp

Explanation: java.sql.Time contains only time. Whereas, java.sql.TimeStamp contains both time and date.

5. What does setAutoCommit(false) do?

a) commits transaction after each query

b) explicitly commits transaction

c) does not commit transaction automatically after each query

d) never commits transaction

Explanation:setAutoCommit(false) does not commit transaction automatically after each query. That saves lot of time of the execution and

hence improves performance.

6. Which of the following is used to callstored procedure?

Advanced Java Questions & Answers – JDBC

a) Statement

b) PreparedStatement

c) CallableStatment

d) CalledStatement

Explanation:CallableStatement is used in JDBC to callstored procedure from Java program.

7. Which of the following is used to limit the number of rows returned?

a) setMaxRows(int i)

b) setMinRows(int i)

c) getMaxrows(int i)

d) getMinRows(int i)

Explanation:setMaxRows(int i) method is used to limit the number of rows that the database returns from the query.

8. Which of the following is method ofJDBC batch process?

a) setBatch()

b) deleteBatch()

c) removeBatch()

d) addBatch()

Explanation: addBatch() is a method ofJDBC batch process. It is faster in processing than executing one statement at a time.

9. Which of the following is used to rollback a JDBC transaction?

a) rollback()

b) rollforward()

c) deleteTransaction()

d) RemoveTransaction()

Explanation:rollback() method is used to rollback the transaction. It willrollback all the changes made by the transaction.

10. Which of the following is not a JDBC connection isolation levels?

a) TRANSACTION_NONE

b) TRANSACTION_READ_COMMITTED

c) TRANSACTION_REPEATABLE_READ

d) TRANSACTION_NONREPEATABLE_READ

Explanation: TRANSACTION_NONREPEATABLE_READ is not a JDBC connection isolation level.

1. Which of the below is not a valid design pattern?

a) Singleton

b) Factory

c) Command

d) Java

Explanation: Design pattern is a generalrepeatable solution to a commonly occurring problem in software design. There are various patterns

available for use in day to day coding problems.

2. Which of the below author is not a part of GOF (Gang of Four)?

a) Erich Gamma

b) Gang Pattern

c) Richard Helm

d) Ralph Johnson

Explanation: Four authors named Richard Helm, Erich Gamma, Ralph Johnson and John Vlissides published a book on design patterns. This

book initiated the concept of Design Pattern in Software development. They are known as Gang of Four (GOF).

3. Which of the below is not a valid classification of design pattern?

a) Creational patterns

b) Structural patterns

c) Behavioural patterns

d) Java patterns

Explanation:Java patterns is not a valid classification of design patterns. The correct one is J2EE patterns.

4. Which design pattern provides a single class which provides simplified methods required by client and delegates call to those methods?

a) Adapter pattern

b) Builder pattern

c) Facade pattern

d) Prototype pattern

Explanation: Facade pattern hides the complexities of the system and provides an interface to the client using which client can access the system.

5. Which design pattern ensures that only one object of particular class gets created?

b) Filter pattern

Explanation: Singleton pattern involves a single class which is responsible to create an object while making sure that only one object gets

created. This class provides a way to access the only object which can be accessed directly without need to instantiate another object of the

same class.

Advanced Java Questions & Answers – Design Patterns

6. Which design pattern suggest multiple classes through which request is passed and multiple but only relevant classes carry out operations on

the request?

a) Singleton pattern

b) Chain of responsibility pattern

c) State pattern

Explanation:Chain of responsibility pattern creates a chain of receiver objects for a particular request. The sender and receiver of a request are

decoupled based on the type of request. This pattern is one of the behavioral patterns.

7. Which design pattern represents a way to access all the objects in a collection?

a) Iterator pattern

b) Facade pattern

c) Builder pattern

d) Bridge pattern

Explanation:Iterator pattern represents a way to access the elements of a collection object in sequential manner without the need to know its

underlying representation.

8. What does MVC pattern stands for?

a) Mock View Control

b) Model view Controller

c) Mock View Class

d) Model View Class

Explanation: Modelrepresents an object or JAVA POJO carrying data.View represents the visualization of the data that model

contains.Controller acts on both model and view.It is usually used in web development.

9. Is design pattern a logical concept.

Explanation: Design pattern is a logical concept. Various classes and frameworks are provided to enable users to implement these design

patterns.

10. Which design pattern works on data and action taken based on data provided?

a) Command pattern

b) Singleton pattern

c) MVC pattern

d) Facade pattern

Explanation:Command pattern is a data driven design pattern. It is a behavioral pattern. A request is wrapped under an object as command

and passed to the invoker object.The invoker object looks for the appropriate object which can handle this command and passes this command

to the corresponding object which executes the command.

1. Which mode allows us to run program interactively while watching source code and variables during execution?

a) safe mode

b) debug mode

c) successfully run mode

d) exception mode

Explanation: Debug mode allows us to run program interactively while watching source code and variables during execution.

2. How can we move from one desired step to another step?

a) breakpoints

b) System.out.println

c) logger.log

d) logger.error

Explanation:Breakpoints are inserted in code. We can move from one point to another in the execution of a program.

3. Which part stores the program arguments and startup parameters?

a) debug configuration

b) run configuration

c) launch configuration

d) project configuration

Explanation: Launch configuration stores the startup class, program arguments and vm arguments.

4. How to deep dive into the execution of a method from a method call?

Explanation: F5 executes currently selected line and goes to the next line in the program. If the selected line is a method call, debugger steps into

the associated code.

5. Which key helps to step out of the caller of currently executed method?

a) F3

b) F5

c) F7

d) F8

Explanation: F7 steps out to the caller of the currently executed method. This finishes the execution of the current method and returns to the

caller of this method.

6. Which view allows us to delete and deactivate breakpoints and watchpoints?

Advanced Java Questions & Answers – Debugging in Eclipse

a) breakpoint view

b) variable view

c) debug view

d) logger view

Explanation: The Breakpoints view allows us to delete and deactivate breakpoints and watchpoints. We can also modify their properties.

7. What is debugging an application which runs on another java virtual machine on another machine?

a) virtual debugging

b) remote debugging

c) machine debugging

d) compiling debugging

Explanation:Remote debugging allows us to debug applications which run on another Java virtual machine or even on another machine. We

need to set certain flags while starting the application.

java -Xdebug -Xnoagent \

-Djava.compiler=NONE \

-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005.

8. What happens when the value of variable change?

a) changed value pop on the screen

b) variable changes are printed in logs

c) dump of variable changes are printed on the screen on end of execution

d) variable tab shows variables highlighted when values change

Explanation: When a variable value changes, the value in variable tab is highlighted yellow in eclipse.

9. Which perspective is used to run a program in debug view?

a) java perspective

b) eclipse perspective

c) debug perspective

d) jdbc perspective

Explanation: We can switch from one perspective to another. Debug perspective shows us the breakpoints, variables, etc.

10. How does eclipse provide capability for debugging browser actions?

a) internal web browser

b) chrome web browser

c) firefox web browser

d) internet explorer browser

Explanation: Eclipse provides internal web browser to debug browser actions.

1. Servlet are used to program which component in a web application?

a) client

b) server

c) tomcat

d) applet

Explanation: A servlet class extends the capabilities ofservers that host applications which are accessed by way of a request-response

programming model.

2. Which component can be used for sending messages from one application to another?

a) server

b) client

c) mq

d) webapp

Explanation: Messaging is a method of communication between software components or applications. MQ can be used for passing message

from sender to receiver.

3. How are java web applications packaged?

a) jar

b) war

c) zip

d) both jar and war

Explanation: war are deployed on apache servers or tomcat servers. With Spring boot and few other technologies tomcat is brought on the

machine by deploying jar.

4. How can we connect to database in a web application?

a) oracle sql developer

b) toad

c) JDBC template

d) mysql

Explanation:JDBC template can be used to connect to database and fire queries against it.

5. How can we take input text from user in HTMLpage?

a) input tag

b) inoutBufferedReader tag

c) meta tag

d) scanner tag

Explanation: HTMLprovides various user input options like input, radio, text, etc.

Advanced Java Questions & Answers – Web application

6. Which of the below is not a javascript framework for UI?

a) Vaadin

b) AngularJS

c) KendoUI

d) Springcore

Explanation: Springcore is not a javascript framework. It is a comprehensive programming and configuration modelfor enterprise applications

based on java.

7. Which of the below can be used to debug front end of a web application ?

a) Junit

b) Fitnesse

c) Firebug

d) Mockito

Explanation: Firebug integrates with firefox and enables to edit, debug and monitor CSS, HTMLand javascript of any web page.

8. What type of protocol is HTTP?

a) stateless

b) stateful

c) transfer protocol

d) information protocol

Explanation: HTTP is a stateless protocol. It works on request and response mechanism and each request is an independent transaction.

9. What does MIME stand for?

a) Multipurpose Internet Messaging Extension

b) Multipurpose Internet Mail Extension

c) Multipurpose Internet Media Extension

d) Multipurpose Internet Mass Extension

Explanation: MIME is an acronym for Multi-purpose Internet Mail Extensions. It is used for classifying file types over the Internet. It contains

type/subtype e.g. application/msword.

10. What is the storage capacity ofsingle cookie?

a) 2048 MB

b) 2048 bytes

c) 4095 bytes

d) 4095 MB

Explanation: Storage capacity of cookies is 4095 bytes/cookie.

1. How does applet and servlet communicate?

a) HTTP

b) HTTPS

c) FTP

d) HTTP Tunneling

Explanation: Applet and Servlet communicate through HTTP Tunneling.

2. In CGI, process starts with each request and will initiate OS level process.

Explanation: A new process is started with each client request and that corresponds to initiate a heavy OS level process for each client request.

3. Which class provides system independent server side implementation?

a) Socket

b) ServerSocket

c) Server

d) ServerReader

Explanation: ServerSocket is a java.net class which provides system independent implementation ofserver side socket connection.

4. What happens if ServerSocket is not able to listen on the specified port?

a) The system exits gracefully with appropriate message

b) The system will wait till port is free

c) IOException is thrown when opening the socket

d) PortOccupiedException is thrown

Explanation: public ServerSocket() creates an unbound server socket.It throws IOException ifspecified port is busy when opening the socket.

5. What does bind() method of ServerSocket offer?

a) binds the serversocket to a specific address (IP Address and port)

b) binds the server and client browser

c) binds the server socket to the JVM

d) binds the port to the JVM

Explanation: bind() binds the server socket to a specific address (IP Address and port). If address is null, the system will pick an ephemeral

port and valid local address to bind socket.

6. Which of the below are common network protocols?

a) TCP

b) UDP

c) TCP and UDP

Advanced Java Questions & Answers – Client and Server

d) CNP

Explanation: Transmission Control Protocol(TCP) and User Datagram Protocol(UDP) are the two common network protocol. TCP/IP allows

reliable communication between two applications. UDP is connection less protocol.

7. Which class represents an Internet Protocol address?

a) InetAddress

b) Address

c) IP Address

d) TCP Address

Explanation:InetAddress represents an Internet Protocol address. It provides static methods like getByAddress(), getByName() and other

instance methods like getHostName(), getHostAddress(), getLocalHost().

8. What does localIP address start with?

a) 10.X.X.X

b) 172.X.X.X

c) 192.168.X.X

d) 10.X.X.X, 172.X.X.X, or 192.168.X.X

Explanation: LocalIP addresses look like 10.X.X.X, 172.X.X.X, or 192.168.X.X.

9. What happens if IP Address of host cannot be determined?

a) The system exit with no message

b) UnknownHostException is thrown

c) IOException is thrown

d) Temporary IP Address is assigned

Explanation: UnknownHostException is thrown when IP Address of host cannot be determined. It is an extension of IOException.

10. What is the java method for ping?

a) hostReachable()

b) ping()

c) isReachable()

d) portBusy()

Explanation: inet.isReachable(5000) is a way to ping a server in java.

1. How constructor can be used for a servlet?

a) Initialization

b) Constructor function

c) Initialization and Constructor function

d) Setup() method

Explanation: We cannot declare constructors for interface in Java. This means we cannot enforce this requirement to any class which implements

Servlet interface.

Also, Servlet requires ServletConfig object for initialization which is created by container.

2. Can servlet class declare constructor with ServletConfig object as an argument?

Explanation: ServletConfig object is created after the constructor is called and before init() is called. So, servlet init parameters cannot be

accessed in the constructor.

3. What is the difference between servlets and applets?

i.Servlets execute on Server; Applets execute on browser

ii.Servlets have no GUI; Applet has GUI

iii.Servlets creates static web pages; Applets creates dynamic web pages

iv.Servlets can handle only a single request; Applet can handle multiple requests

a) i,ii,iii are correct

b) i,ii are correct

c) i,iii are correct

d) i,ii,iii,iv are correct

Explanation: Servlets execute on Server and doesn’t have GUI. Applets execute on browser and has GUI.

4. Which of the following code is used to get an attribute in a HTTP Session object in servlets?

a) session.getAttribute(String name)

b) session.alterAttribute(String name)

c) session.updateAttribute(String name)

d) session.setAttribute(String name)

Explanation:session has various methods for use.

5. Which method is used to get three-letter abbreviation for locale’s country in servlets?

a) Request.getISO3Country()

b) Locale.getISO3Country()

c) Response.getISO3Country()

d) Local.retrieveISO3Country()

Advanced Java Questions & Answers – Servlet

Explanation: Each country is usually denoted by a 3 digit code.ISO3 is the 3 digit country code.

6. Which of the following code retrieves the body of the request as binary data?

a) DataInputStream data = new InputStream()

b) DataInputStream data = response.getInputStream()

c) DataInputStream data = request.getInputStream()

d) DataInputStream data = request.fetchInputStream()

Explanation:InputStream is an abstract class. getInputStream() retrieves the request in binary data.

7. When destroy() method of a filter is called?

a) The destroy() method is called only once at the end of the life cycle of a filter

b) The destroy() method is called after the filter has executed doFilter method

c) The destroy() method is called only once at the begining of the life cycle of a filter

d) The destroyer() method is called after the filter has executed

Explanation: destroy() is an end of life cycle method so it is called at the end of life cycle.

8. Which of the following is true about servlets?

a) Servlets execute within the address space of web server

b) Servlets are platform-independent because they are written in java

c) Servlets can use the fullfunctionality of the Java class libraries

d) Servlets execute within the address space of web server, platform independent and uses the functionality of java class libraries

Explanation: Servlets execute within the address space of a web server. Since it is written in java it is platform independent. The fullfunctionality

is available through libraries.

9. How is the dynamic interception of requests and responses to transform the information done?

a) servlet container

b) servlet config

c) servlet context

d) servlet filter

Explanation: Servlet has various components like container, config, context, filter. Servlet filter provides the dynamic interception of requests and

responses to transform the information.

10. Which are the session tracking techniques?

i. URLrewriting

ii. Using session object

iii.Using response object

iv. Using hidden fields

v. Using cookies

vi. Using servlet object

a) i, ii, iii, vi

b) i, ii, iv, v

c) i, vi, iii, v

d) i, ii, iii, v

Explanation: URLrewriting, using session object, using cookies, using hidden fields are session tracking techniques.

1. Which of the following is used for session migration?

a) Persisting the session in database

b) URLrewriting

c) Create new database connection

d) Killsession from multiple sessions

Explanation: Session migration is done by persisting session in database. It can also be done by storing session in memory on multiple servers.

2. Which of the below is not a session tracking method?

b) History

c) Cookies

d) SSLsessions

Explanation: History is not a session tracking type. Cookies, URLrewriting, Hidden form fields and SSLsessions are session tracking methods.

3. Which of the following is stored at client side?

Explanation:Cookies are stored at client side. Hence, it is advantageous in some cases where clients disable cookies.

4. Which of the following leads to high network traffic?

a) URLrewriting

b) Hidden form fields

c) SSLsessions

d) Cookies

Explanation: WRLrewriting requires large data transfer to and from the server which leads to network traffic and access may be slow.

5. Which of the following is not true about session?

a) All users connect to the same session

b) All users have same session variable

c) Default timeout value for session variable is 20 minutes

d) New session cannot be created for a new user

Explanation: Default timeout value for session variable is 20 minutes. This can be changed as per requirement.

6. SessionIDs are stored in cookies.

Advanced Java Questions & Answers – Session Management

Explanation: SessionIDs are stored in cookies, URLs and hidden form fields.

7. What is the maximum size of cookie?

a) 4 KB

b) 4 MB

c) 4 bytes

d) 40 KB

Explanation: The 4K is the maximum size for the entire cookie, including name, value, expiry date etc. To support most browsers, it is suggested

to keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

8. How can we invalidate a session?

a) session.discontinue()

b) session.invalidate()

c) session.disconnect()

d) session.falsify()

Explanation: We can invalidate session by calling session.invalidate() to destroy the session.

9. Which method creates unique fields in the HTML which are not shown to the user?

a) User authentication

b) URL writing

c) HTML Hidden field

d) HTMLinvisible field

Explanation: HTML Hidden field is the simplest way to pass information but it is not secure and a session can be hacked easily.

10. Which object is used by spring for authentication?

a) ContextHolder

b) SecurityHolder

c) AnonymousHolder

d) SecurityContextHolder

Explanation: The SessionManagementFilter checks the contents of the SecurityContextRepository against the current contents of the

SecurityContextHolder to determine whether user has been authenticated during the current request by a non-interactive authentication

mechanism, like pre authentication or remember me.

1. Which page directive should be used in JSP to generate a PDF page?

a) contentType

b) generatePdf

c) typePDF

d) contentPDF

Explanation: <%page contentType=”application/pdf”> tag is used in JSP to generate PDF.

2. Which tag should be used to pass information from JSP to included JSP?

a) Using <%jsp:page> tag

b) Using <%jsp:param> tag

c) Using <%jsp:import> tag

d) Using <%jsp:useBean> tag

Explanation: <%jsp:param> tag is used to pass information from JSP to included JSP.

3. Application is instance of which class?

a) javax.servlet.Application

b) javax.servlet.HttpContext

c) javax.servlet.Context

d) javax.servlet.ServletContext

Explanation: Application object is wrapper around the ServletContext object and it is an instance of a javax.servlet.ServletContext object.

4. _jspService() method of HttpJspPage class should not be overridden.

Explanation: _jspService() method is created by JSP container. Hence, it should not be overridden.

5. Which option is true about session scope?

a) Objects are accessible only from the page in which they are created

b) Objects are accessible only from the pages which are in same session

c) Objects are accessible only from the pages which are processing the same request

d) Objects are accessible only from the pages which reside in same application

Explanation: Object data is available tillsession is alive.

6. Default value of autoFlush attribute is?

a) true

b) false

Advanced Java Questions & Answers – JSP

Explanation: Default value “true” depicts automatic buffer flushing.

7. Which one is the correct order of phases in JSP life cycle?

a) Initialization, Cleanup, Compilation, Execution

b) Initialization, Compilation, Cleanup, Execution

c) Compilation, Initialization, Execution, Cleanup

d) Cleanup, Compilation, Initialization, Execution

Explanation: The correct order is Compilation, Initialization, Execution, Cleanup.

8. “request” is instance of which one of the following classes?

a) Request

b) HttpRequest

c) HttpServletRequest

d) ServletRequest

Explanation:request is object of HttpServletRequest.

9. Which is not a directive?

a) include

b) page

c) export

d) useBean

Explanation: Export is not a directive.

10. Which is mandatory in tag?

a) id, class

b) id, type

c) type, property

d) type,id

Explanation: The useBean searches existing object and if not found creates an object using class.

1. Which one of the following is correct for directive in JSP?

a) <%@directive%>

b) <%!directive%>

c) <%directive%>

d) <%=directive%>

Explanation: Directive is declared as <%@directive%>.

2. Which of the following action variable is used to include a file in JSP?

a) jsp:setProperty

b) jsp:getProperty

c) jsp:include

d) jsp:plugin

Explanation: jsp:include action variable is used to include a file in JSP.

3. Which attribute uniquely identification element?

a) ID

c) Name

d) Scope

Explanation:ID attribute is used to uniquely identify action element.

4. “out” is implicit object of which class?

a) javax.servlet.jsp.PrintWriter

b) javax.servlet.jsp.SessionWriter

c) javax.servlet.jsp.SessionPrinter

d) javax.servlet.jsp.JspWriter

Explanation:JspWriter object is referenced by the implicit variable out which is initialized automatically using methods in the PageContext

object.

5. Which object stores references to the request and response objects?

a) sessionContext

b) pageContext

c) HttpSession

d) sessionAttribute

Explanation: pageContext object contains information about directives issued to JSP page.

6. What temporarily redirects response to the browser?

Advanced Java Questions & Answers – JSP Elements

b) <%@directive%>

c) response.sendRedirect(URL)

d) response.setRedirect(URL)

Explanation:response.sendRedirect(URL) directs response to the browser and creates a new request.

7. Which tag is used to set a value of a JavaBean?

a)

b)

c)

d)

Explanation: is used to set a value of a java.util.Map object.

8. Can <!–comment–> and <%–comment–%> be used alternatively in JSP?

Explanation: <!–comment–> is an HTMLcomment. <%–comment–%> is JSP comment.

9. Java code is embedded under which tag in JSP?

a) Declaration

b) Scriptlet

c) Expression

d) Comment

Explanation: Scriptlet is used to embed java code in JSP.

10. Which of the following is not a directive in JSP?

a) page directive

b) include directive

c) taglib directive

d) command directive

Explanation: command directive is not a directive in JSP.

1. What are the components of a marker interface?

a) Fields and methods

b) No fields, only methods

c) Fields, no methods

d) No fields, No methods

Explanation: Marker interface in Java is an empty interface in Java.

2. Which of the following is not a marker interface?

a) Serializable

b) Cloneable

c) Remote

d) Reader

Explanation:Reader is not a marker interface. Serializable, Cloneable and Remote interfaces are marker interface.

3. What is not the advantage of Reflection?

a) Examine a class’s field and method at runtime

b) Construct an object for a class at runtime

c) Examine a class’s field at compile time

d) Examine an object’s class at runtime

Explanation:Reflection inspects classes, interfaces, fields and methods at a runtime.

4. How private method can be called using reflection?

Explanation: getDeclaredMethods gives instance of java.lang.reflect.Method.

5. How private field can be called using reflection?

a) getDeclaredFields

b) getDeclaredMethods

c) getMethods

d) getFields

Explanation: getDeclaredFields gives instance of java.lang.reflect.Fields.

6. What is used to get class name in reflection?

a) getClass().getName()

b) getClass().getFields()

Advanced Java Questions & Answers – Reflection API

c) getClass().getDeclaredFields()

d) new getClass()

Explanation: getClass().getName() is used to get a class name from object in reflection.

7. How method can be invoked on unknown object?

a) obj.getClass().getDeclaredMethod()

b) obj.getClass().getDeclaredField()

c) obj.getClass().getMethod()

d) obj.getClass().getObject()

Explanation: obj.getClass().getMethod is used to invoke a method on unknown object obj.

8. How to get the class object of associated class using Reflection?

a) Class.forName(“className”)

b) Class.name(“className”)

c) className.getClass()

d) className.getClassName()

Explanation:forName(String className) returns the Class object associated with the class or interface with the given string name.

9. What does Class.forName(“myreflection.Foo”).getInstance() return?

a) An array of Foo objects

b) class object of Foo

c) Calls the getInstance() method of Foo class

d) Foo object

Explanation:Class.forName(“myreflection.Foo”) returns the class object of Foo and getInstance() would return a new object.

10. What does foo.getClass().getMethod(“doSomething”, null) return?

a) doSomething method instance

b) Method is returned and we can call the method as method.invoke(foo,null);

c) Class object

d) Exception is thrown

Explanation:foo.getClass().getMethod() returns a method and we can call the method using method.invoke();

1. Autocloseable was introduced in which Java version?

d) java SE 4

Explanation:Java 7 introduced autocloseable interface.

2. What is the alternative of using finally to close resource?

a) catch block

b) autocloseable interface to be implemented

c) try block

d) throw Exception

Explanation: Autocloseable interface provides close() method to close this resource and any other underlying resources.

3. Which of the below is a child interface of Autocloseable?

a) Closeable

b) Close

c) Auto

d) Cloneable

Explanation: A closeable interface extends autocloseable interface. A Closeable is a source or destination of data that can be closed.

4. It is a good practise to not throw which exception in close() method of autocloseable?

a) IOException

b) CustomException

c) InterruptedException

d) CloseException

Explanation:InterruptedException interacts with a thread’s interrupted status and runtime misbehavior is likely to occur if an

InterruptedException is suppressed.

a) Runtime Error

b) IOException

c) Compilation Error

d) Runs successfully

Explanation: Using java 7 and above, AutoCloseable objects can be opened in the try-block (within the ()) and will be automatically closed

instead of using the finally block.

6. What is the difference between AutoCloseable and Closeable?

a) Closeable is an interface and AutoCloseable is a concrete class

Advanced Java Questions & Answers – AutoCloseable, Closeable and Flushable Interfaces

b) Closeable throws IOException; AutoCloseable throws Exception

c) Closeable is a concept; AutoCloseable is an implementation

d) Closeable throws Exception; AutoCloseable throws IOException

Explanation:Closeable extends AutoCloseable and both are interfaces. Closeable throws IOException and AutoCloseable throws Exception.

7. What is the use of Flushable interface?

a) Flushes this stream by writing any buffered output to the underlying stream

b) Flushes this stream and starts reading again

c) Flushes this connection and closes it

d) Flushes this stream and throws FlushException

Explanation: Flushable interface provides flush() method which Flushes this stream by writing any buffered output to the underlying stream.

8. Which version of java added Flushable interface?

a) java SE 7

b) java SE 8

c) java SE 6

d) java SE 5

Explanation: Flushable and Closeable interface are added in java SE 5.

9. Does close() implicitly flush() the stream.

Explanation: close() closes the stream but it flushes it first.

10. AutoCloseable and Flushable are part of which package?

a) Autocloseable java.lang; Flushable java.io

b) Autocloseable java.io; Flushable java.lang

c) Autocloseable and Flushable java.io

d) Autocloseable and Flushable java.lang

Explanation: Autocloseable is a part of java.lang; Flushable is a part of java.io.

1. Which of below is not a dependency management tool?

a) Ant

c) Gradle

d) Jenkins

Explanation:Jenkins is continuous integration system. Ant, Maven, Gradle is used for build process.

2. Which of the following is not a maven goal?

a) clean

b) package

c) install

d) debug

Explanation: clean, package, install are maven goals. Debug is used finding and resolving of defects.

3. Which file is used to define dependency in maven?

Explanation: pom.xml is used to define dependency which is used to package the jar. POM stands for project object model.

4. Which file is used to specify the packaging cycle?

a) build.xml

b) pom.xml

c) dependency.xml

d) version.xml

Explanation: Project structure is specified in build.xml.

5. Which environment variable is used to specify the path to maven?

a) JAVA_HOME

b) PATH

c) MAVEN_HOME

d) CLASSPATH

Explanation: MAVEN_HOME should be set to the bin folder of maven installation.

6. Which of the below is a source code management tool?

a) Jenkins

b) Maven

Advanced Java Questions & Answers – Application Lifecycle – Ant, Maven and Jenkins

c) Git

d) Hudson

Explanation: Source code management tools help is version control, compare different versions of code, crash management, etc. Git, SVN are

popular source code management tools.

7. Can we run Junits as a part ofJenkins job?

Explanation: As a part of jenkins job, we can run junits, fitnesse, test coverage reports, callshell or bat scripts, etc.

8. Which command can be used to check maven version?

a) mvn -ver

b) maven -ver

c) maven -version

d) mvn -version

Explanation: mvn -version can be used to check the version of installed maven from command prompt.

9. Which of the following is not true for Ant?

a) It is a tool box

b) It provides lifecycle management

c) It is procedural

d) It doesn’t have formal conventions

Explanation: Ant doesn’t provide lifecycle management. Maven provides lifecycle.

10. Which maven plugin creates the project structure?

a) dependency

b) properties

c) archetype

d) execution

Explanation: Archetype is the maven plugin which creates the project structure.

1. Which version ofJava introduced annotation?

a) Java 5

b) Java 6

c) Java 7

d) Java 8

Explanation: Annotation were introduced with Java 5 version.

2. Annotation type definition looks similar to which of the following?

a) Method

b) Class

c) Interface

d) Field

Answer: c

Explanation: Annotation type definition is similar to an interface definition in which the keyword interface is preceded by the sign @.

3. Which of the following is not pre defined annotation in Java?

a) @Deprecated

b) @Overriden

c) @SafeVarags

d) @FunctionInterface

Explanation: @Overriden is not a pre defined annotation in Java. @Depricated, @Override, @SuppressWarnings, @SafeVarags and

@FunctionInterface are the pre defined annotations.

4. Annotations which are applied to other annotations are called meta annotations.

a) True

b) False

Explanation: Annotations which are applied to other annotations are called meta annotations.

5. Which one of the following annotations is not used in Hibernate?

a) @Entity

b) @Column

c) @Basic

d) @Query

Explanation: @Query is not an annotation used in Hibernate.

6. Which one of the following is not ID generating strategy using @GeneratedValue annotation?

a) Auto

b) Manual

c) Identity

Advanced Java Questions & Answers – Annotations

d) Sequence

Explanation: Auto, Table, Identity and Sequence are the ID generating strategies using @GeneratedValue annotation.

7. Which one of the following is not an annotation used by Junit with Junit4?

a) @Test

b) @BeforeClass

c) @AfterClass

d) @Ignored

Explanation: @Test, @Before, @BeforeClass, @After, @AfterClass and @Ignores are the annotations used by Junit with Junit4.

8. Using which annotation non visible or private method can be tested?

a) @VisibleForTesting

b) @NonVisibleForTesting

c) @Visible

d) @NonVisible

Answer: a

Explanation: Using @VisibleForTesting annotation private or non visible method can be tested.

9. Which of the following annotation is used to avoid execution ofJunits?

a) @NoTest

b) @explicit

c) @avoid

d) @ignore

Answer: d

Explanation: @ignore annotation is used to avoid execution ofJunits.

10. Which is the Parent class of annotation class?

a) Class

b) Object

c) Main

d) Super

View Answer

Answer: b

Explanation: Object is the parent class of annotation class.

Post a Comment

0Comments

Post a Comment (0)