0% found this document useful (0 votes)
18 views41 pages

Screenshot 2024-11-30 at 1.12.44 PM

Uploaded by

gauravjanmare07
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)
18 views41 pages

Screenshot 2024-11-30 at 1.12.44 PM

Uploaded by

gauravjanmare07
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/ 41

JAVA-NOTES (SEM 5)

a) What is use of Javac?

--> javac is the Java compiler used to convert Java source code files (.java) into bytecode
files (.class). This bytecode can then be executed by the Java Virtual Machine (JVM),
enabling cross-platform execution of Java programs.

b) Give the name of any two wrapper classes.

--> Two wrapper classes in Java are Integer and Double. These classes allow primitive data
types like int and double to be treated as objects, providing methods for converting,
manipulating, and comparing values in object form.

c) What is use of 'implements' keyword?

--> The implements keyword in Java is used to declare that a class will provide
implementations for the methods defined in an interface. It allows a class to inherit
abstract methods from an interface and provide specific behavior for those methods.

e) What is use of Array?

--> An array in Java is used to store multiple values of the same type in a single variable. It
allows efficient management of a collection of data, enabling random access to elements
using indices and facilitating operations like sorting and iteration.

f) Give the name of any two listeners.

--> Two common listeners in Java are:

ActionListener: Used to handle action events, like button clicks.

MouseListener: Used to handle mouse events, such as mouse clicks, presses, releases,
and movements on components.

g) What is exception?

--> An exception in Java is an event that disrupts the normal flow of program execution. It
occurs during runtime, indicating errors such as invalid input or system issues. Exceptions
are handled using try, catch, and finally blocks to ensure program stability.

h) Give the syntax of ends with( ) method?


--> The endsWith() method in Java is used to check if a string ends with a specified
suffix. The syntax is:

java,

boolean endsWith(String suffix)

It returns true if the string ends with the given suffix, otherwise returns false. Example
usage:

java,

"Hello".endsWith("lo"); // returns true

i) What is package?

--> A package in Java is a namespace that organizes classes and interfaces, allowing for
easier code management and avoiding name conflicts. It groups related classes together,
making code more modular and maintainable. Examples include java.util and java.io.

j) What is use of new operator?

--> The new operator in Java is used to create new objects or instances of classes. It
allocates memory for the object and calls the constructor to initialize it. For example,
MyClass obj = new MyClass(); creates a new object of MyClass.

a) What is javadoc?

--> Javadoc is a tool in Java that generates API documentation from source code. It extracts
comments written in a specific format (using /** */) above classes, methods, and fields to
create HTML-based documentation. This helps developers understand the functionality
and usage of code components.

b) What are command line argument?

--> Command-line arguments are values passed to a Java program when it is executed from
the command line. They are provided after the program name and can be accessed through
the String[] args parameter in the main method, enabling dynamic input.

c) Define Constructor and its types.

--> A constructor in Java is a special method used to initialize objects. It has the same name
as the class and is called automatically when an object is created.
There are two types of constructors:

Default Constructor: No parameters and initializes objects with default values.

Parameterized Constructor: Takes arguments to initialize objects with specific values


provided during object creation.

e) Write the use of extends key word.

--> The extends keyword in Java is used to create a subclass that inherits the properties and
behaviors (methods) of a superclass. It enables code reuse and facilitates the
implementation of polymorphism, allowing a subclass to override or add functionality to
the inherited methods.

f) Define functional interface.

--> A functional interface in Java is an interface that contains exactly one abstract method.
It can have multiple default or static methods. Functional interfaces are used primarily in
lambda expressions and method references. The @FunctionalInterface annotation is used
to indicate that an interface is functional.

g) List any two uncheck exception.

--> Two common unchecked exceptions in Java are:

1.NullPointerException: Occurs when an application attempts to use null where an object


is required.

2.ArrayIndexOutOfBoundsException: Happens when an array index is accessed that is


outside its valid range, i.e., negative or beyond the array length.

h) How to open file in read mode?

--> To open a file in read mode in Java, use the FileReader or BufferedReader class. For
example:

Code in Java,

FileReader fr = new FileReader("filename.txt");

BufferedReader br = new BufferedReader(fr);

This allows reading the contents of the file.


i) What is AWT?

--> AWT (Abstract Window Toolkit) is a Java library used for creating graphical user
interfaces (GUIs). It provides components like buttons, text fields, and windows. AWT is
platform-dependent as it relies on native OS components for rendering, unlike Swing,
which is platform-independent. AWT also handles event management.

j) Give the names of any two Adaptor class.

--> Two commonly used adapter classes in Java are:

1.MouseAdapter: Provides default implementations for mouse event methods like


mouseClicked(), mousePressed(), and mouseReleased(), allowing subclasses to override
only the methods they need.

2.KeyAdapter: Provides default implementations for key event methods like keyPressed(),
keyReleased(), and keyTyped().

e) What is use of static keyword?

--> The static keyword in Java is used to declare class-level variables and methods,
meaning they belong to the class rather than instances of the class. Static members are
shared by all instances, and static methods can be called without creating an object. It is
also used for static blocks.

a) List any two methods of string buffer class.

--> Two methods of the StringBuffer class in Java are:

1) append(String str): Adds the specified string to the end of the current StringBuffer
object.

Code in java,

StringBuffer sb = new StringBuffer("Hello");

sb.append(" World");

2) insert(int offset, String str): Inserts the specified string at the given index (offset) in
the StringBuffer.

Code in java,

StringBuffer sb = new StringBuffer("Hello");


sb.insert(5, " World");

b) What is use of 'throw' keyword.

--> The throw keyword in Java is used to explicitly throw an exception from a method or
block of code. It allows developers to create custom exceptions or rethrow exceptions
when certain conditions are met. The syntax is throw new ExceptionType("Message");. The
thrown exception can be caught using a try-catch block to handle errors gracefully,
enabling better error control and program flow management.

c) Differentiate between final and finally keyword.

-->

Sr. no. Key final finally finalize

final is the finalize is the


finally is the
keyword and method in
block in Java
access Java which is
Exception
modifier used to
Handling to
which is used perform clean
1. Definition execute the
to apply up processing
important
restrictions on just before
code whether
a class, object is
the exception
method or garbage
occurs or not.
variable. collected.

Finally block is
Final keyword
always related finalize()
is used with
to the try and method is
2. Applicable to the classes,
catch block in used with the
methods and
exception objects.
variables.
handling.

(1) Once (1) finally block finalize


declared, final runs the method
3. Functionality variable important performs the
becomes code even if cleaning
constant and exception activities with
cannot be occurs or not. respect to the
modified. (2) finally block object before
(2) final cleans up all its destruction.
method the resources
cannot be used in try
overridden by block
sub class.
(3) final class
cannot be
inherited.

Finally block is
executed as
soon as the finalize
Final method try-catch method is
is executed block is executed just
4. Execution executed.
only when we before the
call it. It's execution is object is
not dependant destroyed.
on the
exception.

e) What is anonymous inner class?

--> An anonymous inner class in Java is a class defined without a name, created at the
point of instantiation. It extends an existing class or implements an interface, and is
typically used for implementing event listeners or callback methods. Anonymous inner
classes are used when a one-time implementation of an interface or class is needed, often
in GUI programming or when passing functionality as arguments. They are defined using the
new keyword, followed by the class or interface type.

a) Differentiate between String and StringBuffer class.

-->

No. String StringBuffer


The String class is The StringBuffer class is
1)
immutable. mutable.

String is slow and


consumes more memory StringBuffer is fast and
when we concatenate too consumes less memory
2)
many strings because when we concatenate t
every time it creates new strings.
instance.

String class overrides the


equals() method of
StringBuffer class doesn't
Object class. So you can
3) override the equals()
compare the contents of
method of Object class.
two strings by equals()
method.

String class is slower StringBuffer class is faster


4) while performing while performing
concatenation operation. concatenation operation.

String class uses String StringBuffer uses Heap


5)
constant pool. memory

b) State any four features of java.

--> Four key features of Java are:

1.Platform Independence: Java code is compiled into bytecode that can run on any
platform with a Java Virtual Machine (JVM), making it platform-independent.

2.Object-Oriented: Java follows object-oriented principles like inheritance, encapsulation,


polymorphism, and abstraction, allowing for modular and reusable code.

3.Robust: Java has strong memory management, exception handling, and type checking,
reducing errors and enhancing reliability.
4.Multithreading: Java supports multithreading, allowing the simultaneous execution of
multiple threads, making it efficient for performing tasks like animation, database queries,
or web servers.

