Java 2022 Regular (NEP) Questions with Answers (Important)

Section - A

1. Answer any Six question.

a. State the different types of data types?

Primitive data types:

  • byte, short, int, long, float, double, boolean and char.

Reference data types:

  • String, Arrays, Classes and Interfaces.
 
b. Define method overloading?

Method overloading in Java refers to the ability to define multiple methods with the same name in the same class, but with different parameters.

 
c. Define super and sub class.
  • In Java, a superclass (also known as parent class or base class) is a class that is inherited by one or more subclasses.
  • subclass (also known as child class or derived class) is a class that inherits from a superclass
 
d. Define interface.

In Java, an interface is a collection of abstract methods and constant fields that define a contract for implementing classes. An interface defines a set of methods that a class must implement, but it does not provide any implementation for those methods.

e. State any two events.
  • KeyEvent
  • ActionEvent
f. What do you mean by flow layout?

In Java, FlowLayout is a layout manager that arranges components in a flow, or a left-to-right, top-to-bottom order. FlowLayout is the default layout manager for many containers, including JPanel and JFrame.

g. Define exception.

In Java, an exception is an event that occurs during the execution of a program and disrupts the normal flow of instructions. An exception is a mechanism for handling errors and other exceptional events in Java programs.

h. State the I/O java package.
  • InputStream and OutputStream
  • File
  • InputStreamReader and OutputStreamWrite
  • BufferedReader and BufferedWriter
  • Reader and Writer

Section - B

Answer any Three Questions.

a. Describe OOPs concepts.

OOP concepts in Java:

  • Classes and Objects: In Java, a class is a blueprint or template for creating objects. An object is an instance of a class that contains data (fields) and behavior (methods). Classes define the properties and behavior of objects, and objects are created from classes using the “new” keyword.
  • Encapsulation: Encapsulation is the process of hiding the internal details of an object from the outside world and providing a public interface for accessing and manipulating the object’s state. In Java, encapsulation is achieved through the use of access modifiers, such as public, private, and protected.
  • Inheritance: Inheritance is the process by which one class can inherit the properties and behavior of another class. In Java, inheritance is achieved using the “extends” keyword, where a subclass (the class that inherits) extends a superclass (the class being inherited from).
  • Polymorphism: Polymorphism is the ability of objects of different classes to be treated as if they are of the same type. In Java, polymorphism is achieved through method overriding and method overloading. Method overriding is when a subclass provides its own implementation of a method that is already defined in the superclass. Method overloading is when a class provides multiple methods with the same name but different parameter lists.
  • Abstraction: Abstraction is the process of creating a simplified view of an object or system by hiding its complex details. In Java, abstraction is achieved through the use of abstract classes and interfaces. An abstract class is a class that cannot be instantiated and is used as a base class for other classes. An interface is a collection of abstract methods that define a set of behaviors that a class must implement.
b. Define control structure? Explain two decision making statements..

In Java, a control structure is a programming construct that determines the flow of execution in a program.

Here are two common decision-making statements in Java:

If-else Statement: The if-else statement is use Switch Statement: The switch statement is used to execute a block of code based on the value of an expression. It is typically used when you have multiple possible values for a variable and want to perform a different action for each value.

Here is the syntax:

switch (expression)

{

   case value1:

      // block of code to be executed if expression matches value1

      break;

   case value2:

      // block of code to be executed if expression matches value2

      break;

   ...

   default:

      // block of code to be executed if none of the cases match

}

Example :

int day = 3;

switch (day)

 {

   case 1:

      System.out.println("Monday");

      break;

   case 2:

      System.out.println("Tuesday");

      break;

   case 3:

      System.out.println("Wednesday");

      break;

   ...

   default:

      System.out.println("Invalid day");

}
  • Switch Statement: The switch statement is used to execute a block of code based on the value of an expression. It is typically used when you have multiple possible values for a variable and want to perform a different action for each value.

Here is the syntax:

switch (expression)

{

   case value1:

      // block of code to be executed if expression matches value1

      break;

   case value2:

      // block of code to be executed if expression matches value2

      break;

   ...

   default:

      // block of code to be executed if none of the cases match

}

Example :

int day = 3;

switch (day)

 {

   case 1:

      System.out.println("Monday");

      break;

   case 2:

      System.out.println("Tuesday");

      break;

   case 3:

      System.out.println("Wednesday");

      break;

   ...

   default:

      System.out.println("Invalid day");

}
c. Discuss visibility modifiers?

