0% found this document useful (0 votes)
22 views55 pages

Java Programming Unit 1 Notes

The document provides a comprehensive overview of Object-Oriented Programming (OOP) and Java, detailing core concepts such as encapsulation, inheritance, polymorphism, and abstraction. It explains Java's features, including its simplicity, platform independence, security, and robustness, while also discussing the architecture and structure of Java programs. Additionally, it highlights the advantages of OOP in Java, emphasizing modularity, reusability, and maintainability in software development.

Uploaded by

R.Venkadesh
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)
22 views55 pages

Java Programming Unit 1 Notes

The document provides a comprehensive overview of Object-Oriented Programming (OOP) and Java, detailing core concepts such as encapsulation, inheritance, polymorphism, and abstraction. It explains Java's features, including its simplicity, platform independence, security, and robustness, while also discussing the architecture and structure of Java programs. Additionally, it highlights the advantages of OOP in Java, emphasizing modularity, reusability, and maintainability in software development.

Uploaded by

R.Venkadesh
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

JAVA PROGRAMMING

UNIT-I INTRODUCTION TO OOP AND JAVA


Overview of OOP – Object oriented programming paradigms – Features of Object Oriented
Programming – Java Buzzwords – Overview of Java – Data Types, Variables and Arrays – Operators
– Control Statements – Programming Structures in Java – Defining classes in Java –
Constructors-
Methods -Access specifiers - Static members- Java Doc comments
INTRODUCTION TO OOP AND JAVA :-
Object-Oriented Programming (OOP) is a powerful programming paradigm that
organizes software design around objects, which contain both data (attributes) and functions
(methods). OOP makes programs modular, reusable, secure, and easier to maintain, which is
why it is widely used in modern software development.

1. Core Concepts of OOP


OOP is built on four major principles:

a) Encapsulation
 Encapsulation means binding data and methods into a single unit (i.e., a class).
 It protects data from unauthorized access using access modifiers like private,
public, protected.

b) Inheritance
 Inheritance allows a class to acquire the properties and behaviors of another class.

 It promotes code reuse and establishes a natural hierarchical relationship.

c) Polymorphism
 It allows the same function or method to behave differently in different situations.

 Two types:
o Compile-time polymorphism (method overloading)

o Runtime polymorphism (method overriding)


d) Abstraction
 Abstraction shows only essential features and hides the internal implementation.
 Implemented using abstract classes and interfaces.

1
2. Features of OOP
OOP enhances programming by offering:
 Modularity – code broken into classes

 Reusability – through inheritance


 Security – through encapsulation

 Flexibility – due to polymorphism


 Maintainability – clean structure and separation of concerns

INTRODUCTION TO JAVA

Java is a high-level, object-oriented, platform-independent programming language


developed by Sun Microsystems (now Oracle) in 1995. Java follows the principle “Write
Once, Run Anywhere (WORA)” because Java programs run on the Java Virtual Machine
(JVM).

1. Features of Java
a) Simple
Java syntax is easy to learn and similar to C/C++ but avoids complex parts like pointers.

b) Object-Oriented
Everything in Java is written using classes and objects, making it a pure OOP language (except
primitive types).
c) Platform Independent
Java programs compile into bytecode, which can run on any platform using JVM.

d) Portable
Same Java code works on different operating systems without modification.

e) Secure
Java provides a secure execution environment using
 Bytecode verification

 Exception handling
 Absence of pointer manipulation

f) Robust
Java focuses on memory management, garbage collection, and strong exception
handling.

2
g) Multithreaded
Java supports multiple tasks executing simultaneously using the Thread class and
Runnable interface.

h) Distributed
Java supports distributed computing using RMI and network APIs.

2. Java Architecture
The Java architecture has three main parts:

a) Java Compiler (javac)


 Converts .java source code into bytecode (.class).

b) Java Virtual Machine (JVM)


 Executes bytecode

 Provides platform independence

c) Java Runtime Environment (JRE)


 Contains JVM + libraries required to run Java applications.

3. Java Program Structure


A simple Java program consists of:
 Class declaration

 Main method: public static void main(String[] args)

 Statements and methods


Example:
class Hello {
public static void main(String[] args)
{ [Link]("Hello Java");
}

4. Why OOP and Java Work Perfectly Together


Java is designed around OOP, so concepts like classes, objects, inheritance, and
polymorphism are naturally supported. This leads to:
 Better software design

 Easy scalability
 Faster development

3
 High security and modularity

OVERVIEW OF OBJECT-ORIENTED PROGRAMMING (OOP):-


Object-Oriented Programming (OOP) is a programming paradigm that organizes
software design around objects rather than functions or logic. It models real-world entities as
objects that contain both data (attributes) and behavior (methods). OOP improves
modularity, reusability, and maintainability, making it a dominant approach in modern
software development.

1. Basic Concepts of OOP

1.1 Class
 A class is a blueprint or template for creating objects.
 It defines properties (data members) and methods
(functions). Example:
class Car { String color; void start(){} }

1.2 Object
 An object is an instance of a class.
 It represents real-world entities with state and
behavior. Example:
Car c1 = new Car();

1.3 Data Abstraction


