50 Multiple Choice Java Questions with Answers

Overview of Java programming language

Java is a popular, object-oriented programming language that can be used for a wide range of applications. It is easy to learn and is widely used in Android development. Java offers three editions: Java Standard Edition (SE), Java Enterprise Edition (EE) and Java Micro Edition (ME), each designed for specific application development.

Java Development Kit (JDK) is a set of programs that enable us to write programs in Java. The kit contains Java Runtime Environment (JRE), which is used to run our programs.

Java has a unique architecture consisting of three main components: Java Virtual Machine (JVM), Java Runtime Environment (JRE), and JDK. JVM allows developers to write Java code on any operating system, making Java a platform-independent language. JRE creates an environment where Java programs can run, while JDK provides a software development environment for Java applications and applets.

Overall, Java is an important language with unique features that make it a favorite among developers.

Number of Primitive Data Types in Java

In Java, there are 8 primitive data types:

int

- used for integers

char

- used for characters

boolean

- used for boolean values (true or false)

byte

- used for small integers

long

- used for large integers

float

- used for floating point numbers

short

- used for small integers

double

- used for floating point numbers with more precision than float

Java Data Types: Size of Float and Double

In Java, float is a 32-bit single precision floating point type, while double is a 64-bit double precision floating point type.

Therefore, the correct answer is option D: 64 and 32.

Automatic Type Conversion in Java

In Java, automatic type conversion or type coercion is the ability of the compiler to automatically convert one data type to another data type based on the compatibility of the type.

The following are the possible cases of automatic type conversion:

  • byte to short/int/long/float/double
  • short to int/long/float/double
  • int to long/float/double
  • long to float/double
  • float to double

Therefore, in the given list, all the cases are possible except for Byte to int. The correct answer is Int to long.

//example
int i = 50;
long l = i; //automatic type conversion of int to long

H3. Code Output

The code will output:

24I

There will be no space between 24 and I because we are printing two different types of variables without a separator.The output of the program is a compile error which says "Lossy conversion from int to short". This error occurs because of the data type of the variable x which is short and when x is multiplied by 5, the result gets promoted to int which cannot be assigned to the variable x.Code:

java
public class Solution {
    public static void main(String[] args) {
        byte x = 127; //assigning the value 127 to 'x'
        x++; //increment x by 1 
        x++; //increment x by 1 again
        System.out.print(x); //print the value of x
    }
}

Output:

-125

Explanation:

In Java, the range of byte is from -128 to 127. The program initializes a byte variable 'x' with the maximum value of 127 which is within the range. Then, it increments 'x' twice using the ++ operator.

Since the range for byte values is cyclic in nature, the value of 'x' will wrap around to -128 if it increments beyond the maximum value of 127.

Hence, the output is -125.The valid statement for declaring a character array is "char[] ch = new char[5];". This syntax creates a character array named "ch" with a length of 5.Title: Finding the output of a Java program

Code:


public class Solution {
    public static void main(String[] args) {
        int[] x = {120, 200, 016};
        for(int i = 0; i < x.length; i++) {
            System.out.println(x[i]);
        }
    }
}

The output of the program will be:


120
200
14

Explanation: - The program initializes an integer array `x` with three values: `120`, `200`, and `016`. Note that `016` is an octal number (base-8), equivalent to decimal number `14`. - The program then loops through the elements of the array and prints them using `System.out.println()`. - Therefore, the output will be: - `120` (printed on the first line) - `200` (printed on the second line) - `14` (printed on the third line, since `016` is converted to decimal `14`)

Passing Arrays as Arguments to Methods

In Java, when an array is passed to a method, the method receives a reference of the array. This reference points to the original array that was passed as an argument. It does not create a copy of the array. Therefore, any changes made to the array inside the method will also affect the original array outside of the method.


//Example method that takes an Integer array as an argument
public static void manipulateArray(Integer[] arr){
    for(int i = 0; i < arr.length; i++){
        arr[i] = arr[i] * 2; //doubles the value of each element in the array
    }
}

