Sunday, July 28, 2024

Void Methods MCQ

 Void Methods MCQ

What is the return type of a void method in Java?


A. int

B. void

C. double

D. No return value

Which of the following correctly defines a void method in Java?


A. public void myMethod() { return 0; }

B. public int myMethod() { System.out.println("Hello"); }

C. public void myMethod() { System.out.println("Hello"); }

D. public void myMethod() { return "Hello"; }

Can a void method in Java use the return statement?


A. Yes, with a value

B. Yes, without a value

C. No, it cannot use the return statement

D. Only if it returns null

What happens if you try to return a value from a void method in Java?


A. The value is ignored

B. It will compile but throw an exception at runtime

C. It will cause a compile-time error

D. It will cause a runtime error

Which of the following can be a correct implementation of a void method in Java?


A. void myMethod() { return 1; }

B. void myMethod() { return; }

C. void myMethod() { System.out.println("Hello"); }

D. Both B and C

Which statement is true about void methods in Java?


A. They must return a value

B. They cannot have parameters

C. They cannot return any value

D. They must be declared static

Can a void method perform operations and still not return any value?


A. Yes

B. No

What is the default return value of a void method in Java?


A. 0

B. null

C. Nothing

D. -1

In a void method, how can you exit the method prematurely?


A. By using break

B. By using continue

C. By using return

D. By using exit

Which of the following method signatures is a correct void method in Java?


A. public void method() { }

B. public int method() { }

C. void public method() { }

D. public void method(int x) { return x; }

Answers:

D. No return value

C. public void myMethod() { System.out.println("Hello"); }

B. Yes, without a value

C. It will cause a compile-time error

D. Both B and C

C. They cannot return any value

A. Yes

C. Nothing

C. By using return

A. public void method() { }


Methods in Java MCQ

 What is a method in Java?

a) A reserved keyword

b) A way to define a class

c) A block of code that performs a specific task and is reusable

d) A variable declaration


Which of the following is true about methods in Java?

a) Methods cannot have parameters

b) A method can return multiple values

c) Methods must always return a value

d) A method can perform a task without returning a value


What is the process of defining a method within a class known as in Java?

a) Implementing

b) Overriding

c) Overloading

d) Declaring


Which keyword is used to define a method in Java that doesn’t return any value?

a) void

b) int

c) return

d) null


What is the term used for passing values to a method in Java?

a) Initializing

b) Calling

c) Passing by reference

d) Passing by value


In Java, can a method have the same name but different parameters?

a) Yes, but only in interfaces

b) No, Java doesn’t support this feature

c) Yes, this is known as method overloading

d) Yes, this is known as method overriding


What is the purpose of the return type in a method signature in Java?

a) It specifies the method name

b) It defines the method's access level

c) It indicates the type of value the method returns

d) It indicates the number of parameters the method accepts


Which keyword is used to call a method within the same class in Java?

a) run

b) this

c) execute

d) call


What is the term used for calling one method from another method in Java?

a) Looping

b) Nesting

c) Recursion

d) Overloading


Which of the following statements about the main method in Java is correct?

a) It's optional in every Java program.

b) It must return a value.

c) It's the entry point for Java programs.

d) It can have any name other than "main".


Answers:


c) A block of code that performs a specific task and is reusable

d) A method can perform a task without returning a value

d) Declaring

a) void

d) Passing by value

c) Yes, this is known as method overloading

c) It indicates the type of value the method returns

b) this

c) Recursion

c) It's the entry point for Java programs.


MCQs on Methods Without Arguments

What is the correct syntax for a method without arguments in Java?


a) public void methodName() { /* code */ }

b) public void methodName { /* code */ }

c) void methodName() { /* code */ }

d) public methodName() { /* code */ }


Answer: a) public void methodName() { /* code */ }

Explanation: This is the correct syntax for defining a method without arguments in Java.


Which keyword is used to define a method that does not return any value?


a) public

b) static

c) void

d) return


Answer: c) void

Explanation: The void keyword indicates that the method does not return any value.


What will be the output of the following code?


java

Copy code

public void printHello() {

    System.out.println("Hello");

}


public static void main(String[] args) {

    printHello();

}

a) Hello

b) Error: Cannot find symbol

c) Error: Method printHello() must be static

d) No output


Answer: b) Error: Cannot find symbol

Explanation: The printHello method is not static, so it needs to be called on an instance of the class.


Which of the following statements about methods without arguments is true?


a) They must always return a value

b) They do not accept any parameters

c) They are defined using the static keyword

d) They must be called with arguments


Answer: b) They do not accept any parameters

Explanation: Methods without arguments do not accept any input parameters.


What is the default access level for a method defined without an access modifier?


a) public

b) protected

c) private

d) package-private


Answer: d) package-private

Explanation: If no access modifier is specified, the default access level is package-private.


What will be the output of the following code?


java

Copy code

public void display() {

    System.out.println("Display method");

}


public static void main(String[] args) {

    display();

}

a) Display method

b) Error: Cannot find symbol

c) Error: Method display() must be static

d) No output


Answer: b) Error: Cannot find symbol

Explanation: The display method is not static, so it needs to be called on an instance of the class.


Which method is executed when a Java application starts?


a) start()

b) main()

c) init()

d) run()


Answer: b) main()

Explanation: The main() method is the entry point of a Java application.


What will be the output of the following code snippet?


java

Copy code

public void show() {

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

}


public static void main(String[] args) {

    new MyClass().show();

}

a) Hello World!

b) Error: Cannot find symbol

c) Error: Method show() must be static

d) No output


Answer: a) Hello World!

Explanation: The show method is called on an instance of MyClass, so it will print Hello World!.


Which of the following is NOT a characteristic of a method without arguments?


a) It can be called on an instance of the class

b) It must have a return type

c) It can be defined with or without access modifiers

d) It can have a static modifier


Answer: b) It must have a return type

Explanation: Methods without arguments do not necessarily need a return type; they can have void.


How can you call a method without arguments from within another method of the same class?


a) methodName();

b) this.methodName();

c) new methodName();

d) methodName(new Object());


Answer: a) methodName();

Explanation: You can call a method without arguments directly if it is within the same class.


What is the effect of adding the static keyword to a method definition?


a) The method can only be called on an instance of the class

b) The method can be called without creating an instance of the class

c) The method cannot return a value

d) The method must accept arguments


Answer: b) The method can be called without creating an instance of the class

Explanation: The static keyword allows the method to be called without creating an instance of the class.


What will be the result of the following code if myMethod is defined as public void myMethod() {}?


java

Copy code

public void myMethod() {

    System.out.println("Method without arguments");

}


public static void main(String[] args) {

    myMethod();

}

a) Method without arguments

b) Error: Cannot find symbol

c) Error: Method myMethod() must be static

d) No output


Answer: b) Error: Cannot find symbol

Explanation: The method myMethod is not static, so it must be called on an instance of the class.


Which of the following correctly describes method overloading?


a) Methods with the same name but different return types

b) Methods with the same name and same parameters

c) Methods with different names and different parameters

d) Methods with the same name and different parameters


Answer: d) Methods with the same name and different parameters

Explanation: Method overloading involves having multiple methods with the same name but different parameter lists.


Which method will be executed if two methods are defined as follows?


java

Copy code

public void process() {

    System.out.println("Processing");

}


public void process(int value) {

    System.out.println("Processing with value: " + value);

}

a) process() with no arguments

b) process(int value) with an integer argument

c) Both methods will be executed

d) None of the methods will be executed


Answer: a) process() with no arguments

Explanation: The method executed depends on the arguments passed. If no arguments are passed, process() is called.


Which of the following statements about a method that has no arguments and returns a value is true?


a) It must use the void return type

b) It can have a return type other than void

c) It must be declared static

d) It cannot be called from the main method


Answer: b) It can have a return type other than void

Explanation: A method without arguments can still return a value and should specify the return type other than void.


************************

MCQs on Methods with Arguments

What is the correct syntax to define a method with arguments in Java?


a) public void methodName(arg1, arg2) { /* code */ }

b) public void methodName(type arg1, type arg2) { /* code */ }