 Abstraction hides unnecessary details and shows only essential features.
 Implemented through abstract classes and interfaces.

1.4 Encapsulation
 Binding data and methods into a single unit (class).

 Data hiding is achieved using access modifiers, ensuring security.

1.5 Inheritance
 Enables one class to acquire properties and methods of another.
 Promotes code reuse and creates a natural
hierarchy. Types include:
 Single
 Multilevel

 Hierarchical
 Hybrid (using interfaces)

4
1.6 Polymorphism
 Ability to perform a single operation in different
ways. Types:
 Compile-time (Method Overloading)

 Runtime (Method Overriding)


2. Additional OOP Elements

2.1 Message Passing


 Objects communicate by sending messages (method calls).

 Encourages interaction between objects to achieve a task.

2.2 Dynamic Binding


 Code to be executed is decided at runtime, not compile time.

 Supports flexibility and late binding.


2.3 Object Identity
 Each object has its own unique identity even if its data is identical to another object.

3. Advantages of OOP

a) Modularity
 Code is divided into small independent classes, making development easier.

b) Reusability
 Inheritance allows reuse of existing code, reducing duplication.

c) Maintainability
 Easy to update and modify code due to clear structure.

d) Security
 Encapsulation protects sensitive data by restricting access.

e) Flexibility
 Polymorphism allows different behaviors using the same interface.

f) Real-world Modeling
 Programs map directly to real-world entities, improving clarity.

4. Applications of OOP
OOP is used in:
 Software engineering

 GUI applications

5
 Mobile app development

 Game development
 Simulation and modeling

 Distributed and database applications

OBJECT-ORIENTED PROGRAMMING PARADIGMS:-


Object-Oriented Programming (OOP) is the foundational programming model of
Java. Java was designed from the ground up based on objects, and its entire architecture
revolves around representing real-world entities as software objects. The OOP paradigm in
Java brings structure, modularity, reusability, and flexibility to application development.

1. CLASS AND OBJECT

Class
 A class is a blueprint or template that defines attributes (data) and
methods (functions).
 It represents a logical structure.

Object
 An object is an instance of a class.
 It contains a unique identity, state (variables), and behavior
(methods). Example:
class Student
{ int roll;
void display() {}
}

Student s1 = new Student();

6
2. ENCAPSULATION
 Encapsulation is the process of binding data and methods into one unit (class).
 It protects data using private access modifiers.

 Achieved through getters and setters, promoting data security and


control. Example:
private int age;
public void setAge(int a) { age = a; }

3. INHERITANCE
 Inheritance allows one class to acquire properties and methods from another.
 It promotes code reusability and creates hierarchical relationships.

 Java supports:
o Single inheritance

o Multilevel inheritance
o Hierarchical inheritance

o Multiple inheritance through interfaces


Example:

class A {}
class B extends A {}

4. POLYMORPHISM
Polymorphism enables one interface, many implementations.
Types:
1. Compile-time polymorphism – Achieved through method overloading.
2. Runtime polymorphism – Achieved through method overriding using
inheritance. Example:
void show(int a) {}
void show(double b) {}
5. ABSTRACTION
 Abstraction focuses on exposing essential details while hiding internal
implementation.
 Achieved in Java using:

7
o Abstract classes

o Interfaces
This helps reduce complexity and improve flexibility.

6. MESSAGE PASSING
 Objects communicate with each other using method calls.

 This enhances modularity and interaction between


components. Example:
[Link]();
[Link]();
7. DYNAMIC BINDING (LATE BINDING)
 The method to be executed is decided at runtime, not at compile time.
 Supports runtime
polymorphism. Example:
Animal a = new Dog();

[Link](); // Dog’s implementation runs

8. OBJECT IDENTITY
 Each object has a unique identity in memory.
 Even if two objects hold the same values, they are different entities unless
referenced by the same variable.

9. OOP SUPPORT IN JAVA


Java strongly enforces OOP through the following mechanisms:
 Packages for modularization

 Access modifiers for data hiding


 Constructors for object initialization

 Garbage collection for memory management

Advantages of OOP Paradigms in Java


 Modularity – program is divided into classes
 Reusability – inheritance promotes code reuse

 Security – encapsulation protects sensitive data


 Flexibility – polymorphism makes programs adaptable

 Maintainability – clear structure simplifies debugging and updates