//Example usage of the method
Integer[] myArr = {1, 2, 3};
manipulateArray(myArr); //passes the reference of myArr to the method
System.out.println(Arrays.toString(myArr)); //prints [2, 4, 6], as the method changed the values of the original array


Declaring and Initializing Arrays in Java

In Java, arrays are declared using square brackets as follows:

datatype[] arrayName;

To initialize an array, you can use the following syntax:

datatype[] arrayName = {value1, value2, value3, ...};

Therefore, the valid statement to declare and initialize an array containing the values 1, 2, and 3 would be:

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


Finding the Value of an Array Element

Given the following program, we need to find the value of A[1] after its execution.


    int[] nums = {0, 2, 4, 1, 3};
    for(int i = 0; i < nums.length - 1; i++) {
        if(nums[i] > nums[i+1]) {
            int temp = nums[i];
            nums[i] = nums[i+1];
            nums[i+1] = temp;
        }
    }
    System.out.println(nums[1]);

The output of this program will be 1 since A[1] will have a value of 1 after the for loop is finished.

The program uses bubble sorting algorithm to sort the array, where adjacent elements are compared and swapped if necessary. The loop iterates through all but the last element of the array, and if an element is greater than its neighbor, it swaps the two. Once the loop is finished, the second element of the sorted array (which has index 1) is printed.

Java Arrays

In Java, arrays are objects that can hold a fixed number of items of the same data type. Therefore, the answer to the given question is "objects". Arrays can hold object references or primitive data types, depending on their declared type. An array of object references stores references to objects. On the other hand, an array of primitive data types stores the actual primitive values.

When is an object created using the `new` keyword?

An object is created using the `new` keyword during run-time.The corrected definition of a package is "A package is a collection of classes and interfaces."

Restriction on Static Methods

A correct restriction on static methods is that they must only access static data and can only call other static methods. They cannot refer to "this" or "super". Therefore, the answer is I and II.


public class Example {
    private static int count;
    public static void incrementCount() {
        count++;
    }
    public static int getCount() {
        return count;
    }
    public void incorrectMethod() {
        // This line would result in a compile error
        // Static methods cannot refer to "this"
        // count = 0;
    }
}


Java Keyword: Static

In Java, the keyword "static" makes a variable belong to a class, rather than being defined for each instance of the class. Therefore, the correct answer is "static".

Static variables, also known as class variables, are shared across all instances of a class and can be accessed directly using the class name. This means that changes made to a static variable affect all objects of the class.

Example of defining a static variable in a Java class:


public class MyClass {
   public static int myStaticVariable = 10;
}

To access the static variable, you can use the class name followed by the variable name:


int x = MyClass.myStaticVariable;

Static methods also belong to a class and not to any specific instance of the class.

Accessing and Changing the Value of a Variable

In the given code, the variable "res" is declared as private in the Solution class. This means that it can only be accessed and modified within the Solution class and not from any other class.

Therefore, the correct answer is "Only Solution class". Any other class that wants to access or modify the value of "res" would need to create an instance of the Solution class and call its methods or modify the variable indirectly through setters and getters if provided.

Implementation of the toString() method in Java

In Java, the `toString()` method is defined in the `java.lang.Object` class. This method is inherited by all other Java classes. Therefore, it can be called on any object in Java. The `toString()` method is used to get a string representation of an object.

Here is an example of how to use the `toString()` method in Java:


public class Student {
	private String name;
	private int age;
	
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Student{" +
				"name='" + name + '\'' +
				", age=" + age +
				'}';
	}
	
	public static void main(String[] args) {
		Student student = new Student("John", 20);
		System.out.println(student.toString());
	}
}

In the above code, the `toString()` method is overridden in the `Student` class. The `toString()` method returns a string representation of the `Student` object. In the `main()` method, an instance of the `Student` object is created and the `toString()` method is called on it. The `toString()` method returns a string that represents the `Student` object that is printed to the console.