c) public void methodName(type arg1, type arg2) { /* code */ }

d) public methodName(type arg1, type arg2) { /* code */ }


Answer: b) public void methodName(type arg1, type arg2) { /* code */ }

Explanation: The correct syntax requires specifying the types of arguments in the method definition.


What will be the output of the following code snippet?


java

Copy code

public void printSum(int a, int b) {

    System.out.println(a + b);

}


public static void main(String[] args) {

    new MyClass().printSum(5, 10);

}

a) 15

b) 510

c) Error: Cannot find symbol

d) No output


Answer: a) 15

Explanation: The method printSum adds the two arguments and prints the result, which is 15.


How do you call a method with arguments from another method in the same class?


a) methodName(arg1, arg2);

b) new methodName(arg1, arg2);

c) methodName(new arg1, new arg2);

d) methodName();


Answer: a) methodName(arg1, arg2);

Explanation: You call the method with the appropriate arguments in the same class.


Which of the following statements about method parameters is true?


a) Parameters are optional in method definitions

b) Method parameters must always have default values

c) Method parameters are used to pass values to methods

d) You can have methods with variable-length parameters only


Answer: c) Method parameters are used to pass values to methods

Explanation: Parameters allow you to pass data into methods.


What will be the result of the following code snippet?


java

Copy code

public int multiply(int a, int b) {

    return a * b;

}


public static void main(String[] args) {

    System.out.println(new MyClass().multiply(4, 5));

}

a) 20

b) 45

c) Error: Cannot find symbol

d) No output


Answer: a) 20

Explanation: The multiply method returns the product of 4 and 5, which is 20.


What is the purpose of method arguments in Java?


a) To initialize class variables

b) To pass data to the method

c) To define the return type of the method

d) To specify the method access level


Answer: b) To pass data to the method

Explanation: Arguments are used to provide input values to the method.


How can you define a method that accepts multiple arguments of different types?


a) public void methodName(int a, String b) { /* code */ }

b) public void methodName(String a, int b) { /* code */ }

c) public void methodName(int a, int b, String c) { /* code */ }

d) All of the above


Answer: d) All of the above

Explanation: Methods can be defined to accept multiple arguments of various types.


What is method overloading?


a) Methods with the same name but different return types

b) Methods with different names and the same parameters

c) Methods with the same name and different parameters

d) Methods with the same name and the same parameters


Answer: c) Methods with the same name and different parameters

Explanation: Overloading involves defining multiple methods with the same name but different parameter lists.


What will be the output of the following code?


java

Copy code

public void greet(String name) {

    System.out.println("Hello, " + name);

}


public static void main(String[] args) {

    new MyClass().greet("Alice");

}

a) Hello, Alice

b) Hello, name

c) Error: Cannot find symbol

d) No output


Answer: a) Hello, Alice

Explanation: The greet method prints a greeting message using the provided argument.


Which keyword can be used to specify that a method parameter is optional in Java?


a) optional

b) default

c) varargs

d) dynamic


Answer: c) varargs

Explanation: The varargs keyword allows a method to accept a variable number of arguments.


What will be the output of the following code snippet?


java

Copy code

public void addNumbers(int a, int b, int c) {

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

}


public static void main(String[] args) {

    new MyClass().addNumbers(1, 2);

}

a) 3

b) Error: Method addNumbers(int, int, int) not found

c) No output

d) 6


Answer: b) Error: Method addNumbers(int, int, int) not found

Explanation: The addNumbers method requires three arguments, but only two are provided.


How can you call a method with arguments from a static method?


a) methodName(arg1, arg2);

b) new instance.methodName(arg1, arg2);

c) MyClass.methodName(arg1, arg2);

d) this.methodName(arg1, arg2);


Answer: c) MyClass.methodName(arg1, arg2);

Explanation: To call a method with arguments from a static context, you use the class name.


What will be the result of this method call?


java

Copy code

public void displaySum(int a, int b) {

    System.out.println(a + b);

}


public static void main(String[] args) {

    displaySum(5, 10);

}

a) 15

b) 510

c) Error: Cannot find symbol

d) No output


Answer: c) Error: Cannot find symbol

Explanation: displaySum is not static, so it needs to be called on an instance of the class.


What will be the result of the following method call?


java

Copy code

public void printDetails(String name, int age) {

    System.out.println(name + " is " + age + " years old.");

}


public static void main(String[] args) {

    new MyClass().printDetails("John", 30);

}

a) John is 30 years old.

b) Error: Cannot find symbol

c) John is years old.

d) No output


Answer: a) John is 30 years old.

Explanation: The printDetails method formats and prints the provided arguments.


Which of the following statements is true about methods with arguments?


a) They can only accept primitive data types

b) They can accept any data type including objects

c) They must return a value

d) They cannot be overloaded


Answer: b) They can accept any data type including objects

Explanation: Methods with arguments can accept various data types, including primitive types and objects.



MCQs on Methods with Different Data Type Arguments in Java

Which of the following is a valid method signature in Java?


a) public void method(int x, float y, char z)

b) public void method(int x, float x, char z)

c) public void method(int x, float y, int z)

d) public void method(int x, float y, float z)


Answer: a) public void method(int x, float y, char z)

Explanation: Method signatures can have different types for each parameter as long as parameter names are unique within the method.


What will be the output of the following code?


java

Copy code

public class Main {

    public static void printValues(int a, float b, char c) {

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

    }

    

    public static void main(String[] args) {

        printValues(10, 5.5f, 'A');

    }

}

a) 10 5.5 A

b) 10 5.5f A

c) 10 5.5 A

d) Error: incompatible types


Answer: a) 10 5.5 A

Explanation: The method printValues correctly prints the int, float, and char values passed as arguments.


Which of the following method calls will cause a compile-time error?


a) printDetails(10, 10.5f, 'A')

b) printDetails(10, 'A', 10.5f)

c) printDetails('A', 10, 10.5f)

d) printDetails(10, 10.5, 'A')


Answer: d) printDetails(10, 10.5, 'A')

Explanation: The 10.5 is a double, not a float, so it causes a compile-time error because printDetails expects a float.


What is the correct method signature for a method that takes an int, float, and char as arguments and returns a float?


a) public float calculate(int a, float b, char c)

b) public float calculate(int a, float b, char c)

c) public float calculate(float a, int b, char c)

d) public float calculate(int a, char b, float c)


Answer: a) public float calculate(int a, float b, char c)

Explanation: This method signature matches the specified return type and arguments.


What will be the output of the following code snippet?


java

Copy code

public class Main {

    public static void display(int x, char y) {

        System.out.println(x + " " + y);

    }

    

    public static void display(char x, int y) {

        System.out.println(x + " " + y);

    }

    

    public static void main(String[] args) {

        display(5, 'B');

        display('C', 10);

    }

}

a) 5 B and C 10

b) 5 B and 67 10

c) 5 66 and 67 10

d) Error: method display cannot be applied


Answer: a) 5 B and C 10

Explanation: Method overloading allows display to be called with different argument types in different orders.


Which of the following method signatures will not compile due to type mismatch?


a) public void method(int x, float y)

b) public void method(float x, int y)

c) public void method(int x, float y, int z)

d) public void method(int x, double y)


Answer: d) public void method(int x, double y)

Explanation: This method would not compile if there is no matching method call or if a float value is passed where a double is expected.


What will be the output of the following code?


java

Copy code

public class Main {

    public static void sum(int a, float b) {

        System.out.println(a + b);

    }

    

    public static void sum(float a, int b) {

        System.out.println(a + b);

    }

    

    public static void main(String[] args) {

        sum(10, 5.5f);

        sum(5.5f, 10);

    }

}

a) 15.5 and 15.5

b) 15.5 and 55.5

c) 10.0 and 10.0

d) 15.5 and 15.5f


Answer: a) 15.5 and 15.5

Explanation: The sum method with different argument orders will produce the same result because both methods effectively perform addition.


Which of the following method signatures is correct for a method that accepts a char, int, and float in that order?


a) public void method(char a, int b, float c)

b) public void method(int a, char b, float c)

c) public void method(int a, float b, char c)

d) public void method(float a, char b, int c)


