|

Java Important Questions and Answers Class 12 IT (802)

🚀 Want to score full marks in your CBSE Class 12 IT (802) Board Exam? Don’t miss these Java Important Questions and Answers!

Unit 3 – Java Programming is one of the most scoring and important units of Class 12 Information Technology (802), carrying 20 marks (40% of the theory paper) as per the prescribed examination weightage. Preparing this unit thoroughly can make a significant difference to your overall board exam score.

This complete collection of Java Important Questions and Answers for Class 12 IT is based on an in-depth analysis of previous board exam papers, question patterns, frequently asked questions and their trends.

What’s more, the Java programs included in this question set will help you strengthen your programming skills for both the theory examination and practical examination.

Don’t leave any important question behind! Practise the complete set of Class 12 IT Java questions, revise the concepts thoroughly and walk into your board exam with confidence!💯

SECTION-A: Subject Short Answer Questions (1-2 Marks)

Q1. What is the role of the Java Virtual Machine (JVM)?

Answer:  The Java Virtual Machine (JVM) translates Java Bytecode into machine code and executes it. It allows Java programs to run on different platforms that have a JVM.

Q2. Why is a Java IDE useful for a programmer? Name any two IDEs.

Answer:  An IDE provides tools such as a text editor and compiler in one environment, simplifying the writing, compiling and execution of Java programs. Two IDEs are NetBeans and Eclipse.

Q3. Explain the purpose of comments in Java and describe their types.

Answer:  Comments are explanatory notes written in a Java program. They improve the readability of code and are ignored by the compiler.

The two types are:

  1. Single-line comment: Begins with //.
  2. Multiline comment: Written between /* and */.

Q4. Why is the main() method important in a Java application?

Answer:  The main() method is a special method that every Java application must have. When a program runs, the statements in the main() method are the first to be executed.

Q5. What is the use of the break statement and the default case in a switch statement?

Answer:  break terminates the switch and moves control to the statement after it. default is executed when the expression matches none of the case constants.

Q6. Define variable in Java?

Answer:  A variable is a named storage location in the computer’s memory whose value can change during program execution.

Example:

int total_marks = 400;
double marks_obtained = 346;

Q7. What are the primitive data types supported by Java?

Answer: The eight primitive data types are byte, short, int, long, float, double, char and boolean.

Q8. What is the use of the modulus (%) operator?

Answer:  The modulus (%) operator returns the remainder of a division operation.

Example:
System.out.println(11%4);
Output:
3

Q9. What is an array? State one advantage of using an array instead of separate variables.

Answer:  An array is a data structure used to store multiple values of the same data type under a single variable name. It allows related values to be stored and accessed using indices instead of declaring separate variables.

Example:
int marks[] = {85, 90, 78, 92, 88};

Q10. What is the purpose of access modifiers in Java?

Answer:  Access modifiers are keywords in Java that control the visibility and accessibility of classes, methods, constructors and variables. They determine where these members can be accessed, helping to provide data security and maintain proper access control in a program.

Q11. What is exception handling in Java?

Answer:  Exception handling is a mechanism used to handle unexpected errors during program execution so that a program can deal with the errors and continue executing or terminate gracefully.

Q12. Explain the difference between the while and do-while loops.

Answer:

while Loopdo-while Loop
Checks the condition before executing the loop body.Checks the condition after executing the loop body.
May execute zero times.Executes at least once.
Entry-controlled loop.Exit-controlled loop.

Q13. Differentiate between a class and an object in Java.

Answer:  A class is a logical entity that defines data members and method members. An object is an instance of a class that contains specific values for its data members and can invoke its methods.

Q14. What is the purpose of the finally block in Java?

Answer:  The finally block in Java is used to execute important code, such as closing files or releasing resources. It is executed whether an exception occurs or not (except in unusual cases such as JVM termination).

Q15. What is a thread in Java?

Answer: A thread is a small independent part of a program that can execute a specific task concurrently with other threads. Multithreading allows multiple tasks to execute simultaneously, resulting in better utilization of computer resources.

Q16. Name the two ways of creating threads in Java.

Answer: Threads can be created in Java in two ways:

  1. By extending the Thread class.
  2. By implementing the Runnable interface.

Q17. What is a wrapper class in Java? Give an example.