It is important to note that if the `toString()` method is not overridden in a class, it will use the implementation provided in the `java.lang.Object` class. Therefore, it is always a good idea to override the `toString()` method in a custom class to provide a meaningful string representation of the object.

Understanding the method compareTo()

The method compareTo() is commonly used for sorting objects in Java. It is declared in the interface "Comparable" and returns an int value after comparing two objects.

The int value returned by compareTo() can be:

- negative, if the first object is considered less than the second - positive, if the first object is considered greater than the second - zero, if both objects are considered equal

Therefore, the answer to the question is:

- compareTo() returns an int value.

Program Output Identification

The output of the following program will be "bc".

Code:

java
String str = "abcde";
System.out.println(str.substring(1, 3));

Explanation:

The above program is using the substring() method of the String class that returns a new string that is a substring of the original string. In this case, it will return the string starting from index 1 (i.e., "b") up to index 2 (i.e., "c"). As a result, the output of the program will be "bc".

Program Output:

-1

The program declares a String variable named str with the value "Hello". Then, it uses the indexOf(char ch) method of the String class to find the index (position) of the character 't' in the String. Since 't' is not present in the String, the indexOf method returns -1, which is then printed to the console using the println method of the System class.

Identifying String Output


public class Test {
    public static void main(String args[]) {
        String str1 = "one";
        String str2 = "two";
        System.out.println(str1.concat(str2)); // concat() method joins the strings
    }
}

The output of this program is "onetwo".Code:

java
// Declare a string variable str1
// Replace all occurrences of 'e' in str1 with 's' and store the updated string in str1
str1 = str1.replace('e', 's');

Therefore, the answer is B - the code replaces all occurrences of 'e' to 's'.

Class String's location in Java

The String class belongs to the java.lang package in Java.

 
//Example
import java.lang.String;

public class MyClass {
  public static void main(String[] args) {
    String myString = "This is a string";
    System.out.println(myString);
  }
}

In the above example, we import the String class from the java.lang package and use it to create a String variable and print it.

Explanation of String Creation


// Creating a new object using the "new" keyword creates an object every time 

// A string can also be declared without using the "new" keyword


// Hence, the answer is 3.


Number of Constructors in String Class

The String class in Java has a total of 13 constructors.Code:


int ++a = 100;
System.out.println(++a);

Corrected code:


int a = 100;
System.out.println(++a);

Output:


101

Explanation: The original code tries to declare a variable with `++a` as its name and initialize it to `100`. This is not a valid identifier as identifier names cannot start with an operator. The corrected code declares a variable named `a` and initializes it to `100`. Then it prints the value of `++a`, which increments the value of `a` by 1 and returns the new value, `101`, which is printed to the console.

Code:


if(1 + 1 + 1 + 1 + 1 == 5){
    System.out.print("TRUE");
}
else{
    System.out.print("FALSE");
}

The output of this code would be "FALSE". This is because the sum of 1+1+1+1+1 is equal to 5, which is the value being compared to in the if condition. Therefore, the condition is false, and the output statement in the "else" block is executed, printing "FALSE" to the console.

The output of the code is:


50

Because the variable `x` is initialized as 5, and `x *= 3 + 7` is equivalent to `x = x * (3 + 7)` which evaluates to `x = 5 * 10` and thus `x` is assigned the value `50`. Finally, `System.out.println(x)` prints the value of `x`, which is 50.

Correct Return Type for Method that Doesn't Return a Value

In Java, the return type for a method that does not return any value (i.e. returns nothing) is "void", not "int", "double", or "None".

For example, the following method does not return any value, so it should be declared with a return type of "void":


public void printMessage(String message) {
   System.out.println(message);
}

The "printMessage" method simply prints out the given message to the console, but it does not return a value. Therefore, it is declared as a void method in Java.

Math.floor() Function in JavaScript

The output of the

Math.floor(3.6)

