Java Programming Unit 1 Notes
Java Programming Unit 1 Notes
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.
c) Polymorphism
It allows the same function or method to behave differently in different situations.
Two types:
o Compile-time polymorphism (method overloading)
1
2. Features of OOP
OOP enhances programming by offering:
Modularity – code broken into classes
INTRODUCTION TO JAVA
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:
Easy scalability
Faster development
3
High security and modularity
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.4 Encapsulation
Binding data and methods into a single unit (class).
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)
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
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() {}
}
6
2. ENCAPSULATION
Encapsulation is the process of binding data and methods into one unit (class).
It protects data using private access modifiers.
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
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.
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.
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:
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)
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.
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
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
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
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.
13
12. Dynamic
Java programs can adapt to changes at runtime.
Features include:
Loading classes dynamically
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).
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:
14
b) Java Virtual Machine (JVM)
Executes bytecode
Provides platform independence
i) Simple
Easy syntax, no pointers, automatic memory management.
ii) Object-Oriented
Classes, objects, inheritance, encapsulation, abstraction, polymorphism.
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.
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)
5. Java Editions
Java comes in three major editions:
Cloud computing
Enterprise systems
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:
1. Byte
1 byte
Range: –128 to +127
Used for saving memory
2. Short
2 bytes
3. Int
4 bytes
Default integer type
4. Long
8 bytes
5. Float
4 bytes
17
Single-precision decimal values
6. Double
8 bytes
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.
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
2. Instance Variables
Declared inside a class but outside methods
Each object has its own copy
18
3. Static Variables
Declared using the static keyword
Shared by all objects of a class
A. Types of Arrays
1. One-Dimensional Array
Stores a list of elements.
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.
Creation
arr = new int[5];
19
C. Characteristics of Arrays
Fixed size (cannot grow or shrink)
Index-based access (starting at 0)
D. Advantages of Arrays
Easy to store large data sets
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: + - * / %
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 {
3. Logical Operators
Used to connect multiple conditions.
Operators: && || !
a -= 3;
a *= 2;
a /= 3;
[Link]("Final value of a: " + a);
}
}
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);
}
}
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
}
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");
}
}
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");
}
}
}
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);
}
}
Program: for
public class ForDemo {
}
}
3. Jump Statements
Used to change the flow of control in loops.
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);
}
}
}
Program: continue
public class ContinueDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue;
[Link](i);
}
}
Program: return
public class ReturnDemo {
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.
[Link]("Fail");
}
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++;
}
}
}
}
}
[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:
}
}
}
}
34
[Link]("Result = " + result);
}
static int add(int a, int b)
{ return a + b;
}
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
}
}
// Constructor
Student(String n, int a) {
name = n;
age = a;
}
// Method
void display()
{ [Link]("Name: " +
name); [Link]("Age: " +
age);
36
}
37
}
4. Explanation
The Student class contains attributes such as name and age.
It includes a constructor to initialize the values.
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.
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.
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.
// Default constructor
Student() {
name =
"Unknown"; age =
0;
}
void display() {
39
[Link](name + " - " + age);
40
}
}
}
B. Parameterized Constructor
A constructor that takes parameters to assign custom values during object creation.
}
public class Main {
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;
Student(Student s) {
name = [Link]; // copying
}
}
5. Importance of Constructors
Initialize object data
Improve code readability
Support overloading
Help avoid uninitialized objects
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
✔ Return Type
Specifies the type of value the method returns.
Example: int, double, String, or void (returns nothing).
✔ Parameters
✔ Method Body
println() in [Link]
44
✔ Invocation
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
Increases readability
Simplifies debugging
🌟 PROGRAM EXAMPLES
45
[Link]("Hello! Welcome to Java Methods");
46
}
}
void show(String s)
{ [Link]("String: " + s);
}
}
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 {
void setName(String n)
{ name = n;
}
void display()
{ [Link]("Name: " +
name);
48
}
}
public class TestPrivate {
}
}
2. default (Package-Private)
If no access specifier is mentioned, it is default.
Example:
class Student {
void display()
{ [Link]("Name: " +
name);
}
}
public class TestDefault {
49
3. protected
Members declared as protected are accessible:
o Within the same package
Example:
class Student {
protected String name;
}
class College extends Student
{ void setName(String n) {
name = n; // accessible because protected
}
}
public class TestProtected {
}
}
4. public
Members declared as public are accessible from any other class in any package.
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.
51
Example
class Student {
static int count = 0; // static variable
Student() {
count++;
}
static void displayCount() { // static method
[Link]("Total students: " + count);
}
}
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.
*/
Begins with /** and ends with */.
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
*/
int add(int a, int b)
{ return a + b;
}
/**
* Subtracts second number from first
* @return Difference (a - b)
*/
}
}
Generating Documentation
1. Save the file as [Link].
55