0% found this document useful (0 votes)
3 views34 pages

OOP Concepts and Java Basics Guide

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, and polymorphism. It contrasts OOP with Procedure Oriented Programming (POP) and covers Java's structure, data types, type casting, control flow, and input handling using the Scanner class. Additionally, it discusses advanced OOP topics such as inheritance types, polymorphism, and method overloading with examples.

Uploaded by

Nagalikara.Deepa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views34 pages

OOP Concepts and Java Basics Guide

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, and polymorphism. It contrasts OOP with Procedure Oriented Programming (POP) and covers Java's structure, data types, type casting, control flow, and input handling using the Scanner class. Additionally, it discusses advanced OOP topics such as inheritance types, polymorphism, and method overloading with examples.

Uploaded by

Nagalikara.Deepa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit-1: Core Concepts

1. Basic Concept of OOP's

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the


concept of objects. It aims to implement real-world entities like inheritance, hiding,
polymorphism, etc., in programming. The main goal of OOP is to increase the flexibility and
maintainability of programs.

The fundamental concepts of OOP are:

 Class: A blueprint or template from which objects are created. It


specifies the data (variables) and methods (functions) that the objects
of that class will have.
 Object: A real-world entity and an instance of a class. It represents the
state (data) and behavior (methods) defined by the class.
 Encapsulation: The mechanism of binding data (variables) and the
code manipulating that data (methods) together into a single unit
(class). It also helps in data hiding.
 Abstraction: The process of hiding the complex implementation
details and showing only the essential information to the user.
 Inheritance: The mechanism where one class (subclass/child)
acquires the properties and behaviors of another class
(superclass/parent). This promotes reusability.
 Polymorphism: The ability of an object to take on many forms. It
allows a single interface to be used for a general class of actions.

2. Differences between Procedure Oriented and Object-Oriented


Feature Object
Procedure Oriented
Programming (POP) Oriented programming
(OOP)

Focus On procedures On data and objects.


(functions) rather than
data.

Program Division Divided into smaller Divided into smaller


functions. objects.

Approach Top-down approach. Bottom-up approach.

Data Access Data is freely moved and Data is hidden


accessible by external (encapsulated) and
functions. cannot be accessed
externally.
Security Less secure due to global More secure due to
data. data hiding.

Concept Does not support Fully supports


concepts like Inheritance,
Inheritance and Polymorphism,
Polymorphism. Abstraction, and
Encapsulation.
Examples C, Pascal, FORTRAN. Java, C++, Python, C#.

3. Features of OOPs

The primary features (or pillars) of OOPs are:

Encapsulation

Abstraction

Inheritance

Polymorphism

Class

Object

(The explanation for the first four is covered in the answer to “Basic Concept
of OOP’s”.)

4. Structure of Java with example

A basic Java program is structured around a class. The structure typically


includes:

