Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

THEORY FILE - Programming in Java (5th Sem) .

Download as pdf or txt
Download as pdf or txt
You are on page 1of 87

THEORY FILE : Programming in Java .

(FULL NOTES: BY SAHIL RAUNIYAR) .

SUBJECT CODE: UGCA: 1932

BACHELOR OF COMPUTER APPLICATIONS

MAINTAINED BY: TEACHER’S /MAM’:

IL
Sahil Kumar Prof.

COLLEGE ROLL NO: 226617

UNIVERSITY ROLL NO: 2200315


H
SA

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

BABA BANDA SINGH BAHADUR ENGINEERING

COLLEGE FATEGARH SAHIB


1

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.

● Stage for Java ➖


Java was originally designed for embedded systems but gained popularity for web development
H
and enterprise applications due to its robustness, security features, and portability. It is widely
used for building desktop GUI applications, mobile apps (Android), web applications, backend
services, and more recently, in big data technologies such as Hadoop and Spark.

● 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.

● Java Program Development ➖


Java programs are typically developed using an Integrated Development Environment (IDE)
such as IntelliJ IDEA, Eclipse, or NetBeans. The development process involves writing Java
code, compiling it into bytecode using a Java compiler, and running it on a JVM.

● Object-Oriented Programming (OOP) ➖

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.

● Elements of Java Program ➖


A Java program consists of various elements that work together to perform specific tasks.
These elements include:

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.

● Variables and Literals ➖


I. Variable: A named storage location in memory used to hold data. It has a data type that
determines the size and type of values it can hold.
II. Literal: A constant value that appears directly in the source code.

IL
● Primitive Data Types

Java supports eight primitive data types:

I. Numeric Types: byte, short, int, long, float, double


II. Character Type: char
III. Boolean Type: boolean
H
These data types represent basic values and are not objects. They are directly supported by the
Java programming language.

The String Class

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.

Types of Comment in Java ➖