function in JavaScript will be 3.

The

Math.floor()

function is used to return the largest integer less than or equal to a given number. In this case, the given number is 3.6, which is less than 4 but greater than 3. Therefore, when we apply the

Math.floor()

function to 3.6, it returns the largest integer that is less than or equal to 3.6, which is 3.

So, the correct answer is 3.

Code:
js
console.log(Math.floor(3.6)); // Output: 3

Location of Parameters and Local Variables in Java

Stack

is the location where the system stores parameters and local variables whenever a method is invoked in Java. It is a linear data structure that follows the Last In First Out (LIFO) principle, meaning the item that was added last is accessed first. This is different from the heap which is used to store dynamically allocated objects. The stack is created during the method invocation and destroyed after the method returns. It is responsible for keeping track of the program execution, including method calls and variable declarations.

Java: Modifiers for Constructors

In Java, constructors can have one of three access modifiers: public, protected, or private. These modifiers control the visibility of the constructor from other classes.

The "static" modifier is not allowed for constructors as it refers to a method or variable that belongs to a class itself, rather than an instance of that class. Constructors are used to create new instances of a class, and so they cannot be static.

Understanding instance variables in object-oriented programming

In object-oriented programming, the variables that are declared in a class to be used by all methods of the class are called instance variables. These variables are also known as member variables or attributes of the class.

Instance variables hold specific values for each object of the class. They are defined at the class level but are initialized separately for each instance of the class. Instance variables are declared using the access modifiers 'public', 'private', or 'protected' and can be accessed and modified using object references.

Example of declaring instance variables:

Code:


public class Car {
   private String make;
   private String model;
   private int year;
}

In this example, `make`, `model`, and `year` are instance variables of the `Car` class. They are private and can be accessed only within the class. To access them outside the class, we can define public getter and setter methods.

Overall, instance variables play a significant role in object-oriented programming as they allow objects to hold their state.

Implicit Return Type of Constructor

In Java programming language, the implicit return type of a constructor is the class object in which it is defined. This means that the constructor does not explicitly return any value using a return statement. Instead, it creates and initializes an object of the class it belongs to and returns the memory reference of that object.

For example, consider the following code snippet:


public class MyClass{
   int num;

   public MyClass(int n){
      num = n;
   }
}

Here, the constructor of the class MyClass takes an integer argument 'n' and initializes the class variable 'num' with its value. When an object of MyClass is created using this constructor, it will be initialized with the specified value of 'n'.

So, the implicit return type of this constructor is the class object of MyClass itself, which is created and initialized during the constructor execution.

When is the finalize() method called?

The

finalize()

method is called before the garbage collection process to perform any necessary cleanup operations on an object.

Identifying the Prototype of Default Constructor in Java

In Java programming language, a constructor is a special method used to initialize objects. It has the same name as the class and does not have any return type. The default constructor is a type of constructor that is automatically provided by the compiler if no other constructor is defined in the class.

The correct prototype of the default constructor in Java is:

public Solution() 

This prototype does not have a return type and has the same name as the class. Therefore, it is the correct way to define the default constructor in a Java class.

Correct Constructor Declaration in Java

In Java, constructors are methods that are used to initialize objects. They are called when an object of a class is created. Here is the correct way to declare a constructor:

java
public class Solution {
    // default constructor
    public Solution() {
        // initialize variables or perform other tasks
    }
    
    // parameterized constructor
    public Solution(int parameter1, String parameter2) {
        // initialize variables with parameters or perform other tasks
    }
}

Option (A) and (B) in the given question are correct ways of declaring constructor. Option (C) is incorrect because `void` is not a valid keyword to declare a constructor.Code:

java
public class Solution {
    public static void main(String args[]) {
        int i;
        for (i = 1; i <= 6; i++) {
            if (i > 3) continue;
        }
        System.out.println(i);
    }
}

Output:


6

Explanation:

The loop starts at 1 and continues till i <= 6, incrementing i every iteration. When i becomes greater than 3, the `continue` statement is executed and the loop skips to the next iteration without executing the statements after it.


int count = 0;
do{
   count++;
} while(count < TOTAL_NUMBER_OF_ITERATIONS);

The answer is: All of the above.

All of the given for loops are infinite loops. Here's how:

  • The first for loop has no condition, so it will run indefinitely.
  • The second for loop has a condition that's always true. The counter starts at 0, which is less than 1, so it will run the first time. Then the counter is decremented, making it less than 1 again, so it will run again. This will continue indefinitely.
  • The third for loop has no condition in the middle, so it will also run indefinitely.

It's important to avoid infinite loops in programming, as they can cause the program to crash or become unresponsive. Always make sure to include a condition that will eventually cause the loop to exit.


for (;;) {
  // This is an infinite loop
}


Explanation of Runnable Interface in Java

In Java, Runnable is an interface that is used to define a single method run(), which when implemented, runs a thread. The Runnable interface is usually implemented by a class that needs to run in a separate thread.

When a class implements the Runnable interface, an object of the class needs to be created and passed to a Thread object as a parameter. Once the Thread class has been instantiated, the start() method is called, and it automatically calls the run() method of the supplied Runnable class.

The benefit of using the Runnable interface is that a class can implement multiple interfaces, whereas extending another class is limited to one. This is particularly useful if a class needs to extend from another class to inherit some useful functionality but also needs to run in a separate thread.

Therefore, option B is the correct answer.The exception generated by a try block is caught in a catch block. "throw" is not a block, it is a keyword used to throw an exception explicitly. "final" is also not a catch block; it is used to define a block of code that will always be executed regardless of whether an exception was thrown or not. Therefore, the correct answer is "catch".

Identifying Arithmetic Exception when dividing by zero

When a statement that divides by zero is executed, the following exception is thrown:

ArithmeticException


Location of System class

The System class is defined in the java.lang package.

java.lang.System


Core Java Interface for Method Declaration

In Java, the commonly used interface to declare core methods is the "Collection" interface. It is a member of the Java Collection Framework and declares the abstract methods that are common to all collection objects, such as add, remove, and size.

Understanding the finalize() Method in Java

In Java, the `finalize()` method is used to perform cleanup actions on an object just before it is garbage collected. Here are some important things to note about this method:

- The `finalize()` method is protected and defined in the `Object` class, which means that any class can override it. - This method is called by the garbage collector when it determines that there are no more references to the object. - The `finalize()` method can be called zero or one times only. - It is important to note that you should not rely on the `finalize()` method to do critical cleanup of resources such as file handles, socket connections, etc. Instead, you should use the `finally` block to handle these types of resources.

In short, while the `finalize()` method can be helpful for performing certain cleanup actions, it should not be relied upon for critical resource cleanup.

Understanding the Zero Fill Right Shift Operator in JavaScript

In JavaScript, the zero fill right shift operator ">>>" is used to shift the bits of a number to the right. It differs from the regular right shift operator ">>" in that it fills the shifted positions with zeros instead of the sign bit.

Example:


let num = 8; // binary representation: 00001000
num >>> 2; // binary result: 00000010 (equals 2 in decimal)

In the above example, the number 8 is shifted two positions to the right using the zero fill right shift operator. The two least significant bits are dropped, and the resulting binary number is 00000010, which equals 2 in decimal.

Overall, the zero fill right shift operator is useful when working with unsigned binary numbers. However, it should be used with caution, as shifting too many positions to the right can cause unexpected results or loss of data.The incorrect Java feature is the use of pointers. Java does not have the concept of pointers.

Debugging in Java using JDB

In Java programming, JDB is the tool used for debugging. It stands for Java Debugging Tool. JDB helps in finding and fixing bugs in programs. It is accessible from the command line on Windows and Unix-like systems. JDB works by attaching to the JVM (Java Virtual Machine) process and then allowing developers to debug the program with different commands.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.