8
FEATURES OF OBJECT-ORIENTED PROGRAMMING :-
Java is a pure object-oriented programming language (except primitive types) and
supports all major OOP features that make software development modular, flexible, secure,
and reusable. These features allow Java programs to model real-world systems efficiently.
1. Class
A class is the fundamental building block in Java.
It acts as a blueprint that defines:
 Data (fields)

 Behaviour (methods)
A class provides the structure for creating multiple objects with similar properties.

2. Object
Objects are runtime entities created from classes.
Each object has:

 State (values of variables)


 Behavior (methods)

 Identity (unique memory address)


Objects represent real-world entities, making Java programs intuitive and realistic.

3. Encapsulation
Encapsulation means wrapping data and methods inside a single unit (class) and
restricting direct access to internal data.
Java achieves encapsulation using:

 private variables

 public getters/setters
It ensures data security, prevents misuse, and promotes controlled access.

4. Inheritance
Inheritance allows a class (child) to reuse the properties and methods of another class
(parent).
Benefits include:
 Code reuse

 Reduced redundancy
 Easy extension of existing classes

9
Java supports:

 Single
 Multilevel

 Hierarchical inheritance
 Multiple inheritance via interfaces

5. Polymorphism
Polymorphism means same action, different behaviors.

Types in Java:
 Compile-time polymorphism (Method Overloading)
 Runtime polymorphism (Method Overriding)

It enhances flexibility, allowing one interface to handle multiple forms.

6. Abstraction
Abstraction hides complex internal details and shows only essential features.
Achieved using:

 Abstract classes

 Interfaces
It simplifies complex systems by focusing only on necessary information.

7. Dynamic Binding (Late Binding)


In Java, method calls are often resolved at runtime, not compile time. Dynamic
binding supports:
 Runtime polymorphism
 Flexible and dynamic

behavior Example:
A parent class reference pointing to a child class object executes the child’s overridden
method.
8. Message Passing
Objects communicate with each other via method calls, similar to sending messages. This
promotes modular design where objects interact to complete tasks.
9. Object Identity
Every object has a unique identity in memory.
Even if two objects have identical data, they are considered different unless they
reference the same memory location.

10
10. Persistence (Using Memory & Storage)
Java supports persistence through mechanisms like:
 Object serialization

 File handling
 Databases
This allows objects to outlive program execution.

11. Modularity
Through classes, objects, and packages, Java breaks programs into modules, improving:

 Organization
 Testing
 Maintainability

Advantages of OOP Features in Java


 Reusability of code through inheritance

 Security through encapsulation


 Flexibility via polymorphism

 Reduced complexity using abstraction


 Easy maintenance and updates

 Natural mapping to real-world problems

11
JAVA BUZZWORDS:-
Java is described using a set of powerful characteristics known as Java Buzzwords. These
buzzwords highlight the design goals, features, and strengths of the Java programming
language. They explain why Java became so popular for modern software development.
Below are the most important Java buzzwords explained in detail:

1. Simple
Java is easy to learn because its syntax is clean and similar to C/C++ but without
complex features like pointers, multiple inheritance, and memory management.
This reduces programmer errors and makes coding smooth.

2. Object-Oriented
Java is built on the principles of classes and objects.
Everything revolves around:
 Encapsulation

 Inheritance
 Abstraction
 Polymorphism

This makes Java modular and easier to maintain.

3. Distributed
Java supports distributed computing through:
 Remote Method Invocation (RMI)

 Networking packages
 Web technologies
This enables Java programs to run across networks easily.

4. Robust
Java focuses strongly on reliability. It eliminates major error-prone areas.
Features that make Java robust:
 Automatic garbage collection
 Strong type checking

 Exception handling
 No pointer manipulation

12
5. Secure
Security is a major design goal of Java. Java
provides:
 Bytecode verification

 Sandboxed execution
 No direct memory access

 Access control and security manager


This made Java ideal for web applications and distributed systems.

6. Portable
Java programs run the same on any platform.
The .class file (bytecode) is platform-independent, so you don’t need to change the code for
different OS environments.

7. Platform Independent
Java achieves platform independence using the Java Virtual Machine (JVM).
Source code → Bytecode → Runs on any JVM
This is known as WORA (Write Once, Run Anywhere).

8. Multithreaded
Java supports multiple tasks running simultaneously (threads).
Built-in multithreading makes Java perfect for:
 Games
 Animations

 Servers
 Real-time applications

9. Architecture Neutral
Java bytecode is not dependent on processor architecture.
This ensures Java programs behave consistently across all systems.

10. Interpreted
Java programs are executed by the JVM, which interprets bytecode line by line. This
makes debugging and testing easier.

11. High Performance


Java uses Just-In-Time (JIT) compilers, allowing bytecode to convert into native machine code
at runtime.
This improves speed significantly.

