0% found this document useful (0 votes)
215 views

Java Question Paper-2

Uploaded by

fakescout007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
215 views

Java Question Paper-2

Uploaded by

fakescout007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Java Question Paper-2

1 Marks Question

a) What is the use of Javac?


Answer:

The javac command is used in Java to compile Java source code files (files
with a .java extension) into bytecode files (files with a .class extension)
that can be executed by the Java Virtual Machine (JVM).

b) Give the name of any two wrapper classes.


Answer:

Two wrapper classes in Java are:

1. Integer : Wraps the primitive data type int .

2. Boolean : Wraps the primitive data type boolean .

c) What is the use of 'implements' keyword?


Answer:

The implements keyword in Java is used to indicate that a class implements


one or more interfaces. When a class implements an interface, it is required
to provide concrete implementations for all the methods declared in that
interface.

d) List types of constructor.


Answer:

Types of constructors in Java:

1. Default Constructor: Constructor with no parameters.

2. Parameterized Constructor: Constructor with parameters.

3. Copy Constructor: Constructor that creates a new object by copying


the values from an existing object.

e) What is the use of Array?

Java Question Paper-2 1


Answer:

An array in Java is used to store multiple values of the same data type under
a single variable name. It provides a convenient way to work with collections
of data elements.

f) Give the name of any two listeners.


Answer:

Two types of listeners in Java are:

1. ActionListener : Listens for actions, such as button clicks.

2. MouseListener : Listens for mouse events, such as clicks and movements.

g) What is an exception?
Answer:

An exception in Java is an event that occurs during the execution of a


program and disrupts the normal flow of the program. It is an object that
represents an error or an abnormal condition.

h) Give the syntax of the endsWith() method?


Answer:

Syntax of endsWith() method:

javaCopy code
boolean endsWith(String suffix)

i) What is a package?
Answer:

A package in Java is a mechanism for organizing related classes and


interfaces into a single namespace. It helps in avoiding naming conflicts and
provides a way to encapsulate and group related code.

j) What is the use of the new operator?


Answer:

Java Question Paper-2 2


The new operator in Java is used to create an instance of a class or to
allocate memory for an object. It is used to instantiate classes and create
objects dynamically during runtime.

2 Marks Question

a) 'When constructor of class will be called?' Comment.


Answer:

The constructor of a class in Java is called when an object of that class is


created. It is a special method with the same name as the class and is used
to initialize the object's state. Constructors are automatically invoked when
the new keyword is used to create an instance of a class.

b) What is command line argument? Where are they stored in a


program.
Answer:

Command Line Argument:

Command line arguments in Java are values provided to a Java program


when it is executed from the command line. These values are passed as
strings separated by spaces after the program's name.

Storage in a Program:

Command line arguments are stored in the args parameter of the main

method. The main method signature looks like this:

public static void main(String[] args)

The command line arguments can be accessed within the program using
the args array.

c) What is Frame? Give its any two methods.


Answer:

Frame in Java:

A Frame in Java is a top-level window with a title and a border. It is an


instance of the java.awt.Frame class and is used to create GUI
applications.

Java Question Paper-2 3


Two Methods of Frame:

1. setTitle(String title) : Sets the title of the frame.

2. setVisible(boolean visible) : Sets the visibility of the frame. If set to true ,


the frame becomes visible; otherwise, it is hidden.

d) Differentiate between method overloading and method


overriding.
Answer:

Method Overloading:

Method overloading in Java occurs when multiple methods in the same


class have the same name but different parameters (either different
types or a different number of parameters).

Method Overriding:

Method overriding occurs in a subclass when it provides a specific


implementation for a method that is already present in its superclass.
The method signature, including the name and parameters, must be the
same.

e) Write any two access specifiers.


Answer:

Two access specifiers in Java are:

1. public : Accessible from any class or package.

2. private : Accessible only within the same class.

4 Marks Question

a) Define an interface shape with an abstract method area( ) .


Inherit the interface shape into the class triangle . Write a
Java Program to calculate the area of Triangle.
Answer:

// Define the interface 'shape'


interface Shape {
// Abstract method 'area'

Java Question Paper-2 4


double area();
}

// Inherit the interface into the class 'Triangle'


class Triangle implements Shape {
// Triangle properties
double base, height;

// Constructor
Triangle(double base, double height) {
this.base = base;
this.height = height;
}

// Implement the abstract method 'area' for Triangle


public double area() {
return 0.5 * base * height;
}
}

// Java Program to calculate the area of Triangle


public class Main {
public static void main(String[] args) {
// Create an object of Triangle
Triangle triangle = new Triangle(5.0, 8.0);

// Calculate and display the area of Triangle


System.out.println("Area of Triangle: " + triangle
}
}

b) Write a Java Program to copy the contents from one file into
another file. While copying, change the case of all the alphabets
& replace all the digits by '*'.
Answer:

Java Question Paper-2 5


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileCopy {


public static void main(String[] args) {
try {
// Create FileReader and FileWriter objects
FileReader reader = new FileReader("source.txt
FileWriter writer = new FileWriter("destinatio

// Read character by character from the source


int character;
while ((character = reader.read()) != -1) {
char ch = (char) character;

// Change the case of alphabets


if (Character.isAlphabetic(ch)) {
if (Character.isUpperCase(ch)) {
ch = Character.toLowerCase(ch);
} else {
ch = Character.toUpperCase(ch);
}
}

// Replace digits with '*'


if (Character.isDigit(ch)) {
ch = '*';
}

// Write the modified character to the des


writer.write(ch);
}

// Close the FileReader and FileWriter


reader.close();
writer.close();

Java Question Paper-2 6


System.out.println("File copied successfully!"
} catch (IOException e) {
System.out.println("An error occurred while co
e.printStackTrace();
}
}
}

4 Marks Question

a) Differentiate between AWT & Swing.


Answer:

AWT (Abstract Window Toolkit):

AWT is the original set of GUI components in Java.

AWT components are heavyweight, meaning they are dependent on the


native platform's resources.

It is platform-dependent and may have different looks on different


operating systems.

AWT provides fewer components compared to Swing.

Swing:

Swing is a part of the Java Foundation Classes (JFC) and is an


extension of AWT.

Swing components are lightweight and are not dependent on the native
platform's resources.

It provides a consistent look and feel across different operating systems.

Swing provides a rich set of components and supports additional


features like double buffering and pluggable look and feel.

b) Define a user-defined exception ZeroNumberExc . Write a Java


program to accept a number from the user. If it is zero, then
throw the user-defined exception "Number is zero"; otherwise,
calculate the sum of the first and last digits of the given number
(use Static Keyword).

Java Question Paper-2 7


Answer:

// User-defined exception class


class ZeroNumberExc extends Exception {
public ZeroNumberExc(String message) {
super(message);
}
}

// Java program
public class NumberProgram {
// Static method to calculate the sum of the first and
static int sumOfDigits(int num) {
int lastDigit = num % 10;
int firstDigit = 0;

while (num != 0) {
firstDigit = num % 10;
num /= 10;
}

return firstDigit + lastDigit;


}

public static void main(String[] args) {


try {
// Accept a number from the user
int userInput = 0; // replace 0 with user inpu

// Check if the number is zero and throw an exc


if (userInput == 0) {
throw new ZeroNumberExc("Number is zero");
}

// Calculate and display the sum of the first a


int result = sumOfDigits(userInput);
System.out.println("Sum of first and last digi
} catch (ZeroNumberExc e) {

Java Question Paper-2 8


System.out.println(e.getMessage());
}
}
}

c) Write a Java program to accept n numbers from the user and


store only perfect numbers into an array and display that array.
Answer:

import java.util.Scanner;

public class PerfectNumbers {


// Function to check if a number is perfect
static boolean isPerfect(int num) {
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Accept the value of n from the user


System.out.print("Enter the value of n: ");
int n = scanner.nextInt();

// Initialize an array to store perfect numbers


int[] perfectNumbers = new int[n];
int count = 0;

// Accept n numbers from the user and store perfec


for (int i = 0; i < n; i++) {
System.out.print("Enter number " + (i + 1) + "

Java Question Paper-2 9


int num = scanner.nextInt();

// Check if the number is perfect and store it


if (isPerfect(num)) {
perfectNumbers[count++] = num;
}
}

// Display the array of perfect numbers


System.out.println("Perfect Numbers:");
for (int i = 0; i < count; i++) {
System.out.print(perfectNumbers[i] + " ");
}

scanner.close();
}
}

3 Marks Question

a) Explain uses of the final keyword with an example.


Answer:

The final keyword in Java is used to apply restrictions on classes, methods,


and variables.

When applied to a class, it indicates that the class cannot be inherited (i.e., it
is a final class).

When applied to a method, it indicates that the method cannot be overridden


in derived classes.

When applied to a variable, it indicates that the variable's value cannot be


changed once assigned (i.e., it becomes a constant).

Example:

final class FinalClass {


// Class members and methods
}

Java Question Paper-2 10


// The following line would result in a compilation error
// as it is not allowed to inherit from a final class.
// class DerivedClass extends FinalClass {}

class Example {
final int constantValue = 10;

final void display() {


System.out.println("This is a final method.");
}

// The following line would result in a compilation er


// as it is not allowed to override a final method.
// void display() {}
}

b) Define a class Emp with a member Eid and display()


method. Inherit Emp class into the EmpName class. The EmpName
class has a member Ename and a display() method. Write a
Java program to accept details of an employee [Eid, Ename] and
display it. (Use the super keyword).
Answer:

import java.util.Scanner;

// Base class Emp


class Emp {
int Eid;

// Parameterized constructor
public Emp(int eid) {
Eid = eid;
}

// Display method
void display() {
System.out.println("Employee ID: " + Eid);

Java Question Paper-2 11


}
}

// Derived class EmpName inheriting from Emp


class EmpName extends Emp {
String Ename;

// Parameterized constructor
public EmpName(int eid, String ename) {
// Call the constructor of the base class using su
super(eid);
Ename = ename;
}

// Override display method to include employee name


@Override
void display() {
// Call the display method of the base class using
super.display();
System.out.println("Employee Name: " + Ename);
}
}

// Main class to accept details and display


public class EmployeeDetails {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Accept employee details from the user


System.out.print("Enter Employee ID: ");
int eid = scanner.nextInt();

scanner.nextLine(); // Consume newline

System.out.print("Enter Employee Name: ");


String ename = scanner.nextLine();

// Create an object of EmpName class

Java Question Paper-2 12


EmpName empObj = new EmpName(eid, ename);

// Display employee details


empObj.display();

scanner.close();
}
}

Java Question Paper-2 13

You might also like