Java supports three types of comments:

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 {

// Code to execute if condition is false

3. Nested if Statement

A nested if statement is an if statement inside another if statement.

java

if (condition1) {

if (condition2) {

// Code to execute if both conditions are true

}
6
}

4. else-if Ladder

An else-if ladder allows you to evaluate multiple conditions sequentially.

java

if (condition1) {

// Code to execute if condition1 is true

} else if (condition2) {

IL
// Code to execute if condition2 is true

} else {

// Code to execute if all conditions are false

5. switch Statement
H
The switch statement allows you to select one of many code blocks to execute.

java

switch (expression) {
SA
case value1:

// Code to execute if expression matches value1

break;

case value2:

// Code to execute if expression matches value2

break;

default:

// Code to execute if expression doesn't match any case

6. Conditional Operator (Ternary Operator)

The conditional operator (? :) provides a shorthand way of writing an if-else statement.


7
java

variable = (condition) ? expression1 : expression2;

// If condition is true, variable = expression1; otherwise, variable =


expression2;

# 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) {

// Code to execute repeatedly as long as condition is true

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

The for loop executes a block of code a fixed number of times.

java

for (initialization; condition; update) {

// Code to execute repeatedly until condition is false

4. Nested Loops

Java allows nesting loops within each other to create complex looping structures.

java
8
for (int i = 1; i <= 5; i++) {

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

// Code to execute nested loops

# 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

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

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

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

if (i == 5) {

continue; // Skip the rest of the loop body for i equals 5

// Code here executes for all values of i except 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!

# Basic Concepts of OOP ➖


Object-Oriented Programming (OOP) is a paradigm that revolves around the concept of objects,
which are instances of classes. OOP focuses on encapsulation, inheritance, polymorphism, and
abstraction to model real-world entities in software.

# Classes and Objects ➖

IL
Class: A blueprint or template that defines the properties (attributes) and behaviors (methods)
of objects.
java
// Example of a class

public class Car {

// Attributes (instance variables)

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

Car car1 = new Car();

Car car2 = new Car();

// Accessing object attributes and invoking methods

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

public class Car {

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

public class Car {

String model;

int year;

// Overloaded constructors
11
public Car() {

// Default constructor

public Car(String model) {

this.model = model;

public Car(String model, int year) {

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.

# Static Class Members ➖


Static members (variables and methods) belong to the class rather than instances of the class.
SA
They are shared among all instances of the class.

java

public class Car {

static int count = 0; // Static variable

public Car() {

count++;

public static void displayCount() {

System.out.println("Number of cars: " + 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

Car car1 = new Car(); // Object created

car1 = null; // Object no longer referenced

// Garbage collector may reclaim memory for car1

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() {

System.out.println("Animal makes a sound");

} }

// Subclass inheriting Animal

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

}

13
# Inheriting and Overriding Superclass Methods

I. Inheritance: Subclasses inherit methods from their superclass by default.


II. Method Overriding: Subclasses can provide a specific implementation for a method
already defined in the superclass. This allows for runtime polymorphism.

java

class Animal {

void sound() {

System.out.println("Animal makes a sound");

IL
}

class Dog extends Animal {

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");

class Dog extends Animal {

Dog() {

super(); // Calls superclass constructor


14
System.out.println("Dog constructor");

# 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() {

System.out.println("Animal makes a sound");

} }

class Dog extends Animal {

void sound() {
H
System.out.println("Dog barks");

} }
SA
Animal animal = new Dog(); // Polymorphic behavior

animal.sound(); // Outputs: "Dog barks"

# 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

abstract class Animal {

abstract void sound(); // Abstract method

class Dog extends Animal {


15
void sound() {

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

final class Animal {

IL
void sound() {

System.out.println("Animal makes a 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

// Declaration and initialization of an array

int[] numbers = new int[5]; // An array of integers with size 5

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

// Iterating through an array using a for-each loop

for (int num : numbers) {

System.out.println(num);

# Passing Array as Argument ➖


Arrays can be passed as arguments to methods in Java.

java

void printArray(int[] arr) {

for (int num : arr) {


17
System.out.println(num);

} }

# Returning Array from Methods ➖


Methods in Java can return arrays as return types.

java

int[] createArray() {

int[] arr = {1, 2, 3, 4, 5};

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

A 2D array is an array of arrays where each element is itself an array.

java
SA
int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

Arrays with Three or More Dimensions

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

Concatenation of strings in Java is done using the + operator or concat() method.


SA
java

String hello = "Hello";

String world = "World";

String message = hello + ", " + world + "!";

3. Comparing Strings

Strings can be compared in Java using the equals() method for content comparison.

Java

String str1 = "Hello";

String str2 = "Hello";

if (str1.equals(str2)) {
19
// Strings are equal

4. Substring

The substring() method in Java extracts a portion of a string.

java

String str = "Hello, World!";

String substr = str.substring(7); // "World!"

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

StringTokenizer tokenizer = new StringTokenizer("Hello, World!", ",");

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 {

// implement methods from Interface1 and Interface2

}
21
Example:
java
public interface Flyable {

void fly();

public interface Swimmable {

void swim();

IL
public class Duck implements Flyable, Swimmable {

public void fly() {

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();

public interface InterfaceB {

void methodB();

}
22
public class MyClass implements InterfaceA, InterfaceB {

public void methodA() {

System.out.println("Implementing methodA");

public void methodB() {

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();

public interface InterfaceB extends InterfaceA {


SA
void methodB();

public class MyClass implements InterfaceB {

public void methodA() {

System.out.println("Implementing methodA");

public void methodB() {

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;

# Create and Access Packages ➖

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;

public class MyClass {

}
// 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;

public class Test {

public static void main(String[] args) {

MyClass obj = new 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 {

// implement methods from Interface1 and Interface2

Example:
java
public interface Flyable {
25
void fly();

public interface Swimmable {

void swim();

public class Duck implements Flyable, Swimmable {

public void fly() {

IL
System.out.println("Duck is flying");

public void swim() {

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();

public interface InterfaceB {

void methodB();

public class MyClass implements InterfaceA, InterfaceB {

public void methodA() {


26
System.out.println("Implementing methodA");

public 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 {

public void methodA() {

System.out.println("Implementing methodA");

public void methodB() {

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;

Create and Access Packages ➖

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

# Accessing Classes from Packages: ➖


SA
Using Fully Qualified Name:
java
com.example.myapp.MyClass obj = new com.example.myapp.MyClass();

Using Import Statement:


java
import com.example.myapp.MyClass;

public class Test {

public static void main(String[] args) {

MyClass obj = new MyClass();

}

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.*;

public class Test {

public static void main(String[] args) {

System.out.println(sqrt(16)); // instead of Math.sqrt(16)

IL
}

# Access Specifiers in Java ➖


Public: The member is accessible from any other class.
java
public class MyClass {

}
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

int data; // no modifier means default

Private: The member is accessible only within its own class.


java
private int data;

Example Code Demonstration

java

package com.example.myapp;

public interface Animal {

void eat();
29
void sleep();

public interface Flyable {

void fly();

public interface Swimmable {

void swim();

IL
}

public class Duck implements Animal, Flyable, Swimmable {

public void eat() {

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");

public void swim() {

System.out.println("Duck is swimming");

import com.example.myapp.Duck;

public class Test {

public static void main(String[] args) {


30
Duck duck = new Duck();

duck.eat();

duck.sleep();

duck.fly();

duck.swim();

IL
This example demonstrates interfaces, multiple interfaces, packages, and access specifiers in
Java.

# Import and Package Class ➖


Static Import: Allows importing static members of a class so that they can be used without class
qualification.
Java
H
import static java.lang.Math.*;

public class Test {

public static void main(String[] args) {

System.out.println(sqrt(16)); // instead of Math.sqrt(16)


SA
}

# Access Specifiers in Java ➖


Public: The member is accessible from any other class.
java
public class MyClass {

public int data;

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

Private: The member is accessible only within its own class.


java
private int data;

Example Code Demonstration

java

package com.example.myapp;

IL
public interface Animal {

void eat();

void sleep();

}
H
public interface Flyable {

void fly();

public interface Swimmable {


SA
void swim();

public class Duck implements Animal, Flyable, Swimmable {

public void eat() {

System.out.println("Duck is eating");

public void sleep() {

System.out.println("Duck is sleeping");

public void fly() {


32
System.out.println("Duck is flying");

public void swim() {

System.out.println("Duck is swimming");

import com.example.myapp.Duck;

IL
public class Test {

public static void main(String[] args) {

Duck duck = new Duck();

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

# Exception Handling in Java ➖


Introduction

I. Definition: Exception handling in Java is a mechanism to handle runtime errors, ensuring


the normal flow of the application.
33
II. Hierarchy:
A. Throwable: The superclass of all errors and exceptions in Java.
1. Error: Represents serious problems that a reasonable application should not
try to catch (e.g., OutOfMemoryError).
2. Exception: Represents conditions that a reasonable application might want
to catch.

# Try and Catch Blocks ➖


I. Try Block: The code that might throw an exception is placed inside the try block.
II. Catch Block: The code that handles the exception is placed inside the catch block.

IL
Syntax:
java
try {

// code that may throw an exception

} catch (ExceptionType e) {

}
H
// code to handle the exception

Example:
java
try {
SA
int data = 50 / 0; // may throw an exception

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero");

# 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 {

// code that may throw multiple exceptions


34
} catch (ExceptionType1 e1) {

// handle exception type 1

} catch (ExceptionType2 e2) {

// handle exception type 2

Example:
java
try {

IL
int array[] = new int[5];

array[10] = 50 / 0;

} catch (ArithmeticException e) {

System.out.println("Arithmetic Exception: " + e.getMessage());


H
} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array Index Out Of Bounds Exception: " +


e.getMessage());


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 {

// outer try block

try {

// inner try block

} catch (ExceptionType e) {

// inner catch block

}
35
} catch (ExceptionType e) {

// outer catch block

Example:
java
try {

try {

int data = 50 / 0;

IL
} catch (ArithmeticException e) {

System.out.println("Inner catch: " + e.getMessage());

} 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 {

// code that may throw an exception

} catch (ExceptionType e) {

// code to handle the exception

} finally {

// code that will always execute

}
36
Example:
java
try {

int data = 50 / 0;

} catch (ArithmeticException e) {

System.out.println("Exception: " + e.getMessage());

} finally {

System.out.println("Finally block is always executed");

IL
}

# Throw Statement ➖
I. Purpose: To explicitly throw an exception.

Syntax:
java

Example:
java
H
throw new ExceptionType("Error Message");

public void checkAge(int age) {

if (age < 18) {


SA
throw new ArithmeticException("Not eligible to vote");

} 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.

Example Code Demonstration

java

public class ExceptionHandlingDemo {

public static void main(String[] args) {

// Try and Catch Blocks

IL
try {

int data = 50 / 0; // This will cause ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero");

}
H
// Multiple Catch Blocks

try {

int[] array = new int[5];


SA
array[10] = 30 / 0;

} catch (ArithmeticException e) {

System.out.println("Arithmetic Exception: " +


e.getMessage());

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array Index Out Of Bounds Exception: "


+ e.getMessage());

// Nested Try

try {

try {
38
int data = 50 / 0;

} catch (ArithmeticException e) {

System.out.println("Inner catch: " + e.getMessage());

} catch (Exception e) {

System.out.println("Outer catch: " + e.getMessage());

IL
// Finally Block

try {

int data = 50 / 0;

} catch (ArithmeticException e) {
H
System.out.println("Exception: " + e.getMessage());

} finally {

System.out.println("Finally block is always executed");

}
SA
// Throw Statement

try {

checkAge(15);

} catch (ArithmeticException e) {

System.out.println("Caught exception: " + e.getMessage());

public static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Not eligible to vote");


39
} else {

System.out.println("Eligible to vote");

This example demonstrates the various aspects of exception handling in Java.

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 {

public void run() {

// code to be executed by the thread

Example:
java
class MyThread extends Thread {

public void run() {

System.out.println("Thread is running");
41
}

public static void main(String[] args) {

MyThread t1 = new MyThread();

t1.start();

2. By Implementing the Runnable Interface:

IL
Syntax:
java
class MyRunnable implements Runnable {

public void run() {

// code to be executed by the thread

}
}

Example:
H
java
class MyRunnable implements Runnable {
SA
public void run() {

System.out.println("Thread is running");

public static void main(String[] args) {

MyRunnable runnable = new MyRunnable();

Thread t1 = new Thread(runnable);

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 {

public void run() {


SA
for (int i = 0; i < 5; i++) {

System.out.println(i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(e);

public static void main(String[] args) {


43
MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

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 {

public void run() {

System.out.println("Thread is running");

}
44
public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

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 void methodName() {

// synchronised code
SA
}

Example:
java
class Table {

synchronised void printTable(int n) {

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

System.out.println(n * i);

try {

Thread.sleep(400);

} catch (InterruptedException e) {

System.out.println(e);
45
}

class MyThread1 extends Thread {

Table t;

MyThread1(Table t) {

IL
this.t = t;

public void run() {

t.printTable(5);

}
}
H
class MyThread2 extends Thread {

Table t;
SA
MyThread2(Table t) {

this.t = t;

public void run() {

t.printTable(100);

public class TestSynchronization {

public static void main(String[] args) {

Table obj = new Table();


46
MyThread1 t1 = new MyThread1(obj);

MyThread2 t2 = new MyThread2(obj);

t1.start();

t2.start();

III. Synchronized Block:

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
}

class MyThread1 extends Thread {

Table t;

MyThread1(Table t) {

this.t = t;

public void run() {

IL
t.printTable(5);

class MyThread2 extends Thread {

Table t;
H
MyThread2(Table t) {

this.t = t;

}
SA
public void run() {

t.printTable(100);

public class TestSynchronization {

public static void main(String[] args) {

Table obj = new Table();

MyThread1 t1 = new MyThread1(obj);

MyThread2 t2 = new MyThread2(obj);

t1.start();
48
t2.start();

Example Code Demonstration

java

class MultithreadingDemo extends Thread {

public void run() {

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
}

public static void main(String[] args) {

MultithreadingDemo t1 = new MultithreadingDemo();

MultithreadingDemo t2 = new MultithreadingDemo();

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;

# Applet Life Cycle ➖


I. Initialization (init method):
A. Called once when the applet is first loaded.
B. Used for initialization tasks like setting up variables, loading images, etc.

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() {

// code to start or resume the applet

III. Stopping (stop method):

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() {

// code to stop the applet

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

V. Painting (paint method):


A. Called to draw the applet's user interface.

Syntax:
java
public void paint(Graphics g) {

// code to draw the applet's UI

}
51
Example Applet

java

import java.applet.Applet;

import java.awt.Graphics;

public class SimpleApplet extends Applet {

public void init() {

// initialization code

IL
System.out.println("Applet Initialized");

public void start() {

// start or resume the applet

System.out.println("Applet Started");

}
H
public void stop() {

// stop the applet


SA
System.out.println("Applet Stopped");

public void destroy() {

// cleanup code

System.out.println("Applet Destroyed");

public void paint(Graphics g) {

g.drawString("Hello, Applet!", 20, 20);

}

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

public void paint(Graphics g) {

g.drawString("Hello, Applet!", 20, 20);


H
g.drawLine(30, 40, 100, 100);

g.drawRect(50, 50, 150, 100);

g.drawOval(200, 200, 50, 50);


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;

public class EventHandlingApplet extends Applet {

public void init() {

addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

showStatus("Mouse Clicked at (" + e.getX() + ", " +


e.getY() + ")");

IL
}

});

public void paint(Graphics g) {

g.drawString("Click anywhere inside the applet.", 20, 20);

}
}
H
Example HTML to Run Applet
SA
html

<!DOCTYPE html>

<html>

<head>

<title>Simple Applet</title>

</head>

<body>

<applet code="SimpleApplet.class" width="300" height="300">

</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;

public class FileExample {

public static void main(String[] args) {

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

try {

if (file.createNewFile()) {

System.out.println("File created: " + file.getName());

} else {
55
System.out.println("File already exists.");

} catch (IOException e) {

System.out.println("An error occurred.");

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;

public class ByteStreamExample {

public static void main(String[] args) {

try (FileInputStream fis = new FileInputStream("input.txt");


56
FileOutputStream fos = new
FileOutputStream("output.txt")) {

int data;

while ((data = fis.read()) != -1) {

fos.write(data);

} catch (IOException e) {

IL
e.printStackTrace();

# Filtered Byte Streams ➖


I.
II. Classes:
H
Purpose: Provides additional functionalities like buffering, data conversion, etc.

A. BufferedInputStream: Buffers input for efficient reading.


B. BufferedOutputStream: Buffers output for efficient writing.

Example:
SA
java
import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class FilteredByteStreamExample {

public static void main(String[] args) {

try (BufferedInputStream bis = new BufferedInputStream(new


FileInputStream("input.txt"));

FileOutputStream fos = new


FileOutputStream("output.txt")) {
57
int data;

while ((data = bis.read()) != -1) {

fos.write(data);

} catch (IOException e) {

e.printStackTrace();

IL
}

# Random Access File Class ➖


I. Purpose: Allows reading and writing to a file at any position.
II. Class: RandomAccessFile
III.

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;

public class RandomAccessFileExample {

public static void main(String[] args) {

try (RandomAccessFile raf = new


RandomAccessFile("example.txt", "rw")) {

raf.seek(0); // move the file pointer to the beginning


58
raf.write("Hello".getBytes());

raf.seek(0); // move the file pointer to the beginning

byte[] buffer = new byte[5];

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;

public class CharacterStreamExample {

public static void main(String[] args) {

try (FileReader fr = new FileReader("input.txt");

FileWriter fw = new FileWriter("output.txt")) {

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

SOME PREVIOUS YEAR QUESTIONS PAPER AND THEIR SOLUTIONS OF


BCA FIFTH SEMESTER !

JAVA(5th)Dec2018.pdf

SECTION-A

Q1. Answer briefly :

IL
a) Write the structure of a typical Java program.

b) How command line arguments are passed in a Java program?

c) What is the difference between a class and an object?

d) How arrays are declared in a Java program?


H
e) What are parameterised constructors?

f) What are overriding methods?

g) When do we use protected access specifier?

h) What is an Applet? How is an applet different from an application?


SA
i) What is Inheritance? What are the different forms of inheritance in Java?

j) What is CLASSPATH?

ANSWERS ➖
SECTION-A

Q1. Answer Briefly

a) Write the structure of a typical Java program.

java

// Package declaration (if any)

package com.example;

// Import statements
61
import java.util.Scanner;

// Class declaration

public class Main {

// Main method

public static void main(String[] args) {

// Code to be executed

System.out.println("Hello, World!");

IL
}

// Other methods (if any)

public void exampleMethod() {

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

public class CommandLineExample {

public static void main(String[] args) {

for (String arg : args) {

System.out.println(arg);

}
62
If the program is run with java CommandLineExample arg1 arg2 arg3, the output will be:

arg1

arg2

arg3

c) What is the difference between a class and an object?

● 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?

Arrays in Java can be declared using the following syntax:

Java

// Declaration of an array of integers

int[] numbers;
H
// Allocation and initialization

numbers = new int[5];

// Combined declaration and initialization


SA
int[] numbers = {1, 2, 3, 4, 5};

e) What are parameterised constructors?

Parameterized constructors are constructors that take arguments to initialize an object with
specific values at the time of its creation.

Example:

java

public class Example {

int value;

// Parameterized constructor

public Example(int value) {


63
this.value = value;

public static void main(String[] args) {

Example example = new Example(10);

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() {

System.out.println("Display method in Superclass");


SA
}

class Subclass extends Superclass {

@Override

void display() {

System.out.println("Display method in Subclass");

}
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:

public class Base {

protected int value;

protected void display() {

IL
System.out.println("Value: " + value);

class Derived extends Base {

void show() {
H
display(); // Accessing protected method

value = 10; // Accessing protected field

}
SA
}

h) What is an Applet? How is an applet different from an application?

● 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.

i) What is Inheritance? What are the different forms of inheritance in Java?

● 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?

● CLASSPATH: An environment variable used by the Java runtime system to locate


classes and packages needed for a Java program. It specifies the directories and JAR
files where the Java compiler and JVM should look for class files.

IL
● Setting CLASSPATH: It can be set using the -cp or -classpath command-line option
or by setting the CLASSPATH environment variable.

Example:

sh

# Setting CLASSPATH on Windows


H
set CLASSPATH=C:\myproject\lib\mylibrary.jar;C:\myproject\classes

# Setting CLASSPATH on Unix/Linux

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.

Q4. a) What is Interface in Java? How is interface implemented?

b) What is an abstract class? What is its use in Java?

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.

Differences Between Java and C/C++:

● Platform Independence: Java is platform-independent (write once, run anywhere),


whereas C and C++ are platform-dependent.
● Memory Management: Java manages memory automatically with garbage collection,
while C and C++ require manual memory management.
● Pointers: Java does not support explicit pointers, reducing security risks and complexity.
● Multiple Inheritance: Java does not support multiple inheritance directly (uses interfaces
instead), while C++ supports it.
● Syntax: Java syntax is simpler and more straightforward compared to C++.
● Library Support: Java provides a vast standard library (Java Standard API), while C and
C++ rely on third-party libraries for many functionalities.
67
● Compilation: Java code is compiled into bytecode, which is interpreted by the JVM,
whereas C and C++ code is compiled into machine code specific to the platform.

Q3. What are the various operators available in Java? Discuss each with an example.

Types of Operators in Java:

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;

Q4. a) What is Interface in Java? How is interface implemented?

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();

class Dog implements Animal {

@Override

public void makeSound() {

System.out.println("Bark");

}
69
}

public class Main {

public static void main(String[] args) {

Animal dog = new Dog();

dog.makeSound(); // Output: Bark

IL
b) What is an abstract class? What is its use in Java?

Abstract Class:

● An abstract class is a class that cannot be instantiated and is meant to be subclassed.


● It can contain both abstract methods (without a body) and concrete methods (with a
body).
● Usage: Abstract classes are used to provide a base class with some common

Declaration:
java
Copy code
H
implementation, leaving the specific details to be implemented by subclasses.

abstract class Animal {


SA
abstract void makeSound();

void sleep() {

System.out.println("Sleeping");

Implementation:

● Subclasses must provide the implementation for the abstract methods.

Example:
java
abstract class Animal {

abstract void makeSound();


70
void sleep() {

System.out.println("Sleeping");

class Dog extends Animal {

@Override

void makeSound() {

IL
System.out.println("Bark");

public class Main {


H
public static void main(String[] args) {

Animal dog = new Dog();

dog.makeSound(); // Output: Bark

dog.sleep(); // Output: Sleeping


SA
}

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:

1. Checked Exceptions: Exceptions that are checked at compile time.


○ Example: IOException, SQLException
2. Unchecked Exceptions: Exceptions that are checked at runtime.
○ Example: NullPointerException, ArrayIndexOutOfBoundsException
3. Error: Serious problems that a reasonable application should not try to catch.
71
○ Example: OutOfMemoryError, StackOverflowError

Exception Handling in Java:

● 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

} catch (ExceptionType1 e1) {

// Code to handle ExceptionType1

} catch (ExceptionType2 e2) {


H
// Code to handle ExceptionType2

} finally {

// Code that will always execute

}
SA
Example:

java

public class ExceptionHandlingExample {

public static void main(String[] args) {

try {

int result = 10 / 0; // This will throw


ArithmeticException

} catch (ArithmeticException e) {

System.out.println("ArithmeticException caught: " +


e.getMessage());
72
} finally {

System.out.println("This block always executes");

IL
H
SA
73

JAVA(5th)Dec2017.pdf

SECTION A
Q1. Write briefly:

a) What is an object? How we create it?

● 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

public class Main {


SA
public static void main(String[] args) {

Dog myDog = new Dog(); // Creating an object of class Dog

b) What is Java Virtual Machine?

● 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];

Multi-Dimensional Array (2D Array):


java
Copy code
int[][] matrix = new int[3][3];

Jagged Array:
java
Copy code
int[][] jaggedArray = new int[3][];

IL
jaggedArray[0] = new int[2];

jaggedArray[1] = new int[3];

jaggedArray[2] = new int[4];

d) Write steps to create a package.

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

Use the Package: Import the package in other classes.


java
import com.example.MyClass;

e) Name various branching statements of Java.

● if
● if-else
● else-if
● switch
● break
● continue
75
● return

f) What are wrapper classes?

● 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

g) Demonstrate how parameters are passed to an Applet.

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">

<param name="param1" value="value1">


H
<param name="param2" value="value2">

</applet>

In the Applet:
java
SA
import java.applet.Applet;

import java.awt.Graphics;

public class MyApplet extends Applet {

String param1;

String param2;

public void init() {

param1 = getParameter("param1");

param2 = getParameter("param2");

public void paint(Graphics g) {


76
g.drawString("Param1: " + param1, 20, 20);

g.drawString("Param2: " + param2, 20, 40);

h) Use of control loops in Applets.

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;

public class LoopApplet extends Applet {

public void paint(Graphics g) {


H
for (int i = 0; i < 10; i++) {

g.drawOval(50 + i * 10, 50 + i * 10, 50, 50);

}
SA
}

i) Why Exception handling is done?

● 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.

j) What is Java AWT?

● 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?

Looping Statements in Java:

1. for Loop:
○ Used when the number of iterations is known.

Syntax:
for (initialization; condition; update) {

// body of the loop

IL
}

Example:
for (int i = 0; i < 5; i++) {

System.out.println("i: " + 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) {

System.out.println("i: " + i);

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 {

// body of the loop

} while (condition);

Example:
java
int i = 0;

do {

IL
System.out.println("i: " + i);

i++;

} while (i < 5);

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:

for (initialization; condition; update) {

// body of the loop

Example:
outer: for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

if (i == 1 && j == 1) {

break outer;

System.out.println("i: " + i + ", j: " + j);


79
}

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

int add(int a, int b) {

return a + b;

}
H
double add(double a, double b) {

return a + b;
SA
}

public class Main {

public static void main(String[] args) {

MathOperations mo = new MathOperations();

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

System.out.println(mo.add(5.5, 3.3)); // Calls add(double,


double)

}
80
Method Overriding:

● Definition: A subclass provides a specific implementation of a method that is already


defined in its superclass.
● Purpose: Allows a subclass to offer a specific implementation for a method that is
provided by its superclass.

Example:
class Animal {

void makeSound() {

System.out.println("Animal makes a sound");

IL
}

class Dog extends Animal {

@Override
H
void makeSound() {

System.out.println("Dog barks");

}
SA
public class Main {

public static void main(String[] args) {

Animal myDog = new Dog();

myDog.makeSound(); // Calls Dog's makeSound()

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

public void eat() {

System.out.println("Dog eats");
SA
}

@Override

public void walk() {

System.out.println("Dog walks");

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.eat();
82
myDog.walk();

Process Explanation:

Define Interfaces: Define the interfaces with method signatures.


java
Copy code
interface Animal {

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

class Dog implements Animal, Mammal {


SA
@Override

public void eat() {

System.out.println("Dog eats");

@Override

public void walk() {

System.out.println("Dog walks");

}
83
Use the Class: Create an instance of the class and call the methods.
java
public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.eat();

myDog.walk();

IL
}

Q5. Why Exception handling is required? How it is done?

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.

How Exception Handling is Done:

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 {

// Code that may throw an exception

} catch (ExceptionType1 e1) {

// Handle ExceptionType1

} catch (ExceptionType2 e2) {

// Handle ExceptionType2

Finally Block: A finally block can be used to execute code that must run regardless of
whether an exception occurs.
java
try {

// Code that may throw an exception


84
} catch (ExceptionType e) {

// Handle exception

} finally {

// Code that will always execute

Throwing Exceptions: Use the throw keyword to throw an exception explicitly.


java
if (condition) {

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 {

// Code that may throw an exception

Example:
SA
java

public class ExceptionHandlingExample {

public static void main(String[] args) {

try {

int result = 10 / 0; // This will throw


ArithmeticException

} catch (ArithmeticException e) {

System.out.println("ArithmeticException caught: " +


e.getMessage());

} finally {
85
System.out.println("This block always executes");

Q6. Explain Event delegation. How Action listener class is implemented?

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.

Steps to Implement ActionListener:

1. Implement ActionListener Interface: A class implements the ActionListener


H
interface and overrides the actionPerformed method.
2. Register the Listener: Attach the listener to the event source using the
addActionListener method.

Example:

Java
SA
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class ButtonClickExample implements ActionListener {

JFrame frame;

JButton button;

public ButtonClickExample() {

frame = new JFrame("Event Handling Example");

button = new JButton("Click Me");

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) {

System.out.println("Button was clicked!");

public static void main(String[] args) {

}
H
new ButtonClickExample();

Explanation:
SA
● Implement ActionListener: The ButtonClickExample class implements
ActionListener and overrides actionPerformed.
java
Copy code
public class ButtonClickExample implements ActionListener {

You might also like