13
12. Dynamic
Java programs can adapt to changes at runtime.
Features include:
 Loading classes dynamically

 Linking libraries during execution


 Reflection API

This flexibility supports large, evolving applications.

OVERVIEW OF JAVA :-
Java is a high-level, object-oriented, platform-independent programming language
developed by Sun Microsystems in 1995 (now owned by Oracle). Java was created with the
goal of building secure, portable, and robust applications for a wide range of platforms. Its
motto “Write Once, Run Anywhere (WORA)” transformed software development by
ensuring that Java programs can run on any system equipped with a Java Virtual Machine
(JVM).

1. History and Evolution


 Developed by James Gosling at Sun Microsystems.
 Originally called Oak, later renamed Java.

 Designed mainly for embedded systems but quickly expanded to web, enterprise,
and mobile applications.
 Today Java is maintained by Oracle and widely used worldwide.

2. Java Architecture
Java programs follow a unique architecture that ensures platform independence:

a) Java Compiler (javac)


 Converts source code (.java) into bytecode (.class files).

14
b) Java Virtual Machine (JVM)
 Executes bytecode
 Provides platform independence

 Handles memory management, security, and garbage collection

c) Java Runtime Environment (JRE)


 Includes the JVM + essential libraries needed to run Java programs.

d) Java Development Kit (JDK)


 Contains JRE + development tools like compiler, debugger, documentation generator.

3. Features of Java (Buzzwords)


Java is built on several powerful features:

i) Simple
Easy syntax, no pointers, automatic memory management.

ii) Object-Oriented
Classes, objects, inheritance, encapsulation, abstraction, polymorphism.

iii) Platform Independent


Bytecode runs on any JVM.

iv) Portable
Java programs behave the same on all platforms.

v) Secure
No direct memory access, security manager, bytecode verifier.

vi) Robust
Strong memory management, exception handling.

vii) Multithreaded
Supports concurrent execution using threads.

viii) High Performance


JIT compiler improves runtime performance.

ix) Distributed
Supports RMI, networking APIs.

x) Dynamic
Loads classes at runtime and supports adaptive programs.

15
4. Java Program Structure
A typical Java program contains:

 Class definition
 Main method: public static void main(String[] args)

 Statements and methods


Example:
class Example {

public static void main(String[] args)


{ [Link]("Hello Java");
}
}

5. Java Editions
Java comes in three major editions:

a) Java SE (Standard Edition)


Core libraries, basic programming, desktop apps.

b) Java EE (Enterprise Edition)


Web applications, enterprise systems, Servlets, JSP, EJB.

c) Java ME (Micro Edition)


Mobile and embedded device applications.
6. Applications of Java
Java is used in a wide range of domains:
 Web applications

 Mobile apps (Android)


 Desktop software

 Cloud computing
 Enterprise systems

 Gaming and simulations


 IoT devices
Its stability and scalability make it ideal for large, long-term projects.

16
DATA TYPES, VARIABLES AND ARRAYS:-
Java is a strongly typed and object-oriented programming language. Every value stored
in Java must have a specific data type, accessed through variables, and structured using
arrays when working with collections of similar data. These three components form the
foundation of Java programming.
1. DATA TYPES IN JAVA
Java supports two major categories of data types:

A. Primitive Data Types


Primitive types store simple values directly in memory. There are 8 primitives:

1. Byte
 1 byte
 Range: –128 to +127
 Used for saving memory

2. Short
 2 bytes

 Range: –32,768 to 32,767

3. Int
 4 bytes
 Default integer type

4. Long
 8 bytes

 Used for large integer values

5. Float
 4 bytes

17
 Single-precision decimal values

6. Double
 8 bytes

 Double-precision decimal values (default for floating numbers)

7. Char
 2 bytes (Unicode)
 Stores a single character

8. Boolean
 Represents true or false
These primitive data types allow efficient memory usage and faster execution.

B. Non-Primitive (Reference) Data Types


These store references to memory locations, not actual values.
Examples include:
 Strings

 Arrays
 Classes

 Objects
 Interfaces
They are created using the new keyword and are more flexible than primitives.

2. VARIABLES IN JAVA
A variable is a named memory location that holds a value. Java uses variables to store
data during program execution.

A. Types of Variables
1. Local Variables
 Declared inside methods, constructors, or blocks
 Must be initialized before use

 Scope is limited to the block where declared

2. Instance Variables
 Declared inside a class but outside methods
 Each object has its own copy

 Represent object properties

18
3. Static Variables
 Declared using the static keyword
 Shared by all objects of a class

 Memory allocated only once

B. Variable Declaration and Initialization


int age = 20;
double price = 99.99;
String name = "Java";
Variables store data of specific types and are essential for computations and data manipulation.
3. ARRAYS IN JAVA
An array is a fixed-size data structure used to store multiple values of the same type in a
contiguous memory location.