Answer: A wrapper class in Java converts a primitive data type into an object of its corresponding class. For example, the Integer class is a wrapper class for the primitive int data type.

SECTION-B: Subjective Long Answer Questions (3-5 Marks)

Q1. What are Getter and Setter methods in Java? Explain their purpose with a suitable example.

Answer:

  • Getter Method: A getter method is used to retrieve or return the value of a private data member of a class.
  • Setter Method: A setter method is used to modify or update the value of a private data member. It can also apply conditions to control how the value is changed.

Example:

class Student {
    private int age;
    // Setter method
    void setAge(int a) {
        age = a;
    }
    // Getter method
    int getAge() {
        return age;
    }
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setAge(18);
        System.out.println(s1.getAge());
    }
}

Q2. What is the purpose of access modifiers in Java? Name the different types of access modifiers.

Answer:  Access modifiers are keywords in Java that control the visibility and accessibility of classes, methods, constructors and variables. They determine where these members can be accessed and help maintain proper access control in a program.

Types of Access Modifiers in Java:

  1. public: Members can be accessed from anywhere.
  2. private: Members can be accessed only within the same class.
  3. protected: Members can be accessed within the same package and by subclasses.

Q3. Explain the if-else statement in Java with syntax and an example.

Answer: The if-else statement executes one block of code when a condition is true and another block when the condition is false.

Syntax:

if (condition) {
    statements;
}
else {
    statements;
}

Example:

int number = 10;
if (number > 0) {
    System.out.println(“Positive”);
}
else {
    System.out.println(“Not Positive”);
}

Q4. What is a nested if statement? Explain with example.

Answer: A nested if statement is an if statement placed inside another if or else block. It allows a program to evaluate additional conditions.

Example:

if (percentage >= 40) {
    if (percentage >= 60) {
        System.out.println(“First Division”);
    }
    else {
        System.out.println(“Pass”);
    }
}
else {
    System.out.println(“Fail”);
}

Q5. Explain the working of the while loop with syntax and a suitable example.

Answer:

The while loop evaluates its condition before executing the loop body. If the condition is true, the loop body executes. The condition is evaluated again after each iteration.

Syntax:

while (condition) {
    statements;
}

Example:

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

Q6. Explain the for loop in Java.

Answer: The for loop is a repetition statement that includes initialization, condition and update expressions in its structure.

Example:

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Q7. Explain the concept of an array in Java. How are array elements accessed? Illustrate with a suitable example.

Answer: An array is a data structure used to store multiple values of the same data type under a single variable name. Each element can be accessed using its index, which begins at 0.

Example:

int[] marks = {80, 90, 75};
System.out.println(marks[0]);
System.out.println(marks[2]);

The first statement displays 80 and the second displays 75.

Q8. Explain user defined methods with an example.

Answer:  A user defined method is a named block of statements written by the programmer to perform a specific task. It can be called whenever that task is needed, which avoids repeating code.

Example:

static double rectangle_area(double length, double breadth) {
    double area = length * breadth;
    return area;
}

Method call:
double a = rectangle_area(45.5, 78.5);

Q9. Differentiate between data members and method members with suitable examples.

Answer: Data members are variables that store the attributes or characteristics of an object, whereas method members are functions that define the behaviour or actions performed by an object.

Example: In a Student class, name and rollNo are data members, whereas display() is a method member that displays the student’s details.

Q10. What is a constructor? Write two of its features.

Answer:  A constructor is a special member of a class that is used to initialize the data members of an object when it is created.

Features of a Constructor:

  1. It has the same name as the class and does not have any return type, not even void.
  2. It is automatically invoked when an object of the class is created.

Example:

class Student {
    int age;
    Student() {
        age = 15;
    }
    public static void main(String[] args) {
        Student s1 = new Student();
        System.out.println(s1.age);
    }
}

Q11. Explain how exception is handlled in Java using try, catch and finally.

Answer: Exception handling allows a program to deal with unexpected errors during execution.

  • try: Encloses the code where an exception may occur.
  • catch: Handles the exception thrown by the try block.
  • finally: Executes when the try block exits, whether an exception occurs or not.

Example:

class ExceptionDemo { public static void main(String[] args) { try { int quotient = 10 / 0; System.out.println(“Quotient = ” + quotient); } catch (Exception e) { System.out.println(“Exception occurred: ” + e.getMessage()); } finally { System.out.println(“Execution completed.”); } } }