There are four types of visibility modifiers in Java: public, private, protected, and default.

  1. Public: A public visibility modifier makes the class, method, field, or constructor accessible to any other class in the program, regardless of the package in which it is located. This means that any class can access a public member of another class by simply referencing it.
  2. Private: A private visibility modifier restricts the accessibility of the class, method, or field to only within the same class in which it is defined. This means that no other class in the program can access a private member of a class, even if it is within the same package.
  3. Protected: A protected visibility modifier makes the class, method, or field accessible within the same package and to any subclasses of the class, regardless of the package in which they are located. This means that any subclass of a protected member can access it, even if the subclass is located in a different package.
  4. Default: A default visibility modifier, also known as package-private, restricts the accessibility of the class, method, or field to only within the same package. This means that any class within the same package can access a default member, but no class outside of the package can access it.
d. Write a java program to find the factorial of given n.
import java.util.Scanner;

public class Sagar

{

    public static void main(String[] args)

    {

           Scanner input = new Scanner(System.in);

           System.out.print(“Enter a number: “);

           int n = input.nextInt();

           long fact = 1;

           for (int i = 1; i <= n; i++)

           {

              fact *= i;

           }

           System.out.println(“Factorial of ” + n + ” is: ” + fact);

    }

}

Answer any Three Questions.

a. Explain the types of inheritance.

Single Inheritance: In this type of inheritance, a subclass extends a single parent class.

class Animal

{

    public void eat()

   {

       System.out.println("The animal is eating");

    }

}

class Dog extends Animal
{
    public void bark()
     {
       System.out.println("The dog is barking");
   }
}

public class Main
{
     public static void main(String[] args)
     {
         Dog d = new Dog();

          d.eat(); // Inherited from Animal class

          d.bark(); // Defined in Dog class
   }
}

Multilevel Inheritance: In this type of inheritance, a subclass extends another subclass, which in turn extends a parent class.

class Animal

{

    public void eat()

    {

       System.out.println("The animal is eating");

   }

}

class Dog extends Animal
{
   public void bark()
   {
       System.out.println("The dog is barking");
    }
}

class Labrador extends Dog
{
    public void color()
   {
       System.out.println("The Labrador is black in color");
    }
}

public class Main
{
    public static void main(String[] args)
    {
       Labrador l = new Labrador();

        l.eat(); // Inherited from Animal class

        l.bark(); // Inherited from Dog class

        l.color(); // Defined in Labrador class
    }
}

Hierarchical Inheritance: In this type of inheritance, multiple subclasses extend a single parent class. For example:

class Shape
{
      public void draw()
      {
         System.out.println("Drawing shape");
      }
}

class Circle extends Shape
{
    public void draw()
    {
       System.out.println("Drawing circle");
   }
}

class Rectangle extends Shape
{
      public void draw()
      {
         System.out.println("Drawing rectangle");
      }
}

public class Main
{
     public static void main(String args[])
     {
          Circle c = new Circle();

          Rectangle r = new Rectangle();

          c.draw();

        r.draw();
      }
}
b. Write a program to demonstrate method overriding.
class Animal
{
    public void makeSound()
   {
       System.out.println("Animal is making a sound");
     }
}

class Dog extends Animal
{
   public void makeSound()
   {
       System.out.println("Dog is barking");
    }
}

public class Main
{
   public static void main(String args[])
    {
       Animal a = new Animal();

       a.makeSound();

        Dog d = new Dog();

        d.makeSound();
    }
}
c. Explain interfaces in java with example?
  • In Java, an interface is a collection of abstract methods and constant fields.
  • It is similar to a class, but it only defines the methods that must be implemented by its implementing classes, and does not provide any implementation of those methods.

Here’s an example to illustrate how interfaces work in Java:

// Defining an interface

interface Shape
{
    public void draw(); // abstract method
}

// Implementing the interface

class Circle implements Shape
{
   public void draw()
    {
        System.out.println("Drawing a Circle");
   }
}

class Rectangle implements Shape
{
   public void draw()
    {
        System.out.println("Drawing a Rectangle");
   }
}

public class Main
{
    public static void main(String[] args)
   {
        Shape s1 = new Circle();

        s1.draw();

         Shape s2 = new Rectangle();

        s2.draw();
   }
}
d. Write a steps to define and import the user defined packages.