Answer: a) public void method(char a, int b, float c)

Explanation: The order of arguments must match the method signature.


What will be the output of the following code?


java

Copy code

public class Main {

    public static void display(int a, float b) {

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

    }

    

    public static void display(float a, int b) {

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

    }

    

    public static void main(String[] args) {

        display(10, 5.5f);

    }

}

a) 10 5.5

b) 10.0 5

c) 5.5 10

d) Error: method display cannot be applied


Answer: a) 10 5.5

Explanation: The method display(int a, float b) is called with matching argument types.


How can you change the method signature to accept a char and a float and return an int?


a) public int method(char a, float b)

b) public int method(float a, char b)

c) public void method(char a, float b)

d) public float method(char a, float b)


Answer: a) public int method(char a, float b)

Explanation: This method signature matches the required return type and argument types.


What will be the output of the following code snippet?


java

Copy code

public class Main {

    public static void compute(int a, float b) {

        System.out.println(a + b);

    }

    

    public static void compute(float a, int b) {

        System.out.println(a * b);

    }

    

    public static void main(String[] args) {

        compute(5, 3.5f);

        compute(3.5f, 5);

    }

}

a) 8.5 and 17.5

b) 8.5 and 3.5

c) 5.0 and 17.5

d) Error: method compute cannot be applied


Answer: a) 8.5 and 17.5

Explanation: The first call uses addition, and the second uses multiplication due to method overloading.


Which method signature will be chosen for the call process(10, 5.0)?


a) public void process(int a, float b)

b) public void process(float a, int b)

c) public void process(double a, int b)

d) public void process(int a, double b)


Answer: d) public void process(int a, double b)

Explanation: 5.0 is a double, and int can be implicitly cast to int, so this method is chosen.


What is the output of the following code?


java

Copy code

public class Main {

    public static void calculate(float a, int b) {

        System.out.println(a - b);

    }

    

    public static void calculate(int a, float b) {

        System.out.println(a / b);

    }

    

    public static void main(String[] args) {

        calculate(5.5f, 2);

    }

}