Q12. Explain how user input is taken in Java using the Scanner class.

Answer:  The Scanner class, in the java.util package, is used to read input from the keyboard during program execution.

Example:

import java.util.Scanner;
class InputDemo {
    public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);
        System.out.print(“Enter your age: “);
        int age = Integer.parseInt(user_input.next());
        System.out.println(“Age = ” + age);
    }
}

Here, next() returns the value as a String, so it is converted to a number using the wrapper class method Integer.parseInt().

Q13. Explain the two ways of writing an assertion statement in Java with suitable examples.

Answer: Java provides two ways to write assertion statements:

  1. Without an error message: It checks whether the given condition is true. If the condition is false, an AssertionError is thrown.
    Example: assert age >= 18;
  2. With an error message: It checks the given condition and displays the specified error message if the condition is false.
    Example: assert age >= 18 : “Age not Valid”;

SECTION-C: Find the Output based Questions (2-3 Marks)

Q1. What will be the output of the following code?

int a = 20;
int b = 30;
System.out.println(b / a);

Answer:  1

Q2. What will be the output of the following code?

int a = 14;
int b = 4;
System.out.println(a % b);

Answer:  2

Q3. What will be the output of the following code?

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

Answer:  21

Q4. What will be the output of the following code?

int a = 20;
int b = 30;
a += b;
System.out.println(a);

Answer:  50

Q5. What will be the output of the following code?

int a = 20;
int b = 30;
a *= b;
System.out.println(a);

Answer:  600

Q6. What will be the output of the following code?

int number = 5;
if (number > 0) {
    System.out.println(“Positive”);
}
else {
    System.out.println(“Negative”);
}

Answer:  Positive

Q7. What will be the output of the following code?

int i = 3;
do {
    System.out.println(i);
    i–;
} while (i > 0);

Answer:

3
2
1

Q8. What will be the output of the following code?

String myString = “Hello World”;
System.out.println(myString.length());

Answer:  11

Q9. What will be the output of the following code?

String myString = “Hello World”;
System.out.println(myString.toUpperCase());

Answer:  HELLO WORLD

SECTION-D: Case-Based Questions (4-5 Marks)

Case Study:
A student is developing a Java program to process and manipulate text. For this purpose, the student has declared the following string variables:

String str1 = “Computer”;
String str2 = “Science and Technology”;

Write the Java code statements for the following:

(a)    To display the length of the string str1.
(b)    To display the character at index 5 in the string str2.
(c)    To display the index of the first occurrence of the letter ‘e’ in the string str1.
(d)    To display the string str2 after converting it into lowercase.

Answer:

PartJava Statement
(a)System.out.println(str1.length());
(b)System.out.println(str2.charAt(5));
(c)System.out.println(str1.indexOf(‘e’));
(d)System.out.println(str2.toLowerCase());

SECTION-E: Java Programming Questions (2-3 Marks)

Q1. Write a Java program to input the length and breadth of a rectangle and calculate its area.

Answer:

import java.util.Scanner;
class Rectangle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print(“Enter length: “);
        double length = sc.nextDouble();
        System.out.print(“Enter breadth: “);
        double breadth = sc.nextDouble();
        double area = length * breadth;
        System.out.println(“Area of Rectangle = ” + area);
    }
}

import java.util.Scanner;
class Rectangle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter length: ");
        double length = sc.nextDouble();
        System.out.print("Enter breadth: ");
        double breadth = sc.nextDouble();
        double area = length * breadth;
        System.out.println("Area of Rectangle = " + area);
    }
}

Q2. Write a Java program to convert temperature from Celsius to Fahrenheit.

Answer:

import java.util.Scanner;
class Temperature {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print(“Enter temperature in Celsius: “);
        double celsius = sc.nextDouble();
        double fahrenheit = (celsius * 9 / 5) + 32;
        System.out.println(“Temperature in Fahrenheit = ” + fahrenheit);
    }
}

Q3. Write a Java program to input a number and check whether it is even or odd.

Answer:

import java.util.Scanner;
class EvenOdd {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print(“Enter a number: “);
        int n = sc.nextInt();
        if (n % 2 == 0)
            System.out.println(“Even Number”);
        else
            System.out.println(“Odd Number”);
    }
}

Q4. Write a Java program to input three numbers and display the greatest among them using if-else statements.

