Screenshot 2024-11-30 at 1.12.44 PM
Screenshot 2024-11-30 at 1.12.44 PM
--> 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.
--> 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.
--> 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.
--> 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.
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.
java,
It returns true if the string ends with the given suffix, otherwise returns false. Example
usage:
java,
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.
--> 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.
--> 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.
--> 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:
--> 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.
--> 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.
--> To open a file in read mode in Java, use the FileReader or BufferedReader class. For
example:
Code in Java,
--> 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.
2.KeyAdapter: Provides default implementations for key event methods like keyPressed(),
keyReleased(), and keyTyped().
--> 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.
1) append(String str): Adds the specified string to the end of the current StringBuffer
object.
Code in java,
sb.append(" World");
2) insert(int offset, String str): Inserts the specified string at the given index (offset) in
the StringBuffer.
Code in java,
--> 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.
-->
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.
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.
--> 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.
-->
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.
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.
--> 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.
class MathOperation {
return a + b;
return a + b;
}
In this example, the add method is overloaded with different parameter types,
demonstrating compile-time polymorphism.
--> 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.
--> 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.
--> 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.
--> 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.
--> 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.
-->
Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.
The argument list should be different The argument list should be the same in
while doing method overloading. method overriding.
--> 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.
Triangle.
--> // Define the Shape interface with an abstract method area()
interface Shape {
double area();
this.base = base;
this.height = height;
@Override
OUTPUT:
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 '*'.
if (Character.isLetter(ch)) {
if (Character.isLowerCase(ch)) {
modifiedLine.append(Character.toUpperCase(ch));
} else {
modifiedLine.append(Character.toLowerCase(ch));
else if (Character.isDigit(ch)) {
modifiedLine.append('*');
else {
modifiedLine.append(ch);
}
// Write the modified line to the output file
writer.write(modifiedLine.toString());
writer.newLine();
} catch (IOException e) {
OUTPUT:
Java 1010
a) Write a java program to copy the content from one file to another file,
String line;
if (Character.isLowerCase(ch)) {
modifiedLine.append(Character.toUpperCase(ch));
} else if (Character.isUpperCase(ch)) {
modifiedLine.append(Character.toLowerCase(ch));
} else {
modifiedLine.append(ch);
writer.write(modifiedLine.toString());
writer.newLine();
} catch (IOException e) {
OUTPUT:
Hello World!
Java is Fun.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create 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);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
displayButton.addActionListener(new ActionListener() {
@Override
});
c) Define abstract class shape with abstract method area (). Write a java
program to calculate area of circle.
this.radius = radius;
@Override
OUTPUT:
import java.awt.event.*;
};
frame.setLayout(new BorderLayout());
frame.add(table, BorderLayout.CENTER);
frame.add(changeColorButton, BorderLayout.SOUTH);
changeColorButton.addActionListener(new ActionListener() {
@Override
});
frame.setSize(400, 300);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
interface Shape {
double area();
}
// Rectangle class that implements Shape and calculates area of the rectangle
this.length = length;
this.width = width;
@Override
OUTPUT:
-->
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.
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
super(message);
// Static method to calculate the sum of the first and last digits
public static int sumFirstAndLastDigit(int number) {
return firstDigit + lastDigit; // Return the sum of the first and last digits
try {
if (number == 0) {
} else {
} catch (ZeroNumberException e) {
// Catch and display the exception message
System.out.println(e.getMessage());
} finally {
Enter a number: 0
Number is zero
c) Write a Java program to accept n number from user & store only perfect
if (number % i == 0) {
sum += i;
int n = scanner.nextInt();
int index = 0;
// Accept n numbers and check for perfect numbers
if (isPerfectNumber(number)) {
perfectNumbers[index] = number;
index++;
--> 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");
}
}
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
}
}
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
super(message);
long factorial = 1;
factorial *= i;
return factorial;
try {
if (number == 0) {
} else {
} catch (ZeroNumberException e) {
System.out.println(e.getMessage());
} finally {
Example Output:
Case 1: User enters a non-zero number (e.g., 5):
Enter a number: 5
Factorial of 5 is: 120
int count = 0;
str = str.toLowerCase();
char ch = str.charAt(i);
count++;
}
return count;
}
Example Output:
--> 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.
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.
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
class Emp {
}
// Child class EmpName inherits Emp
employee.Eid = scanner.nextInt();
employee.Ename = scanner.nextLine();
System.out.println("\nEmployee Details:");
employee.display();
Example Output:
Employee Details:
Employee ID: 101
Employee Name: John Doe
x----------END----------x