1.Define the package: To define a package, create a new directory with the same name as the package name, and place the source files in that directory. For example, if you want to create a package called mypackage, you would create a directory called mypackage and place the source files in that directory.

2.Specify the package name: In each source file that belongs to the package, add the package statement at the beginning of the file. For example, if you want to place a class called MyClass in the mypackage package, you would add the following statement at the beginning of the source file:

                                package mypackage;

3.Compile the source files: Compile all the source files that belong to the package using the javac command. Make sure to specify the correct classpath that includes the directory containing the package.

                          javac -d . MyPackage/MyClass.java

The -d option specifies the destination directory where the compiled class files should be stored. In this example, we specify the current directory with the . symbol.

4.Create a JAR file: Once the source files have been compiled, create a JAR file containing the class files using the jar command.

                      jar cf MyPackage.jar MyPackage/*.class

This command creates a JAR file called MyPackage.jar that contains all the compiled class files in the MyPackage directory.

5.Import the package: In any Java program that needs to use the package, import the package using the import statement.

                         import mypackage.MyClass;

This statement imports the MyClass class from the mypackage package.

6.Use the package: Once the package has been imported, you can use the classes and other members of the package in your Java program.

MyClass obj = new MyClass();

obj.doSomething();

This code creates a new instance of the MyClass class and calls the doSomething() method on the instance.

Answer any Three Questions.

a. Discuss Event handling in java with example

Event handling in Java refers to the mechanism that allows Java programs to respond to user actions such as mouse clicks, keyboard input, and button presses. Event handling in Java is based on the Observer pattern, where event sources (such as buttons) generate events that are sent to event listeners (such as event handlers) that have registered interest in those events.

Example :

import java.awt.*;

import java.awt.event.*;

public class ButtonClickDemo extends Frame implements ActionListener

 {

    private Button button;

    public ButtonClickDemo()

    {

        // Set up the frame

        setTitle("Button Click Demo");

        setSize(300, 200);

        setLayout(new FlowLayout());

        // Create a button and add it to the frame

        button = new Button("Click me!");

        add(button);

        // Register the event listener for the button

        button.addActionListener(this);

    }

    public void actionPerformed(ActionEvent event)

  {

        // This method is called when the button is clicked

        System.out.println("Button clicked!");

   }

    public static void main(String[] args)

   {

        // Create an instance of the frame and show it

        ButtonClickDemo frame = new ButtonClickDemo();

        frame.setVisible(true);

    }

}

In this example, we create a new Frame and add a Button to it. We then register an event listener (this) with the button using the addActionListener method. When the button is clicked, the actionPerformed method of the event listener is called, and we print a message to the console.

b. Explain any two Mouse and key events?

In Java, there are several mouse and key events available that can be used to handle user input in graphical user interfaces. Here are two examples:

MouseEvent:

MouseEvent is an event that is generated when the mouse is moved or clicked. It provides information about the location of the mouse cursor, the type of button pressed, and the number of clicks.

Some of the commonly used MouseEvent methods are:

getX() and getY(): returns the x and y coordinates of the mouse cursor relative to the source component.

getButton(): returns the button that was pressed or released.

getClickCount(): returns the number of clicks associated with the event.

Example :

myComponent.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
       int x = e.getX();

        int y = e.getY();

        int button = e.getButton();

        int clicks = e.getClickCount();

        // Do something with the event information
}

});

KeyEvent:

KeyEvent is an event that is generated when a key is pressed or released. It provides information about the key that was pressed, such as the key code and whether modifier keys like Shift or Ctrl were pressed at the same time.

Some of the commonly used KeyEvent methods are:

getKeyCode(): returns the keycode associated with the key that was pressed.

isShiftDown(), isControlDown(), etc.: returns whether the Shift, Ctrl, or other modifier keys were pressed.

Example :

myComponent.addKeyListener(new KeyAdapter()
{
   public void keyPressed(KeyEvent e)
   {
          int keyCode = e.getKeyCode();

           boolean shiftPressed = e.isShiftDown();

          boolean ctrlPressed = e.isControlDown();

          // Do something with the event information
   }
});
c. explain textfield with examples.
  • In Java, a TextField is a graphical component that allows the user to input a single line of text.
  • It is a subclass of the Component class and is part of the java.awt package

importing AWT class  

import java.awt.*; 

public class TextFieldExample1
{
    // main method 

    public static void main(String args[])
{  

    // creating a frame 

    Frame f = new Frame("TextField Example");   

    // creating objects of textfield 

    TextField t1, t2;   

    // instantiating the textfield objects 

    // setting the location of those objects in the frame 

    t1 = new TextField("Welcome to Javatpoint.");   

    t1.setBounds(50, 100, 200, 30);   

    t2 = new TextField("AWT Tutorial");   

    t2.setBounds(50, 150, 200, 30);   

    // adding the components to frame 

    f.add(t1); 

    f.add(t2);  

    // setting size, layout and visibility of frame   Output :

    f.setSize(400,400);   

    f.setLayout(null);   

    f.setVisible(true);   
}  
}

Output:

d. Write a program which creates and display a message on the window.
import java.awt.*;
import java.applet.*;
public class Window extends Applet
{
           public void paint(Graphics g)
           {
              g.drawString(" Hello World ",80,40);
           }
}


Window.html
<html>
<head>
           <body>
                       <applet code=Window.class height=400 width=400></applet>
           </body>
</head>
</html>

Output:

Answer any Three Questions.

a. Discuss Event handling in java with example

The life cycle of a thread in Java can be divided into five states: new, runnable, blocked, waiting, and terminated.

  1. New: When a thread is created, it is in the new state. At this stage, the thread has been initialized but has not started running yet.
  1. Runnable: When the start() method is called on the thread, it enters the runnable state. In this state, the thread is eligible to run, but it may or may not be currently executing, as the scheduling of threads is handled by the operating system.
  1. Blocked: If a thread is unable to acquire a lock on a shared resource, it enters the blocked state. In this state, the thread is still alive but is not eligible to run until the lock is released by another thread.
  1. Waiting: If a thread is waiting for some specific action to occur, it enters the waiting state. In this state, the thread does not consume CPU time and waits for a signal or notification from another thread to resume execution.
  1. Terminated: A thread enters the terminated state when it completes its execution or when an unhandled exception occurs. Once a thread is terminated, it cannot be restarted or resumed.
b. Write a program to demonstrate exception handling with try, catch and finally.
import java.util.Scanner;
public class Sagar
{
   public static void main(String[] args)
   {

           try
           {
                       int a=0;
                       int div;
                       div=100/a;
           }

           catch (ArithmeticException e)
           {
                      System.out.println(e);
           }

            finally
           {
                       System.out.println("End of program.");
           }
    }
}
c. Briefly describe Byte stream with example.

In Java, Byte streams are used for reading and writing bytes of data.

  • The Byte streams are implemented by the InputStream and OutputStream classes and are used for reading and writing binary data.
import java.io.*;
public class Sagar
{
   public static void main(String[] args)
   {
           try
           {
                   FileOutputStream output = new FileOutputStream("output.txt");
                   output.write("Hello, world!".getBytes());
                   output.close();
          }

            catch (IOException e)
           {
                  e.printStackTrace();
          }
   }
}
 
d. Explain Runnable Interface with example.

In Java, the Runnable interface is used to create threads. It is a functional interface that has a single method called “run()” which represents the code that will be executed by the thread. The Runnable interface is often used as an alternative to extending the Thread class, as it allows for greater flexibility and code reusability.

Here’s an example of using the Runnable interface to create a new thread:

public class RunnableExample implements Runnable
{
   public void run()
    {

          // This code will be executed when the thread starts

          System.out.println("Thread is running");

   }
    public static void main(String[] args)
   {
         // Create a new instance of the RunnableExample class

          RunnableExample runnable = new RunnableExample();


         // Create a new thread with the runnable object

          Thread thread = new Thread(runnable);


          // Start the thread

          thread.start();
   }
}
 
  • In this example, we create a new class called Runnable Example that implements the Runnable interface. We then override the run() method to specify the code that will be executed by the thread.
  • In the main method, we create a new instance of the RunnableExample class and a new thread with the runnable object. We then start the thread using the start() method of the Thread class.
  • When the thread starts, the run() method of the RunnableExample class is executed, which prints “Thread is running” to the console.
  • Overall, the Runnable interface is a powerful tool for creating and managing threads in Java. It provides a simple and flexible way to define the code that will be executed by a thread, which can greatly improve the efficiency and scalability of multi-threaded applications.
 

    Leave a Reply

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

    error: Content is protected !!