c) What is polymorphism? How to implement it at compile time?

--> Polymorphism in Java refers to the ability of a single entity, such as a method or object,
to take multiple forms. It allows objects of different classes to be treated as objects of a
common superclass, enhancing flexibility and reusability in code.

Compile-time polymorphism (also known as method overloading) occurs when multiple


methods with the same name are defined in the same class, but they have different
parameter lists (either in the number, type, or both of parameters). The appropriate method
is selected at compile-time based on the arguments passed.

Example of compile-time polymorphism:

class MathOperation {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

public class Main {

public static void main(String[] args) {

MathOperation operation = new MathOperation();

System.out.println(operation.add(5, 3)); // Calls int add method

System.out.println(operation.add(5.5, 3.5)); // Calls double add method

}
In this example, the add method is overloaded with different parameter types,
demonstrating compile-time polymorphism.

d) How to define and handle user defined exception?

--> To define a user-defined exception in Java, create a new class that extends the
Exception class (for checked exceptions) or RuntimeException (for unchecked exceptions).
You can add custom constructors to pass messages or other relevant information. To
handle this exception, use a try-catch block. In the try block, the exception is explicitly
thrown using the throw keyword when a specific condition occurs. In the catch block, the
exception is caught and handled appropriately, allowing for custom error messages or
recovery actions to be performed. This approach provides flexibility for handling specific
application errors.

e) What is listener? How to inherit it in program?

--> A listener in Java is an interface that reacts to specific events, such as user actions like
mouse clicks, key presses, or window changes. It allows the program to respond to these
events by defining appropriate methods.

To inherit a listener, a class must implement the corresponding listener interface,


overriding its methods to define event handling logic. For example, to handle mouse
events, a class implements the MouseListener interface. After implementing, the listener is
registered with a GUI component (like a button) to monitor and respond to the events.

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

--> The constructor of a class in Java is called when an object of that class is created. It is
automatically invoked to initialize the object, ensuring that it starts with a valid state. The
constructor can either be a default constructor (provided by the compiler if no constructor
is defined) or a parameterized constructor (defined explicitly to initialize the object with
specific values). If a class has no constructor defined, Java uses the default constructor,
which initializes object fields to default values like null, 0, or false, depending on their type.

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

--> Command-line arguments are values passed to a Java program when it is executed from
the command line or terminal. These arguments are provided after the program name and
are stored as an array of strings (String[] args) in the main method. They allow users to
provide dynamic input during program execution, influencing its behavior. For example,
running java MyProgram arg1 arg2 would store "arg1" and "arg2" in the args array. These
arguments can be accessed and processed within the program to customize its
functionality.

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

--> In Java, a Frame is a top-level container used to create a window in a graphical user
interface (GUI). It is part of the Abstract Window Toolkit (AWT) and provides a foundation for
building desktop applications. Frames can hold components like buttons, text fields, and
labels.

Two commonly used methods of the Frame class are:

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

2.setSize(int width, int height): Defines the dimensions of the frame.

Frames are essential for creating windowed applications in Java.

d) Differentiate between method overloading and method overriding.

-->

Method Overloading Method Overriding

Method overloading is a compile-time


Method overriding is a run-time polymorphism.
polymorphism.

Method overriding is used to grant the specific


Method overloading helps to increase
implementation of the method which is already
the readability of the program.
provided by its parent class or superclass.

It is performed in two classes with inheritance


It occurs within the class.
relationships.

Method overloading may or may not


Method overriding always needs inheritance.
require inheritance.
In method overloading, methods must
In method overriding, methods must have the
have the same name and different
same name and same signature.
signatures.

In method overloading, the return


type can or can not be the same, but In method overriding, the return type must be
we just have to change the the same or co-variant.
parameter.

Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.

Private and final methods can be


Private and final methods can’t be overridden.
overloaded.

The argument list should be different The argument list should be the same in
while doing method overloading. method overriding.

e) Write any two access specifiers.

--> In Java, access specifiers control the visibility and accessibility of classes, methods,
and variables. Two commonly used access specifiers are:

1.public: The public access specifier allows a class, method, or variable to be accessible
from any other class, both within the same package or in different packages. It provides the
least restrictive access.

2.private: The private access specifier restricts access to a class, method, or variable only
within the defining class. It ensures that members are not accessible from outside the
class, enhancing encapsulation and data security.

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