A. Types of Arrays
1. One-Dimensional Array
Stores a list of elements.

int marks[] = {90, 80, 85, 95};

2. Two-Dimensional Array
Stores data in rows and columns (matrix form). int
matrix[][] = {{1,2,3},{4,5,6}};

3. Multidimensional Arrays
Arrays of arrays with more dimensions.

B. Array Declaration and


Initialization Declaration
int arr[];

Creation
arr = new int[5];

Declaration + Creation + Initialization


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

19
C. Characteristics of Arrays
 Fixed size (cannot grow or shrink)
 Index-based access (starting at 0)

 Homogeneous elements (same data type)


 Stored in continuous memory

 Accessed using loops (for, foreach)

D. Advantages of Arrays
 Easy to store large data sets

 Fast access using index


 Useful for mathematical and tabular data

OPERATORS:-
Operators in Java are symbols used to perform operations on variables and values. They
are essential for building expressions, decision making, and logical processing in programs.
Java provides several categories of operators, each designed for specific types of operations.

1. Arithmetic Operators
Used for basic mathematical calculations.

Operators: + - * / %

Program: Arithmetic Operators


public class ArithmeticDemo {
public static void main(String[] args) {
int a = 15, b = 4;
[Link]("Addition: " + (a + b));
[Link]("Subtraction: " + (a - b));

20
[Link]("Multiplication: " + (a * b));
[Link]("Division: " + (a / b));
[Link]("Modulus: " + (a % b));

}
}

2. Relational Operators
Used to compare two values, result is boolean.
Operators: == != > < >= <=
Program: Relational Operators
public class RelationalDemo {

public static void main(String[] args) {


int x = 10, y = 20;
[Link](x == y);
[Link](x != y);
[Link](x > y);
[Link](x < y);
[Link](x >= y);
[Link](x <= y);
}

3. Logical Operators
Used to connect multiple conditions.
Operators: && || !

Program: Logical Operators


public class LogicalDemo {

public static void main(String[] args) {


boolean a = true, b = false;
[Link](a && b);
[Link](a || b);
[Link](!a);
}}
21
4. Assignment Operators
Used to assign values to variables.
Operators: = += -= *= /= %=
Program: Assignment
Operators public class
AssignmentDemo {
public static void main(String[] args) {
int a = 10;
a += 5;

a -= 3;
a *= 2;

a /= 3;
[Link]("Final value of a: " + a);

}
}

5. Increment & Decrement Operators


Used to increase or decrease values by 1.

Operators: ++ --
Types: pre & post
Program: Increment/Decrement
public class IncDecDemo {
public static void main(String[] args) {
int a = 5;
[Link](a++);
[Link](++a);
[Link](a--);
[Link](--a);
}
}

6. Conditional (Ternary) Operator


Short form of if-else.

22
Operator: condition ? value1 : value2

23
Program: Ternary Operator
public class TernaryDemo {
public static void main(String[] args) {
int a = 30, b = 20;
int max = (a > b) ? a : b;
[Link]("Maximum: " + max);
}
}

7. Bitwise Operators
Used for bit-level operations.
Operators: & | ^ << >>
Program: Bitwise Operators
public class BitwiseDemo {
public static void main(String[] args) {
int a = 5, b = 3;
[Link](a & b);
[Link](a | b);
[Link](a ^ b);
[Link](a << 1);
[Link](a >> 1);
}

8. Special Operators
Used for specific functions.

Operators:
 instanceof
 new

 . (dot operator)

24
Program: instanceof Operator
class Test {}
public class SpecialOperatorDemo
{ public static void main(String[] args)
{
Test obj = new Test();
[Link](obj instanceof
Test);
}
}

CONTROL STATEMENTS :-
Control statements determine the flow of execution in a program. They allow decisions,
looping, and branching. Java provides three major categories of control statements:

1. Selection Statements
Used to make decisions based on conditions.

(A) if Statement
Executes a block when a condition is true.

Program: if
public class IfDemo {
public static void main(String[] args) {
int age = 20;
if (age >= 18)
{ [Link]("Eligible to vote");
25
}

26
}

(B) if-else Statement


Executes one block when condition is true and another when false.

Program: if-else
public class IfElseDemo {
public static void main(String[] args) {
int num = 7;
if (num % 2 == 0)
[Link]("Even number");
else
[Link]("Odd number");

}
}

(C) else-if Ladder


Used to check multiple conditions.

Program: else-if
public class ElseIfDemo {
public static void main(String[] args) {
int marks = 85;
if (marks >= 90)
[Link]("A Grade");
else if (marks >= 75)
[Link]("B Grade");
else
[Link]("C Grade");
}

27
(D) switch Statement
Used to select one from many choices.

Program: switch
public class SwitchDemo {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}

}
}

2. Iteration (Looping) Statements


Used to repeat a block of code.

(A) while Loop


Executes until condition becomes false.

Program: while
public class WhileDemo {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
}

28
(B) do-while Loop
Executes at least once, even if condition is false.

Program: do-while
public class DoWhileDemo {
public static void main(String[] args) {
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);

}
}

(C) for Loop


Used when number of iterations is known.

Program: for
public class ForDemo {

public static void main(String[] args) {


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

}
}

3. Jump Statements
Used to change the flow of control in loops.

(A) break Statement


Terminates loop immediately.

Program: break
public class BreakDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3)
29
break;