a) `3.



MCQs on Method Return Types in Java

Which of the following methods has a return type of void?


a) public void displayMessage()

b) public int getValue()

c) public String getName()

d) public float calculateAverage()


Answer: a) public void displayMessage()

Explanation: The void return type indicates that the method does not return any value.


What will be the output of the following code?


java

Copy code

public class Main {

    public static int getNumber() {

        return 42;

    }

    

    public static void main(String[] args) {

        System.out.println(getNumber());

    }

}

a) 42

b) 0

c) Error: incompatible types

d) null


Answer: a) 42

Explanation: The method getNumber() returns an int value, which is printed in the main method.


Which method signature is correct for a method that returns a float?


a) public float getTotalAmount()

b) public void getTotalAmount()

c) public float getTotalAmount(int a)

d) public float getTotalAmount(int a, String b)


Answer: a) public float getTotalAmount()

Explanation: The method signature should include the return type float if the method returns a float.


What is the return type of the method in the following code?


java

Copy code

public class Main {

    public static char getInitial() {

        return 'A';

    }

}

a) void

b) int

c) char

d) String


Answer: c) char

Explanation: The method getInitial() returns a char value.


Which method correctly returns a boolean value?


a) public boolean isAvailable() { return true; }

b) public void isAvailable() { return true; }

c) public boolean isAvailable() { return 1; }

d) public boolean isAvailable() { return "true"; }


Answer: a) public boolean isAvailable() { return true; }

Explanation: The method returns a boolean value, which is correctly specified in the return type.


What will be the result of calling the following method?


java

Copy code

public class Main {

    public static String getMessage() {

        return "Hello, World!";

    }

    

    public static void main(String[] args) {

        System.out.println(getMessage());

    }

}

a) Hello, World!

b) Error: incompatible types

c) null

d) Hello


Answer: a) Hello, World!

Explanation: The method getMessage() returns a String value, which is printed in the main method.


Which of the following is a valid method that returns an array of int?


a) public int[] getArray() { return new int[10]; }

b) public int getArray() { return new int[10]; }

c) public void[] getArray() { return new int[10]; }

d) public int[] getArray(int size) { return new int[size]; }


Answer: a) public int[] getArray() { return new int[10]; }

Explanation: This method signature correctly returns an array of int.


What is the output of the following code?


java

Copy code

public class Main {

    public static int[] getNumbers() {

        return new int[] {1, 2, 3};

    }

    

    public static void main(String[] args) {

        int[] numbers = getNumbers();

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

    }

}

a) 2

b) 1

c) 3

d) Error: ArrayIndexOutOfBoundsException


Answer: a) 2

Explanation: The method getNumbers() returns an array, and the second element is 2.


Which method signature will return an array of String?


a) public String[] getNames()

b) public array<String> getNames()

c) public String getNames()

d) public String getNames[]()


Answer: a) public String[] getNames()

Explanation: The method signature should include String[] to return an array of String.


What will be the result of the following method call?


java

Copy code

public class Main {

    public static boolean isValid() {

        return 1 == 1;

    }

    

    public static void main(String[] args) {

        System.out.println(isValid());

    }

}

a) true

b) false

c) 1

d) Error: incompatible types


Answer: a) true

Explanation: The method isValid() returns true because 1 == 1 evaluates to true.


Which method signature is used to return a float value from a method?


a) public float getDiscount()

b) public float getDiscount(int a)

c) public void getDiscount()

d) public float getDiscount(float a)


Answer: a) public float getDiscount()

Explanation: This method signature specifies a return type of float.


What is the output of the following code?


java

Copy code

public class Main {

    public static float getPi() {

        return 3.14f;

    }

    

    public static void main(String[] args) {

        System.out.println(getPi());

    }

}

a) 3.14

b) 3.14f

c) 3

d) Error: incompatible types


Answer: a) 3.14

Explanation: The method getPi() returns a float, and it is printed in the main method.


Which method signature will correctly return a char value?


a) public char getFirstLetter()

b) public void getFirstLetter()

c) public char getFirstLetter(int index)

d) public char getFirstLetter(char letter)


Answer: a) public char getFirstLetter()

Explanation: This method signature correctly specifies a char return type.


Which of the following methods correctly returns a String and an int array?


a) public String getMessage() { return "Hello"; }

public int[] getNumbers() { return new int[10]; }

b) public String getMessage() { return new int[10]; }

public int[] getNumbers() { return "Hello"; }

c) public void getMessage() { return "Hello"; }

public void getNumbers() { return new int[10]; }

d) public String getMessage() { return "Hello"; }

public void getNumbers() { return new int[10]; }


Answer: a) public String getMessage() { return "Hello"; }

public int[] getNumbers() { return new int[10]; }

Explanation: These method signatures correctly return a String and an int array.


What is the correct method signature for a method that returns a boolean?


a) public boolean isActive()

b) public void isActive()

c) public boolean isActive(int a)

d) public boolean isActive(boolean status)


Answer: a) public boolean isActive()

Explanation: This method signature specifies that the method returns a boolean.



MCQs on Math.min(), Math.max(), and Math.sqrt() Methods

What does the Math.min() method do in Java?


a) Returns the maximum value among two numbers

b) Returns the minimum value among two numbers

c) Returns the square root of a number

d) Returns the larger value among multiple numbers


Answer: b) Returns the minimum value among two numbers

Explanation: The Math.min() method returns the smaller of two specified numbers.


Which method would you use to find the larger of two numbers?


a) Math.sqrt()

b) Math.min()

c) Math.max()

d) Math.abs()


Answer: c) Math.max()

Explanation: The Math.max() method returns the larger of two specified numbers.


If you call Math.min(10, 20), what will be the output?


a) 10

b) 20

c) 30

d) 0


Answer: a) 10

Explanation: The Math.min() method returns the smaller value, which is 10 in this case.


What does the Math.sqrt() method return?


a) The square of a number

b) The square root of a number

c) The cube root of a number

d) The logarithm of a number


Answer: b) The square root of a number

Explanation: The Math.sqrt() method returns the square root of a specified number.


Which method will you use to find the smaller number between 5.5 and 7.8?


a) Math.max()

b) Math.sqrt()

c) Math.min()

d) Math.round()


Answer: c) Math.min()

Explanation: The Math.min() method returns the smaller of two specified numbers.


What is the result of Math.max(-5, -10)?


a) -10

b) -5

c) 0

d) 5


Answer: b) -5

Explanation: The Math.max() method returns the larger of two specified numbers, which is -5 in this case.


If you call Math.sqrt(16), what is the result?


a) 2

b) 4

c) 8

d) 16


Answer: b) 4

Explanation: The Math.sqrt() method returns the square root of 16, which is 4.


What type of arguments can the Math.min() and Math.max() methods accept?


a) Only integers

b) Only floating-point numbers

c) Both integers and floating-point numbers

d) Only characters


Answer: c) Both integers and floating-point numbers

Explanation: The Math.min() and Math.max() methods can accept both int and double types.


What will be the output of Math.sqrt(0)?


a) 0

b) 1

c) -1

d) Error


Answer: a) 0

Explanation: The Math.sqrt() method returns the square root of 0, which is 0.


Which of the following statements is correct about the Math.min() method?


a) It can only compare integers.

b) It returns the maximum of two numbers.

c) It can compare both integers and floating-point numbers.

d) It always returns 0.


Answer: c) It can compare both integers and floating-point numbers.

Explanation: The Math.min() method can compare both int and double types.


If Math.sqrt(x) is called where x is -4, what will be the result?


a) 2

b) -2

c) NaN

d) Error


Answer: c) NaN

Explanation: The Math.sqrt() method returns NaN (Not a Number) for negative input values.


What is the return type of Math.min() and Math.max() methods?


a) double

b) int

c) float

d) long


Answer: a) double

Explanation: When Math.min() and Math.max() are used with double arguments, they return a double. When used with int, they return an int.


What will be the output of Math.max(3.5, 2.7)?


a) 3.5

b) 2.7

c) 6.2

d) 3.0


Answer: a) 3.5

Explanation: The Math.max() method returns the larger of two double values, which is 3.5.


If Math.sqrt(25.0) is executed, what is the result?


a) 5.0

b) 25.0

c) 0.5

d) 10.0


Answer: a) 5.0

Explanation: The Math.sqrt() method returns the square root of 25.0, which is 5.0.


Which method would you use to find the smaller number between -1.2 and 3.4?


a) Math.sqrt()

b) Math.min()

c) Math.max()

d) Math.round()


Answer: b) Math.min()

Explanation: The Math.min() method returns the smaller of two specified numbers, which is -1.2.



MCQs on Method Return Types in Java

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


a) void

b) int

c) null

d) String


Answer: a) void

Explanation: The void return type indicates that the method does not return any value.


What will be the return type of the following method? public int calculateSum(int a, int b)


a) void

b) int

c) String

d) double


Answer: b) int

Explanation: The return type int indicates that the method returns an integer value.


Which return type should be used if a method needs to return a floating-point number?


a) int

b) double

c) char

d) boolean


Answer: b) double

Explanation: The double return type is used for methods that return a floating-point number.


What will be the result of calling a method with void return type?


a) It returns null.

b) It returns a default value.

c) It does not return any value.

d) It returns an empty string.


Answer: c) It does not return any value.

Explanation: A method with a void return type does not return any value.


If a method has a return type of boolean, what kind of value should it return?


a) An integer

b) A string

c) A boolean value (true or false)

d) A floating-point number


Answer: c) A boolean value (true or false)

Explanation: The boolean return type requires the method to return a boolean value.


What is the return type of a method that returns a single character?


a) String

b) char

c) int

d) boolean


Answer: b) char

Explanation: The char return type is used for methods that return a single character.


Which return type is suitable for a method that needs to return a reference to a string object?


a) char

b) String

c) int

d) boolean


Answer: b) String

Explanation: The String return type is used for methods that return a reference to a string object.


What will be the return type of the following method: public double getAverage(int a, int b)?


a) void

b) int

c) float

d) double


Answer: d) double

Explanation: The double return type indicates that the method returns a double-precision floating-point number.


What is the return type of a method that returns an array of integers?


a) int

b) int[]

c) ArrayList<int>

d) Array<int>


Answer: b) int[]

Explanation: The return type int[] represents an array of integers.


What type of return value is expected from a method that is declared with boolean return type?


a) An integer

b) A floating-point number

c) true or false

d) A string


Answer: c) true or false

Explanation: A boolean return type expects a value of true or false.


If a method has a return type of float, what should it return?


a) An integer

b) A floating-point number

c) A boolean value

d) A string


Answer: b) A floating-point number

Explanation: The float return type is used for methods that return a floating-point number.


What will happen if you try to return a value of type String from a method declared with int return type?


a) It will compile successfully.

b) It will throw a runtime error.

c) It will cause a compilation error.

d) It will return null.


Answer: c) It will cause a compilation error.

Explanation: The return type of a method must match the type of the value returned.


What return type is appropriate for a method that performs an operation but does not need to return any result?


a) int

b) boolean

c) void

d) String


Answer: c) void

Explanation: The void return type is used for methods that do not return any result.


What is the return type of the Math.sqrt() method?


a) int

b) double

c) float

d) char


Answer: b) double

Explanation: The Math.sqrt() method returns a double value representing the square root of a number.


If a method is defined as public char getInitial(), what kind of value should it return?


a) A single character

b) An integer

c) A boolean value

d) A string


Answer: a) A single character

Explanation: The char return type indicates that the method returns a single character.


MCQs on Method Return Type Casting in Java

Which of the following is true about type casting when returning a value from a method?


a) You cannot cast the return type of a method.

b) You can cast the return type only if it is compatible.

c) You can cast the return type to any type regardless of compatibility.

d) Type casting is automatically handled by the compiler for all return types.


Answer: b) You can cast the return type only if it is compatible.

Explanation: You can cast return types if they are compatible, such as casting a float to double.


What will happen if you cast an int return type to double in a method?


a) Compilation error

b) Runtime error

c) The cast will be performed implicitly without error

d) The method will return null


Answer: c) The cast will be performed implicitly without error

Explanation: Casting from int to double is safe and done implicitly without error.


If a method returns a String and you cast it to Object, what happens?


a) Compilation error

b) Runtime error

c) The cast will be performed implicitly without error

d) The method will return null


Answer: c) The cast will be performed implicitly without error

Explanation: String is a subclass of Object, so casting a String to Object is safe and done implicitly.


Can you cast a float return type to int?


a) Yes, but it may lead to loss of precision.

b) No, it will cause a compilation error.

c) Yes, and it will automatically round the value.

d) No, it will cause a runtime error.


Answer: a) Yes, but it may lead to loss of precision.

Explanation: Casting from float to int is allowed but may lead to loss of precision.


What is the result of casting a double value to int?


a) The method returns the double value.

b) The fractional part of the double value is lost.

c) The double value is rounded to the nearest integer.

d) The method returns null.


Answer: b) The fractional part of the double value is lost.

Explanation: Casting from double to int truncates the fractional part.


What happens if you cast an Object to a specific subclass type that is not actually an instance of that subclass?


a) The code will compile successfully.

b) A ClassCastException will be thrown at runtime.

c) The cast will be performed implicitly without error.

d) The method will return null.


Answer: b) A ClassCastException will be thrown at runtime.

Explanation: Casting to a type that is not an instance of the subclass will result in a ClassCastException at runtime.


If a method returns an int and you try to cast it to char, what will happen?


a) Compilation error

b) Runtime error

c) The cast will be performed implicitly without error

d) The method will return null


Answer: c) The cast will be performed implicitly without error

Explanation: Casting from int to char is allowed, but it may lead to unexpected results if the int value is outside the valid range for char.


Can you cast a boolean value to int?


a) Yes, it will work without error.

b) No, it will cause a compilation error.

c) Yes, but it will cause a runtime error.

d) Yes, but it will return null.


Answer: b) No, it will cause a compilation error.

Explanation: Casting between boolean and numerical types (int, float, etc.) is not allowed.


What will be the result if you cast an int to a float in a method return type?


a) Compilation error

b) Runtime error

c) The cast will be performed implicitly without error

d) The method will return null


Answer: c) The cast will be performed implicitly without error

Explanation: Casting from int to float is safe and done implicitly.


When casting a double to float, what should you be aware of?


a) No issues arise as double and float are the same type.

b) Loss of precision may occur since double has a higher precision than float.

c) The cast will automatically round the value.

d) The method will throw a ClassCastException.


Answer: b) Loss of precision may occur since double has a higher precision than float.

Explanation: Casting from double to float may result in loss of precision due to the difference in their precision levels.


What happens if you cast an ArrayList<Integer> to ArrayList<Number>?


a) Compilation error

b) Runtime error

c) The cast will be performed implicitly without error

d) The method will return null


Answer: a) Compilation error

Explanation: Generics are invariant in Java, so casting between generic types with different type parameters is not allowed.


What is the result of casting an int to double?


a) The method returns an int value.

b) The int value is rounded to the nearest double.

c) The int value is implicitly converted to double without loss of data.

d) The method returns null.


Answer: c) The int value is implicitly converted to double without loss of data.

Explanation: Casting from int to double is safe and done implicitly, as double can represent all values of int without loss of data.


Can you cast an int array to a String array?


a) Yes, the cast will be performed implicitly without error.

b) No, it will cause a compilation error.

c) Yes, but it will cause a runtime error.

d) Yes, but the method will return null.


Answer: b) No, it will cause a compilation error.

Explanation: Casting between arrays of different types is not allowed.


What happens when casting a float to an int in a method return type?


a) The float value is rounded to the nearest int.

b) The float value is truncated to the nearest int.

c) The float value is cast without any change.

d) The method will throw a ClassCastException.


Answer: b) The float value is truncated to the nearest int.

Explanation: Casting from float to int truncates the fractional part.


If a method returns a long and you cast it to int, what should you expect?


a) Compilation error

b) Runtime error

c) Loss of data if the long value exceeds the int range

d) The cast will be performed implicitly without error


Answer: c) Loss of data if the long value exceeds the int range

Explanation: Casting from long to int may result in loss of data if the long value exceeds the int range.



Difficult MCQs on Return Statement in Java

What is the output of the following Java code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(getValue());

    }


    static int getValue() {

        try {

            return 1;

        } finally {

            return 2;

        }

    }

}

a) 1

b) 2

c) 0

d) Compilation error


Answer: b) 2

Explanation: In Java, if a finally block has a return statement, it overrides any return value from the try block.


What will be the result of the following code if executed?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(test(5));

    }


    static int test(int x) {

        if (x < 10) {

            return x;

        } else {

            return 10;

        }

    }

}

a) The code will print 5.

b) The code will print 10.

c) The code will cause a runtime error.

d) The code will cause a compilation error.


Answer: a) The code will print 5.

Explanation: Since x is 5 and 5 < 10, the method returns 5.


Given the following method, what is the output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(calculate());

    }


    static int calculate() {

        int result = 5;

        return result * 2;

    }

}

a) 5

b) 10

c) 0

d) Compilation error


Answer: b) 10

Explanation: The calculate method returns result * 2, which is 5 * 2 = 10.


What is the behavior of the following Java code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(method(10));

    }


    static int method(int num) {

        return num > 5 ? 100 : 200;

    }

}

a) 100

b) 200

c) 0

d) Compilation error


Answer: a) 100

Explanation: Since num is 10 which is greater than 5, the ternary operator returns 100.


What will be the output of this code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(foo());

    }


    static int foo() {

        try {

            return 1;

        } catch (Exception e) {

            return 2;

        } finally {

            return 3;

        }

    }

}

a) 1

b) 2

c) 3

d) Compilation error


Answer: c) 3

Explanation: The finally block has a return statement that overrides the return value from the try block.


Given the following code, what will be the result?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(check(7));

    }


    static int check(int value) {

        if (value > 5) {

            return value - 1;

        } else if (value == 5) {

            return value + 1;

        } else {

            return value;

        }

    }

}

a) 6

b) 7

c) 8

d) 5


Answer: a) 6

Explanation: Since value is 7, which is greater than 5, the method returns value - 1, which is 6.


What will be the output of the following Java method?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(multiply(2, 3));

    }


    static int multiply(int a, int b) {

        return a * b;

    }

}

a) 6

b) 5

c) 7

d) Compilation error


Answer: a) 6

Explanation: The method multiply returns the product of a and b, which is 2 * 3 = 6.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(subtract(10, 5));

    }


    static int subtract(int a, int b) {

        int result = a - b;

        return result;

    }

}

a) 10

b) 5

c) 15

d) 0


Answer: b) 5

Explanation: The subtract method returns the result of 10 - 5, which is 5.


What will be the result of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(getValue(3));

    }


    static int getValue(int x) {

        switch(x) {

            case 1:

                return 10;

            case 2:

                return 20;

            default:

                return 30;

        }

    }

}

a) 10

b) 20

c) 30

d) Compilation error


Answer: c) 30

Explanation: Since x is 3, which does not match any case in the switch statement, the default case is executed, returning 30.


What happens if you try to return a value from a method that has a return type of void?


a) Compilation error

b) Runtime error

c) The method will return null.

d) The return statement will be ignored.


Answer: a) Compilation error

Explanation: A method with a return type of void cannot return a value.


Given the following code, what is the output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(sum(1, 2, 3));

    }


    static int sum(int... numbers) {

        int total = 0;

        for (int num : numbers) {

            total += num;

        }

        return total;

    }

}

a) 6

b) 3

c) 1

d) Compilation error


Answer: a) 6

Explanation: The method sum takes a variable number of arguments, sums them, and returns 6.


What will be the output of this method?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(calculate(4));

    }


    static int calculate(int num) {

        return num < 5 ? num * 2 : num * 3;

    }

}

a) 8

b) 12

c) 4

d) 10


Answer: a) 8

Explanation: Since num is 4, which is less than 5, the method returns num * 2, which is 8.


What is the result of the following code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(getResult(2));

    }


    static int getResult(int a) {

        if (a > 0) {

            return a;

        } else {

            return -a;

        }

    }

}

a) 2

b) -2

c) 0

d) Compilation error


Answer: a) 2

Explanation: Since a is 2, which is greater than 0, the method returns a, which is 2.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        System.out.println(performAction(true));

    }


    static String performAction(boolean flag) {

        if (flag) {

            return "True";

        } else {

            return "False";

        }

    }

}

a) True

b) False

c) true

d) false


Answer: a) True

Explanation: The




Type Casting In Java MCQ

 What is typecasting in Java?

a) Assigning a value to a variable

b) Converting a value from one data type to another

c) Defining the type of a variable explicitly

d) Declaring a variable with a specific data type


Which of the following is an implicit type conversion in Java?

a) Converting a smaller data type to a larger one

b) Converting a larger data type to a smaller one

c) Converting a string to an integer

d) Converting a character to a string


What is the result of casting a floating-point number to an integer in Java?

a) Truncation of the decimal part

b) Rounding up to the nearest integer

c) Rounding down to the nearest integer

d) Conversion to a string


What is the purpose of explicit typecasting in Java?

a) To convert a larger data type to a smaller one

b) To convert a smaller data type to a larger one

c) To avoid compilation errors

d) To define custom data types


Which keyword is used for explicit typecasting in Java?

a) cast

b) convert

c) (type)

d) typecast


What is the result of casting a double value to an integer when the double value is beyond the range of integer data type?

a) It results in a compilation error.

b) It throws a runtime exception.

c) The value is rounded to the nearest integer.

d) It results in an overflow.


When converting a higher data type to a lower data type, what might occur in Java?

a) Truncation of data

b) Loss of precision

c) No change in data

d) Conversion to a string


What happens when you cast an object of one class to another unrelated class in Java?

a) It results in a runtime error.

b) It throws a compilation error.

c) It's allowed but can lead to unexpected behavior.

d) It automatically converts to the new class type.


Which of the following types of casting requires explicit type conversion in Java?

a) Casting between integers

b) Casting between floats and doubles

c) Casting between primitive data types

d) Casting between objects of unrelated classes


In Java, what does narrowing conversion refer to?

a) Converting a smaller data type to a larger one

b) Converting a larger data type to a smaller one

c) Converting objects to primitive data types

d) Converting strings to numerical values


Answers:


b) Converting a value from one data type to another

a) Converting a smaller data type to a larger one

a) Truncation of the decimal part

b) To convert a smaller data type to a larger one

c) (type)

d) It results in an overflow.

b) Loss of precision

c) It's allowed but can lead to unexpected behavior.

c) Casting between primitive data types

b) Converting a larger data type to a smaller one


MCQs on Type Casting in Java

What is type casting in Java?


a) Converting one primitive data type into another

b) Converting an object from one class type to another

c) Changing the value of a variable

d) Declaring multiple variables of different types


Answer: a) Converting one primitive data type into another

Explanation: Type casting refers to converting one primitive data type into another, such as from int to double.


Which of the following is an example of implicit type casting?


a) int i = 10; double d = i;

b) double d = 10.5; int i = (int) d;

c) char c = (char) 65;

d) float f = (float) 3.14;


Answer: a) int i = 10; double d = i;

Explanation: Implicit casting happens when converting from a smaller type to a larger type without explicit casting.


Which type of casting requires explicit casting?


a) Implicit casting

b) Automatic casting

c) Widening casting

d) Narrowing casting


Answer: d) Narrowing casting

Explanation: Narrowing casting (e.g., double to int) requires explicit casting because it involves converting a larger type to a smaller type.


What will be the result of the following code snippet?


java

Copy code

double d = 9.78;

int i = (int) d;

System.out.println(i);

a) 9

b) 9.78

c) 10

d) Error: incompatible types


Answer: a) 9

Explanation: Explicit casting from double to int truncates the decimal part, resulting in 9.


What does the following code snippet do?


java

Copy code

char c = 'A';

int i = c;

System.out.println(i);

a) Prints the ASCII value of A

b) Prints A

c) Prints 65

d) Causes a compilation error


Answer: c) Prints 65

Explanation: The char type is implicitly cast to int, which prints the ASCII value of A.


What is the output of this code snippet?


java

Copy code

int i = 10;

double d = i;

System.out.println(d);

a) 10.0

b) 10

c) Error: incompatible types

d) 10.00


Answer: a) 10.0

Explanation: Implicit casting from int to double adds a decimal point to the value.


Which type of casting is used to convert a float to an int?


a) Implicit casting

b) Narrowing casting

c) Widening casting

d) Automatic casting


Answer: b) Narrowing casting

Explanation: Converting float to int is narrowing casting as it involves converting a larger type to a smaller type.


How can you convert a String to an int in Java?


a) int i = String.valueOf("123");

b) int i = (int) "123";

c) int i = Integer.parseInt("123");

d) int i = String.toInt("123");


Answer: c) int i = Integer.parseInt("123");

Explanation: Integer.parseInt() method converts a String to an int.


What will be the output of the following code?


java

Copy code

double d = 9.99;

int i = (int) d;

System.out.println(i);

a) 9

b) 9.99

c) 10

d) Error: incompatible types


Answer: a) 9

Explanation: Explicit casting from double to int truncates the decimal part.


What is the result of casting an int to a byte?


a) No change in value

b) Possible loss of data

c) Automatic widening

d) Error: incompatible types


Answer: b) Possible loss of data

Explanation: Casting int to byte can result in loss of data if the int value exceeds the range of a byte.


What is the output of the following code snippet?


java

Copy code

byte b = 100;

int i = b;

System.out.println(i);

a) 100

b) Error: incompatible types

c) 100.0

d) byte


Answer: a) 100

Explanation: Implicit casting from byte to int does not change the value, only the type.


Which method is used to convert a double to a String in Java?


a) String.valueOf(double)

b) String.toString(double)

c) String.convert(double)

d) String.parse(double)


Answer: a) String.valueOf(double)

Explanation: String.valueOf() method converts a double to its String representation.


What will be the output of the following code snippet?


java

Copy code

int i = 300;

byte b = (byte) i;

System.out.println(b);

a) 44

b) 300

c) Error: incompatible types

d) 300


Answer: a) 44

Explanation: int value 300 exceeds the range of byte, so it wraps around, resulting in 44.


How do you convert a float to a String?


a) String.valueOf(float)

b) Float.toString(float)

c) String.convert(float)

d) String.parseFloat(float)


Answer: a) String.valueOf(float)

Explanation: String.valueOf() method can be used to convert a float to its String representation.


What will be the result of the following code snippet?


java

Copy code

char c = 'Z';

int i = c + 1;

System.out.println((char) i);

a) [

b) Y

c) Z

d) Error: incompatible types


Answer: a) [

Explanation: The character 'Z' has an ASCII value of 90. Adding 1 results in 91, which corresponds to the character '['.


Do while loop MCQ

What is the primary difference between a do-while loop and a while loop in Java?

a) do-while executes its body at least once even if the condition is false initially.

b) do-while always executes its body at least once.

c) There is no difference between do-while and while loops.

d) while loop executes its body only if the condition is true initially.


What is the syntax to create a do-while loop in Java?

a) do { } while ();

b) while { } do ();

c) do { } while {};

d) do { } while ();


In a do-while loop, when is the condition checked?

a) Before executing the loop body

b) After executing the loop body

c) Before and after executing the loop body

d) Only once at the start


Which of the following statements is true regarding the termination condition in a do-while loop?

a) It is optional.

b) It must always be placed before the loop body.

c) It must be enclosed in parentheses after the do keyword.

d) It must end with a semicolon after the condition.


What happens if the condition in a do-while loop is initially false?

a) The loop body is executed at least once.

b) The loop body is skipped entirely.

c) It results in a compilation error.

d) The loop becomes an infinite loop.


What statement is used to exit a do-while loop prematurely in Java?

a) exit

b) break

c) terminate

d) skip


Which part of the do-while loop contains the condition that determines whether the loop body should execute again?

a) Initialization

b) Condition

c) Iteration

d) Termination


What is the primary purpose of the do-while loop?

a) To execute a block of code repeatedly as long as a specified condition is true

b) To perform a one-time check of a condition

c) To execute a block of code a fixed number of times

d) To execute a block of code once regardless of the condition


How many times will a do-while loop execute if the condition is false from the beginning?

a) It depends on the loop structure.

b) Once

c) Twice

d) Indefinitely


In a do-while loop, where is the loop condition evaluated?

a) Before executing the loop body

b) After executing the loop body

c) Both before and after executing the loop body

d) Only once at the start


Answers:


a) do-while executes its body at least once even if the condition is false initially.

d) do { } while ();

b) After executing the loop body

c) It must be enclosed in parentheses after the do keyword.

a) The loop body is executed at least once.

b) break

b) Condition

a) To execute a block of code repeatedly as long as a specified condition is true

b) Once

a) Before executing the loop body


Difficult MCQs on do-while Loop

What will be the output of the following code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i++;

        } while (i < 5);

        System.out.println(i);

    }

}

a) 4

b) 5

c) 6

d) 0


Answer: b) 5

Explanation: The loop increments i from 0 to 5. The condition i < 5 becomes false when i equals 5, thus the loop exits and 5 is printed.


What will be the output of this code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int x = 5;

        int y = 0;

        do {

            y++;

            x--;

        } while (x > 0 && y < 5);

        System.out.println(y);

    }

}

a) 4

b) 5

c) 6

d) 0


Answer: b) 5

Explanation: The do-while loop continues while x > 0 and y < 5. Since x is decremented and y is incremented on each iteration, the loop stops when y reaches 5.


What will the following code output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i++;

            if (i == 3) {

                continue;

            }

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

        } while (i < 5);

    }

}

a) 1 2 4 5

b) 1 2 4

c) 1 2 3 4

d) 1 2 3 4 5


Answer: b) 1 2 4

Explanation: The continue statement skips the current iteration when i equals 3, so 3 is not printed.


What will be the output of this code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 10;

        do {

            if (i % 3 == 0) {

                break;

            }

            i--;

        } while (i > 5);

        System.out.println(i);

    }

}

a) 9

b) 10

c) 8

d) 6


Answer: a) 9

Explanation: The break statement terminates the loop when i % 3 == 0, so when i is 9, the loop exits and 9 is printed.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i++;

            if (i == 3) {

                continue;

            }

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

        } while (i < 5);

    }

}

a) 1 2 4

b) 1 2 3 4

c) 1 2 3 4 5

d) 1 2 3


Answer: a) 1 2 4

Explanation: When i equals 3, the continue statement skips printing and moves to the next iteration.


What will be the result of the following code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 10;

        do {

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

            i -= 2;

        } while (i > 0);

    }

}

a) 10 8 6 4 2

b) 10 8 6 4

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

d) 10 8 6 4 2 0


Answer: a) 10 8 6 4 2

Explanation: The do-while loop decrements i by 2 each time, stopping when i is no longer greater than 0.


What will the following code output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int x = 5;

        int y = 0;

        do {

            y++;

            x--;

            if (x == 3) {

                break;

            }

        } while (y < 5);

        System.out.println(y);

    }

}

a) 3

b) 4

c) 5

d) 0


Answer: a) 3

Explanation: The break statement terminates the loop when x equals 3, so the loop exits with y equal to 3.


What is the output of the following code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i++;

            if (i % 2 == 0) {

                continue;

            }

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

        } while (i < 5);

    }

}

a) 1 3

b) 1 2 3

c) 2 4

d) 1 2 3 4 5


Answer: a) 1 3

Explanation: The continue statement skips printing for even values of i.


What will be the result of this code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i++;

            if (i > 3) {

                break;

            }

        } while (i < 5);

        System.out.println(i);

    }

}

a) 3

b) 4

c) 5

d) 0


Answer: b) 4

Explanation: The break statement terminates the loop when i becomes 4, and 4 is printed.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i++;

            if (i == 2) {

                continue;

            }

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

        } while (i < 4);

    }

}

a) 1 3

b) 1 2 3

c) 2 3

d) 1 2


Answer: a) 1 3

Explanation: When i equals 2, continue skips printing 2, so only 1 and 3 are printed.


What does the following code output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i++;

            if (i == 3) {

                return;

            }

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

        } while (i < 5);

    }

}

a) 1 2

b) 1 2 3

c) 1 2 3 4

d) 1 2 3 4 5


Answer: a) 1 2

Explanation: The return statement terminates the method, stopping the loop and printing 1 2.


What is the result of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            if (i == 3) {

                break;

            }

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

            i++;

        } while (i < 5);

    }

}

a) 0 1 2

b) 0 1 2 3

c) 1 2 3

d) 0 1 2 3 4


Answer: a) 0 1 2

Explanation: The break statement terminates the loop when i equals 3, so only 0 1 2 are printed.


What will the following code output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 1;

        do {

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

            i += 2;

        } while (i < 10);

    }

}

a) 1 3 5 7 9

b) 1 3 5 7

c) 1 3 5 7 9 11

d) 1 2 3 4 5 6 7 8 9


Answer: a) 1 3 5 7 9

Explanation: The loop increments i by 2 each time, so the output is the series 1 3 5 7 9.


What does this code output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i++;

            if (i == 4) {

                continue;

            }

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

        } while (i < 5);

    }

}

a) 1 2 3 4

b) 1 2 3

c) 1 2 3 5

d) 1 2 3 4 5


Answer: a) 1 2 3 5

Explanation: The continue statement skips the printing of 4, so 1 2 3 and 5 are printed.


What will the following code snippet output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        do {

            i += 2;

            if (i == 4) {

                continue;

            }

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

        } while (i < 6);

    }

}

a) 2 6

b) 2 4 6

c) 2 6 8

d) 2 6


Answer: a) 2 6

Explanation: The continue statement skips printing 4, so 2 and 6 are printed.

While Loop MCQ

 What is the primary purpose of a while loop in Java?

a) To execute a block of code repeatedly as long as a specified condition is true

b) To execute a block of code a fixed number of times

c) To perform a one-time check of a condition

d) To execute a block of code once regardless of the condition


In a while loop, what happens if the condition is initially false?

a) The loop body is executed at least once.

b) The loop body is skipped entirely.

c) It results in a compilation error.

d) The loop becomes an infinite loop.


What is the syntax to create a while loop in Java?

a) while { }

b) while () { }

c) while <> { }

d) while [] { }


Which part of the while loop is responsible for modifying the loop control variable?

a) Initialization

b) Condition

c) Iteration

d) Termination


What is the primary difference between a while loop and a do-while loop in Java?

a) The do-while loop executes its body at least once even if the condition is false initially.

b) The while loop always executes its body at least once.

c) There is no difference between while and do-while loops.

d) while loop executes its body only if the condition is true initially.


Which statement is used to exit a while loop prematurely in Java?

a) terminate

b) skip

c) exit

d) break


What happens if the loop body in a while loop lacks an instruction to modify the loop control variable?

a) It results in a runtime error.

b) The loop will run indefinitely.

c) The loop will only execute once.

d) It leads to a compilation error.


Which part of the while loop contains the condition that determines whether the loop body should execute?

a) Initialization

b) Condition

c) Iteration

d) Termination


How is the condition evaluated in a while loop?

a) Before each iteration

b) After each iteration

c) Only once at the start

d) It depends on the loop structure


What is the role of the condition in a while loop?

a) It defines when the loop should terminate.

b) It specifies the loop's body.

c) It initializes the loop control variable.

d) It updates the loop control variable.


Answers:


a) To execute a block of code repeatedly as long as a specified condition is true

b) The loop body is skipped entirely.

b) while () { }

c) Iteration

a) The do-while loop executes its body at least once even if the condition is false initially.

d) break

b) The loop will run indefinitely.

b) Condition

a) Before each iteration

a) It defines when the loop should terminate.



MCQs on while Loop in Java

What will be the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 3) {

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

            i++;

        }

    }

}

a) 0 1 2

b) 0 1 2 3

c) 1 2 3

d) 0 1 2 3 4


Answer: a) 0 1 2

Explanation: The loop prints i from 0 to 2, and then exits.


What will be the output of this code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 5;

        while (i > 0) {

            if (i == 3) {

                break;

            }

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

            i--;

        }

    }

}

a) 5 4 3

b) 5 4

c) 5 4 3 2 1

d) 5 4 3 2


Answer: b) 5 4

Explanation: The loop breaks when i equals 3, so 5 and 4 are printed.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 3) {

            i++;

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

        }

    }

}

a) 1 2 3

b) 0 1 2 3

c) 1 2 3 4

d) 0 1 2


Answer: a) 1 2 3

Explanation: The loop increments i before printing, so it starts from 1.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 5) {

            if (i % 2 == 0) {

                i++;

                continue;

            }

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

            i++;

        }

    }

}

a) 1 3

b) 0 1 2 3 4

c) 1 2 3 4

d) 1 2 4


Answer: a) 1 3

Explanation: The continue statement skips the even numbers, so only odd numbers are printed.


What is the result of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 3;

        while (i > 0) {

            i--;

            if (i == 1) {

                continue;

            }

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

        }

    }

}

a) 2 1

b) 2 0

c) 2

d) 1 0


Answer: c) 2

Explanation: The continue statement skips the 1 value.


What will be the output of this code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 3) {

            if (i == 1) {

                i++;

                continue;

            }

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

            i++;

        }

    }

}

a) 0 2

b) 0 1 2

c) 0 1 2 3

d) 1 2


Answer: a) 0 2

Explanation: The loop skips printing 1 due to the continue statement.


What will be the result of this code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        int j = 5;

        while (i < j) {

            i++;

            j--;

            System.out.print(i + " " + j + " ");

        }

    }

}

a) 1 4 2 3

b) 1 4 2 3 3 3

c) 1 4 2 3 3 2 2

d) 1 4 2 3 4 1


Answer: a) 1 4 2 3

Explanation: The values of i and j converge and are printed until i equals j.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 3) {

            i++;

            if (i == 2) {

                break;

            }

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

        }

    }

}

a) 1

b) 1 2

c) 1 2 3

d) 0 1


Answer: a) 1

Explanation: The loop breaks when i equals 2, so only 1 is printed.


What is the result of this code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 10) {

            i += 2;

            if (i == 6) {

                continue;

            }

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

        }

    }

}

a) 2 4 8 10

b) 2 4 8 10

c) 2 4 8

d) 2 4 8 10


Answer: d) 2 4 8 10

Explanation: The continue statement skips the 6, so the output includes all numbers except 6.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 5) {

            i++;

            if (i % 2 == 0) {

                continue;

            }

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

        }

    }

}

a) 1 3 5

b) 1 2 3 4

c) 0 2 4

d) 1 2 3


Answer: a) 1 3 5

Explanation: The continue statement skips even numbers, so only odd numbers are printed.


What is the result of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 1;

        while (i < 10) {

            if (i % 2 == 0) {

                i++;

                continue;

            }

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

            i++;

        }

    }

}

a) 1 3 5 7 9

b) 2 4 6 8

c) 1 2 3 4 5 6 7 8 9

d) 1 3 5 7 9 10


Answer: a) 1 3 5 7 9

Explanation: The loop prints odd numbers and skips even numbers due to the continue statement.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 5) {

            i++;

            if (i == 4) {

                break;

            }

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

        }

    }

}

a) 1 2 3

b) 1 2 3 4

c) 1 2 3 4 5

d) 1 2 3 4


Answer: a) 1 2 3

Explanation: The loop breaks when i equals 4, so the numbers 1 2 3 are printed.


What will the following code output?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 1;

        while (i < 4) {

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

            i++;

            if (i == 2) {

                continue;

            }

        }

        System.out.print(i);

    }

}

a) 1 2 3 4

b) 1 2 3

c) 1 2 3 3

d) 1 2 3 4


Answer: b) 1 2 3

Explanation: The continue statement skips printing 2, so the result is 1 2 3.


What will be the output of this code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 5) {

            i++;

            if (i == 3) {

                continue;

            }

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

        }

    }

}

a) 1 2 4 5

b) 1 2 3 4 5

c) 1 2 4

d) 0 1 2 4


Answer: a) 1 2 4 5

Explanation: The continue statement skips printing 3, so 1 2 4 5 are printed.


What is the result of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 5;

        while (i > 0) {

            i--;

            if (i % 2 != 0) {

                continue;

            }

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

        }

    }

}

a) 4 2 0

b) 4 2

c) 5 4 3 2 1

d) 5 4 3 2 1 0


Answer: a) 4 2 0

Explanation: The loop prints even numbers only due to the continue statement.




Difficult MCQs on while Loop in Java

What will be the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 1;

        while (i <= 5) {

            if (i % 2 == 0) {

                i++;

                continue;

            }

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

            i++;

        }

    }

}

a) 1 3 5

b) 2 4 6

c) 1 2 3 4 5

d) 1 3


Answer: a) 1 3 5

Explanation: The continue statement skips even numbers. Hence, only odd numbers are printed.


What will be the result of this code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 1;

        while (i < 10) {

            if (i % 2 == 0) {

                i += 3;

            } else {

                i++;

            }

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

        }

    }

}

a) 2 6 10

b) 2 5 8

c) 4 8 12

d) 2 5 9


Answer: b) 2 5 8

Explanation: When i is even, it is incremented by 3; otherwise, it is incremented by 1. This pattern results in 2 5 8.


What will the output be for the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 5) {

            if (i % 2 == 0) {

                i++;

                continue;

            }

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

            i += 2;

        }

    }

}

a) 1 3

b) 1 3 5

c) 0 2 4

d) 2 4


Answer: a) 1 3

Explanation: The continue statement skips even values, and only odd values 1 and 3 are printed.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i++ < 5) {

            if (i % 2 == 0) {

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

            }

        }

    }

}

a) 2 4 6

b) 1 3 5

c) 2 4

d) 1 2 3 4 5


Answer: c) 2 4

Explanation: The while loop increments i before checking the condition and printing only even numbers.


What is the output of this code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 10;

        while (i > 0) {

            if (i % 3 == 0) {

                i -= 2;

            } else {

                i -= 1;

            }

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

        }

    }

}

a) 8 6 4 2 0

b) 9 7 5 3 1

c) 8 6 4 2

d) 10 8 6 4 2 0


Answer: a) 8 6 4 2 0

Explanation: If i is divisible by 3, it decreases by 2; otherwise, it decreases by 1. This sequence results in 8 6 4 2 0.


What is the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 5;

        while (i > 0) {

            if (i % 2 == 1) {

                i--;

                continue;

            }

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

            i -= 2;

        }

    }

}

a) 4 2

b) 5 3 1

c) 4 2 0

d) 5 3


Answer: a) 4 2

Explanation: The continue statement skips odd numbers. Only even numbers 4 and 2 are printed.


What will be the output of this code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 1;

        while (i < 6) {

            if (i % 2 == 1) {

                i += 2;

                continue;

            }

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

            i++;

        }

    }

}

a) 2 4

b) 1 3 5

c) 2 4 6

d) 1 2 3 4


Answer: a) 2 4

Explanation: Odd numbers are skipped due to the continue statement, resulting in only even numbers being printed.


What is the result of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 5;

        while (i > 0) {

            i--;

            if (i == 2) {

                continue;

            }

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

        }

    }

}

a) 4 3 1 0

b) 4 3 1

c) 5 4 3 1 0

d) 4 3 1 2


Answer: b) 4 3 1

Explanation: The continue statement skips printing when i equals 2, so the output is 4 3 1.


What will be the output of this code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 5) {

            if (i % 2 == 0) {

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

            }

            i++;

        }

    }

}

a) 0 2 4

b) 1 3 5

c) 1 2 3 4

d) 2 4


Answer: a) 0 2 4

Explanation: The loop prints only even numbers from 0 to 4.


What is the output of the following code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 5;

        while (i > 0) {

            if (i % 3 == 0) {

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

            }

            i--;

        }

    }

}

a) 3 6

b) 3

c) 5 3

d) 0


Answer: b) 3

Explanation: The loop prints values divisible by 3 and i starts from 5.


What will be the output of this code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 1;

        while (i <= 10) {

            if (i % 2 == 0) {

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

            }

            i += 2;

        }

    }

}

a) 2 4 6 8 10

b) 1 3 5 7 9

c) 2 4 6 8

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


Answer: a) 2 4 6 8 10

Explanation: The loop increments i by 2 and prints only even numbers.


What will be the result of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 0;

        while (i < 10) {

            if (i % 3 == 0) {

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

            }

            i += 2;

        }

    }

}

a) 0 3 6 9

b) 0 2 4 6 8

c) 1 4 7

d) 3 6 9


Answer: a) 0 3 6 9

Explanation: The loop prints numbers divisible by 3 with an increment of 2.


What is the output of this code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 5;

        while (i > 0) {

            if (i == 3) {

                i--;

                continue;

            }

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

            i--;

        }

    }

}

a) 5 4 3 2 1

b) 5 4 2 1

c) 5 4 3 2

d) 5 4 3 1


Answer: b) 5 4 2 1

Explanation: When i equals 3, the continue statement skips printing 3, and the loop continues with 2 and 1.


What will be the output of the following code?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 1;

        while (i < 10) {

            if (i % 2 == 0) {

                i += 2;

                continue;

            }

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

            i++;

        }

    }

}

a) 1 3 5 7 9

b) 1 2 3 4 5 6 7 8 9

c) 1 4 7

d) 1 3 5 7


Answer: a) 1 3 5 7 9

Explanation: The loop increments i by 2 if i is even and prints odd numbers.


What is the result of the following code snippet?


java

Copy code

public class Main {

    public static void main(String[] args) {

        int i = 10;

        while (i >= 0) {

            if (i % 2 != 0) {

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

            }

            i--;

        }

    }

}

a) 10 8 6 4 2 0

b) 9 7 5 3 1

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

d) 10 8 6 4 2


Answer: b) 9 7 5 3 1

Explanation: The loop prints odd numbers from 10 to 0 by decrementing i each time.



git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...