shape into the class traingle.Write a Java Program to calculate area of

Triangle.
--> // Define the Shape interface with an abstract method area()

interface Shape {

double area();

// Implement the Shape interface in the Triangle class

class Triangle implements Shape {

private double base;

private double height;

// Constructor to initialize base and height

public Triangle(double base, double height) {

this.base = base;

this.height = height;

// Implement the area method to calculate the area of the triangle

@Override

public double area() {

return 0.5 * base * height;

public class Main {


public static void main(String[] args) {

// Create a Triangle object with base 5 and height 10

Triangle triangle = new Triangle(5, 10);

// Calculate and print the area of the triangle

System.out.println("Area of the Triangle: " + triangle.area());

OUTPUT:

Area of the Triangle: 25.0

c) Write a Java Program to copy the contents form one file into another file.

While copying, change the case of cell the alphabets & replace all the

digital by '*'.

--> import java.io.*;

public class FileCopyWithModifications {

public static void main(String[] args) {

// Input and output file paths

String inputFilePath = "input.txt";

String outputFilePath = "output.txt";

// Try with resources to handle file reading and writing

try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));

BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {


String line;

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

// Process each line by changing case and replacing digits

StringBuilder modifiedLine = new StringBuilder();

for (char ch : line.toCharArray()) {

// Change case of alphabets

if (Character.isLetter(ch)) {

if (Character.isLowerCase(ch)) {

modifiedLine.append(Character.toUpperCase(ch));

} else {

modifiedLine.append(Character.toLowerCase(ch));

// Replace digits with '*'

else if (Character.isDigit(ch)) {

modifiedLine.append('*');

// Keep non-alphabetic, non-digit characters as is

else {

modifiedLine.append(ch);

}
// Write the modified line to the output file

writer.write(modifiedLine.toString());

writer.newLine();

System.out.println("File copied and modified successfully!");

} catch (IOException e) {

System.err.println("Error during file operations: " + e.getMessage());

OUTPUT:

Hello World! 123

Java 1010

a) Write a java program to copy the content from one file to another file,

while copying change the case of alphabets.

--> import java.io.*;

public class FileCopyWithCaseChange {

public static void main(String[] args) {

// Input and output file paths

String inputFilePath = "input.txt";

String outputFilePath = "output.txt";


// Try-with-resources to handle file reading and writing

try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));

BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {

String line;

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

// Process each line by changing the case of the alphabets

StringBuilder modifiedLine = new StringBuilder();

for (char ch : line.toCharArray()) {

// Change case of alphabets

if (Character.isLowerCase(ch)) {

modifiedLine.append(Character.toUpperCase(ch));

} else if (Character.isUpperCase(ch)) {

modifiedLine.append(Character.toLowerCase(ch));

} else {

// Keep non-alphabetic characters unchanged

modifiedLine.append(ch);

// Write the modified line to the output file

writer.write(modifiedLine.toString());
writer.newLine();

System.out.println("File copied and case changed successfully!");

} catch (IOException e) {

System.err.println("Error during file operations: " + e.getMessage());

OUTPUT:

Hello World!

Java is Fun.

b) Write a java program using swing to accept details of employee (eno,

ename, esal) and display it by clicking on a button.

--> import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class EmployeeDetailsApp {

public static void main(String[] args) {

// Create frame

JFrame frame = new JFrame("Employee Details");


// Create labels, text fields, and button

JLabel labelEno = new JLabel("Employee Number:");

JLabel labelEname = new JLabel("Employee Name:");

JLabel labelEsal = new JLabel("Employee Salary:");

JTextField textEno = new JTextField(20);

JTextField textEname = new JTextField(20);

JTextField textEsal = new JTextField(20);

JButton displayButton = new JButton("Display Details");

// Label to display employee details

JLabel outputLabel = new JLabel("");

// Set layout for the frame

frame.setLayout(new GridLayout(5, 2));

// Add components to frame

frame.add(labelEno);

frame.add(textEno);

frame.add(labelEname);

frame.add(textEname);

frame.add(labelEsal);

frame.add(textEsal);
frame.add(displayButton);

frame.add(outputLabel);

// Set frame properties

frame.setSize(300, 200);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

// Add action listener to the button

displayButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// Get input from text fields

String eno = textEno.getText();

String ename = textEname.getText();

String esal = textEsal.getText();

// Display employee details

outputLabel.setText("<html>Employee Number: " + eno + "<br>Employee Name: " +


ename + "<br>Employee Salary: " + esal + "</html>");

});

c) Define abstract class shape with abstract method area (). Write a java
program to calculate area of circle.

--> // Define an abstract class Shape with an abstract method area()

abstract class Shape {

// Abstract method to calculate area

public abstract double area();

// Circle class that extends Shape and implements area() method

class Circle extends Shape {

private double radius;

// Constructor to initialize the radius of the circle

public Circle(double radius) {

this.radius = radius;

// Implement the area method to calculate the area of the circle

@Override

public double area() {

return Math.PI * radius * radius; // Area = π * r^2

public class Main {


public static void main(String[] args) {

// Create a Circle object with radius 5

Circle circle = new Circle(5);

// Calculate and print the area of the circle

System.out.println("Area of the Circle: " + circle.area());

OUTPUT:

Area of the Circle: 78.53981633974483

a) Write a Java program using AWT to change background color of

table to 'RED' by clicking on button.

--> import java.awt.*;

import java.awt.event.*;

public class ChangeTableBackgroundColor {

public static void main(String[] args) {

// Create the frame

Frame frame = new Frame("Change Table Background Color");

// Create a button to change the background color

Button changeColorButton = new Button("Change Background to Red");

// Create data for the table


String[][] data = {

{"1", "John", "5000"},

{"2", "Jane", "6000"},

{"3", "Mark", "7000"}

};

// Column names for the table

String[] columnNames = {"Employee ID", "Name", "Salary"};

// Create the table with the data and column names

Table table = new Table(data, columnNames);

// Set layout for the frame

frame.setLayout(new BorderLayout());

// Add the table and button to the frame

frame.add(table, BorderLayout.CENTER);

frame.add(changeColorButton, BorderLayout.SOUTH);

// Action listener for the button

changeColorButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// Change the background color of the table to RED


table.setBackground(Color.RED);

});

// Set frame properties

frame.setSize(400, 300);

frame.setVisible(true);

// Close the application when the frame is closed

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

});

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

program to calculate area of rectangle.

--> // Define an interface Shape with an abstract method area()

interface Shape {

// Abstract method to calculate area

double area();

}
// Rectangle class that implements Shape and calculates area of the rectangle

class Rectangle implements Shape {

private double length;

private double width;

// Constructor to initialize length and width of the rectangle

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

// Implement the area method to calculate the area of the rectangle

@Override

public double area() {

return length * width; // Area = length * width

public class Main {

public static void main(String[] args) {

// Create a Rectangle object with length 5 and width 3

Rectangle rectangle = new Rectangle(5, 3);

// Calculate and print the area of the rectangle


System.out.println("Area of the Rectangle: " + rectangle.area());

OUTPUT:

Area of the Rectangle: 15.0

a) Differentiate between AWT & Swing.

-->

S. AWT Swing
N
O

1 Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
. applications in Java and is used to create various applications.

2 The components of Java AWT are The components of Java Swing are light
. heavy weighted. weighted.

3 Java AWT has comparatively less Java Swing has more functionality as
. functionality as compared to Swing. compared to AWT.

4 The execution time of AWT is more The execution time of Swing is less than
. than Swing. AWT.

5 The components of Java AWT are The components of Java Swing are platform
. platform dependent. independent.
6 MVC pattern is not supported by
MVC pattern is supported by Swing.
. AWT.

7 AWT provides comparatively less


Swing provides more powerful components.
. powerful components.

AWT components require java.awt Swing components requires javax.swing


8
package package

b) Define user define exception zeronumber Exc. Write a Java program to

accept a number from user. If it is zero then throw user define exception

"Number is zero" otherwise calculate the sum of first & last digit of

given number. (use Static Keyword).

--> import java.util.Scanner;

// Define a user-defined exception for zero number

class ZeroNumberException extends Exception {

public ZeroNumberException(String message) {

super(message);

public class SumFirstLastDigit {

// Static method to calculate the sum of the first and last digits
public static int sumFirstAndLastDigit(int number) {

int lastDigit = number % 10; // Get the last digit

int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1)); // Get the first


digit

return firstDigit + lastDigit; // Return the sum of the first and last digits

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Accept input from the user

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

int number = scanner.nextInt();

try {

// Check if the number is zero

if (number == 0) {

// Throw the user-defined exception if the number is zero

throw new ZeroNumberException("Number is zero");

} else {

// Calculate the sum of the first and last digits

int sum = sumFirstAndLastDigit(number);

System.out.println("Sum of first and last digits: " + sum);

} catch (ZeroNumberException e) {
// Catch and display the exception message

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

} finally {

scanner.close(); // Close the scanner resource

Case 1: User enters a non-zero number (e.g., 1234):

Enter a number: 1234


Sum of first and last digits: 5

Case 2: User enters zero:

Enter a number: 0
Number is zero

c) Write a Java program to accept n number from user & store only perfect

numbers into array & display that array.

--> import java.util.Scanner;

public class PerfectNumberArray {

// Function to check if a number is perfect

public static boolean isPerfectNumber(int number) {


int sum = 0;

// Find divisors and sum them

for (int i = 1; i <= number / 2; i++) {

if (number % i == 0) {

sum += i;

// A perfect number is equal to the sum of its divisors

return sum == number;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Accept the number of elements to check

System.out.print("Enter the number of elements: ");

int n = scanner.nextInt();

// Create an array to store perfect numbers

int[] perfectNumbers = new int[n];

int index = 0;
// Accept n numbers and check for perfect numbers

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

for (int i = 0; i < n; i++) {

int number = scanner.nextInt();

// Check if the number is a perfect number

if (isPerfectNumber(number)) {

perfectNumbers[index] = number;

index++;

// Display the perfect numbers stored in the array

System.out.print("Perfect numbers: ");

for (int i = 0; i < index; i++) {

System.out.print(perfectNumbers[i] + " ");

scanner.close(); // Close the scanner

Case 1: User enters 5 numbers and one of them is a perfect number:

Enter the number of elements: 5


Enter the numbers:
6
28
15
35
6
Perfect numbers: 6 28

Case 2: User enters no perfect numbers:

Enter the number of elements: 3


Enter the numbers:
10
20
30
Perfect numbers: //nothing will be return(NULL)

b) Explain the uses of super keyword with example.

--> The super keyword in Java is used to refer to the immediate parent class object. It can
be used in the following ways:

1.Access Parent Class Constructor: The super() is used to call the constructor of the parent
class. If no constructor is explicitly called in the child class, Java automatically calls the
default constructor of the parent class.

2.Access Parent Class Methods: super.method() is used to call a method from the parent
class if it is overridden in the child class.

3.Access Parent Class Fields: super.field is used to access a field in the parent class if it is
shadowed by a field in the child class.

Example:

java
Copy code
class Parent {
int num = 10;
Parent() {
System.out.println("Parent Constructor");
}

void show() {
System.out.println("Parent Show");
}
}

class Child extends Parent {


int num = 20;

Child() {
super(); // Calls Parent constructor
System.out.println("Child Constructor");
}

void display() {
System.out.println("Child num: " + num);
System.out.println("Parent num using super: " + super.num); //
Access parent field
}
}

public class SuperExample {


public static void main(String[] args) {
Child obj = new Child();
obj.display();
}
}
Output:
Parent Constructor
Child Constructor
Child num: 20
Parent num using super: 10
In this example, super() is used to call the constructor of the parent class, and
super.num accesses the num field from the parent class.

c) What is string? Explain its any three method with an example.

--> A String in Java is an object that represents a sequence of characters. It is immutable,


meaning once created, its value cannot be changed. The String class provides various
methods to manipulate strings.

Three Common String Methods:

1. length():
a. Returns the length of the string.
b. Example:
Java code,
String str = "Hello";
System.out.println(str.length()); // Output: 5

2. substring(int start):
a. Returns a new string that is a substring starting from the specified index.
b. Example:
Java code,
String str = "Hello";
System.out.println(str.substring(1)); // Output: ello

3. toUpperCase():
a. Converts all characters in the string to uppercase.
b. Example:
Java code,
String str = "hello";
System.out.println(str.toUpperCase()); // Output: HELLO

These methods allow efficient string manipulation in Java.


a) Write a Java program to accept a number from user. If it is zero then

throw user defined exception "Number is zero". Otherwise calculate

its factorial.(Use Static Keyword).

--> import java.util.Scanner;

// Define a user-defined exception for zero number

class ZeroNumberException extends Exception {

public ZeroNumberException(String message) {

super(message);

public class FactorialCalculation {

// Static method to calculate factorial of a number

public static long calculateFactorial(int number) {

long factorial = 1;

for (int i = 1; i <= number; i++) {

factorial *= i;

return factorial;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Accept input from the user

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

int number = scanner.nextInt();

try {

// If the number is zero, throw the custom exception

if (number == 0) {

throw new ZeroNumberException("Number is zero");

} else {

// Calculate the factorial if the number is not zero

long factorial = calculateFactorial(number);

System.out.println("Factorial of " + number + " is: " + factorial);

} catch (ZeroNumberException e) {

// Catch and display the custom exception message

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

} finally {

scanner.close(); // Close the scanner resource

Example Output:
Case 1: User enters a non-zero number (e.g., 5):
Enter a number: 5
Factorial of 5 is: 120

Case 2: User enters zero:


Enter a number: 0
Number is zero

a) Write a Java program to count number of vowels from given string.

--> import java.util.Scanner;

public class VowelCount {

// Method to count vowels in a string

public static int countVowels(String str) {

int count = 0;

// Convert string to lowercase to handle both uppercase and lowercase vowels

str = str.toLowerCase();

// Loop through each character in the string

for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);

// Check if the character is a vowel

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {

count++;

}
return count;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Accept the input string from the user

System.out.print("Enter a string: ");

String inputString = scanner.nextLine();

// Count vowels in the input string

int vowelCount = countVowels(inputString);

// Display the result

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

scanner.close(); // Close the scanner

}
Example Output:

Case 1: Input string "Hello World":

Enter a string: Hello World


Number of vowels in the given string: 3

Case 2: Input string "Programming":

Enter a string: Programming


Number of vowels in the given string: 3

a) Explain the execution process of java program.

--> The execution process of a Java program involves several key steps:

1.Writing the Program: The Java program is written in a text editor or an Integrated
Development Environment (IDE) and saved with a .java extension.

2.Compilation: The Java compiler (javac) compiles the source code into bytecode,
creating a .class file. The compiler checks for syntax errors during this step.

3.Loading: The Java Virtual Machine (JVM) loads the compiled .class file into memory using
the class loader.

4.Bytecode Execution: The JVM's interpreter or Just-In-Time (JIT) compiler translates the
bytecode into native machine code for the operating system.

5.Execution: The main() method is called, and the program executes. Java handles
memory management through garbage collection.

This entire process ensures platform independence, as the bytecode can run on any
system with the JVM.

b) Explain MVC architecture in details.

--> MVC (Model-View-Controller) is a design pattern used to separate concerns in


software development, especially for user interfaces.
1.Model: Represents the data and business logic of the application. It directly manages the
data, logic, and rules of the application. Any changes in the model are reflected in the view.

2.View: The presentation layer of the application. It displays the data from the model to the
user and sends user input to the controller. It is responsible for rendering the user
interface.

3.Controller: Acts as an intermediary between the model and the view. It receives input
from the user, processes it (with possible updates to the model), and updates the view
accordingly.

This separation enhances maintainability, scalability, and testability by isolating business


logic, user interface, and input handling.

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

EmP class into the Emp Name class, Emp Name class having a member

Ename & display ( ) method. Write a Java program to accept details of

employee [Eid, Ename] & display it. (Use super keyword).

--> import java.util.Scanner;

// Parent class Emp

class Emp {

int Eid; // Employee ID

// Method to display employee ID

public void display() {

System.out.println("Employee ID: " + Eid);

}
// Child class EmpName inherits Emp

class EmpName extends Emp {

String Ename; // Employee Name

// Method to display employee name

public void display() {

super.display(); // Calling the display() method of parent class

System.out.println("Employee Name: " + Ename);

public class EmployeeDetails {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Creating an instance of EmpName (child class)

EmpName employee = new EmpName();

// Accepting employee details

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

employee.Eid = scanner.nextInt();

scanner.nextLine(); // Consume the newline character


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

employee.Ename = scanner.nextLine();

// Displaying employee details using display() method

System.out.println("\nEmployee Details:");

employee.display();

scanner.close(); // Closing the scanner

Example Output:

Enter Employee ID: 101


Enter Employee Name: John Doe

Employee Details:
Employee ID: 101
Employee Name: John Doe

x----------END----------x

You might also like