[Link](i);
}

}
}

(B) continue Statement


Skips the current iteration.

Program: continue
public class ContinueDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue;
[Link](i);
}
}

(C) return Statement


Used to return value and exit method.

Program: return
public class ReturnDemo {

public static void main(String[] args)


{ [Link](sum(5, 10));
}

public static int sum(int a, int b)


{ return a + b;
}
}

30
PROGRAMMING STRUCTURES IN JAVA :-
Programming structures (or control structures) are fundamental building blocks used to
control the execution flow of a Java program. They determine how statements are executed
and help implement decision-making, looping, and modular programming. Java provides
three main programming structures:

1. Sequence Structure
Sequence is the default execution flow, where statements run one after another in the
order they appear. There is no branching or looping.
It is used for simple programs such as input–output operations, assignments, or
calculations.
Example Program: Sequence Structure
public class SequenceDemo {
public static void main(String[] args) {
int a = 10, b = 20;
int sum = a + b;
[Link]("Sum = " + sum);
}
}

Explanation:
Each line executes sequentially: variable declaration → calculation → output.

2. Selection Structure
Selection (decision-making) allows the program to choose alternative paths based on
conditions. Java provides four types of selection statements:
 if statement

 if-else statement

31
 else-if ladder

 switch statement
These structures help the program make decisions depending on logical or relational conditions.

Example Program: Selection Structure (if-else)


public class SelectionDemo {

public static void main(String[] args) {


int marks = 75;
if (marks >= 50)
[Link]("Pass");
else

[Link]("Fail");
}

Example Program: switch


public class SwitchDemo {
public static void main(String[] args)
{ int day = 2;
switch (day) {

case 1: [Link]("Monday"); break;


case 2: [Link]("Tuesday");
break; default: [Link]("Invalid
Day");
}
}

3. Iterative (Looping) Structure


Iteration allows repetition of a block of code multiple times. Loops are useful when tasks need
repetition, such as printing numbers, processing arrays, or reading data repeatedly. Java
supports three loop types:
 while loop

 do-while loop
 for loop
32
Example Program: while Loop
public class WhileDemo {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}

}
}

Example Program: for Loop


public class ForDemo {

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {
[Link](i);
}

}
}

Example Program: do-while Loop


public class DoWhileDemo {
public static void main(String[] args) {
int i = 1;
do {

[Link](i); i++;
} while (i <= 5);
}

33
4. Jump (Branching) Structure
Jump statements change the flow of the program by breaking loops, skipping iterations, or
exiting a function.
Java provides three jump statements:

 break → exits loop or switch


 continue → skips current iteration

 return → exits method and returns value

Example Program: break Statement


public class BreakDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3)
break;
[Link](i);
}

}
}

Example Program: continue Statement


public class ContinueDemo {

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {
if (i == 3)
continue;
[Link](i);

}
}

Example Program: return Statement


public class ReturnDemo {
public static void main(String[] args) {
int result = add(5, 10);

34
[Link]("Result = " + result);

}
static int add(int a, int b)
{ return a + b;
}

DEFINING CLASSES IN JAVA:-


In Java, a class is the fundamental building block of Object-Oriented Programming
(OOP). It serves as a blueprint or template from which objects are created. A class
encapsulates data (variables) and behavior (methods) into a single unit. Java programs are
built by defining classes and creating objects from them.

1. Structure of a Java Class


A typical class definition includes the following:

1. Class Declaration
Uses the keyword class.
Example: class Student { … }
2. Data Members (Fields / Variables)
Represent properties or attributes of an object.
Example: String name; int age;
3. Methods (Member Functions)
Define the behavior or operations of the class.
Example: void display() { … }
4. Constructors (Optional)
Special methods used to initialize objects.

5. Access Modifiers
Control visibility → public, private, protected.
35
2. Syntax of a Class in Java
class ClassName {
// Data members
type variable1;
type variable2;

// Constructor
ClassName() {
// initialization
}

// Methods

returnType methodName(parameters) {
// code

}
}

3. Example: Defining a Class in Java


class Student {
// Data members
String name;
int age;

// Constructor
Student(String n, int a) {
name = n;
age = a;
}
// Method

void display()
{ [Link]("Name: " +
name); [Link]("Age: " +
age);
36
}

37
}

public class Main {

public static void main(String[] args) {


// Creating an object

Student s1 = new Student("Kishore", 20);


[Link]();
}

4. Explanation
 The Student class contains attributes such as name and age.
 It includes a constructor to initialize the values.

 The display() method prints student details.


 Inside main(), we create an object using new.

 [Link]() accesses the method using the dot operator.

5. Key Points
 A class defines the structure and behavior of objects.
 Objects are instances of classes.
 Classes support OOP principles like abstraction, encapsulation, and modularity.

 All Java applications are composed of one or more classes.

38
CONSTRUCTORS:-
A constructor in Java is a special type of method used to initialize objects. It is
automatically called at the time of object creation. Constructors have the same name as the
class and do not have a return type, not even void. They help assign initial values to object
variables and prepare the object for use.

1. Characteristics of Constructors
1. Same name as class
Example: class Student → constructor is Student()

2. No return type
They cannot return values.

3. Automatically invoked
Called when an object is created using new.

4. Can be overloaded
Multiple constructors with different parameter lists can exist.

5. Used for initialization


Set default or user-defined values.

2. Types of Constructors
Java provides two main types:

A. Default Constructor
A constructor with no parameters.
If the programmer does not define any constructor, Java provides a compiler-
generated default constructor.

Example: Default Constructor


class Student {
String
name; int
age;

// Default constructor
Student() {
name =
"Unknown"; age =
0;
}
void display() {

39
[Link](name + " - " + age);

40
}

public class Main {


public static void main(String[] args) {
Student s = new Student();
[Link]();

}
}

B. Parameterized Constructor
A constructor that takes parameters to assign custom values during object creation.

Example: Parameterized Constructor


class Student {
String
name; int
age;
// Parameterized constructor
Student(String n, int a) {
name =
n; age =
a;
}
void display() {

[Link](name + " - " + age);


}

}
public class Main {

public static void main(String[] args)


{ Student s = new Student("Kishore", 20);
[Link]();
}

3. Constructor Overloading
41
Defining more than one constructor within a class, each with different parameter lists.

42
Example: Overloaded Constructors
class Box {
int length, width;

Box() { length = width = 0; } // Default


Box(int l) { length = width = l; } // One
parameter
Box(int l, int w) { length = l; width = w; } // Two parameters
}

4. Copy Constructor (User-defined)


Java does not have a built-in copy constructor, but programmers can create one manually.
class Student {
String name;
Student(String n) {
name = n;
}

Student(Student s) {
name = [Link]; // copying

}
}

5. Importance of Constructors
 Initialize object data
 Improve code readability

 Support overloading
 Help avoid uninitialized objects

 Used in object-oriented design patterns

43
METHODS IN JAVA – 14 MARKS
A method in Java is a block of code that performs a specific task. Methods help achieve
modularity, code reusability, readability, and a clean program structure. They form the core of
Java’s object-oriented programming style because behavior of objects is represented through
methods.

1. Definition of a Method
A method in Java is a group of statements defined inside a class to perform an operation.
General syntax:
return_type methodName(parameter_list) {
// method body
}

2. Components of a Method
✔ Method Name

Identifies the method (e.g., sum(), display()).

✔ Return Type
Specifies the type of value the method returns.
Example: int, double, String, or void (returns nothing).
✔ Parameters

Used to pass values into methods.


Example: sum(int a, int b).

✔ Method Body

Contains the statements to be executed.

3. Types of Methods in Java


(A) Predefined Methods
These methods are already available in Java libraries.
Examples:
 sqrt() in Math class

 println() in [Link]

(B) User-defined Methods


Created by programmers based on need.

4. Method Declaration vs Method Invocation


✔ Declaration

Where the method is defined inside a class.

44
✔ Invocation

Calling the method from another method (usually main()).


Example:
add(10, 20); // method call

5. Parameter Passing in
Methods Java supports pass-by-
value only. Two types:
1. Actual Parameters – values passed during method call
2. Formal Parameters – variables declared in the method header

6. Return Statement
A method may return a single value using:

return value;
Example:
return a + b;

7. Method Overloading
Method overloading occurs when multiple methods have the same name but different
parameter lists. It increases flexibility and readability.
Example:
void display(int a) { }
void display(double b) { }
8. Advantages of Methods

 Eliminates code duplication


 Enhances modularity

 Increases readability
 Simplifies debugging

