0% found this document useful (0 votes)
20 views12 pages

Java IMP Questions Solutions

Java books pdf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views12 pages

Java IMP Questions Solutions

Java books pdf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Core Java Must Prepare QA before exam

Short QA

a) Define excep on: An excep on in Java is an event that disrupts the normal flow of a program's
instruc ons during execu on. It represents an abnormal condi on that requires special handling.

b) Define Interface: An interface in Java is a collec on of abstract methods and constants. It defines a
contract that classes must follow when implemen ng the interface. It's a way to achieve abstrac on
and mul ple inheritances in Java.

c) What is Javadoc? Javadoc is a tool in Java used for genera ng API documenta on in HTML format
from Java source code. It helps in documen ng the code by adding comments in a specific format
that can be processed by the Javadoc tool.

d) What is AWT? AWT stands for Abstract Window Toolkit. It's a part of Java's standard library used
for crea ng graphical user interfaces (GUIs) for Java programs. It provides various components like
bu ons, menus, and windows.

e) What is the use of the sta c keyword? In Java, the sta c keyword is used to create variables or
methods that belong to the class itself rather than instances of the class. It allows access without
crea ng an object of the class.

f) What is a command line argument? Command line arguments are the parameters passed to a Java
program when it's invoked from the command line. These arguments are accessed within the main
method's parameter list.

g) List the types of constructor: In Java, there are three types of constructors: default (no-argument)
constructor, parameterized constructor, and copy constructor.

h) What is a package? A package in Java is a namespace that organizes a set of related classes and
interfaces. It helps in avoiding naming conflicts and provides access protec on.

i) How to open a file in read mode? In Java, you can open a file in read mode using classes like File,
FileReader, or BufferedReader. Here's an example using FileReader:

File file = new File("filename.txt");

FileReader fr = new FileReader(file);

j) List any two listeners: Two types of listeners in Java are Ac onListener and MouseListener.

k) What is the use of Javac? javac is the Java compiler that translates Java source code into
bytecode, which can be executed by the Java Virtual Machine (JVM).

l) Give the name of any two wrapper classes. Two wrapper classes in Java are Integer and Boolean.
These classes wrap primi ve data types into objects.

NR Classes LLP – BCS / BCA Classes - 9730381255


m) What is the use of the 'implements' keyword? In Java, the implements keyword is used to
indicate that a class is implemen ng an interface, thus enforcing the implementa on of all the
methods defined in that interface.

n) List types of constructors. Constructors in Java can be of three types: default (no-argument)
constructor, parameterized constructor (with arguments), and copy constructor (which ini alizes an
object by copying another object of the same class).

o) What is the use of an Array? An array in Java is used to store a fixed-size sequen al collec on of
elements of the same type. It allows efficient manipula on and access to a group of variables.

p) What is an excep on? An excep on in Java is an object that represents an abnormal condi on
that arises during the execu on of a program. It disrupts the normal flow of the program.

q) Give the syntax of the ends with( ) method? The endsWith() method checks whether a string
ends with a specified suffix. Its syntax is: boolean endsWith(String suffix).

r) What is the use of the new operator? The new operator is used in Java to create new objects. It
allocates memory for an object and returns a reference to that memory loca on. For example,
ClassName obj = new ClassName(); creates an object of type ClassName.

Long QA

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

A constructor in Java is a special type of method that ini alizes an object of a class. It is called
implicitly whenever an object of that class is created using the new keyword. The constructor is
responsible for ini alizing the instance variables or performing any necessary setup for the object. If
there are mul ple constructors within a class, the appropriate constructor is invoked based on the
arguments provided or the absence of arguments when the object is created.

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

Command line arguments are the parameters passed to a Java program when it's executed from the
command line. They are provided a er the name of the class when invoking the java command.
These arguments are stored as strings in the args parameter of the main method:

public sta c void main(String[] args) {

// args is an array storing command line arguments

// For example, "java MyClass arg1 arg2"

// args[0] will contain "arg1" and args[1] will contain "arg2"

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

NR Classes LLP – BCS / BCA Classes - 9730381255


In Java, Frame is a class defined in the Abstract Window Toolkit (AWT) that represents a window with
borders and tle. It is used to create graphical user interfaces (GUIs). Two methods of the Frame
class are:

1. setTitle(String tle): This method sets the tle of the frame window.

2. setVisible(boolean visible): It makes the frame visible if the argument passed is true;
otherwise, it hides the frame.

d) Differen ate between method overloading and method overriding.

 Method Overloading: It occurs when mul ple methods in the same class have the same
name but different parameters (number, type, or order). Overloaded methods are
differen ated by their method signatures. It allows a class to have mul ple methods with the
same name but different behaviors.

 Method Overriding: It occurs in inheritance when a subclass provides a specific


implementa on of a method that is already present in its superclass. The overriding method
must have the same name, return type, and parameters as the method in the superclass. It
allows a subclass to provide its own implementa on of a method inherited from the
superclass.

e) Write any two access specifiers.

Access specifiers in Java determine the accessibility or visibility of classes, methods, and variables in
different contexts. Two access specifiers are:

1. public: It allows access from any other class or package.

2. private: It restricts access to only within the same class.

These keywords control the visibility of members of a class to other classes and are used to enforce
encapsula on and maintain code security and integrity.

f) List any two methods of the StringBuffer class.

1. append(String str): This method is used to append the specified string to the end of the
StringBuffer object.

2. insert(int offset, String str): It inserts the specified string into the StringBuffer object at the
specified offset.

The StringBuffer class in Java is used to create mutable sequences of characters. It is similar to String
but allows modifica ons to the contents.

g) What is the use of the 'throw' keyword?

The throw keyword in Java is used to explicitly throw an excep on within a method or block of code.
It is used to indicate excep onal condi ons that might occur during the execu on of a program.
When a throw statement is encountered, it throws an excep on object, which can be caught and
handled using try-catch blocks.

h) Differen ate between final and finally keywords.

 final keyword: In Java, final is a keyword used to apply restric ons on classes, methods, and
variables. When applied to a class, it prevents the class from being subclassed. When applied

NR Classes LLP – BCS / BCA Classes - 9730381255


to a method, it prevents method overriding. When applied to a variable, it makes the
variable a constant, and its value cannot be changed.

 finally keyword: finally is a block associated with excep on handling. It is used in a try-catch-
finally block. The code inside the finally block always executes, regardless of whether an
excep on is thrown or not. It is commonly used for cleanup opera ons like closing resources
(files, database connec ons) to ensure they are released even in case of excep ons.

i) What is method overloading?

Method overloading in Java occurs when mul ple methods in the same class have the same name
but different parameters (number, type, or order). It allows a class to have mul ple methods with the
same name but different behaviors based on the parameters passed. The compiler differen ates
between overloaded methods based on their method signatures.

j) What is an anonymous inner class?

An anonymous inner class in Java is a class without a name that is defined and instan ated
simultaneously using the new keyword. It is typically used when a class needs to be used only once
for a specific purpose. Anonymous inner classes are usually used in event handling (like listeners) or
to override methods of a class or interface.

For example:

InterfaceName obj = new InterfaceName() {

// Anonymous inner class defini on

// Override methods or add new methods here

};

k)Difference between AWT and Swing

Characteris cs AWT (Abstract Window Toolkit) Swing

Relies on na ve OS resources. Implemented en rely in Java, providing a


Pla orm Components have a na ve look and consistent look and feel across different
Dependence feel, varying across opera ng systems. pla orms.

Offers an extensive set of lightweight and


customizable components. Includes
Component Provides a basic set of GUI advanced components like tables, trees,
Types components. etc.

Highly customizable, allowing developers to


Limited customiza on and appearance alter the appearance and behavior of
Customizability op ons for components. components extensively.

Slower rendering compared to AWT as


Uses na ve resources, can be faster in components are en rely drawn using Java
Performance rendering due to direct OS integra on. code.

NR Classes LLP – BCS / BCA Classes - 9730381255


Characteris cs AWT (Abstract Window Toolkit) Swing

Provides a consistent UI experience across


Directly integrates with the na ve GUI different pla orms, regardless of the na ve
Integra on of the underlying OS. OS.

Was the original Java GUI toolkit but Became the primary GUI toolkit for Java
Popularity has been largely replaced by Swing. due to its extensive features and flexibility.

l) Explain uses of the super keyword with a suitable example:

In Java, the super keyword is used to refer to the immediate parent class object or invoke its
constructor or method. It's par cularly useful in scenarios involving inheritance, where a subclass
wants to access the members (fields or methods) of its superclass.

Uses of super:

1. Accessing Superclass Members: The super keyword is used to access superclass members
(fields or methods) that are overridden or hidden by a subclass.

class Parent {
int number = 10;
void display() {
System.out.println("Inside Parent class");
}
}

class Child extends Parent {


int number = 20;
void display() {
System.out.println("Inside Child class");
System.out.println("Child number: " + number);
System.out.println("Parent number: " + super.number); // Accessing superclass field
super.display(); // Invoking superclass method
}
}
Invoking Superclass Constructor: The super() constructor call is used to explicitly call a constructor of
the superclass from the constructor of the subclass. This is par cularly important when the
superclass has parameterized constructors that need to be explicitly invoked.
class Parent {
Parent(int num) {
System.out.println("Parent constructor with number: " + num);
}
}

class Child extends Parent {


Child() {
super(5); // Invoking superclass constructor

NR Classes LLP – BCS / BCA Classes - 9730381255


System.out.println("Child constructor");
}
}

m) Explain the features of Java:


Java is a versa le and powerful programming language known for its robustness, pla orm
independence, and rich set of features:
1. Object-Oriented: Java follows an object-oriented programming (OOP) paradigm, suppor ng
concepts like encapsula on, inheritance, polymorphism, and abstrac on.
2. Pla orm Independence: Java programs are compiled into pla orm-neutral bytecode,
executed by the Java Virtual Machine (JVM), enabling them to run on any device or opera ng
system with a JVM implementa on.
3. Simple and Familiar: Java syntax is similar to C/C++, making it rela vely easy to learn for
developers familiar with these languages. It also emphasizes readability and simplicity.
4. Rich Standard Library: Java provides a vast collec on of libraries and APIs for various
purposes, including networking, I/O, data structures, GUI development (Swing, JavaFX), and
more.
5. Security: Java incorporates various security features like bytecode verifica on, sandboxing,
and security manager, making it a secure language for networked environments.
6. Memory Management: Java handles memory management through automa c garbage
collec on, freeing developers from manual memory alloca on and dealloca on tasks.
7. Mul threading: Java supports mul threading, allowing concurrent execu on of mul ple
threads to achieve parallelism and efficient u liza on of system resources.
8. Performance: While not as fast as some compiled languages, Java provides good
performance through its Just-In-Time (JIT) compila on and op miza on techniques.

Prac ce Programs

a) Java program using AWT to change background color of table to 'RED' by clicking on bu on:
import java.awt.*;
import java.awt.event.*;

public class BackgroundColorChange extends Frame implements ActionListener {


Button changeColor;
Panel panel;

public BackgroundColorChange() {
panel = new Panel();
changeColor = new Button("Change Color");
changeColor.addActionListener(this);

// Table creation
TextArea table = new TextArea("This is a table.", 10, 30);
panel.add(table);

NR Classes LLP – BCS / BCA Classes - 9730381255


// Button addition to change background color
panel.add(changeColor);

add(panel);
setSize(400, 300);
setTitle("Change Table Color");
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == changeColor) {
panel.setBackground(Color.RED);
}
}

public static void main(String[] args) {


new BackgroundColorChange();
}
}