Answer:

import java.util.Scanner;
class Greatest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print(“Enter three numbers: “);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        if (a >= b && a >= c)
            System.out.println(“Greatest = ” + a);
        else if (b >= a && b >= c)
            System.out.println(“Greatest = ” + b);
        else
            System.out.println(“Greatest = ” + c);
    }
}

Q5. Write a Java program to calculate the factorial of a number entered by the user using a for loop.

Answer:

import java.util.Scanner;
class Factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print(“Enter a number: “);
        int n = sc.nextInt();
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact = fact * i;
        }
        System.out.println(“Factorial = ” + fact);
    }
}

Q6. Write a Java program to input a year and check whether it is a leap year or not using if-else statements.

Answer:

import java.util.Scanner;
class LeapYear {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print(“Enter a year: “);
        int year = sc.nextInt();
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
            System.out.println(“Leap Year”);
        else
            System.out.println(“Not a Leap Year”);
    }
}

Q7. Write a Java program to display all even numbers from 1 to 50 using a for loop.

Answer:

class EvenNumbers {
    public static void main(String[] args) {
        for (int i = 1; i <= 50; i++) {
            if (i % 2 == 0) {
                System.out.println(i);
            }
        }
    }
}

Q8. Write a Java program to input a number and check whether it is a prime number or not using a for loop.

Answer:

import java.util.Scanner;
class PrimeNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print(“Enter a number: “);
        int n = sc.nextInt();
        int count = 0;
        for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
                count++;
            }
        }
        if (count == 2)
            System.out.println(“Prime Number”);
        else
            System.out.println(“Not a Prime Number”);
    }
}

Q9. Write a program in Java to accept and display 5 numbers using an array.

import java.util.Scanner;
class ArrayNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] numbers = new int[5];
        System.out.println(“Enter 5 numbers:”);
        for (int i = 0; i < 5; i++) {
            numbers[i] = sc.nextInt();
        }
        System.out.println(“The numbers are:”);
        for (int i = 0; i < 5; i++) {
            System.out.println(numbers[i]);
        }
        sc.close();
    }
}

Q10. Write a program in Java to print the square of every alternate number of an array.

class AlternateSquare {
    public static void main(String[] args) {
        int[] numbers = {2, 4, 6, 8, 10, 12};
        System.out.println(“Squares of alternate numbers:”);
        for (int i = 0; i < numbers.length; i += 2) {
            System.out.println(numbers[i] * numbers[i]);
        }
    }
}

Q11. Write a program in Java to create a class Triangle with the data members base, height, area and color. The members base, height and area are of type double and color is of type String. Write getter and setter methods for base, height and color, and write a method to compute_area(). Create two objects of class Triangle, compute their area, and compare their area and color. If area and color both are same for the objects, display “Matching Triangles” otherwise display “Non matching Triangles”.

class Triangle {
    private double base, height, area;
    private String color;
    public void setBase(double base) {
        this.base = base;
    }
    public double getBase() {
        return base;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    public double getHeight() {
        return height;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getColor() {
        return color;
    }
    public void compute_area() {
        area = 0.5 * base * height;
    }
    public double getArea() {
        return area;
    }
}
class TriangleTest {
    public static void main(String[] args) {
        Triangle t1 = new Triangle();
        Triangle t2 = new Triangle();
        t1.setBase(10);
        t1.setHeight(5);
        t1.setColor(“Red”);
        t2.setBase(10);
        t2.setHeight(5);
        t2.setColor(“Red”);
        t1.compute_area();
        t2.compute_area();
        if (t1.getArea() == t2.getArea() &&
            t1.getColor().equals(t2.getColor())) {
            System.out.println(“Matching Triangles”);
        }
        else {
            System.out.println(“Non matching Triangles”);
        }
    }
}

Q12. Write a program in Java to enable the user to handle divide-by-zero exception.

import java.util.Scanner;
class DivideException {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print(“Enter numerator: “);
        int num = sc.nextInt();
        System.out.print(“Enter denominator: “);
        int den = sc.nextInt();
        try {
            int result = num / den;
            System.out.println(“Result = ” + result);
        }
        catch (ArithmeticException e) {
            System.out.println(“Error: Division by zero is not allowed.”);
        }
        finally {
            System.out.println(“Program execution completed.”);
        }
        sc.close();
    }
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *