THEORY FILE - Programming in Java (5th Sem) .
THEORY FILE - Programming in Java (5th Sem) .
THEORY FILE - Programming in Java (5th Sem) .
IL
Sahil Kumar Prof.
Program BCA ➖➖
Course Name ➖
Semester 5th.
Programming in Java (Theory).
UNIT ➖01
# Java Programming Fundamentals : ➖
● Introduction to Java ➖
IL
Java is a high-level, object-oriented programming language developed by Sun Microsystems
(now owned by Oracle) in 1995. It was designed to be platform-independent and to have a
simpler syntax compared to languages like C++. Java achieves platform independence through
its "Write Once, Run Anywhere" (WORA) philosophy, meaning Java programs can run on any
device or operating system that supports Java without the need for recompilation.
● Origin ➖
Java was initiated by James Gosling and his team at Sun Microsystems in the early 1990s. It
SA
was initially called "Oak" but was later renamed "Java" in 1995. The language was influenced by
C and C++ but aimed to eliminate certain drawbacks of these languages, such as memory leaks
and platform dependency issues.
● Challenges of Java ➖
Java has faced challenges such as performance compared to lower-level languages like C++,
its initial slow startup time for applications (less relevant now), and the complexity of managing
memory in earlier versions (now largely mitigated by automatic memory management).
● Java Features ➖
I. Platform Independence: Java programs are compiled into bytecode, which can run on any
Java Virtual Machine (JVM).
II. Object-Oriented: Encapsulation, inheritance, polymorphism, and abstraction are
fundamental principles.
III. Automatic Memory Management: Garbage collection relieves developers from manual
memory management.
IV. Security: Java provides a secure execution environment with features like bytecode
verification.
2
V. Multi-threading: Built-in support for concurrent programming with threads and
synchronisation.
VI. Rich Standard Library: Java includes a vast library (Java API) for common tasks and
functionalities.
IL
Java is a pure object-oriented programming language, meaning everything in Java is an object
(instances of classes). Key principles of OOP in Java include:
I. Classes and Objects: Classes define the structure and behaviour of objects.
II. Encapsulation: Bundling of data (attributes) and methods that operate on the data into a
single unit (class).
III. Inheritance: Mechanism by which one class acquires the properties and behaviours of
IV.
V.
H
another class.
Polymorphism: Ability of an object to take on many forms, typically achieved through
method overriding and method overloading.
Abstraction: Simplifying complex systems by modelling classes appropriate to the
problem.
Java's OOP features make it suitable for building modular, reusable, and maintainable
SA
codebases, facilitating software development and maintenance.
I. Class: The basic building block in Java, containing data (variables) and methods
(functions).
II. Method: A collection of statements that perform a specific task.
III. Variable: A named storage location used to store data temporarily during program
execution.
IV. Statement: An executable unit that performs an action.
V. Comment: Used to enhance code readability and provide explanations.
➖
3
● Java API
The Java API (Application Programming Interface) is a library of classes and interfaces provided
by Java. It includes packages for performing tasks such as input/output operations, networking,
GUI development, database connectivity, and more. Developers can use these predefined
classes and interfaces to simplify and expedite application development.
IL
● Primitive Data Types
The String class in Java represents a sequence of characters. It is widely used for
manipulating strings and is immutable, meaning once created, its value cannot be changed.
SA
● Variables and Constants ➖
I. Variables: Named storage locations whose values can change during program execution.
II. Constants: Variables whose values do not change once assigned. In Java, constants are
typically declared using the final keyword.
● Operators ➖
Java supports various types of operators:
I. Arithmetic Operators: +, -, *, /, %
II. Relational Operators: ==, !=, >, <, >=, <=
III. Logical Operators: &&, ||, !
IV. Assignment Operators: =, +=, -=, *=, /=, %=
V. Bitwise Operators: &, |, ^, ~, <<, >>, >>>
➖
4
● Scope of Variables & Blocks
I. Scope: Defines the visibility and lifetime of a variable within a program.
II. Local Variables: Defined within a method, constructor, or block. They are accessible only
within the block where they are declared.
III. Instance Variables: Belong to an instance of a class. They are declared within a class
but outside of any method, constructor, or block.
IV. Class Variables (Static Variables): Shared among all instances of a class. They are
declared with the static keyword.
IL
I. Single-line comments: Begin with // and extend to the end of the line.
II. Multi-line comments: Enclosed between /* and */, can span multiple lines.
III. Documentation comments: Begin with /** and are used for generating documentation
using tools like Javadoc.
These comments are ignored by the compiler and are used for documentation and code
readability purposes.
H
SA
5
UNIT ➖02
# Decision-making Statements
1. if Statement
The if statement evaluates a condition and executes a block of code if the condition is true.
java
if (condition) {
IL
// Code to execute if condition is true
2. if-else Statement
The if-else statement executes one block of code if the condition is true and another block if
the condition is false.
java
if (condition) {
H
// Code to execute if condition is true
SA
} else {
3. Nested if Statement
java
if (condition1) {
if (condition2) {
}
6
}
4. else-if Ladder
java
if (condition1) {
} else if (condition2) {
IL
// Code to execute if condition2 is true
} else {
5. switch Statement
H
The switch statement allows you to select one of many code blocks to execute.
java
switch (expression) {
SA
case value1:
break;
case value2:
break;
default:
# Looping Statements
1. while Loop
The while loop executes a block of code repeatedly as long as a condition is true.
java
IL
while (condition) {
2. do-while Loop
H
The do-while loop is similar to while loop, but it always executes the block of code at least
once before checking the condition.
java
do {
SA
// Code to execute repeatedly as long as condition is true
} while (condition);
3. for Loop
java
4. Nested Loops
Java allows nesting loops within each other to create complex looping structures.
java
8
for (int i = 1; i <= 5; i++) {
# Jumping Statements
1. break Statement
IL
The break statement terminates the loop or switch statement and transfers control to the
statement immediately following the loop or switch.
java
if (i == 5) {
}
H
break; // Exit the loop when i equals 5
2. continue Statement
SA
The continue statement skips the current iteration of a loop and proceeds to the next iteration.
java
if (i == 5) {
}
9
These control statements are fundamental in Java programming for controlling the flow of
execution based on conditions, iterating over data, and altering the normal flow of execution
within loops. If you have any specific questions or want to explore any of these statements
further, feel free to ask!
IL
Class: A blueprint or template that defines the properties (attributes) and behaviors (methods)
of objects.
java
// Example of a class
String model;
int year;
H
// Methods
void displayDetails() {
SA
System.out.println("Model: " + model + ", Year: " + year);
# Object: An instance of a class. Objects have state (attributes) and behavior (methods).
java
// Creating objects of the class Car
car1.model = "Toyota";
car1.year = 2022;
10
car1.displayDetails(); // Output: Model: Toyota, Year: 2022
# Modifiers ➖
Modifiers in Java control the visibility, accessibility, and behavior of classes, methods, and
variables. Examples include public, private, protected, static, final, etc.
# Passing Arguments ➖
Arguments can be passed to methods in Java through parameters. Java uses pass-by-value,
meaning a copy of the variable's value is passed to the method.
# Constructors ➖
IL
Constructors are special methods used to initialise objects. They have the same name as the
class and do not have a return type.
java
String model;
int year;
// Constructor
H
public Car(String model, int year) {
this.model = model;
SA
this.year = year;
} }
# Overloaded Constructors ➖
Java allows constructors to be overloaded, meaning a class can have multiple constructors with
different parameter lists.
java
String model;
int year;
// Overloaded constructors
11
public Car() {
// Default constructor
this.model = model;
IL
this.model = model;
this.year = year;
➖
H
# Overloaded Operators
Java does not support operator overloading like some other languages (e.g., C++). Operators in
Java have predefined meanings for built-in types.
java
public Car() {
count++;
} }
➖
12
# Garbage Collection
Java's garbage collector automatically manages memory by reclaiming objects that are no
longer referenced or reachable by the program. Developers do not explicitly free memory as in
languages like C++.
Java
IL
These concepts form the foundation of Java's object-oriented programming model. They enable
developers to create modular, reusable, and maintainable code. If you have further questions or
need clarification on any topic, feel free to ask!
# Basics of Inheritance ➖
Inheritance is a key concept in object-oriented programming (OOP) where a new class
(subclass or derived class) is created based on an existing class (superclass or base class).
The subclass inherits attributes and behaviours (methods) from its superclass.
H
Example of Inheritance
Java
// Superclass
SA
class Animal {
void sound() {
} }
void sound() {
System.out.println("Dog barks");
}
➖
13
# Inheriting and Overriding Superclass Methods
java
class Animal {
void sound() {
IL
}
void sound() {
System.out.println("Dog barks");
}
}
H
# Calling Superclass Constructor ➖
SA
Subclasses can call the constructor of their superclass using the super() keyword. This is
often used to initialise inherited attributes.
java
class Animal {
Animal() {
System.out.println("Animal constructor");
Dog() {
# Polymorphism ➖
Polymorphism means the ability of objects to take on multiple forms. In Java, polymorphism is
achieved through method overriding (runtime polymorphism) and method overloading
(compile-time polymorphism).
java
IL
class Animal {
void sound() {
} }
void sound() {
H
System.out.println("Dog barks");
} }
SA
Animal animal = new Dog(); // Polymorphic behavior
# Abstract Classes ➖
An abstract class in Java cannot be instantiated and is used to define common characteristics
for subclasses. It may contain abstract methods (methods without a body) that subclasses must
implement.
java
System.out.println("Dog barks");
} }
# Final Class ➖
A final class in Java cannot be subclassed. It prevents extension of the class and is often used
for classes that should not have any subclasses or for performance reasons.
java
IL
void sound() {
} }
Understanding inheritance, polymorphism, abstract classes, and final classes enhances the
flexibility, reusability, and structure of Java programs. If you have more questions or need further
H
explanation on any of these topics, feel free to ask!
SA
16
UNIT ➖03
# Arrays ➖
# Introduction to Array ➖
An array in Java is a collection of elements of the same type stored in contiguous memory
locations. Arrays are indexed starting from 0 and allow efficient storage and retrieval of
elements.
IL
java
numbers[0] = 1;
numbers[1] = 2;
// ...
H
# Processing Array Contents ➖
Arrays can be processed using loops or stream operations to iterate through elements and
perform operations.
SA
java
System.out.println(num);
java
} }
java
int[] createArray() {
IL
return arr;
# Array of Objects ➖
Arrays can also hold objects (instances of classes) as elements.
java
H
String[] names = {"Sahil", "Rohit", "Vikki"};
2D Arrays
java
SA
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Java supports arrays with more than two dimensions by nesting arrays.
java
int[][][] cube = {
{
18
{1, 2},
{3, 4}
},
{5, 6},
{7, 8}
IL
};
# Strings
1. String Class
Strings in Java are objects of the String class, which provides methods to manipulate strings.
java
H
String str = "Hello, World!";
2. String Concatenation
3. Comparing Strings
Strings can be compared in Java using the equals() method for content comparison.
Java
if (str1.equals(str2)) {
19
// Strings are equal
4. Substring
java
IL
5. Difference between String and StringBuffer Class
● String: Immutable (cannot be changed once created). Concatenation creates a new string
object.
● StringBuffer: Mutable (can be modified). Efficient for concatenating multiple strings.
6. StringTokenizer Class
H
The StringTokenizer class in Java is used to break a string into tokens (smaller parts).
java
while (tokenizer.hasMoreTokens()) {
SA
String token = tokenizer.nextToken();
System.out.println(token);
Understanding arrays and strings in Java is crucial for manipulating data efficiently.
20
● Interface and Packages: Basics of interface, Multiple Interfaces, Multiple
➖
Inheritance Using Interface, Multilevel Interface, Packages, Create and Access
Packages, Static Import and Package Class, Access Specifiers
# Interfaces in Java➖
Basics of Interface ➖
I. Definition: An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types.
Interfaces cannot contain instance fields or constructors.
Syntax:
java
IL
public interface InterfaceName {
// constant declarations
// method signatures
// default methods
Example:
H
// static methods
java
public interface Animal {
SA
void eat();
void sleep();
# Multiple Interfaces ➖
I. Implementing Multiple Interfaces: A class can implement multiple interfaces, providing
definitions for all the methods declared in the interfaces.
Syntax:
java
Copy code
public class ClassName implements Interface1, Interface2 {
}
21
Example:
java
public interface Flyable {
void fly();
void swim();
IL
public class Duck implements Flyable, Swimmable {
System.out.println("Duck is flying");
}
H
public void swim() {
System.out.println("Duck is swimming");
}
SA
# Multiple Inheritance Using Interface ➖
I. Concept: Java does not support multiple inheritance through classes to avoid complexity
and simplify the design. However, multiple inheritance is achievable using interfaces.
Example:
java
public interface InterfaceA {
void methodA();
void methodB();
}
22
public class MyClass implements InterfaceA, InterfaceB {
System.out.println("Implementing methodA");
System.out.println("Implementing methodB");
IL
}
# Multilevel Interface ➖
I. Concept: An interface can extend another interface, allowing for multilevel inheritance.
Syntax:
java
H
public interface InterfaceA {
void methodA();
System.out.println("Implementing methodA");
System.out.println("Implementing methodB");
}
➖
23
# Packages in Java
Basics of Packages
I. Definition: A package in Java is a namespace that organizes a set of related classes and
interfaces.
II. Benefits: Packages help in avoiding name conflicts, controlling access, and making it
easier to locate and use classes, interfaces, enumerations, and annotations.
Syntax:
java
package packageName;
IL
Creating a Package: To create a package, use the package keyword at the top of your Java
source file.
java
package com.example.myapp;
}
// class body
H
# Accessing Classes from Packages: ➖
1. Using Fully Qualified Name:
SA
java
com.example.myapp.MyClass obj = new com.example.myapp.MyClass();
2. Using Import Statement:
java
import com.example.myapp.MyClass;
}
24
# StaticInterfaces in Java
Basics of Interface
● Definition: An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types.
Interfaces cannot contain instance fields or constructors.
Syntax:
java
public interface InterfaceName {
// constant declarations
IL
// method signatures
// default methods
// static methods
Example:
java
H
public interface Animal {
void eat();
void sleep();
SA
}
# Multiple Interfaces ➖
I. Implementing Multiple Interfaces: A class can implement multiple interfaces, providing
definitions for all the methods declared in the interfaces.
Syntax:
java
public class ClassName implements Interface1, Interface2 {
Example:
java
public interface Flyable {
25
void fly();
void swim();
IL
System.out.println("Duck is flying");
System.out.println("Duck is swimming");
}
}
H
# Multiple Inheritance Using Interface ➖
I. Concept: Java does not support multiple inheritance through classes to avoid complexity
and simplify the design. However, multiple inheritance is achievable using interfaces.
SA
Example:
java
public interface InterfaceA {
void methodA();
void methodB();
System.out.println("Implementing methodB");
# Multilevel Interface ➖
IL
● Concept: An interface can extend another interface, allowing for multilevel inheritance.
Syntax:
java
public interface InterfaceA {
void methodA();
}
H
public interface InterfaceB extends InterfaceA {
void methodB();
}
SA
public class MyClass implements InterfaceB {
System.out.println("Implementing methodA");
System.out.println("Implementing methodB");
}
➖
27
# Packages in Java
Basics of Packages
A. Definition: A package in Java is a namespace that organizes a set of related classes and
interfaces.
B. Benefits: Packages help in avoiding name conflicts, controlling access, and making it
easier to locate and use classes, interfaces, enumerations, and annotations.
Syntax:
java
package packageName;
IL
Creating a Package: To create a package, use the package keyword at the top of your Java
source file.
java
package com.example.myapp;
H
public class MyClass {
// class body
}
➖
28
# Static Import and Package Class
Static Import: Allows importing static members of a class so that they can be used without class
qualification.
java
import static java.lang.Math.*;
IL
}
}
H
public int data;
Protected: The member is accessible within its own package and by subclasses.
java
SA
protected int data;
Default (Package-Private): The member is accessible only within its own package.
Java
java
package com.example.myapp;
void eat();
29
void sleep();
void fly();
void swim();
IL
}
System.out.println("Duck is eating");
}
H
public void sleep() {
System.out.println("Duck is sleeping");
}
SA
public void fly() {
System.out.println("Duck is flying");
System.out.println("Duck is swimming");
import com.example.myapp.Duck;
duck.eat();
duck.sleep();
duck.fly();
duck.swim();
IL
This example demonstrates interfaces, multiple interfaces, packages, and access specifiers in
Java.
Protected: The member is accessible within its own package and by subclasses.
java
protected int data;
31
Default (Package-Private): The member is accessible only within its own package.
java
int data; // no modifier means default
java
package com.example.myapp;
IL
public interface Animal {
void eat();
void sleep();
}
H
public interface Flyable {
void fly();
System.out.println("Duck is eating");
System.out.println("Duck is sleeping");
System.out.println("Duck is swimming");
import com.example.myapp.Duck;
IL
public class Test {
duck.eat();
H
duck.sleep();
duck.fly();
duck.swim();
}
SA
}
This example demonstrates interfaces, multiple interfaces, packages, and access specifiers in
Java.
➖
● Exception Handling: Introduction, Try and Catch Blocks, Multiple Catch, Nested
Try, Finally, Throw Statement, Built-In Exceptions
IL
Syntax:
java
try {
} catch (ExceptionType e) {
}
H
// code to handle the exception
Example:
java
try {
SA
int data = 50 / 0; // may throw an exception
} catch (ArithmeticException e) {
# Multiple Catch ➖
I. Purpose: To handle more than one type of exception that may be thrown by the try block.
Syntax:
java
Copy code
try {
Example:
java
try {
IL
int array[] = new int[5];
array[10] = 50 / 0;
} catch (ArithmeticException e) {
➖
SA
# Nested Try
I. Purpose: A try block within another try block to handle exceptions that might be thrown in
nested scopes.
Syntax:
java
try {
try {
} catch (ExceptionType e) {
}
35
} catch (ExceptionType e) {
Example:
java
try {
try {
int data = 50 / 0;
IL
} catch (ArithmeticException e) {
} catch (Exception e) {
}
H
System.out.println("Outer catch: " + e.getMessage());
# Finally Block ➖
I. Purpose: To execute important code such as closing resources, regardless of whether an
SA
exception is thrown or not.
Syntax:
java
try {
} catch (ExceptionType e) {
} finally {
}
36
Example:
java
try {
int data = 50 / 0;
} catch (ArithmeticException e) {
} finally {
IL
}
# Throw Statement ➖
I. Purpose: To explicitly throw an exception.
Syntax:
java
Example:
java
H
throw new ExceptionType("Error Message");
} else {
System.out.println("Eligible to vote");
# Built-In Exceptions ➖
I. Common Exceptions:
A. ArithmeticException: Thrown when an arithmetic operation is attempted on illegal
arguments (e.g., division by zero).
B. NullPointerException: Thrown when an application attempts to use null where
an object is required.
C. ArrayIndexOutOfBoundsException: Thrown to indicate that an array has been
accessed with an illegal index.
37
D. FileNotFoundException: Thrown when an attempt to open the file denoted by a
specified pathname has failed.
E. IOException: Thrown when an I/O operation fails or is interrupted.
java
IL
try {
} catch (ArithmeticException e) {
}
H
// Multiple Catch Blocks
try {
} catch (ArithmeticException e) {
} catch (ArrayIndexOutOfBoundsException e) {
// Nested Try
try {
try {
38
int data = 50 / 0;
} catch (ArithmeticException e) {
} catch (Exception e) {
IL
// Finally Block
try {
int data = 50 / 0;
} catch (ArithmeticException e) {
H
System.out.println("Exception: " + e.getMessage());
} finally {
}
SA
// Throw Statement
try {
checkAge(15);
} catch (ArithmeticException e) {
System.out.println("Eligible to vote");
IL
H
SA
40
UNIT ➖ 04
➖
● Multithreading: Introduction, Threads in Java, Thread Creation, Lifecycle of Thread,
Joining a Thread, Thread Scheduler, Thread Priority, Thread Synchronisation
# Multithreading in Java ➖
# Introduction ➖
IL
I. Definition: Multithreading is a process of executing multiple threads simultaneously to
maximise the utilisation of the CPU.
II. Benefits: Multithreading improves the performance of a program by executing multiple
tasks concurrently. It also helps in efficient utilisation of resources and improves the
responsiveness of applications.
# Threads in Java ➖
II.
I.
H
Definition: A thread is a lightweight process that performs a task. Each thread runs in a
separate path of execution.
Java Thread Class: Java provides a Thread class to create and manage threads.
# Thread Creation ➖
1. By Extending the Thread Class:
SA
Syntax:
java
class MyThread extends Thread {
Example:
java
class MyThread extends Thread {
System.out.println("Thread is running");
41
}
t1.start();
IL
Syntax:
java
class MyRunnable implements Runnable {
}
}
Example:
H
java
class MyRunnable implements Runnable {
SA
public void run() {
System.out.println("Thread is running");
t1.start();
}
➖
42
# Life Cycle of Thread
I. New: A thread is in this state when it is created but not yet started.
II. Runnable: The thread is ready to run and waiting for CPU time.
III. Running: The thread is executing.
IV. Blocked: The thread is waiting for a monitor lock to enter or re-enter a synchronized
block/method.
V. Waiting: The thread is waiting indefinitely for another thread to perform a particular
action.
VI. Timed Waiting: The thread is waiting for another thread to perform a specific action
within a specified waiting time.
VII. Terminated: The thread has finished its execution.
IL
# Joining a Thread ➖
I. Purpose: The join() method allows one thread to wait for the completion of another.
Syntax:
java
thread.join();
Example:
Java
H
class MyThread extends Thread {
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
System.out.println(e);
IL
}
t2.start();
➖
# Thread Scheduler
II.
I.
H
Definition: The thread scheduler in Java is part of the JVM that decides which thread
should run.
Behaviour: The behaviour of the thread scheduler can be non-deterministic and
platform-dependent.
➖
SA
# Thread Priority
I. Definition: Thread priority in Java is a value that a thread can have to suggest the priority
level for scheduling.
II. Range: Thread priority ranges from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5
(NORM_PRIORITY) being the default.
Syntax:
java
thread.setPriority(Thread.MAX_PRIORITY);
Example:
java
class MyThread extends Thread {
System.out.println("Thread is running");
}
44
public static void main(String[] args) {
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
IL
}
# Thread Synchronisation ➖
I. Purpose: Synchronisation in Java is a mechanism to control the access of multiple threads
to shared resources to prevent data inconsistency.
II.
Syntax:
java
H
Synchronized Method:
// synchronised code
SA
}
Example:
java
class Table {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
System.out.println(e);
45
}
Table t;
MyThread1(Table t) {
IL
this.t = t;
t.printTable(5);
}
}
H
class MyThread2 extends Thread {
Table t;
SA
MyThread2(Table t) {
this.t = t;
t.printTable(100);
t1.start();
t2.start();
IL
Syntax:
java
synchronised (object) {
// synchronised code
Example:
java
class Table {
H
void printTable(int n) {
synchronised (this) {
SA
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
System.out.println(e);
}
47
}
Table t;
MyThread1(Table t) {
this.t = t;
IL
t.printTable(5);
Table t;
H
MyThread2(Table t) {
this.t = t;
}
SA
public void run() {
t.printTable(100);
t1.start();
48
t2.start();
java
IL
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
H
System.out.println(i);
}
SA
}
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
System.out.println(e);
}
49
t2.start();
This example demonstrates the creation, joining, and basic management of threads in Java,
along with synchronisation.
➖
● Applets: Introduction, Applet Class, Applet Life Cycle, Graphics in Applet,
Event-Handling
IL
# Applets in Java
Introduction
I. Definition: An applet is a small Java program that runs in a web browser or an applet
viewer. It is designed to be embedded within an HTML page.
II. Features: Applets are mainly used for creating interactive features in a web application,
such as animations, graphics, and games.
➖
# Applet Class
I.
H
Superclass: The Applet class, part of the java.applet package, extends Panel from
the java.awt package.
Import Statements:
Java
SA
import java.applet.Applet;
import java.awt.Graphics;
Syntax:
java
public void init() {
// initialization code
}
50
II. Starting (start method):
A. Called after init and each time the applet becomes active (e.g., when the user
returns to the page containing the applet).
Syntax:
java
public void start() {
IL
A. Called each time the applet becomes inactive (e.g., when the user leaves the page
containing the applet).
Syntax:
java
public void stop() {
IV.
H
Destroying (destroy method):
A. Called once when the applet is about to be destroyed.
B. Used for cleanup tasks, such as releasing resources.
SA
Syntax:
java
public void destroy() {
// cleanup code
Syntax:
java
public void paint(Graphics g) {
}
51
Example Applet
java
import java.applet.Applet;
import java.awt.Graphics;
// initialization code
IL
System.out.println("Applet Initialized");
System.out.println("Applet Started");
}
H
public void stop() {
// cleanup code
System.out.println("Applet Destroyed");
}
➖
52
# Graphics in Applet
I. Graphics Class: Provides methods for drawing strings, lines, rectangles, circles, and other
shapes.
II. Common Methods:
A. drawString(String str, int x, int y): Draws the specified string at the
specified coordinates.
B. drawLine(int x1, int y1, int x2, int y2): Draws a line between the
specified coordinates.
C. drawRect(int x, int y, int width, int height): Draws a rectangle
with the specified dimensions.
D. drawOval(int x, int y, int width, int height): Draws an oval inside
IL
the specified rectangle.
Example:
Java
➖
SA
# Event-Handling
I. Definition: Handling user interactions with the applet, such as mouse clicks, key presses,
etc.
II. Event Handling in AWT: Applets use the event-handling mechanism provided by the
Abstract Window Toolkit (AWT).
III. Listeners and Adapters: Commonly used for event handling.
A. MouseListener: Handles mouse events.
B. KeyListener: Handles keyboard events.
C. ActionListener: Handles action events (e.g., button clicks).
Example:
java
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
53
import java.awt.event.MouseEvent;
addMouseListener(new MouseAdapter() {
IL
}
});
}
}
H
Example HTML to Run Applet
SA
html
<!DOCTYPE html>
<html>
<head>
<title>Simple Applet</title>
</head>
<body>
</applet>
</body>
54
</html>
This example demonstrates the basics of applets in Java, including their lifecycle, graphics
capabilities, and event-handling mechanisms.
➖
● File and I/O Streams: File Class, Streams, Byte Streams, Filtered Byte Streams,
Random Access File Class, Character Streams
IL
# File and I/O Streams in Java
# File Class ➖
I. Purpose: The File class represents a file or directory path in the file system.
II. Common Methods:
A. exists(): Checks if the file or directory exists.
B. createNewFile(): Creates a new empty file.
H
C. mkdir(): Creates a new directory.
D. delete(): Deletes the file or directory.
E. getName(): Returns the name of the file or directory.
F. getAbsolutePath(): Returns the absolute path.
G. length(): Returns the length of the file in bytes.
SA
Example:
Java
import java.io.File;
import java.io.IOException;
try {
if (file.createNewFile()) {
} else {
55
System.out.println("File already exists.");
} catch (IOException e) {
e.printStackTrace();
IL
}
# Streams ➖
I. Definition: Streams are a sequence of data. Java provides InputStream and
OutputStream for byte streams, and Reader and Writer for character streams.
II. Types:
A. Byte Streams: Used to handle raw binary data.
# Byte Streams
H
B. Character Streams: Used to handle character data.
➖
I. Classes:
A. InputStream: Abstract class for reading byte streams.
B. OutputStream: Abstract class for writing byte streams.
SA
II. Common Subclasses:
A. FileInputStream: Reads bytes from a file.
B. FileOutputStream: Writes bytes to a file.
Example:
Java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
int data;
fos.write(data);
} catch (IOException e) {
IL
e.printStackTrace();
Example:
SA
java
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
fos.write(data);
} catch (IOException e) {
e.printStackTrace();
IL
}
IV.
Modes:
H
A. "r": Read-only mode.
B. "rw": Read and write mode.
Common Methods:
A. seek(long pos): Sets the file-pointer offset.
B. read(): Reads a byte of data.
SA
C. write(int b): Writes a byte of data.
Example:
Java
import java.io.IOException;
import java.io.RandomAccessFile;
raf.read(buffer);
System.out.println(new String(buffer));
} catch (IOException e) {
e.printStackTrace();
IL
}
# Character Streams ➖
I. Classes:
II.
H
A. Reader: Abstract class for reading character streams.
B. Writer: Abstract class for writing character streams.
Common Subclasses:
A. FileReader: Reads characters from a file.
B. FileWriter: Writes characters to a file.
SA
Example:
Java
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
int data;
59
while ((data = fr.read()) != -1) {
fw.write(data);
} catch (IOException e) {
e.printStackTrace();
IL
}
# Summary ➖
I. File Class: Used for file and directory operations.
II. Streams: Sequence of data; includes byte streams and character streams.
III. Byte Streams: Handle raw binary data (InputStream, OutputStream).
IV. Filtered Byte Streams: Enhance byte streams with buffering and other capabilities.
V.
VI.
H
Random Access File: Allows non-sequential reading and writing.
Character Streams: Handle character data (Reader, Writer).
😀!
SA
HAPPY ENDING BY : SAHIL RAUNIYAR / PTU-CODER
60
JAVA(5th)Dec2018.pdf
SECTION-A
IL
a) Write the structure of a typical Java program.
j) What is CLASSPATH?
ANSWERS ➖
SECTION-A
java
package com.example;
// Import statements
61
import java.util.Scanner;
// Class declaration
// Main method
// Code to be executed
System.out.println("Hello, World!");
IL
}
// Method code
}
}
H
b) How command line arguments are passed in a Java program?
Command line arguments are passed to a Java program as a string array to the main method.
SA
Each argument is separated by a space.
Example:
Java
System.out.println(arg);
}
62
If the program is run with java CommandLineExample arg1 arg2 arg3, the output will be:
arg1
arg2
arg3
● Class: A blueprint or template for creating objects. It defines properties (fields) and
behaviours (methods) that the objects created from the class can have.
● Object: An instance of a class. It is a concrete entity that has state (fields) and behavior
(methods) as defined by the class.
IL
d) How arrays are declared in a Java program?
Java
int[] numbers;
H
// Allocation and initialization
Parameterized constructors are constructors that take arguments to initialize an object with
specific values at the time of its creation.
Example:
java
int value;
// Parameterized constructor
System.out.println(example.value); // Output: 10
IL
f) What are overriding methods?
Method overriding occurs when a subclass provides a specific implementation for a method that
is already defined in its superclass. The overridden method in the subclass should have the
same name, return type, and parameters as the method in the superclass.
Example:
Java
class Superclass {
H
void display() {
@Override
void display() {
}
64
g) When do we use protected access specifier?
The protected access specifier is used to allow access to class members (fields and
methods) within the same package and in subclasses (including subclasses in different
packages).
Example:
IL
System.out.println("Value: " + value);
void show() {
H
display(); // Accessing protected method
}
SA
}
● Applet: A small Java program that runs inside a web browser or applet viewer. It is
embedded in an HTML page and requires a Java-enabled browser to execute.
● Differences:
○ Execution: Applets run within a browser or applet viewer, while applications run
directly on the Java Virtual Machine (JVM).
○ Lifecycle: Applets have a specific lifecycle (init, start, stop, destroy), while
applications have a main method as their entry point.
○ Security: Applets are subject to security restrictions, limiting their access to local
system resources, while applications have fewer restrictions.
● Inheritance: A mechanism in which one class (subclass or derived class) inherits the
properties and behaviors of another class (superclass or base class). It allows for code
reuse and the creation of hierarchical relationships between classes.
65
● Forms of Inheritance in Java:
○ Single Inheritance: A class inherits from one superclass.
○ Multilevel Inheritance: A class inherits from another class, which in turn inherits
from another class.
○ Hierarchical Inheritance: Multiple classes inherit from a single superclass.
○ Multiple Inheritance: Java does not support multiple inheritance directly through
classes, but it can be achieved using interfaces.
j) What is CLASSPATH?
IL
● Setting CLASSPATH: It can be set using the -cp or -classpath command-line option
or by setting the CLASSPATH environment variable.
Example:
sh
export
SA
CLASSPATH=/home/user/myproject/lib/mylibrary.jar:/home/user/myproject/
classes
SECTION-B
Q2. Discuss the salient features of Java programming language. How Java is different from C
and C++?
Q3. What are the various operators available in Java? Discuss each with an example.
Q5. What is an Exception? What are the types of exceptions? Discuss in detail exception
handling in Java.
66
Q6. Create an applet that receives three numeric values as input from the user and then
displays
the largest of these on the screen. Write a sample HTML page to include this applet.
Q7. Explain with examples the various methods supported by the Graphics class.
ANSWERS ➖
SECTION-B
Q2. Discuss the salient features of Java programming language. How Java is different from C and C++?
IL
Salient Features of Java:
1. Simple: Java's syntax is clean and easy to understand. It removes many of the complex
features of C and C++ such as pointers and operator overloading.
2. Object-Oriented: Everything in Java is an object, which makes it easy to extend and
maintain.
3. Platform-Independent: Java programs are compiled into bytecode, which can be run on
any system with a JVM.
H
4. Secure: Java provides a secure environment with features like bytecode verification,
sandboxing, and no explicit pointer use.
5. Robust: Java has strong memory management, exception handling, and type-checking
mechanisms to ensure robustness.
6. Multithreaded: Java supports multithreading, allowing concurrent execution of two or
more threads.
7. High Performance: Although slower than compiled languages like C and C++, Java's
SA
Just-In-Time (JIT) compilers improve performance.
8. Distributed: Java has a rich set of APIs for networking, making it suitable for distributed
applications.
9. Dynamic: Java programs can dynamically link in new class libraries, methods, and
objects.
Q3. What are the various operators available in Java? Discuss each with an example.
1. Arithmetic Operators:
○ + (addition): int sum = 10 + 5;
○ - (subtraction): int diff = 10 - 5;
○ * (multiplication): int product = 10 * 5;
○ / (division): int quotient = 10 / 5;
○ % (modulus): int remainder = 10 % 3;
IL
2. Unary Operators:
○ + (unary plus): int positive = +5;
○ - (unary minus): int negative = -5;
○ ++ (increment): int x = 5; x++;
○ -- (decrement): int y = 5; y--;
○ ! (logical complement): boolean flag = !true;
3. Assignment Operators:
H
○ = (assignment): int a = 5;
○ += (addition assignment): a += 5; // a = a + 5
○ -= (subtraction assignment): a -= 5; // a = a - 5
○ *= (multiplication assignment): a *= 5; // a = a * 5
○ /= (division assignment): a /= 5; // a = a / 5
○ %= (modulus assignment): a %= 5; // a = a % 5
SA
4. Relational Operators:
○ == (equal to): boolean isEqual = (5 == 5);
○ != (not equal to): boolean isNotEqual = (5 != 3);
○ > (greater than): boolean isGreater = (5 > 3);
○ < (less than): boolean isLess = (5 < 3);
○ >= (greater than or equal to): boolean isGreaterOrEqual = (5 >= 5);
○ <= (less than or equal to): boolean isLessOrEqual = (5 <= 5);
5. Logical Operators:
○ && (logical AND): boolean result = (true && false);
○ || (logical OR): boolean result = (true || false);
○ ! (logical NOT): boolean result = !true;
6. Bitwise Operators:
○ & (bitwise AND): int result = 5 & 3;
○ | (bitwise OR): int result = 5 | 3;
○ ^ (bitwise XOR): int result = 5 ^ 3;
○ ~ (bitwise complement): int result = ~5;
○ << (left shift): int result = 5 << 2;
68
○ >> (right shift): int result = 5 >> 2;
○ >>> (unsigned right shift): int result = 5 >>> 2;
7. Ternary Operator:
○ ?: (ternary): int result = (5 > 3) ? 10 : 20;
8. Instanceof Operator:
○ instanceof: boolean result = "Hello" instanceof String;
Interface in Java:
● An interface is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types.
IL
● Interfaces cannot contain instance fields and are implemented by classes or extended by
other interfaces.
Declaration:
java
Copy code
interface Animal {
void makeSound();
}
H
Implementation of Interface:
● A class implements an interface by providing the body for all the methods declared in the
interface.
SA
Example:
java
Copy code
interface Animal {
void makeSound();
@Override
System.out.println("Bark");
}
69
}
IL
b) What is an abstract class? What is its use in Java?
Abstract Class:
Declaration:
java
Copy code
H
implementation, leaving the specific details to be implemented by subclasses.
void sleep() {
System.out.println("Sleeping");
Implementation:
Example:
java
abstract class Animal {
System.out.println("Sleeping");
@Override
void makeSound() {
IL
System.out.println("Bark");
Q5. What is an Exception? What are the types of exceptions? Discuss in detail exception handling in
Java.
Exception:
● An exception is an event that disrupts the normal flow of the program's instructions during
execution.
● Exceptions are objects that encapsulate information about the error.
Types of Exceptions:
● Java provides a robust framework to handle exceptions using try, catch, finally, throw, and
throws.
Syntax:
java
Copy code
try {
IL
// Code that may throw an exception
} finally {
}
SA
Example:
java
try {
} catch (ArithmeticException e) {
IL
H
SA
73
JAVA(5th)Dec2017.pdf
SECTION A
Q1. Write briefly:
● Object: An object is an instance of a class. It represents a real-world entity with state and
behavior defined by the class. An object has fields (attributes) and methods (behaviors).
IL
Creating an Object:
java
Copy code
ClassName objectName = new ClassName();
Example:
java
Copy code
class Dog {
H
// Fields and methods
● Java Virtual Machine (JVM): JVM is an abstract computing machine that enables a
computer to run a Java program. It provides a runtime environment and executes Java
bytecode. The JVM performs functions like loading, verifying, and executing code, as well
as managing memory and providing a secure execution environment.
c) What are various types of arrays? Give syntax of creating each of them.
Single-Dimensional Array:
java
74
Copy code
int[] array = new int[5];
Jagged Array:
java
Copy code
int[][] jaggedArray = new int[3][];
IL
jaggedArray[0] = new int[2];
Define the Package: Use the package keyword at the beginning of your Java source file.
java
Copy code
package com.example;
H
Create the Directory Structure: Ensure the directory structure matches the package name.
bash
SA
Copy code
src/com/example/
Compile the Classes: Compile the Java files within the directory.
sh
Copy code
javac -d . MyClass.java
● if
● if-else
● else-if
● switch
● break
● continue
75
● return
● Wrapper Classes: Wrapper classes provide a way to use primitive data types (int, char,
etc.) as objects. Each primitive type has a corresponding wrapper class in the
java.lang package.
○ int -> Integer
○ char -> Character
○ double -> Double
○ boolean -> Boolean
IL
Passing Parameters to an Applet: Parameters are passed to applets via HTML using the
<param> tag. Applet retrieves these parameters using the getParameter method.
Example:
html
<applet code="MyApplet.class" width="300" height="300">
</applet>
In the Applet:
java
SA
import java.applet.Applet;
import java.awt.Graphics;
String param1;
String param2;
param1 = getParameter("param1");
param2 = getParameter("param2");
Control Loops: Control loops (for, while, do-while) can be used in applets to perform repetitive
tasks such as drawing shapes or updating the display.
Example:
java
IL
Copy code
import java.applet.Applet;
import java.awt.Graphics;
}
SA
}
● Exception Handling: Exception handling is done to handle runtime errors, maintain the
normal flow of the program, and provide meaningful error messages. It helps in
preventing program crashes and allows the program to recover from unexpected
conditions.
● Java AWT (Abstract Window Toolkit): AWT is a part of the Java Foundation Classes
(JFC) that provides a set of APIs for creating graphical user interfaces (GUIs) in Java. It
includes components like windows, buttons, and menus, as well as event-handling
mechanisms. AWT is platform-dependent and uses the native GUI components of the
operating system.
77
SECTION B
Q2. Explain the difference of various looping statements with the help of appropriate examples. What are
labeled loops?
1. for Loop:
○ Used when the number of iterations is known.
Syntax:
for (initialization; condition; update) {
IL
}
Example:
for (int i = 0; i < 5; i++) {
2. while Loop:
H
○ Used when the number of iterations is not known and depends on a condition.
Syntax:
java
while (condition) {
SA
// body of the loop
Example:
int i = 0;
while (i < 5) {
i++;
3. do-while Loop:
○ Similar to while, but it guarantees at least one iteration since the condition is
checked after the loop body.
78
Syntax:
Java
do {
} while (condition);
Example:
java
int i = 0;
do {
IL
System.out.println("i: " + i);
i++;
Labeled Loops:
H
● Labels are used to identify a loop uniquely. They are particularly useful in nested loops to
break or continue a specific loop.
Syntax:
java
Copy code
SA
labelName:
Example:
outer: for (int i = 0; i < 3; i++) {
if (i == 1 && j == 1) {
break outer;
Q3. What is method overloading? How it is different from method overriding? Explain with an example.
Method Overloading:
● Definition: Multiple methods with the same name but different parameters (number, type,
or order of parameters) within the same class.
● Purpose: Provides a way to define methods that perform similar but slightly different
tasks.
Example:
IL
Java
class MathOperations {
// Overloaded methods
return a + b;
}
H
double add(double a, double b) {
return a + b;
SA
}
}
80
Method Overriding:
Example:
class Animal {
void makeSound() {
IL
}
@Override
H
void makeSound() {
System.out.println("Dog barks");
}
SA
public class Main {
Differences:
● Method Overloading:
○ Occurs within the same class.
○ Methods must have the same name but different parameter lists.
○ Return type can be different.
● Method Overriding:
81
○ Occurs in a subclass.
○ Methods must have the same name, parameter list, and return type.
○ Access modifier cannot be more restrictive.
Q4. Write a program to implement Multiple Inheritance using Interfaces. Also explain the process.
Java does not support multiple inheritance directly through classes to avoid complexity and ambiguity.
However, multiple inheritance can be achieved using interfaces.
Example Program:
interface Animal {
void eat();
IL
}
interface Mammal {
void walk();
}
H
class Dog implements Animal, Mammal {
@Override
System.out.println("Dog eats");
SA
}
@Override
System.out.println("Dog walks");
myDog.eat();
82
myDog.walk();
Process Explanation:
void eat();
IL
}
interface Mammal {
void walk();
}
H
Implement Interfaces: A class implements multiple interfaces by providing implementations for
the methods defined in the interfaces.
java
System.out.println("Dog eats");
@Override
System.out.println("Dog walks");
}
83
Use the Class: Create an instance of the class and call the methods.
java
public class Main {
myDog.eat();
myDog.walk();
IL
}
Exception Handling:
● Purpose: Exception handling is required to manage runtime errors, ensure the smooth
execution of the program, and provide meaningful error messages to users. It helps in
H
maintaining the program's flow and preventing crashes.
Try-Catch Block: Wrap the code that may throw an exception in a try block, and handle
exceptions using one or more catch blocks.
java
SA
try {
// Handle ExceptionType1
// Handle ExceptionType2
Finally Block: A finally block can be used to execute code that must run regardless of
whether an exception occurs.
java
try {
// Handle exception
} finally {
IL
throw new ExceptionType("Error message");
Declaring Exceptions: Use the throws keyword in the method signature to declare that the
method may throw exceptions.
java
Copy code
H
public void myMethod() throws ExceptionType {
Example:
SA
java
try {
} catch (ArithmeticException e) {
} finally {
85
System.out.println("This block always executes");
Event Delegation:
IL
● Definition: The event delegation model in Java is a design pattern used to handle events
(like user actions) by separating event sources from event handlers.
● Process: Events are generated by event sources (like buttons) and are handled by event
listeners. The event source delegates the responsibility of handling the event to the event
listener.
Example:
Java
SA
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JFrame frame;
JButton button;
public ButtonClickExample() {
button.addActionListener(this);
86
frame.setLayout(new FlowLayout());
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
@Override
IL
public void actionPerformed(ActionEvent e) {
}
H
new ButtonClickExample();
Explanation:
SA
● Implement ActionListener: The ButtonClickExample class implements
ActionListener and overrides actionPerformed.
java
Copy code
public class ButtonClickExample implements ActionListener {