Documentation Section: Comments (e.g., // or /* */).

Package Statement: The first statement, used to declare the package the
class belongs to (e.g., package [Link];).

Import Statements: To include classes from other packages (e.g., import


[Link];).
Class Definition: The main body of the program enclosed within the class
keyword.

Main Method: The entry point for execution (public static void main(String[]
args)).

Example:

// 1. Documentation Section: A simple Java program

Package [Link]; // 2. Package Statement

Import [Link].*; // 3. Import Statement (implicitly imported)

Public class SimpleProgram { // 4. Class Definition

// Instance variables and methods can go here

Public static void main(String[] args) { // 5. Main Method

[Link](“Hello, World!”);

5. Data Types in Java

Java is a statically-typed language, meaning all variables must be declared


before use. Java data types are broadly divided into two categories:

A. Primitive Data Types (8 types)

These are predefined by Java and hold a single, simple value.

Type Default Value Size (Bytes)Range / Purpose

Byte 0 1 Small integer

Short 0 2 Short integer


Int 0 4 Most commonly used integer type

Long 0L 8 Large integer

Float 0.0f 4 Single-precision floating point

Double 0.0d 8 Double-precision floating point (default for decimals)

Char \u0000 2 Single Unicode character

Boolean false varies Logical values (true or false)

B. Non-Primitive (Reference) Data Types

These are created by the programmer and do not hold the actual value but a
reference (address) to the object in memory.

Classes: e.g., String, Scanner, SimpleProgram.

Interfaces: e.g., Runnable, Comparable.

Arrays: e.g., int[], String[].

6. What is mean JVM, JRE, JDK

These three components are crucial for running and developing Java
applications.
7. Types Casting

Type Casting is the process of converting a variable of one data type into
another data type.

A. Widening Casting (Automatic/Implicit)

Converting a smaller data type to a larger data type.

Java performs this automatically and safely as there is no chance of data


loss.

Order: byte -> short -> char -> int -> long -> float -> double.

Example:

Int myInt = 9;

Double myDouble = myInt; // Automatic casting

// myDouble is now 9.0

B. Narrowing Casting (Manual/Explicit)

Converting a larger data type to a smaller data type.

This must be done manually by the programmer using parentheses


(targetType) because there is a potential risk of data loss or loss of precision.

Example:

Double myDouble = 9.78;

Int myInt = (int) myDouble; // Manual casting

// myInt is now 9 (data after the decimal is truncated)

8. Command Line Argument

Command Line Arguments are information that is passed to a Java program


at the time of execution. They are stored as an array of strings and are
accessible inside the main() method through the String[] args parameter.

Syntax in main:

Public static void main(String[] args)

Execution:
If the class is named MyClass:

Java MyClass argument1 argument2 123

In this case, the args array will contain:

Args[0] will be “argument1”

Args[1] will be “argument2”

Args[2] will be “123”

Use: Used for providing initial configuration or input values to the program
without hardcoding them.

9. Operators

Operators are special symbols used to perform operations on variables and


values.

Type Description Examples


Arithmetic Used for mathematical operations. +, -, *, /, % (Modulus)
Used to check relationships (comparison) between == (Equal to), !=, >, <, >=,
Relational
values; returns a boolean. <=
Used to combine conditional statements; returns a
Logical && (AND), `
boolean.
Assignment Used to assign values to variables. =, +=, -=, *=, /=, %=
++ (Increment), --
Unary Requires only one operand.
(Decrement), +, -
condition ? expression1 :
Ternary A conditional operator that takes three operands.
expression2
Bitwise Operates on binary representations (bits) of the data. &, `
Unit-2: Control Flow and IO

1. Conditional Statements

Conditional Statements are used to execute a set of instructions based on


whether a specified condition evaluates to true or false.

Statement Purpose
if Statement Executes a block of code if the condition is true.
Executes one block of code if the condition is true and a different block if it
if-else Statement
is false.
if-else if-else
Used to check multiple conditions sequentially.
Ladder
Used to select one of many code blocks to be executed based on the value of
switch Statement
a single expression.

Int day = 3;

String dayName;

Switch (day) {

Case 1: dayName = “Monday”; break;

Case 2: dayName = “Tuesday”; break;

Default: dayName = “Other Day”;

2. Looping Statements

Looping Statements (or Iteration Statements) are used to execute a block of


code repeatedly until a specific condition is met.

Loop
Description
Type
Used when the number of iterations is known beforehand. It has initialization,
for Loop
condition, and increment/decrement in its header.
while Used when the number of iterations is unknown. The condition is checked at the
Loop beginning of the loop. If the condition is false initially, the loop body never executes.
do-while Similar to while, but the condition is checked at the end of the loop. This guarantees
Loop the loop body will execute at least once, regardless of the condition.
for-each Used specifically to iterate over elements of arrays and collections (Enhanced for
Loop loop).

3. How to create a class, object, method

A. Creating a Class

A class is defined using the class keyword. It serves as a blueprint.// Syntax:


[access_modifier] class ClassName { ... }

Public class Dog {

// Attributes (fields/variables)

String breed;

Int age;

// Methods (functions)

Public void bark() {

[Link](“Woof!”);

C. Creating an Object

An object is an instance of a class, created using the new keyword and the
class’s constructor.

// Syntax: ClassName objectName = new Constructor();

Dog myDog = new Dog(); // Creates an object named ‘myDog’

The object’s properties can be accessed and modified using the dot (.)
operator:

[Link] = “Golden Retriever”;


[Link] = 5;

D. Creating a Method

A method is a block of code that performs a specific task. It is defined inside


a class.

// Syntax: [access_modifier] [return_type] methodName([parameters]) { ... }

Public class Calculator {

Public int add(int a, int b) { // Method definition

Int sum = a + b;

Return sum; // Returns an integer value

3. Define Constructor and its Types

A Constructor is a special type of method that is automatically invoked when


an object of a class is created. Its main purpose is to initialize the object’s
state (set initial values for instance variables).

Key Rules:

The constructor name must be the same as the class name.

It cannot have an explicit return type (not even void).

It cannot be inherited.

Types of Constructors

Default Constructor:

It is a constructor that has no parameters.

If the programmer does not write a constructor, Java inserts a no-argument


default constructor automatically. It initializes numeric fields to 0, boolean to
false, and reference types to null.

<!—end list 

Public class Bike {


// Java provides public Bike() {} if no constructor is written

No-Argument Constructor (User-Defined):

A constructor written by the programmer with no parameters.

<!—end list 

Public class Bike {

String color;

Public Bike() {

Color = “Red”; // Custom initialization

Parameterized Constructor:

A constructor that has one or more parameters.

It allows the programmer to initialize the object with specific values at the
time of creation.

<!—end list 

Public class Bike {

String color;

// Parameterized Constructor

Public Bike(String c) {

Color = c;

// Usage: Bike b = new Bike(“Blue”);


4. Define Array and its Types

An Array is a container object that holds a fixed number of values of a single


data type. It is an index-based data structure, where the first element is at
index 0. Arrays are objects in Java, stored in the heap memory.

Types of Arrays

Single-Dimensional Array:

A list of elements, where each element is referred to by a single index.

Declaration: dataType[] arrayName; (e.g., int[] numbers;)

Initialization: int[] numbers = new int[5]; (size 5)

Literal Initialization: String[] names = {“Alice”, “Bob”, “Charlie”};

Multi-Dimensional Array (e.g., Two-Dimensional):

An array of arrays, often visualized as a table (rows and columns). It requires


two indices to access an element.

Declaration: dataType[][] arrayName; (e.g., int[][] matrix;)

Initialization: int[][] matrix = new int[3][4]; (3 rows, 4 columns)

Jagged Array:

A two-dimensional array where the number of columns in each row can be


different.

<!—end list 

Int[][] jagged = new int[3][];

Jagged[0] = new int[3]; // Row 0 has 3 elements

Jagged[1] = new int[2]; // Row 1 has 2 elements


5. How can you read inputs? Explain with Scanner
Class

In Java, the most common and standard way to read inputs from the user
(from the console) is by using the Scanner class, which is part of the [Link]
package.

Steps to Read Input using Scanner

Import the Class: You must import the Scanner class into your program.

Import [Link];

Create a Scanner Object: Create an instance of the Scanner class, passing


the standard input stream ([Link]) to its constructor.

Scanner scanner = new Scanner([Link]);

Read the Input: Use the appropriate methods of the Scanner object to read
different data types.

Method Purpose
nextInt() Reads the next integer.
nextDouble() Reads the next double.
nextLine() Reads the entire line of text (including spaces).
next() Reads the next token (up to the next whitespace).
nextBoolean() Reads the next boolean value.

Ex:import [Link];

Public class InputExample {

Public static void main(String[] args) {

// 1. Create a Scanner object for reading input

Scanner scanner = new Scanner([Link]);

[Link](“Enter your name: “);


// 2. Read String input

String name = [Link]();

[Link](“Enter your age: “);

// 3. Read Integer input

Int age = [Link]();

[Link](“Hello, “ + name + “. You are “ + age + “ years


old.”);

// 4. Close the scanner (important to free resources)

[Link]();

}
Unit-3: Advanced OOP and Keywords

1. Define Inheritance and its Types

Inheritance is one of the key pillars of OOPs where a new class (the subclass,
child class, or derived class) acquires the properties (fields) and behavior
(methods) of an existing class (the superclass, parent class, or base class).
The keyword used is extends.

Purpose:

Reusability: Code defined in the parent class can be reused by the child
class.

Polymorphism: It enables runtime polymorphism (Method Overriding).

Creating a hierarchy (is-a relationship).

Types of Inheritance in Java

Single Inheritance:

A class inherits from only one superclass.

(Class A \rightarrow Class B)

Multilevel Inheritance:

A chain of inheritance where one class inherits from a second class, which in
turn inherits from a third class.

(Class A \rightarrow Class B \rightarrow Class C)

Hierarchical Inheritance:

Multiple subclasses inherit from a single superclass.

(Class B and Class C \rightarrow Class A)


Note: Java does not support Multiple Inheritance (inheriting from two or more
classes directly) to avoid the “Diamond Problem.” However, it can be
achieved using Interfaces.

2. Define Polymorphism its Types

Polymorphism (Greek for “many forms”) is the ability of a single interface


(method) to be used for a general class of actions. In Java, it allows objects to
be treated as instances of their parent class rather than their actual class.

Types of Polymorphism

Compile-Time Polymorphism (Static Polymorphism):

Achieved through Method Overloading.

The Java compiler determines which method to call at compile time based on
the method signature (number, type, or order of arguments).

Run-Time Polymorphism (Dynamic Polymorphism):

Achieved through Method Overriding.

The Java Virtual Machine (JVM) determines which method to call at runtime
based on the actual object type. This is also called Dynamic Method
Dispatch.

3. Method Overloading with Example

Method Overloading is a feature of Compile-Time Polymorphism where a


class has multiple methods with the same name but different method
signatures.

Rules for Overloading:

Methods must have the same name.

Methods must have different argument lists (different number of arguments,


different data types of arguments, or different order of arguments).

The return type can be the same or different, but a difference in return type
alone is NOT sufficient for overloading.

Example:

Public class Calculator {

// Overload 1: Adds two integers


Public int add(int a, int b) {

Return a + b;

// Overload 2: Adds three integers (different number of arguments)

Public int add(int a, int b, int c) {

Return a + b + c;

// Overload 3: Adds two doubles (different type of arguments)

Public double add(double a, double b) {

Return a + b;

// Compiler decides which ‘add’ to call based on the arguments provided.

4. Method Overriding with Example

Method Overriding is a feature of Run-Time Polymorphism where a subclass


provides a specific implementation for a method that is already defined in its
superclass. This is done to achieve specialized behavior for the subclass.

Rules for Overriding:

The method in the subclass must have the same name, same parameters,
and same return type as the method in the superclass (or a compatible
covariant return type).

The access modifier in the overriding method cannot be more restrictive than
in the overridden method.

The method must be inherited (i.e., not static, final, or private).

The @Override annotation is recommended for clarity.


Example:

Class Vehicle {

Public void run() { // Overridden method

[Link](“Vehicle is running”);

Class Car extends Vehicle {

@Override

Public void run() { // Overriding method

[Link](“Car is running at 100 km/h”);

// Execution:

// Vehicle v = new Car();

// [Link](); // Calls Car’s run() method at runtime (Dynamic Dispatch)

5. Explain about This Keyword

The this keyword is a reference variable in Java that refers to the current
object (the object whose method or constructor is being called).

Uses of this:

To differentiate instance variables from local variables (Most common): When


a parameter name in a method or constructor is the same as an instance
variable, this is used to refer to the instance variable.
Class Student {

String name;

Public Student(String name) {

[Link] = name; // ‘[Link]’ refers to the instance variable

 To invoke the current class method (implicitly or explicitly):


[Link]();
 To invoke the current class constructor: this(arguments); (used for
constructor chaining).
 To pass the current object as an argument in a method call.

6. Explain about Final Keyword


The final keyword in Java is used to restrict the user. It can be applied
to variables, methods, and classes.

Applied
Purpose/Restriction Example
to
Makes the variable a constant. Its value can be initialized only final int
Variable
once and cannot be changed thereafter. MIN_VALUE = 1;
Prevents the method from being overridden by any subclass. This
final void display()
Method guarantees that the implementation of the method is the same
{ ... }
across the inheritance hierarchy.
Prevents the class from being inherited. No other class can extend
final class
Class a final class. This is often used for security and efficiency (e.g.,
MathUtils { ... }
String class).

7. What is an Abstract class and Abstract method with example


Abstract Class
An Abstract Class is a class that is declared with the abstract keyword.
It cannot be instantiated (you cannot create objects of an abstract
class).
It can have constructors, static methods, and instance methods (both
abstract and non-abstract).
Its purpose is to provide a common base and define a template for its
subclasses.
Abstract Method
An Abstract Method is a method that is declared with the abstract
keyword and has no body (it ends with a semicolon).
Any class that contains one or more abstract methods must be
declared an abstract class.
A subclass that inherits an abstract class must provide
implementations (override) for all of its abstract methods, or else the
subclass must also be declared abstract.
Example:

// Abstract Class
Abstract class Shape {
String color;

// Abstract method (no body)


Abstract double getArea();

// Non-abstract method
Public void displayColor() {
[Link](“Color: “ + color);
}
}

// Concrete subclass
Class Circle extends Shape {
Double radius;

Public Circle(double r) {
[Link] = r;
[Link] = “Blue”;
}

// Must implement the abstract method


@Override
Double getArea() {
Return [Link] * radius * radius;
}
}

8. Define Interface
An Interface in Java is a blueprint of a class that can contain only
abstract methods and final and static variables. (Note: From Java 8,
interfaces can also contain default and static methods, and from Java
9, private methods).
It is declared using the interface keyword.
Interfaces define a contract: any class that implements an interface
must implement all the abstract methods defined in that interface.
Interfaces support the concept of multiple inheritance of type (or
behavior).
Key Features:
All fields are implicitly public static final.
All methods are implicitly public abstract (before Java 8).
A class uses the implements keyword to use an interface.
Example:
Public interface Animal {
// public static final int MAX_AGE = 100;
Int MAX_AGE = 100;

// public abstract void eat();


Void eat(); // Abstract method

Void sleep();
}

9. How to implement multiple inheritances using interface


Java does not allow a class to extend more than one class (no multiple
class inheritance) to prevent the Diamond Problem. However, multiple
inheritance of behavior is achieved using Interfaces.
A class can implement any number of interfaces. By implementing
multiple interfaces, the class promises to adhere to the contracts
(methods) defined by all of them, effectively combining their
behaviors.
Example:
Interface Swimmer {
Void swim();
}

Interface Runner {
Void run();
}

// A class can implement both interfaces, achieving multiple


inheritance of behavior
Class Athlete implements Swimmer, Runner {
@Override
Public void swim() {
[Link](“The athlete is swimming.”);
}

@Override
Public void run() {
[Link](“The athlete is running.”);
}
}

// Usage:
// Athlete a = new Athlete();
// [Link](); // Valid
// [Link](); // Valid

10. Define a String. And its functions (like length, reverse etc)
Definition of String
In Java, a String is not a primitive data type but an object that
represents a sequence of characters. It is one of the most used classes
in the Java standard library ([Link]).
Key characteristic: Strings are immutable in Java. Once a String object
is created, its content cannot be changed. Any operation that appears
to modify a String actually creates a new String object.
Important String Functions/Methods

Function Purpose Example


Returns the number of characters in
length() "Hello".length() \rightarrow 5
the string.
Returns the character at the
charAt(int index) "Java".charAt(1) \rightarrow 'a'
specified index.
Returns a new string that is a
"Example".substring(3) \
substring(int beginIndex) substring of this string, starting from
rightarrow "mple"
the specified index to the end.
Returns a new string from the begin
substring(int begin, int "Example".substring(0, 3) \
index (inclusive) to the end index
end) rightarrow "Exa"
(exclusive).
Compares this string to the specified
"a".equals("A") \rightarrow
equals(Object another) object. It returns true only if the
false
content is the same.
equalsIgnoreCase(String Compares two strings, ignoring case "a".equalsIgnoreCase("A") \
another) considerations. rightarrow true
Concatenates the specified string to
"Hi".concat(" there") \
concat(String str) the end of this string (same as +
rightarrow "Hi there"
operator).
Converts all characters in the string "JAVA".toLowerCase() \
toLowerCase()
to lowercase. rightarrow "java"
Converts all characters in the string "java".toUpperCase() \
toUpperCase()
to uppercase. rightarrow "JAVA"
Returns a copy of the string, with
" test ".trim() \rightarrow
trim() leading and trailing whitespace
"test"
removed.
Returns the index within this string
"banana".indexOf("an") \
indexOf(String str) of the first occurrence of the
rightarrow 1
specified substring.
Returns true if the string contains "abc".contains("b") \rightarrow
contains(CharSequence s)
the specified sequence of characters. true
Unit-4: Packages and Threads

1. Define Package

A Package in Java is a mechanism used to group related classes, interfaces,


and sub-packages. Think of it as a folder or directory in a file system.

Purpose and Benefits:

Naming Conflict Prevention: Packages allow classes with the same name to
exist, provided they are in different packages (e.g., [Link] and
[Link]).

Access Protection: Packages help to implement controlled access by


providing different protection levels (public, private, protected,
default/package-private).

Modularity and Organization: They make programs easier to maintain and


manage by organizing related code into logical units.

Declaration: A package is declared using the package keyword as the first


non-comment statement in a Java source file.

// Syntax

Package [Link];

2. Types of Packages

Java packages are primarily classified into two types:

1. Built-in Packages (Java API Packages)

These are predefined packages that come bundled with the Java
Development Kit (JDK) and contain a vast collection of classes to perform
common operations. They are also known as Standard Packages.
[Link]: Contains fundamental classes that are automatically imported into
every Java program (e.g., Object, String, System, Math, Wrapper Classes).

[Link]: Used for input/output operations, such as reading from or writing to


files and streams.

[Link]: Contains utility classes like the Collections Framework (ArrayList,


HashMap), date/time facilities, and the Scanner class.

[Link]: Used for networking operations.

[Link] and [Link]: Used for Graphical User Interface (GUI)


programming.

2. User-Defined Packages

These are packages created by the programmer to group their own classes
and interfaces. They follow the same naming conventions as built-in
packages and are typically named using the reverse domain name
convention (e.g., [Link]).

3. How to create user defined package

Creating and using a user-defined package involves three main steps:

Step 1: Create the Source File with Package Declaration

Use the package keyword as the first statement in your Java file.

// File: [Link]

Package [Link];

Public class Calculator {

Public int add(int a, int b) {

Return a + b;

Step 2: Compile and Create the Package Directory Structure


[Link] must first create the directory structure that matches the package
name (e.g., com/mycompany/calc).

[Link] the Java file using the -d flag, which tells the compiler to place the
generated .class file in the specified directory structure.

Javac -d . [Link]

# The ‘.’ Means place the directory structure in the current directory.

This creates the structure: ./com/mycompany/calc/[Link].

Step 3: Use the Package in Another File

To use the class from this package in another Java file, you must either use
its fully qualified name or use the import statement.

// File: [Link]

Import [Link]; // Import the class

Public class Test {

Public static void main(String[] args) {

Calculator c = new Calculator();

Int result = [Link](5, 7);

[Link](“Result: “ + result);

4. Define Thread

A Thread is the smallest unit of execution within a program. It is a lightweight


process that can run concurrently with other threads within the same
program. A single program can have multiple threads running at the same
time, allowing for parallel execution and maximum utilization of the CPU.
Multithreading: The capability of a program to execute multiple threads
concurrently.

Process vs. Thread: A process is a program in execution and has its own
separate memory space. Threads, however, share the memory space (heap
memory) of the process they belong to, which makes context switching
between threads faster and cheaper than switching between processes.

5. Life cycle of Thread

A thread goes through several distinct stages from its creation to its
termination. This sequence of stages is called the Thread Life Cycle.

New: The thread is created (new Thread()), but it has not yet started to
execute. It remains in this state until the program starts the thread.

Runnable (Ready-to-Run): The thread is ready to run and is waiting for the
CPU time (waiting to be selected by the Thread Scheduler). When a thread
invokes the start() method, it moves from New to Runnable.

Running: The Thread Scheduler has selected the thread, and it is actively
executing its task (i.e., the run() method).

Blocked / Waiting / Timed Waiting: The thread is temporarily inactive and not
eligible to run. It transitions here when:

It calls the sleep() method (Timed Waiting).

It calls the wait() method (Waiting).

It is waiting to acquire a lock (monitor) to enter a synchronized block


(Blocked).

It is waiting for an I/O operation to complete.

Terminated (Dead): The thread finishes its execution, either normally (when
the run() method completes) or abnormally (e.g., due to an unhandled
exception). Once a thread is terminated, it cannot be resurrected (restarted).

6. How many ways to create a Thread with Example

There are two primary ways to create a thread in Java:

1. By Extending the Thread Class

A class can inherit from the built-in [Link] class and override its
run() method, which contains the code that the thread will execute.
Example:

Class MyThread extends Thread {

@Override

Public void run() {

[Link](“Thread created by extending Thread class.”);

// Usage

MyThread t1 = new MyThread();

[Link](); // Moves thread to Runnable state

Limitation: Since Java does not support multiple inheritance of classes, if


your class is already extending another class, you cannot use this method.

2. By Implementing the Runnable Interface

A class can implement the [Link] interface, which contains a


single abstract method, run().

Example:

Class MyRunnable implements Runnable {

@Override

Public void run() {

[Link](“Thread created by implementing Runnable


interface.”);

// Usage

MyRunnable r = new MyRunnable();


Thread t2 = new Thread(r); // Pass the Runnable object to the Thread
constructor

[Link]();

Advantage: This is the preferred method as it allows your class to still extend
another class (and hence avoid the single inheritance limitation). The class
only implements the run behavior, while the Thread class handles the actual
threading logic.

Unit-5: Exception Handling and Applets

1. Define Exception

An Exception is an event that occurs during the execution of a program (at


runtime) that disrupts the normal flow of the program’s instructions.

When an exception occurs, the Java runtime environment creates an


Exception Object that contains information about the error (type, state of the
program when the error occurred, etc.). If this exception object is not
properly handled, the program will terminate abnormally.

Purpose of Exception Handling: To provide a mechanism to handle these


runtime errors gracefully, allowing the program to continue execution or exit
in a controlled manner, thus ensuring robustness.

2. Explain Types of Exception

In Java, all exception and error classes are derived from the
[Link] class. Throwable has two main subclasses: Exception
and Error.

1. Errors

These represent serious problems that are generally beyond the control of
the program (e.g., hardware failure, system crashes, running out of
memory).

Errors are unchecked (the compiler doesn’t force handling).


Example: OutOfMemoryError, StackOverflowError.

2. Exceptions

These represent problems that the program can often anticipate and handle.
They are further categorized:

A. Checked Exceptions (Compile-Time Exceptions)

These are exceptions that the compiler forces you to handle (using try-catch
or by declaring them with throws).

They typically represent external conditions that are predictable but beyond
the program’s control.

They inherit from the Exception class but not from RuntimeException.

Example: IOException (file not found), SQLException.

B. Unchecked Exceptions (Runtime Exceptions)

These are exceptions that the compiler does not force you to handle.

They usually occur due to programming errors or bad logic.

They inherit from the RuntimeException class.

Example: ArithmeticException (division by zero), NullPointerException,


ArrayIndexOutOfBoundsException.

3. Types of Errors (Built-in, User defined)

The term Errors usually refers to the severe, unrecoverable problems covered
in the [Link] class hierarchy (like OutOfMemoryError). However,
when discussing the source of problems in a program, we consider three
types:

1. Compile-Time Errors (Syntax Errors)

These are errors detected by the Java compiler before the program is
executed.

They result from violating Java’s grammatical rules (syntax).

The program cannot be compiled until these errors are fixed.

Example: Missing a semicolon, incorrect keyword usage.


2. Runtime Errors (Exceptions)

These occur during the execution of the program and are the primary focus
of Java Exception Handling.

They stop the normal flow of execution (e.g., NullPointerException).

3. Logical Errors

These are errors in the program’s design or logic, where the program runs
without crashing but produces incorrect or unexpected output.

These are the hardest to debug as they don’t throw an exception.

Example: Using addition where multiplication was required, infinite loops.

4. What is Exception handling? Explain with Example

Exception Handling is the mechanism in Java that manages runtime errors


gracefully. It is a structured way to separate the error-handling code from the
regular programming logic, ensuring that the program can recover from
errors or terminate safely.

The core tools for Java exception handling are the keywords try, catch,
finally, and throw.

Example: Handling division by zero, which causes an ArithmeticException.

Public class ExceptionHandlingExample {

Public static void main(String[] args) {

Int numerator = 10;

Int denominator = 0; // This will cause an exception

Try {

// The code block where an exception might occur

Int result = numerator / denominator;

[Link](“Result: “ + result); // This line is skipped if


exception occurs

} catch (ArithmeticException e) {
// The code block that executes if an ArithmeticException is caught

[Link](“An error occurred: Cannot divide by zero.”);

// [Link]() provides the details of the exception

} catch (Exception e) {

// A generic catch block to handle any other unexpected exceptions

[Link](“A different, unexpected error occurred.”);

} finally {

// The code block that always executes, regardless of whether

// an exception occurred or was caught. (Used for cleanup)

[Link](“Execution of the division attempt is complete.”);

5. Explain about try, catch, finally block with example

These three blocks are the fundamental components of Java’s structured


exception handling mechanism.

Keyword Purpose Placement


Contains the code segment that is expected to
A try block must be followed by at
throw an exception. If an exception occurs, the
try least one catch block or a finally
execution immediately jumps to the corresponding
block.
catch block.
Contains the code that is executed when an
There can be multiple catch blocks
exception of a particular type is thrown in the try
catch (multi-catch) following a single
block. It takes the exception object as an
try block.
argument.
Used primarily for cleanup
Contains code that is always executed after the try
operations like closing files,
finally block and any catch blocks, regardless of whether
database connections, or network
an exception was thrown, caught, or not caught.
sockets.
(The structure and example are provided in the answer to “What is Exception
handling?” above.)

6. Explain Life cycle of Applet

An Applet is a small Java program designed to be included in an HTML web


page and executed by a Java-enabled web browser. Applets are largely
obsolete today, replaced by JavaScript and other web technologies.

The Applet life cycle is managed by the browser or the Applet Viewer and
consists of four main stages, represented by five key methods:

Init():

Purpose: Initialization phase. This method is called only once when the applet
is first loaded.

Action: Used to set up initial conditions, initialize variables, load images, and
set parameters.

Start():

Purpose: Begins execution. This method is called every time the applet is
started (e.g., when the user navigates to the page or restores a minimized
window).

Action: Used to start the applet’s normal execution, such as starting threads
or playing audio.

Paint(Graphics g):

Purpose: Drawing phase. This method is called whenever the applet needs to
be redrawn.
Action: Used for all graphic output. It is implicitly called after init() and
start(), and whenever the applet is resized or uncovered.

Stop():

Purpose: Pauses execution. This method is called when the applet is


temporarily stopped (e.g., when the user navigates away from the page).

Action: Used to suspend execution threads or stop computationally


expensive operations.

Destroy():

Purpose: Clean-up phase. This method is called only once when the applet is
about to be terminated and removed from memory (e.g., when the browser
closes).

Action: Used to release resources, close files, and perform final cleanup

7. Discuss the steps involved in developing and running a remote Applet

Developing and running a remote Applet (one loaded from a web server)
involves the following steps:

Step 1: Development (Writing the Java Code)

[Link] the Applet Class: Create a Java class that extends [Link]
and implements the necessary life cycle methods (init(), start(), paint(), etc.).

[Link] the Applet: Compile the .java file into a .class file using the Java
compiler (javac).

Javac [Link]

Step 2: Packaging (Creating the JAR File)

[Link] an applet may consist of multiple .class files and resource files
(images, audio), it is packaged into a Java Archive (JAR) file for efficient
deployment and faster loading over a network.

[Link] the jar tool to bundle the compiled class file(s).

Jar cf [Link] [Link]

Step 3: Deployment (Placing on the Web Server)

Upload the generated [Link] file to a public directory on a web server.


Step 4: HTML Integration

Create an HTML file ([Link]) that uses the <applet> tag (or the modern
<object> tag) to embed the applet.

<applet code=”[Link]”

Archive=”[Link]”

Width=”300”

Height=”200”>

Applet failed to load.

</applet>

 Code: Specifies the name of the main .class file.


 Archive: Specifies the name of the JAR file containing the class.

Step 5: Running the Remote Applet

[Link] via Browser: The user opens the [Link] file using a Java-
enabled web browser. The browser contacts the web server, downloads
the [Link] file, and the browser’s Java Virtual Machine (JVM)
executes the applet code locally.

[Link] via Applet Viewer (Local Testing): Before deployment, the Applet
can be tested locally using the appletviewer tool by placing the <applet>
tag inside comments in the Java source file or in a separate HTML file.

Appletviewer [Link]

You might also like