b) Java program to copy content from one file into another file, replacing digits with '*':
import java.io.*;

public class FileContentCopy {


public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new
FileReader("source.txt"));
BufferedWriter writer = new BufferedWriter(new
FileWriter("destination.txt"));
String line;

while ((line = reader.readLine()) != null) {


line = line.replaceAll("[0-9]", "*");
writer.write(line);
writer.newLine();
}

reader.close();
writer.close();
System.out.println("Content copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

c) Java program to calculate the area of a rectangle using an interface

NR Classes LLP – BCS / BCA Classes - 9730381255


interface Shape {
double area();
}

class Rectangle implements Shape {


double length;
double width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

public double area() {


return length * width;
}
}

public class CalculateRectangleArea {


public static void main(String[] args) {
Rectangle rect = new Rectangle(5.0, 10.0);
System.out.println("Area of rectangle: " + rect.area());
}
}

d) Java program to accept a number, calculate its factorial, and handle a user-defined excep on.
class ZeroNumberException extends Exception {
ZeroNumberException(String message) {
super(message);
}
}

public class FactorialCalculation {


static int calculateFactorial(int n) throws ZeroNumberException {
if (n == 0) {
throw new ZeroNumberException("Number is zero");
} else {
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
return factorial;
}
}

public static void main(String[] args) {


int number = 5; // You can modify this value to test different numbers

NR Classes LLP – BCS / BCA Classes - 9730381255


try {
int result = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + result);
} catch (ZeroNumberException e) {
System.out.println(e.getMessage());
}
}
}

e) Java program to count the number of vowels in a given string


public class VowelCounter {
public static void main(String[] args) {
String inputString = "Example String"; // Replace this with your
desired string
int vowelCount = 0;

for (char c : inputString.toLowerCase().toCharArray()) {


if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}

System.out.println("Number of vowels in the string: " + vowelCount);


}
}

f) Java program using user-defined excep on to handle zero input


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

public class SumFirstLastDigit {


static int sumFirstLastDigit(int num) throws ZeroNumberExc {
if (num == 0) {
throw new ZeroNumberExc("Number is zero");
} else {
int lastDigit = num % 10;
int firstDigit = 0;

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

return firstDigit + lastDigit;


}

NR Classes LLP – BCS / BCA Classes - 9730381255


}

public static void main(String[] args) {


int number = 504; // Change this number to test different scenarios
try {
int result = sumFirstLastDigit(number);
System.out.println("Sum of first and last digit: " + result);
} catch (ZeroNumberExc e) {
System.out.println(e.getMessage());
}
}
}

g) Java program to accept n numbers from the user and store only perfect numbers in an array

import java.util.*;

public class PerfectNumber {


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);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();

int[] inputArray = new int[n];


int[] perfectNumbersArray = new int[n];
int perfectNumbersCount = 0;

System.out.println("Enter the elements:");


for (int i = 0; i < n; i++) {
inputArray[i] = scanner.nextInt();
if (isPerfect(inputArray[i])) {
perfectNumbersArray[perfectNumbersCount++] = inputArray[i];
}
}

System.out.println("Perfect numbers in the array:");


for (int i = 0; i < perfectNumbersCount; i++) {
System.out.print(perfectNumbersArray[i] + " ");

NR Classes LLP – BCS / BCA Classes - 9730381255


}
scanner.close();
}
}
h) Java program using inheritance and super keyword to accept and display
employee details

class Emp {
int Eid;

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

class EmpName extends Emp {


String Ename;

void display() {
super.display();
System.out.println("Employee Name: " + Ename);
}
}

public class EmployeeDetails {


public static void main(String[] args) {
EmpName emp = new EmpName();
emp.Eid = 101; // Change this ID
emp.Ename = "John Doe"; // Change this name
emp.display();
}
}

NR Classes LLP – BCS / BCA Classes - 9730381255


NR Classes LLP – BCS / BCA Classes - 9730381255

You might also like