 Allows reusability of code

🌟 PROGRAM EXAMPLES

1. Simple User-Defined Method


class Demo
{ void greet()
{

45
[Link]("Hello! Welcome to Java Methods");

46
}

public static void main(String[] args) {


Demo d = new Demo();
[Link](); // method call
}

2. Method with Parameters and Return Value


class Addition {

int add(int a, int b)


{ return a + b;
}
public static void main(String[] args) {
Addition ob = new Addition();
int result = [Link](10, 20);
[Link]("Sum = " + result);
}

3. Method Overloading Example


class OverloadDemo
{ void show(int a) {
[Link]("Integer: " + a);

}
void show(String s)
{ [Link]("String: " + s);
}

public static void main(String[] args)


{ OverloadDemo ob = new OverloadDemo();
[Link](100);
[Link]("Java");
}

}
47
ACCESS SPECIFIERS :-
Access specifiers in Java determine the visibility and accessibility of classes, methods,
and variables. They control which parts of the program can access certain members of a
class. Java provides four types of access specifiers:
1. private
2. default (no specifier)

3. protected
4. public

1. private
 Members declared as private are accessible only within the same class.

 Not accessible from other classes, even if they are in the same package.

Example:
class Student {

private String name;

void setName(String n)
{ name = n;
}
void display()
{ [Link]("Name: " +
name);
48
}

}
public class TestPrivate {

public static void main(String[] args) {


Student s = new Student();
[Link]("Kishore");
[Link]();
// [Link] = "Ravi"; // Error: name has private access

}
}

2. default (Package-Private)
 If no access specifier is mentioned, it is default.

 Members are accessible only within the same package.


 Cannot be accessed from classes in different packages.

Example:
class Student {

String name; // default access

void display()
{ [Link]("Name: " +
name);
}

}
public class TestDefault {

public static void main(String[] args) {


Student s = new Student();
[Link] = "Kishore"; // Accessible within same package
[Link]();
}
}

49
3. protected
 Members declared as protected are accessible:
o Within the same package

o By subclasses in different packages


 Useful for inheritance.

Example:
class Student {
protected String name;

protected void display()


{ [Link]("Name: " + name);
}

}
class College extends Student
{ void setName(String n) {
name = n; // accessible because protected

}
}
public class TestProtected {

public static void main(String[] args) {


College c = new College();
[Link]("Kishore");
[Link]();

}
}

4. public
 Members declared as public are accessible from any other class in any package.

 Provides the widest accessibility.


Example:
class Student {

public String name;


50
public void display()
{ [Link]("Name: " + name);
}
}

public class TestPublic {


public static void main(String[] args) {
Student s = new Student();
[Link] = "Kishore"; // Accessible anywhere
[Link]();
}
}

Access Specifiers Table

Access Within Same Subclass (Different Everywhere


Specifier Class Package Package)
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes

STATIC MEMBERS:-
Definition:
Static members belong to the class itself rather than any object. They are shared among all
instances of the class and can be accessed without creating objects.

Types of Static Members:


1. Static Variables – shared by all objects.

2. Static Methods – can access only static variables/methods directly.


3. Static Block – used to initialize static variables when the class is loaded.

51
Example
class Student {
static int count = 0; // static variable
Student() {
count++;

}
static void displayCount() { // static method
[Link]("Total students: " + count);
}
}

public class TestStatic {


public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();

[Link](); // Access static method without object


}

Output:
Total students: 2

52
JAVA DOC COMMENTS IN JAVA:-

Definition:
JavaDoc is a tool in Java used for generating API documentation in HTML format from
Java source code. The documentation is generated from special comments in the source code
called JavaDoc comments.

Syntax of JavaDoc Comment:


/**
* This is a JavaDoc comment

*/
 Begins with /** and ends with */.

 Usually placed before classes, methods, and fields.


 Can include special tags like @author, @param, @return, @see, @since, @version.

Common JavaDoc Tags

Tag Purpose
@author Specifies the author of the class or code
@version Specifies the version of the class
@param Describes a method parameter
@return Describes what the method returns
@see Refers to another class or method
@since Specifies the version since the class/method is present

Example
/**
* Class to perform simple arithmetic operations

* @author Kishore
* @version 1.0

* @since 2025
*/

class Calculator {

/**
* Adds two numbers
53
* @param a First number

* @param b Second number


* @return Sum of a and b

*/
int add(int a, int b)
{ return a + b;
}

/**
* Subtracts second number from first

* @param a First number


* @param b Second number

* @return Difference (a - b)
*/

int subtract(int a, int b)


{ return a - b;
}
}
public class TestJavaDoc {

public static void main(String[] args)


{ Calculator calc = new Calculator();
[Link]("Sum: " + [Link](5, 3));
[Link]("Difference: " + [Link](5, 3));

}
}

Generating Documentation
1. Save the file as [Link].

2. Open command prompt or terminal and navigate to the file directory.


3. Run the command:
javadoc [Link]
4. An HTML documentation will be generated in the current folder.
54
Advantages
 Provides standardized documentation for classes, methods, and fields.
 Helps other programmers understand and use code easily.

 Can generate HTML files automatically.

55

You might also like