Java 39072810 2025 01 23 16 01
Java 39072810 2025 01 23 16 01
Basics of Java:
• Java Overview:
o Java is an object-oriented programming language designed to be platform-
independent.
o WORA (Write Once, Run Anywhere): Java code is compiled into bytecode,
which can run on any system with a Java Virtual Machine (JVM).
Overloading:
• Method Overloading: Methods in a class with the same name but different
parameters.
• Constructor Overloading: Multiple constructors in a class with different parameter
lists.
Key Points:
1. Same Method Name: All overloaded methods must have the same name.
2. Different Parameters: Overloaded methods must differ in the type or number of
their parameters. It can also be a combination of both.
3. Return Type: The return type can be different, but it alone cannot be used to
distinguish overloaded methods. The parameter list must differ.
4. Constructor Overloading: Constructors can also be overloaded in a similar way to
methods.
Example:
class MathUtils {
// Overloaded method with two int parameters
public int add(int a, int b) {
return a + b;
}
// Overloaded method with three int parameters
public int add(int a, int b, int c) {
return a + b + c;
}
• Improved Readability: Having methods with the same name but different
parameters improves code readability.
• Simplifies Development: Overloading allows you to define multiple methods that do
similar work with different parameters, simplifying the development process.
Rules to Remember:
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
1. Single Inheritance
In single inheritance, a class inherits from one superclass only. This is the simplest form of
inheritance.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
2. Multilevel Inheritance
In multilevel inheritance, a class is derived from another class, which is also derived from
another class. This creates a chain of inheritance.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
3. Hierarchical Inheritance
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
Java does not support multiple inheritance with classes to avoid complexity and simplify
design, but it does support multiple inheritance through interfaces. A class can implement
multiple interfaces.
Example:
interface Animal {
void eat();
}
interface Pet {
void play();
}
Key Points:
1. Same Method Signature: The overridden method in the subclass must have the same
name, return type, and parameters as the method in the superclass.
2. Annotations: The @Override annotation is used to indicate that a method is
intended to override a method in the superclass. This helps catch errors at compile
time.
3. Access Modifiers: The access level of the overriding method cannot be more
restrictive than that of the overridden method.
4. Runtime Polymorphism: Overriding allows for runtime polymorphism, where the
method that gets called is determined at runtime based on the object's actual type
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
1. Same Method Signature: The method in the child class must have the same
signature as the method in the parent class.
2. Covariant Return Type: The return type of the overriding method can be a subtype
of the return type of the overridden method.
3. Access Level: The overriding method cannot have a more restrictive access level than
the overridden method.
4. Checked Exceptions: The overriding method cannot throw new or broader checked
exceptions than those declared by the overridden method.
class Animal {
Animal getInstance() {
return new Animal();
}
}
Runtime Polymorphism
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
In this example, the sound method is overridden in both Dog and Cat classes. The method
that gets called depends on the actual object type assigned to myAnimal at runtime.
Interfaces:
• Definition: An interface is a reference type in Java that can contain only constants,
method signatures, default methods, static methods, and nested types.
Key Points:
Defining an Interface
Example:
interface Animal {
void sound();
void eat();
}
Implementing an Interface
A class implements an interface using the implements keyword and must provide concrete
implementations for all abstract methods declared in the interface.
Example:
@Override
public void eat() {
System.out.println("Dog eats");
}
}
Example:
interface Animal {
void sound();
}
interface Pet {
void play();
}
@Override
public void play() {
System.out.println("Dog plays");
}
}
Default Methods
Example:
interface Animal {
void sound();
Static Methods
Example:
interface Animal {
void sound();
Packages:
Key Points:
A package is defined using the package keyword at the top of the Java source file.
Example:
// File: com/example/Animal.java
package com.example;
Using a Package
To use a class or interface from a package, you need to import it using the import keyword.
Example:
// File: Main.java
import com.example.Animal;
Types of Packages
Creating a Package
Example:
Importing Packages
You can import classes and interfaces from other packages using the import statement.
Example:
import com.example.Dog;
import com.example.Cat;
You can also use the wildcard * to import all classes and interfaces from a package.
Example:
import com.example.*;
Access modifiers control the accessibility of classes, interfaces, and their members. The four
access levels are:
Example:
// File: com/example/Animal.java
package com.example;
// File: com/example/Main.java
package com.example;
I/O (Input/Output) Streams in Java are used to read from and write to data sources such as
files, network connections, or other external systems. The java.io package provides a
wide range of classes for handling input and output.
Key Concepts:
1. Stream: A sequence of data. Input streams are used to read data, and output streams
are used to write data.
2. Byte Streams: Handle raw binary data. Classes include InputStream and
OutputStream.
3. Character Streams: Handle character data (text). Classes include Reader and
Writer.
Byte Streams
Byte streams are used for reading and writing binary data. The main classes are
InputStream and OutputStream.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamExample {
public static void main(String[] args) {
try (FileInputStream in = new
FileInputStream("input.txt");
FileOutputStream out = new
FileOutputStream("output.txt")) {
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Character Streams
Character streams are used for reading and writing text data. The main classes are Reader
and Writer.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
Buffered streams use an internal buffer to reduce the number of I/O operations, improving
performance. Classes include BufferedInputStream, BufferedOutputStream,
BufferedReader, and BufferedWriter.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
Collections:
The java.util package provides the Collections Framework, which includes a set of
interfaces and classes to handle groups of objects in a standard way.
Key Interfaces:
Example (ArrayList):
import java.util.ArrayList;
import java.util.List;
Set Interface
Example (HashSet):
import java.util.HashSet;
import java.util.Set;
A Map is a collection that maps keys to values, with no duplicate keys allowed.
Example (HashMap):
import java.util.HashMap;
import java.util.Map;
Exception handling in Java is a mechanism to handle runtime errors, ensuring the normal
flow of the application. Java provides a robust and flexible exception handling framework
through its try, catch, finally, throw, and throws keywords.
Key Concepts:
Java exceptions are represented by the Throwable class, which has two main subclasses:
Error and Exception.
• Error: Represents serious issues that a typical application should not catch. Examples
include OutOfMemoryError, StackOverflowError.
• Exception: Represents conditions that a typical application might want to catch.
There are two main types:
o Checked Exceptions: Must be either caught or declared in the method
signature. Examples include IOException, SQLException.
o Unchecked Exceptions (RuntimeExceptions): Do not need to be declared or
caught. Examples include NullPointerException,
ArithmeticException.
1. Try-Catch Block
A try block is used to wrap code that might throw an exception, and a catch block is used
to handle the exception.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example:
try {
// Code that might throw multiple exceptions
} catch (IOException e) {
// Handle IOException
} catch (SQLException e) {
// Handle SQLException
}
Example:
import java.io.*;
3. Finally Block
A finally block contains code that is always executed, regardless of whether an exception
is thrown or not. It's typically used for cleanup activities like closing resources.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always be executed
}
Example:
import java.io.*;
4. Throw Keyword
Example:
5. Throws Keyword
The throws keyword is used in method signatures to declare that a method might throw one
or more exceptions.
Example:
import java.io.*;
Custom Exceptions
You can create your own exception classes by extending the Exception class or
RuntimeException class.
Example:
Multithreaded Programming:
Multithreading in Java allows concurrent execution of two or more threads to maximize the
utilization of CPU. Each thread runs in parallel to perform its task independently, enabling
more efficient execution of complex and time-consuming tasks.
Key Concepts:
1. Thread: A lightweight process. Multiple threads share the same process memory
space.
2. Multithreading: A process of executing multiple threads simultaneously.
3. Concurrency: The ability to run multiple threads or tasks in parallel.
4. Synchronization: A mechanism to control the access of multiple threads to shared
resources.
Creating Threads
To create a thread by extending the Thread class, you need to override the run method and
create an instance of the class.
Example:
To create a thread by implementing the Runnable interface, you need to implement the
run method and pass an instance of the class to a Thread object.
Example:
1. New: A thread that has been created but not yet started.
2. Runnable: A thread that is ready to run and waiting for CPU time.
3. Running: A thread that is currently executing.
4. Blocked/Waiting: A thread that is blocked or waiting for some condition or resource.
5. Terminated: A thread that has completed its execution or has been terminated.
Thread Methods
try {
thread.join(); // Wait for the thread to finish
System.out.println("Thread has finished
execution");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Synchronization
Synchronized Method
class Counter {
private int count = 0;
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
t1.start();
t2.start();
t1.join();
t2.join();
A synchronized block can be used to synchronize a specific block of code instead of the
whole method.
class Counter {
private int count = 0;
Inter-Thread Communication
Inter-thread communication in Java can be achieved using the wait(), notify(), and
notifyAll() methods, which are part of the Object class.
Example:
class SharedResource {
private int count = 0;
private boolean available = false;
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
resource.produce();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
resource.consume();
Thread.sleep(1500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
producer.start();
consumer.start();
}
}
Key Concepts:
To create a basic Java applet, you typically extend the java.applet.Applet class and
override methods such as init(), start(), stop(), and destroy(). Here’s an
example of a simple applet:
import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet {
@Override
public void init() {
// Initialization code
}
@Override
public void start() {
// Start code (e.g., start animation or timer)
}
@Override
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 20, 20);
}
@Override
public void stop() {
// Stop code (e.g., stop animation or timer)
}
@Override
public void destroy() {
// Cleanup code (e.g., release resources)
}
}
To embed a Java applet in an HTML page, you use the <applet> or <object> tag.
Here’s an example using the <applet> tag:
<!DOCTYPE html>
<html>
<head>
<title>Java Applet Example</title>
</head>
<body>
<applet code="SimpleApplet.class" width="300"
height="200">
Your browser does not support Java applets.
</applet>
</body>
</html>
• init(): Initializes the applet. Called once when the applet is first loaded.
• start(): Starts the applet. Called each time the applet is revisited or resumed.
• paint(Graphics g): Called whenever the applet needs to redraw itself. Typically
overridden to draw graphics or text.
• stop(): Stops the applet. Called when the applet is no longer visible or needs to stop
processing.
• destroy(): Cleans up resources used by the applet. Called when the applet is about to
be unloaded.
Applet Security
Java applets ran with certain security restrictions imposed by the Java Runtime Environment
(JRE). These restrictions included limitations on accessing the local file system, network
connections, and other system resources. Despite these restrictions, vulnerabilities were
discovered over time, leading to security concerns and the eventual deprecation of Java
applets in modern browsers.
Deprecated Status
As of Java 9, the java.applet package and the Applet API have been deprecated. Modern
browsers have also dropped support for Java applets due to security issues and the availability
of more secure and versatile web technologies.
Alternatives
Instead of Java applets, web developers now use technologies such as:
AWT (Abstract Window Toolkit) is a set of classes and methods provided by Java for
creating and managing graphical user interface (GUI) elements such as windows, buttons,
menus, and dialogs. AWT is part of the Java Foundation Classes (JFC) and is the original
GUI framework for Java.
Key Concepts:
AWT Components
AWT provides a set of GUI components that can be used to create user interfaces. Some of
the commonly used components include:
• Window: Represents a top-level window with a title bar and border. Example:
Frame.
• Panel: A container for holding other components. Example: Panel.
• Button: A clickable button. Example: Button.
• Label: Displays a text or image. Example: Label.
• TextField: Allows users to input single-line text. Example: TextField.
• TextArea: Allows users to input multiple lines of text. Example: TextArea.
• Checkbox: A checkable option. Example: Checkbox.
• Choice: A drop-down list of choices. Example: Choice.
AWT Containers
Containers are components that can contain other components. Some common containers in
AWT include:
Layout managers control how components are arranged within containers. AWT provides
several layout managers, including:
Here's a simple example demonstrating how to create a basic GUI using AWT:
import java.awt.*;
// Create components
Label label = new Label("Enter your name:");
TextField textField = new TextField(20);
Button button = new Button("Submit");
AWT uses the event-delegation model for event handling. Events are generated by user
actions (e.g., mouse clicks, keystrokes) and are handled by event listeners registered with
components. Some common event listener interfaces in AWT include ActionListener,
MouseListener, KeyListener, etc.
import java.awt.*;
import java.awt.event.*;
frame.add(button);
frame.setSize(200, 100);
frame.setVisible(true);
}
}
Swing, introduced later in Java's development, is built on top of AWT but provides a more
powerful and flexible set of components and features. Swing components are lightweight and
offer a more consistent look and feel across different platforms compared to AWT, which
uses native platform components.
Event Handling:
Here’s a basic example of handling a button click event using Java Swing:
import javax.swing.*;
import java.awt.event.*;
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In this example:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Handle button click
}
});
2. MouseListener: Handles mouse events, like clicks, enters, exits.
component.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
// Handle mouse click
}
// Other mouse event methods
});
component.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
// Handle key press
}
// Other key event methods
});
In JavaFX, which is the successor to Swing for GUI applications, event handling is similar
but uses its own set of classes and interfaces. JavaFX provides more modern and flexible
ways to handle events, leveraging features like event filters, event handlers, and properties
binding.
IMPORTANT MCQS
1) What is the primary purpose of the Java Virtual Machine (JVM)?
• a) int
• b) float
• c) double
• d) String
• a) start()
• b) main()
• c) init()
• d) run()
• a) Defining multiple methods with the same name but different parameters.
• b) Defining a method in a subclass that has the same signature as a method in the
superclass.
• c) Changing the return type of a method.
• d) Using the same method name in different classes.
• a) implements
• b) extends
• c) inherits
• d) super
7) Which of the following concepts allows you to define methods in an interface without
implementation?
• a) Polymorphism
• b) Abstraction
• c) Encapsulation
• d) Inheritance
• a) Runnable
• b) Threadable
• c) Executable
• d) ActionListener
• a) true
• b) false
• c) null
• d) 0
12) Which collection class allows you to access its elements by associating a key with an
element's value, and allows you to retrieve elements in the order in which they were
inserted?
• a) HashSet
• b) TreeSet
• c) LinkedHashMap
• d) TreeMap
14) Which of these statements is true about the 'File' class in Java?
• a) It is an abstract class.
• b) It can be used to create files and directories.
• c) It can read from and write to files.
• d) It is part of the java.util package.
• a) NullPointerException
• b) ArithmeticException
• c) ArrayIndexOutOfBoundsException
• d) NumberFormatException
• a) final
• b) static
• c) abstract
• d) sealed
• a) run()
• b) start()
• c) init()
• d) execute()
• a) java.io
• b) java.lang
• c) java.util
• d) java.net
19) Which method is used to read a line of text from the console in Java?
• a) readLine()
• b) read()
• c) nextLine()
• d) getLine()
• a) Object
• b) int
• c) long
• d) boolean
• a) Hello World
• b) Hello
• c) Hello WorldHello
• d) World
22) Which of the following can be used to create an abstract class in Java?
• a) transient
• b) volatile
• c) static
• d) unsigned
int a = 10;
int b = 20;
int c = 30;
a = b = c;
System.out.println(a);
• a) 10
• b) 20
• c) 30
• d) Compilation Error
• a) sleep()
• b) wait()
• c) join()
• d) yield()
26) What is the correct syntax for creating a new instance of the File class?
27) Which of the following is true about the 'ArrayList' class in Java?
• a) It is synchronized.
• b) It can grow dynamically.
• c) It is part of java.lang package.
• d) It is an abstract class.
• a) sleep()
• b) wait()
• c) run()
• d) yield()
29) Which of these data types can be used for a switch statement expression in Java?
• a) int
• b) float
• c) boolean
• d) long
• a) Vector is synchronized.
• b) Vector cannot grow dynamically.
• c) Vector is part of java.lang package.
• d) Vector does not allow duplicate elements.
KEY
1) b) To interpret bytecode
2) d) String
3) b) main()
4) c) The method belongs to the class, not any particular object.
5) a) Defining multiple methods with the same name but different parameters.
6) b) extends
7) b) Abstraction
8) a) Runnable
9) b) false
10) b) It is called automatically before an object is garbage collected.
11) c) To refer to the current object
12) c) LinkedHashMap
13) b) The method cannot be overridden.
14) b) It can be used to create files and directories.
15) b) ArithmeticException
16) a) final
17) b) start()
18) c) java.util
19) c) nextLine()
20) b) int
21) b) Hello
22) a) The abstract keyword
23) d) unsigned
24) c) 30
25) c) join()
26) a) File file = new File("filename");
27) b) It can grow dynamically.
28) b) wait()
29) a) int
30) a) Vector is synchronized.