0% found this document useful (0 votes)
11 views57 pages

Java Module 1

Module-1 covers Java Fundamentals, focusing on Object-Oriented Programming (OOP) principles such as encapsulation, inheritance, and polymorphism. It discusses data types, variables, operators, and control statements, emphasizing the importance of blocks of code for organizing and managing complexity. The module also highlights the advantages and disadvantages of OOP compared to procedural programming, along with practical examples and applications in software development.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views57 pages

Java Module 1

Module-1 covers Java Fundamentals, focusing on Object-Oriented Programming (OOP) principles such as encapsulation, inheritance, and polymorphism. It discusses data types, variables, operators, and control statements, emphasizing the importance of blocks of code for organizing and managing complexity. The module also highlights the advantages and disadvantages of OOP compared to procedural programming, along with practical examples and applications in software development.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module-1

08 October 2025 15:25

Module-1: Java Fundamentals

1. An Overview of Java
Object-Oriented Programming (OOP):
• Two Paradigms: Procedural vs Object-Oriented
• Abstraction: Hiding implementation details
• Three OOP Principles:
1. Encapsulation – Keeping data and methods together
and controlling access.
2. Inheritance – Reusing code from existing classes.
3. Polymorphism – Ability to take many forms (method
overloading & overriding).
• Using Blocks of Code: { } for scoping variables, methods,
loops, or standalone blocks.
Lexical Issues:
• Whitespace – spaces, tabs, newlines (ignored by compiler
except to separate tokens).
• Identifiers – Names of classes, variables, methods (must
follow naming rules).
• Literals – Fixed values like 10, 'A', true.
• Comments: // single-line, /* multi-line */, /**
documentation */
• Separators: ; , . ( ) { } [ ]
• Java Keywords: Reserved words like class, if, for, return,
etc.

2. Data Types, Variables, and Arrays


Primitive Types:
• Integers: byte, short, int, long
• Floating-Point Types: float, double
• Characters: char
• Booleans: boolean (true or false)
Variables:
Module-1 Syllabus Page 1
Variables:
• Storage locations with a name and type.
• Must be declared before use.
Type Conversion and Casting:
• Implicit: Automatic conversion (e.g., int to double).
• Explicit: Manual conversion using casting (e.g., (int) 3.14).
Automatic Type Promotion in Expressions:
• Smaller types promoted to larger types during calculations
(e.g., byte + int -> int).
Arrays:
• Contiguous memory storage of same type elements.
• One-dimensional: int[] arr = new int[5];
• Two-dimensional: int[][] matrix = new int[3][3];
Type Inference with Local Variables:
• Using var keyword (Java 10+):
var number = 10; // compiler infers type as int

3. Operators
• Arithmetic Operators: + - * / %
• Relational Operators: == != > < >= <=
• Boolean Logical Operators: && || !
• Assignment Operator: =
• Ternary Operator (? :)
int result = (a > b) ? a : b;
• Operator Precedence: Determines order of evaluation.
• Using Parentheses: Overrides default precedence.

4. Control Statements
Selection Statements:
• if, if-else, if-else-if
• Traditional switch (supports int, char, String from Java 7+)
Iteration Statements:
• while, do-while, for
• For-each loop (enhanced for loop) for arrays/collections
• Local variable type inference in for-loop:
for (var num : numbers) {
Module-1 Syllabus Page 2
for (var num : numbers) {
[Link](num);
}
• Nested Loops: Loops inside loops
Jump Statements:
• break – exits a loop/switch
• continue – skips current iteration
• return – exits from a method and optionally returns a value

Module-1 Syllabus Page 3


oops
08 October 2025 15:31

=====================================================
OBJECT-ORIENTED PARADIGM (OOP)
=====================================================

Object-Oriented Programming
Object-oriented programming (OOP) is at the core of Java. In fact, all Java programs are to at least some extent
object-oriented. OOP is so integral to Java that it is best to understand its basic principles before you begin
writing even simple Java programs.
Two Paradigms
• All computer programs consist of two elements: code and data. Furthermore, a program can be conceptually
organized around its code or around its data.
• The first way is called the process-oriented model. This approach characterizes a program as a series of
linear steps (that is, code). The process-oriented model can be thought of as code acting on data. Procedural
languages such as C employ this model to considerable success.
• To manage increasing complexity, the second approach, called object-oriented programming, was
conceived. Object-oriented programming organizes a program around its data (that is, objects) and a set of
well-defined interfaces to that data. An object-oriented program can be characterized as data controlling
access to code.
Abstraction
Process of identifying the essential details to be known and ignoring the non-essential details from the
perspective of the end users.
• An essential element of object-oriented programming is abstraction. Humans manage complexity through
abstraction.
• For example, people do not think of a car as a set of tens of thousands of individual parts. They think of it as
a well-defined object with its own unique behavior.
• This abstraction allows people to use a car to drive to the grocery store without being overwhelmed by the
complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and
braking systems work. Instead, they are free to utilize the object as a whole.

INTRODUCTION
-----------------------------------------------------
Object-Oriented Paradigm (OOP) is a programming approach
that focuses on "objects" rather than functions or logic.
An object represents a real-world entity that has data
(attributes) and behavior (methods).

In OOP, programs are designed using classes and objects.

-----------------------------------------------------
NEED FOR OOP
-----------------------------------------------------
- Procedural languages (like C) focus on functions and
use global data, which can lead to complex, unmanageable code.
- OOP solves this by combining data and methods into a single
unit called an object.

Benefits:
✔ Better code organization
✔ Data hiding and security
✔ Code reusability
✔ Easier maintenance

Module-1 Syllabus Page 4


✔ Easier maintenance

-----------------------------------------------------
BASIC CONCEPTS OF OOP
-----------------------------------------------------

1. CLASS
- A blueprint or template for creating objects.
- Defines data members and methods.
Example:
class Car {
String brand;
void start() {
[Link](brand + " is starting...");
}
}

2. OBJECT
- Instance of a class; represents a real-world entity.
Example:
Car c1 = new Car();
[Link] = "Tesla";
[Link]();

3. ENCAPSULATION

- Binding data and methods together in one unit.


- Achieved using access modifiers (private, public, etc.).
Example:
class Student {
private int marks;
public void setMarks(int m) { marks = m; }
public int getMarks() { return marks; }
}

4. ABSTRACTION
- Showing only essential features and hiding details.
- Achieved using abstract classes or interfaces.
Example:
interface Vehicle {
void start();
}

5. INHERITANCE
- One class can inherit properties and behaviors from another.
- Promotes code reusability.
Example:
class Animal {
void eat() { [Link]("Eating..."); }
}
class Dog extends Animal {
void bark() { [Link]("Barking..."); }
}

6. POLYMORPHISM
- Means "many forms."
- Same method behaves differently based on the object.

Types:
a) Compile-time (Method Overloading)

Module-1 Syllabus Page 5


a) Compile-time (Method Overloading)
Example:
class Display {
void show(int a) { [Link](a); }
void show(String s) { [Link](s); }
}

b) Runtime (Method Overriding)


Example:
class Animal {
void sound() { [Link]("Animal sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Bark"); }
}

7. MESSAGE PASSING
- Objects communicate by sending messages (method calls).
Example:
[Link](arguments);

-----------------------------------------------------
FEATURES OF OOP
-----------------------------------------------------
1. Modularity – Code is divided into classes.
2. Reusability – Classes can be reused using inheritance.
3. Extensibility – Easy to add new features.
4. Data Security – Data hidden inside classes.
5. Maintainability – Easier to debug and manage.
6. Flexibility – Code adapts easily to changes.

-----------------------------------------------------
ADVANTAGES OF OOP
-----------------------------------------------------
✔ Models real-world problems effectively.
✔ Improves productivity and code reuse.
✔ Easier to maintain and upgrade.
✔ Provides data security.
✔ Promotes teamwork in large projects.

-----------------------------------------------------
DISADVANTAGES OF OOP
-----------------------------------------------------
✖ Slightly complex to learn.
✖ Uses more memory due to objects.
✖ Slower for small tasks compared to procedural programs.

-----------------------------------------------------
PROCEDURAL VS OBJECT-ORIENTED PROGRAMMING
-----------------------------------------------------
| Feature | Procedural Programming | Object-Oriented Programming |
|--------------------|------------------------|------------------------------|
| Focus | Functions | Objects |
| Data | Global | Hidden inside classes |
| Code Reuse | Difficult | Easy (via inheritance) |
| Example Languages | C, Pascal | Java, C++, Python |
| Security | Low | High (Encapsulation) |
| Structure | Top-down | Bottom-up |

-----------------------------------------------------
Module-1 Syllabus Page 6
-----------------------------------------------------
EXAMPLE PROGRAM (Java)
-----------------------------------------------------
class Student {
String name;
int age;

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

public class Main {


public static void main(String[] args) {
Student s1 = new Student();
[Link] = "John";
[Link] = 20;
[Link]();
}
}

Output:
Name: John
Age: 20

-----------------------------------------------------
APPLICATIONS OF OOP
-----------------------------------------------------
- Software development (Java, C++)
- Game development (Unity, Unreal)
- GUI applicatio0ns (JavaFX, Swing)
- Web frameworks (Spring, Django)
- Simulation and modeling tools

-----------------------------------------------------
CONCLUSION
-----------------------------------------------------
The Object-Oriented Paradigm simplifies software design by
representing real-world entities as objects. It improves
code reuse, security, and maintainability and is the foundation
of modern languages like Java, Python, C++, and C#.
=====================================================

Module-1 Syllabus Page 7


oops
08 October 2025 21:01

Object-Oriented Programming
Object-oriented programming (OOP) is at the core of Java. In fact, all Java programs are to at least
some extent object-oriented. OOP is so integral to Java that it is best to understand its basic
principles before you begin writing even simple Java programs.
Two Paradigms
• All computer programs consist of two elements: code and data. Furthermore, a program can
be conceptually organized around its code or around its data.
• The first way is called the process-oriented model. This approach characterizes a program as a
series of linear steps (that is, code). The process-oriented model can be thought of as code
acting on data. Procedural languages such as C employ this model to considerable success.
• To manage increasing complexity, the second approach, called object-oriented programming,
was conceived. Object-oriented programming organizes a program around its data (that is,
objects) and a set of well-defined interfaces to that data. An object-oriented program can be
characterized as data controlling access to code.
Abstraction
Process of identifying the essential details to be known and ignoring the non-essential details from
the perspective of the end users.
• An essential element of object-oriented programming is abstraction. Humans manage
complexity through abstraction.
• For example, people do not think of a car as a set of tens of thousands of individual parts. They
think of it as a well-defined object with its own unique behavior.
• This abstraction allows people to use a car to drive to the grocery store without being
overwhelmed by the complexity of the parts that form the car. They can ignore the details of
how the engine, transmission, and braking systems work. Instead, they are free to utilize the
object as a whole.

The Three OOP Principles


All object-oriented programming languages provide mechanisms that help you implement the
object-oriented model. They are encapsulation, inheritance, and polymorphism.
1. Encapsulation
• Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse. One way to think about encapsulation
is as a protective wrapper that prevents the code and data from being arbitrarily accessed by
other code defined outside the wrapper.
• Access to the code and data inside the wrapper is tightly controlled through a well-defined
interface.
• Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the
complexity of the implementation inside the class. Each method or variable in a class may be
marked private or public.
• The public interface of a class represents everything that external users of the class need to
know, or may know.
• The private methods and data can only be accessed by code that is a member of the class.
Therefore, any other code that is not a member of the class cannot access a private method or
variable.
• FIGURE 2-1: Encapsulation: public methods can be used to protect private data (Diagram of a
class showing public and private instance variables and methods).
2. Inheritance
• Inheritance is the process by which one object acquires the properties of another object. This
is important because it supports the concept of hierarchical classification.
• For example, a Golden Retriever is part of the classification dog, which in turn is part of the
mammal class, which is under the larger class animal.

Module-1 Syllabus Page 8


mammal class, which is under the larger class animal.
• Without the use of hierarchies, each object would need to define all of its characteristics
explicitly. By use of inheritance, an object need only define those qualities that make it unique
within its class. It can inherit its general attributes from its parent. Thus, it is the inheritance
mechanism that makes it possible for one object to be a specific instance of a more general
case.
3. Polymorphism
• Polymorphism (from Greek, meaning "many forms") is a feature that allows one interface to
be used for a general class of actions. More generally, the concept of polymorphism is often
expressed by the phrase "one interface, multiple methods".
• This means that it is possible to design a generic interface to a group of related activities. This
helps reduce complexity by allowing the same interface to be used to specify a general class of
action.

Module-1 Syllabus Page 9


Using Block of code
08 October 2025 15:37

Using Blocks of Code in Java


In Java, two or more statements can be grouped together into a block of code, also called a code
block. A block of code is created by enclosing one or more statements within curly braces { }.
Once a block is created, it becomes a single logical unit that can be used wherever a single
statement is allowed.

Syntax
{

// one or more statements

Example
if (x < y) { // begin a block

x = y;

y = 0;

} // end of block

Explanation
In the above example:

- The if condition checks whether x is less than y.

- If the condition is true, then both statements inside the block will be executed.

- Both statements act as a single logical unit; one cannot execute without the other.

Why Use Blocks?


1. To group multiple statements as one logical unit.

2. To define scope for variables.

3. To use with control statements like if, for, while, etc.

4. To organize code clearly and improve readability.

Key Point
Whenever you need to logically link two or more statements so that they execute together, you
should place them inside a block of code.

Example 2: Using Blocks in Loops


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

[Link]("Count: " + i);

[Link]("Inside loop block");

Output
Count: 1

Inside loop block

Module-1 Syllabus Page 10


Count: 2

Inside loop block

Count: 3

Inside loop block

Using Blocks of Code in Java – Example 2


The following program demonstrates how a block of code can be used as the target of a for loop.

/*

Demonstrate a block of code.

Call this file '[Link]'

*/

class BlockTest {

public static void main(String[] args) {

int x, y;

y = 20;

// the target of this loop is a block

for(x = 0; x < 10; x++) {

[Link]("This is x: " + x);

[Link]("This is y: " + y);

y = y - 2;

The output generated by this program is:

This is x: 0

This is y: 20

This is x: 1

This is y: 18

This is x: 2

This is y: 16

This is x: 3

Module-1 Syllabus Page 11


This is x: 3

This is y: 14

This is x: 4

This is y: 12

This is x: 5

This is y: 10

This is x: 6

This is y: 8

This is x: 7

This is y: 6

This is x: 8

This is y: 4

This is x: 9

This is y: 2

In this case, the target of the for loop is a block of code and not just a single statement. Thus,
each time the loop iterates, the three statements inside the block will be executed. This is
evidenced by the output shown above.

As you will see later, blocks of code have additional properties and uses. However, the main
reason for their existence is to create logically inseparable units of code.

Module-1 Syllabus Page 12


Lexical Issues
08 October 2025 15:54

Lexical Issues
Java programs are a collection of whitespace, identifiers,
literals, comments, operators, separators, and keywords.

• Whitespace: In Java, whitespace is a space, tab, or


newline.

• Identifiers: Identifiers are used for class names, method


names, and variable names. An identifier may be any
descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters.
Java is case-sensitive.
Rules for identifiers:
1. All identifiers should begin with a letter (A to Z or a to
z), currency character ($), or an underscore (_).
2. After the first character, identifiers can have any
combination of characters.
3. A keyword cannot be used as an identifier.
4. Examples of legal identifiers: age, $salary, _value,
l_value.
5. Examples of illegal identifiers: 123abc, _salary.
6. Some valid identifiers are: AvgTemp, count_a4, $test,
this_is_ok.
7. Invalid identifiers are: count, high-temp, Not/ok.

• Literals: A constant value in Java is created using a literal


representation of it. Examples are: 100 (integer), 98.6
(floating-point), 'X' (character), "This is a test" (string),
and true (boolean).

• Comments: There are three types of comments: single-


line (//), multi-line (/*...*/), and documentation (/**...*/).
• Separators: In Java, the semicolon (;) is the most
Module-1 Syllabus Page 13
• Separators: In Java, the semicolon (;) is the most
commonly used separator, used to terminate statements.
The table below lists the characters that are used as
separators:
Symb Name Purpose
ol
() Paren Used to contain lists of parameters in
theses method definition and invocation. Also
used for defining precedence in
expressions, containing expressions in
control statements, and surrounding cast
types.
[] Brace Used to contain the values of automatically
s initialized arrays. Also used to define a
block of code, for classes, methods, and
local scopes.
; Brack Used to declare array types. Also used
ets when dereferencing array values.
, Semic Terminates statements.
olon
. Com Separates consecutive identifiers in a
ma variable declaration. Also used to chain
statements together inside a for
statement.
Period Used to separate package names from
subpackages and classes. Also used to
separate a variable or method from a
reference variable.
The Java Keywords
• There are 50 keywords currently defined in the Java
language. These keywords, combined with the syntax
of the operators and separators, form the foundation
of the Java language.
• These keywords cannot be used as names for a
Module-1 Syllabus Page 14
• These keywords cannot be used as names for a
variable, class, or method. The keywords const and
goto are reserved but not used.

abstrac contin for new switch assert


t ue
default goto packag synchroni boolea do
e zed n
if private this break double impleme
nts
protect throw byte else import public
ed
throws case enum instanceo return transient
f
catch extend int short try char
s
final interfa static void class finally
ce
long strictfp volatil const float native
e
super while

Module-1 Syllabus Page 15


Datatypes
08 October 2025 15:58

Primitive Data Types


• Java defines eight primitive types of data: byte, short, int,
long, char, float, double, and boolean. These primitive
types are also commonly referred to as simple types.
• These can be put in four groups:
○ Integers: This group includes byte, short, int, and
long, which are for whole-valued signed numbers.
○ Floating-point numbers: This group includes float and
double, which represent numbers with fractional
precision.
○ Characters: This group includes char, which
represents symbols in a character set, like letters and
numbers.
○ Boolean: This group includes boolean, which is a
special type for representing true/false values.
a) Integers
• Java defines four integer types: byte, short, int, and long.
All of these are signed, positive and negative values.
• The width of an integer type should not be thought of as
the amount of storage it consumes, but rather as the
behavior it defines for variables and expressions of that
type.
• The Java run-time environment is free to use whatever
size it wants, as long as the types behave as you declared
them.
Nam Widt Range
e h
long 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 -2,147,483,648 to 2,147,483,647
short 16 -32,768 to 32,767

Module-1 Syllabus Page 16


short 16 -32,768 to 32,767
byte 8 -128 to 127
Export to Sheets
b) byte
• The smallest integer type is byte. This is a signed 8-bit
type that has a range from -128 to 127. Variables of type
byte are especially useful when you're working with a
stream of data from a network or file.
• byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables
called b and c:

byte b, c;
c) short
• short is a signed 16-bit type. It has a range from -32,768
to 32,767. It is probably the least-used Java type. short s;
short t;
d) int
• The most commonly used integer type is int. It is a signed
32-bit type that has a range from -2,147,483,648 to
2,147,483,647.
• When byte and short values are used in an expression
they are promoted to int when the expression is
evaluated.
e) long
• long is a signed 64-bit type and is useful for those
occasions where an int type is not large enough to hold
the desired value. The range of a long is quite large.
Example using long variables ([Link]):
Java

// Compute distance light travels using long variables.


class Light {
public static void main(String args[]) {
int lightspeed;
Module-1 Syllabus Page 17
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;

// specify number of days here


days = 1000;

// convert to seconds
seconds = days * 24 * 60 * 60;

// compute distance
distance = lightspeed * seconds;
[Link]("In " + days);
[Link](" days light will travel about ");
[Link](distance + " miles.");
}
}

Output: In 1000 days light will travel about 16070400000000


miles.
➤ Floating-Point Types
• Floating-point numbers, also known as real numbers, are
used when evaluating expressions that require fractional
precision. For example, calculations such as square root,
or transcendental such as sine and cosine, result in a
value whose precision requires a floating-point type.
• There are two kinds of floating-point types: float and
double, which represent single- and double-precision
numbers, respectively.
a) float
• The type float specifies a single-precision value that uses
32 bits of storage. For example, float can be useful when

Module-1 Syllabus Page 18


32 bits of storage. For example, float can be useful when
representing dollars and cents. float hightemp, lowtemp;
b) double
• Double precision, as denoted by the keyword double,
uses 64 bits to store a value.
• Double precision is actually faster than single precision on
some modern processors that have been optimized for
high-speed mathematical calculations.
Example using double variables ([Link]):
Java

// Compute the area of a circle.


class Area {
public static void main(String args[]) {
double pi, r, a;
// radius of circle
r = 10.8;
// pi, approximately
pi = 3.1416;
// compute area
a = pi * r * r;
[Link]("Area of circle is " + a);
}
}
c) Characters
• In Java, the data type used to store characters is char.
• char in Java is not the same as char in C or C++. In C/C++,
char is 8 bits wide. This is not the case in Java. Java uses
Unicode to represent characters. Unicode defines a fully
international character set that can represent all of the
characters found in all human languages.
• In Java char is a 16-bit type. The range of a char is 0 to
65,536. There are no negative char values.
Example demonstrating char variables ([Link]):
Java

Module-1 Syllabus Page 19


// char variables behave like integers
class CharDemo {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
[Link]("character in ch1 is: " + ch1);
// increment ch1
ch1++;
[Link]("ch1 is now " + ch1);
}
}
Output:
Output: character in ch1 is: X
ch1 is now Y
• In the program, ch1 is first given the value X. Next, ch1 is
incremented. This results in ch1 containing Y, the next
character in the ASCII (and Unicode) sequence.
d) boolean
• Java has a primitive type, called boolean, for logical
values. It can have only one of two possible values: true
or false.
• This is the type returned by all relational operators (e.g.,
in the case of a < b, the result is a boolean).
• boolean values are also the type required by the
conditional expressions that govern the control
statements such as if and for.
Example demonstrating boolean values ([Link]):
Java

// Demonstrate boolean values.


class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
[Link]("b is " + b);
Module-1 Syllabus Page 20
[Link]("b is " + b);
b = true;
[Link]("b is " + b);
// a boolean value can control the if statement
if(b) [Link]("This is executed.");
b = false;
if(b) [Link]("This is not executed.");
// outcome of a relational operator is a boolean value
[Link]("10 > 9 is " + (10 > 9));
}
}
Output:
b is false
b is true
This is executed.
10 > 9 is true
• When a boolean value is output by println(), true or false
is displayed.
• Second, the value of a boolean variable is sufficient, by
itself, to control the if statement. There is no need to
write an if statement like this: if(b == true).
• Third, the outcome of a relational operator, such as 9 >
10, displays the value true.
• Further, the extra set of parentheses around (10 > 9) is
necessary because the + operator has a higher
precedence than the > operator.

Module-1 Syllabus Page 21


Variabels
08 October 2025 15:58

Variables
• The variable is the basic unit of storage in a Java program. A
variable is defined by the combination of an identifier, a
type, and an optional initializer. In addition, all variables
have a scope, which defines their visibility, and a lifetime.
a. Declaring a Variable
• In Java, all variables must be declared before they can be
used.
○ Basic form:
○ type identifier [ = value][, identifier [= value]...];
• The identifier is the name of the variable. You can initialize
the variable by specifying an equal sign and a value.
Examples:
Java

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
b. Dynamic Initialization
• Java allows variables to be initialized dynamically, using any
expression valid at the time the variable is declared.
Example demonstrating dynamic initialization ([Link]):
Java

// Demonstrate dynamic initialization.


class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = [Link](a * a + b * b);
[Link]("Hypotenuse is " + c);
}
}

Module-1 Syllabus Page 22


}
• The variable c is initialized dynamically to the length of the
hypotenuse.
• The program uses another of Java's built-in methods, sqrt(),
which is a member of the Math class, to compute the
square root of its argument.
➤ The Scope and Lifetime of Variables
• Java allows variables to be declared within any block. A
block is begun with an opening curly brace and ended by a
closing curly brace. A block defines a scope.
• A scope determines what objects are visible to other parts
of your program. It also determines the lifetime of those
objects.
• Traditional scopes defined two general categories: global
and local. These traditional scopes do not fit well with
Java's strict, object-oriented model.
• As a general rule, variables declared inside a scope are not
visible (that is, accessible) to code that is defined outside
that scope.
• Thus, when you declare a variable within a scope, you are
localizing that variable and protecting it from unauthorized
access and/or modification.
Example demonstrating block scope ([Link]):
Java

// Demonstrate block scope.


class Scope {
public static void main(String args[]) {
int x = 10; // known to all code within main x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
[Link]("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
[Link]("x is " + x);
Module-1 Syllabus Page 23
[Link]("x is " + x);
}
}
• The variable x is declared at the start of main()'s scope and
is accessible to all subsequent code within main().
• Within the if block, y is declared. Since a block defines a
scope, y is only visible to other code within its block.
• If you remove the leading comment symbol from // y =
100;, a compile-time error will occur, because y is not
visible outside of its block.
• Within the if block, x can be used because code within a
block (that is, a nested scope) has access to variables
declared by an enclosing scope.
• Within a block, variables can be declared at any point, but
are valid only after they are declared.
• If you declare a variable at the end of a block, it is
effectively useless, because no code will have access to it.
• Here is another important point to remember: variables are
created when their scope is entered, and destroyed when
their scope is left. This means that a variable will not hold
its value once it has gone out of scope.
• A variable declared within a block will lose its value when
the block is left. Thus, the lifetime of a variable is confined
to its scope.
• If a variable declaration includes an initializer, then that
variable will be reinitialized each time the block in which it
is declared is entered.
Example demonstrating lifetime of a variable ([Link]):
Java

// Demonstrate lifetime of a variable.


class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
[Link]("y is: " + y); // this always prints -1
y = 100;
Module-1 Syllabus Page 24
y = 100;
[Link]("y is now: " + y);
}
}
}
Output:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
➤ Type Conversion and Casting
• The process of converting one data type to another data
type is known as type conversion.
• If the two types are compatible, then Java will perform the
conversion automatically. For example, it is always possible
to assign an int value to a long variable.
• Not all types are compatible, and thus, not all type
conversions are implicitly allowed. For instance, there is no
automatic conversion defined from double to byte.
• Fortunately, it is still possible to obtain a conversion
between incompatible types. To do so, you must use a cast,
which performs an explicit conversion between
incompatible types.
➤ Java's Automatic Conversions
• When one type of data is assigned to another type of
variable, an automatic type conversion will take place if the
following two conditions are met:
○ The two types are compatible.
○ The destination type is larger than the source type.
• When these two conditions are met, a widening conversion
takes place. For example, the int type is always large
enough to hold all valid byte values, so no explicit cast
statement is required.
• For widening conversions, the numeric types, including
integer and floating-point types, are compatible with each
other. However, there are no automatic conversions from
Module-1 Syllabus Page 25
other. However, there are no automatic conversions from
the numeric types to char or boolean. Also, char and
boolean are not compatible with each other.
➤ Casting Incompatible Types
• Although automatic type conversions are helpful, they will
not fulfill all needs.
• For example, if you want to assign an int value to a byte
variable? This conversion will not be performed
automatically, because a byte is smaller than an int.
• This kind of conversion is called a narrowing conversion,
since you are explicitly making the value narrower so that it
will fit into the target type.
• To create a conversion between two incompatible types,
you must use a cast. A cast is simply an explicit type
conversion.
• General form of a cast: (target-type) value
• target-type specifies the desired type to convert the
specified value to.
• For example, the following fragment casts an int to a byte:
Java

int a;
byte b;
//...
b = (byte) a;

If the integer's value is larger than the range of a byte, it will


be reduced modulo (the remainder of an integer division by
the) byte's range.
• A different type of conversion will occur when a floating-
point value is assigned to an integer type: truncation.
• Integers do not have fractional components. Thus, when a
floating-point value is assigned to an integer type, the
fractional component is lost.
Example demonstrating casts ([Link]):
Java

// Demonstrate casts.
Module-1 Syllabus Page 26
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
[Link]("\nConversion of int to byte.");
b = (byte) i;
[Link]("i and b " + i + " " + b);
[Link]("\nConversion of double to int.");
i = (int) d;
[Link]("d and i " + d + " " + i);
[Link]("\nConversion of double to byte.");
b = (byte) d;
[Link]("d and b " + d + " " + b);
}
}
Output:
Conversion of int to byte. i and b 257 1
Conversion of double to int. d and i 323.142 323
Conversion of double to byte. d and b 323.142 67

Module-1 Syllabus Page 27


Arrays
08 October 2025 20:45

Arrays
• An array is a group of like-typed variables that are
referred to by a common name.
• Arrays of any type can be created and may have one or
more dimensions.
• A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related
information.
a) One-Dimensional Arrays
A one-dimensional array is essentially a list of like-typed
variables. To create an array, you first must create an array
variable of the desired type.
• General form of a one-dimensional array declaration:
type var-name[];
• type declares the base type of the array. The base type
determines the data type of each element that comprises
the array. Thus, the base type for the array determines
what type of data the array will hold. For example, the
following declares an array named month_days with the
type "array of int": int month_days[];
• The general form of new as it applies to one-dimensional
arrays appears as follows:

array-var = new type[size];


• Here, type specifies the type of data being allocated, and
size specifies the number of elements in the array. array-
var is the array variable that is linked to the array.
• To use new to allocate an array, you must specify the
type and number of elements to allocate. The elements in
the array allocated by new will automatically be
initialized to zero.

Module-1 Syllabus Page 28


Example of array allocation: month_days = new int[12];
• Once you have allocated an array, you can access a
specific element in the array by specifying its index within
square brackets. All array indexes start at zero.
• For example, this statement assigns the value 28 to the
second element of month_days: month_days[1] = 28;
• The next line displays the value stored at index 3:
[Link](month_days[3]);
Example demonstrating a one-dimensional array
([Link]):
Java

// Demonstrate a one-dimensional array.


class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
[Link]("April has " + month_days[3] + "
days.");
}
}
• When you run this program, it prints the number of days
in April. Java array indexes start with zero, so the number
Module-1 Syllabus Page 29
in April. Java array indexes start with zero, so the number
of days in April is month_days[3] or 30.
• It is possible to combine the declaration of the array
variable with the allocation of the array itself:

int month_days[] = new int[12];


• Arrays can be initialized when they are declared. An
array initializer is a list of comma-separated expressions
surrounded by curly braces.
• The array will automatically be created large enough to
hold the number of elements you specify in the array
initializer. There is no need to use new.
Example using an array initializer ([Link]):
Java

class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
[Link]("April has " + month_days[3] + "
days.");
}
}
• Java strictly checks to make sure you do not accidentally
try to store or reference values outside of the range of
the array. The Java run-time system will check to be sure
that all array indexes are in the correct range.
b) Multidimensional Arrays
• In Java, multidimensional arrays are actually arrays of
arrays.
• To declare a multidimensional array variable, specify each
additional index using another set of square brackets.
• Example for a two-dimensional array called twoD:

int twoD[][] = new int[4][5]; This allocates a 4 by 5 array


and assigns it to twoD. (Image showing the 4x5 array with
Module-1 Syllabus Page 30
and assigns it to twoD. (Image showing the 4x5 array with
row and column indices)
Demonstrate a two-dimensional array ([Link]):
Java

// Demonstrate a two-dimensional array.


class TwoDArray {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
int i, j, k = 0;
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++) {
[Link](twoD[i][j] + " ");
}
[Link]();
}
}
}
Output:
01234
56789
10 11 12 13 14
15 16 17 18 19
• When you allocate memory for a multidimensional array,
you need only specify the memory for the first (leftmost)
dimension. You can allocate the remaining dimension
separately.
• For example, this following code allocates memory for
the first dimension of twoD when it is declared. It
allocates the second dimension manually:
Module-1 Syllabus Page 31
allocates the second dimension manually:
Java

int twoD[][] = new int[4][];


twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
• This is not an advantage if all the rows are the same
length. However, this ability to individually allocate the
second dimension arrays in this situation means that you
can create ragged arrays (arrays of arrays of different
lengths).
Example demonstrating differing size second dimensions
([Link]):
Java

// Manually allocate differing size second dimensions.


class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for (i = 0; i < 4; i++) {
for (j = 0; j < i + 1; j++) {
twoD[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < i + 1; j++) {
[Link](twoD[i][j] + " ");
}
Module-1 Syllabus Page 32
}
[Link]();
}
}
}
Output:
0
12
345
6789
➤ Alternative Array Declaration Syntax
• There is a second form that may be used to declare an
array: type [] var-name;.
• The square brackets follow the type specifier, and not the
name of the array variable.
• Example (equivalent declarations):
Java

// Traditional
int intA1[] = new int[3];
int intA2[] = new int[3];

// Alternative
int[] intA3 = new int[3];
int[] intA4 = new int[3];
• The following declarations are also equivalent:
Java

char twod1[][] = new char[3][4];


char[][] twod2 = new char[3][4];
• This alternative declaration form offers convenience
when declaring several arrays at the same time: int[]
nums1, nums2, nums3; // create three arrays of type int
• The alternative declaration form is also useful when
specifying an array as a return type for a method.

Module-1 Syllabus Page 33


specifying an array as a return type for a method.

Module-1 Syllabus Page 34


Operators
08 October 2025 20:46

Java Operators: Notes


Operators are special symbols used to perform specific
operations on one, two, or three operands and then return a
result. Java supports a rich set of operators, which can be
grouped into the following categories:
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical
operations.
Oper Name Description Exa Resu
ator mple lt
+ Additi Adds two operands. 10 + 15
on 5
- Subtra Subtracts the second operand from 10 - 5
ction the first. 5
* Multip Multiplies two operands. 10 * 50
licatio 5
n
/ Divisio Divides the left operand by the right. 10 / 3
n Returns an integer result if both 3
operands are integers (truncates the
decimal part).
% Modul Returns the remainder of the division 10 % 1
us operation. 3

2. Unary Operators
Unary operators act on a single operand.
Operat Name Description Example
or
++ Increme Increases the value of a++ (Post-increment)
nt an operand by 1. or ++a (Pre-
increment)
-- Decrem Decreases the value of a-- (Post-decrement)
Module-1 Syllabus Page 35
-- Decrem Decreases the value of a-- (Post-decrement)
ent an operand by 1. or --a (Pre-
decrement)
+ Unary Indicates a positive +5
Plus value (rarely used).
- Unary Negates an -a
Minus expression's value.
! Logical Inverts the boolean !isTrue
NOT value (e.g., !true is
false).

3. Relational (Comparison) Operators


Relational operators compare two operands and always return
a boolean result (true or false). These are crucial for decision-
making in if statements and loops.
Oper Name Description Exa Result
ator mple
== Equal To Checks if two operands are a == true or
equal. b false
!= Not Equal Checks if two operands are a != true or
To not equal. b false
> Greater Checks if the left operand is a > b true or
Than greater than the right. false
< Less Than Checks if the left operand is a < b true or
less than the right. false
>= Greater Checks if the left operand is a >= true or
Than or greater than or equal to the b false
Equal To right.
<= Less Than or Checks if the left operand is a <= true or
Equal To less than or equal to the b false
right.

4. Logical Operators (Boolean)


Logical operators combine multiple boolean expressions to
Module-1 Syllabus Page 36
Logical operators combine multiple boolean expressions to
produce a single boolean result.
Oper Name Description Example
ator
&& Conditional Returns true only if both (x > 0) &&
AND (Short- operands are true. Stops (y < 10)
Circuit) evaluation if the first operand
is false.
` ` Conditional
OR (Short-
Circuit)
& Bitwise Same logic as && but always condition1
AND evaluates both operands. &
condition2
` ` Bitwise OR Same logic
as `
! Logical NOT Inverts the state of a boolean !(x == y)
expression.
Short-Circuit vs. Bitwise Logical Operators: The conditional
operators (&& and ||) are generally preferred for boolean logic
because of short-circuit evaluation, which can improve
efficiency by skipping the evaluation of the second operand if
the result is already known.
5. Assignment Operators
The assignment operator (=) is used to assign a value to a
variable. Compound assignment operators provide a shorthand
way to perform an operation and assign the result back to the
original variable.
Operato Name Example Equivalent
r Shorthand To
= Simple Assignment a = 10 a = 10
+= Addition Assignment a += 5 a=a+5
-= Subtraction a -= 5 a=a-5
Assignment

Module-1 Syllabus Page 37


Assignment
*= Multiplication a *= 5 a=a*5
Assignment
/= Division Assignment a /= 5 a=a/5
%= Modulus Assignment a %= 3 a=a%3

6. The Conditional (Ternary) Operator


The conditional operator ? : is a shorthand for a simple if-else
statement. It takes three operands and is the only ternary
operator in Java.
Format:
Java

result = (condition) ? value_if_true : value_if_false;


Example:
Java

int max = (a > b) ? a : b;


// If a is greater than b, max = a; otherwise, max = b;
7. Bitwise and Bit Shift Operators
These operators perform operations directly on the individual
bits of integer types (long, int, short, char, byte).
Operat Name Description
or
& Bitwise AND Sets each bit to 1 if both
corresponding bits are 1.
` ` Bitwise OR
^ Bitwise XOR Sets each bit to 1 if only one of the
(Exclusive OR) corresponding bits is 1.
~ Bitwise Inverts all the bits (0 becomes 1, and
Complement 1 becomes 0).
<< Signed Left Shift Shifts the bit pattern to the left.
>> Signed Right Shifts the bit pattern to the right,
Shift preserving the sign bit.

Module-1 Syllabus Page 38


Shift preserving the sign bit.
>>> Unsigned Right Shifts the bit pattern to the right,
Shift filling the leftmost bits with 0s.

Operator Precedence
Precedence determines the order in which operators in an
expression are evaluated. Operators with higher precedence
are evaluated before those with lower precedence.
Precedenc Category Operators Associativi
e ty
Highest Postfix [] . (params) expr++ expr-- Left to
Right
Unary ++expr --expr +expr -expr Right to
~! Left
Multiplicati * / % Left to
ve Right
Additive +- Left to
Right
Shift << >> >>> Left to
Right
Relational < > <= >= instanceof Left to
Right
Equality == != Left to
Right
Bitwise & Left to
AND Right
Bitwise ^ Left to
XOR Right
Bitwise OR ` `
Logical AND && Left to
Right
Logical OR `

Module-1 Syllabus Page 39


Logical OR `
Conditional ? : Right to
Left
Lowest Assignment = += -= *= /= %= >>= <<= Right to
&= ^= |= Left

• Parentheses () can always be used to override the default


precedence and force an order of evaluation.

Module-1 Syllabus Page 40


Control Statements
08 October 2025 20:48

Control statements are the foundation of program flow,


determining the order in which a program's code is executed.
Java supports three main categories of control statements:

1. Selection Statements (Decision Making)


Selection statements allow a program to choose between
different paths of execution based on the result of a Boolean
condition.
A. The if Statement
The if statement is Java's most basic control statement, used to
conditionally execute a statement or a block of code.

Type Syntax Description


Simpl if Executes the statement (or block) only if
e if (condition) the condition evaluates to true.
{ statement;
}
if-else if (condition) Executes the "true block" if the condition
{ // True is true, and the "false block" if it is false.
Block } else
{ // False
Block }
if- if Allows for multiple conditions to be
else-if (condition1) tested sequentially. The first true
Ladde { ... } else if condition's block is executed, and the
r (condition2) entire structure is exited. The else block
{ ... } else (optional) executes if none of the
{ ... } preceding conditions are met.

B. The switch Statement


The switch statement provides a multiway branch for simpler,
more efficient selection over the if-else-if ladder when
comparing a single expression against multiple constant values.
• Expression: The expression must resolve to a value of type

Module-1 Syllabus Page 41


• Expression: The expression must resolve to a value of type
byte, short, int, char, an enum, or a String.
• case labels: Each case must specify a unique, constant
value.
• break: The break keyword is essential. Without it, execution
will "fall through" to the next case block, regardless of
whether that case label matches the switch expression.
• default: The default statement is optional and executes if
no case match is found.

switch (expression) {
case constant1:
// code block 1
break;
case constant2:
// code block 2
break;
default:
// code block if no match is found
}

2. Iteration Statements (Looping)


Iteration statements, or loops, enable a block of code to be
repeatedly executed as long as a specified Boolean condition
remains true.
A. The for Loop
The for loop is ideal for situations where the number of
iterations is known or where a loop control variable needs to be
initialized, tested, and incremented/decremented.
Compone Description
nt
Initializat Executed once at the start of the loop (e.g., int i = 0).
ion
Conditio Checked before every iteration. If true, the loop
n continues; if false, the loop terminates.
Iteration Executed after every iteration (e.g., i++).
Module-1 Syllabus Page 42
Iteration Executed after every iteration (e.g., i++).
Export to Sheets
Syntax (General Form):

for (initialization; condition; iteration) {


// code to be executed repeatedly
}
B. The while Loop
The while loop is Java's most fundamental loop. It iterates a
block of code as long as its Boolean condition remains true.
• Pre-test loop: The condition is tested before the loop body
is executed. If the condition is initially false, the loop body
will never execute.
Syntax:

while (condition) {
// code block
}
C. The do-while Loop
The do-while loop is similar to the while loop but guarantees
that the loop body will be executed at least once.
• Post-test loop: The condition is tested after the loop body is
executed.
Syntax:

do {
// code block (always executed at least once)
} while (condition); // semicolon is required
D. The for-each Loop (Enhanced for Loop)
This simplified iteration is designed to cycle through the
elements of arrays and collections. It eliminates the need for a
loop counter.
Syntax:

Module-1 Syllabus Page 43


for (type element : collectionOrArray) {
// code to process 'element'
}

3. Jump Statements
Jump statements are used to unconditionally transfer program
control to another part of the code.
A. The break Statement
The break statement has three uses:
1. Terminate a switch statement: Prevents fall-through to the
next case.
2. Exit a loop: Forces immediate termination of a for, while, or
do-while loop, bypassing any remaining code in the loop
body and continuing execution after the loop.
3. Go to a label (rarely used): Can be used with a label to
jump to the end of a specific block of code.
B. The continue Statement
The continue statement forces an early iteration of a loop,
skipping the remainder of the current loop body and
proceeding immediately to the next iteration.
• In a for loop, it skips to the iteration expression.
• In while and do-while loops, it skips to the conditional
expression.
C. The return Statement
The return statement is used to explicitly return from a
method.
• It causes program control to transfer back to the caller of
the method.
• If the method is declared to return a value (not void), return
must be followed by the value or expression to be returned.
Syntax:

return; // for void methods


return value; // for methods that return a type

Module-1 Syllabus Page 44


break statement
• Used to exit from a loop or switch statement immediately.
• Control moves to the statement after the loop or switch.
Example:

class BreakExample {
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
if(i == 3) {
break; // exit the loop when i is 3
}
[Link](i);
}
[Link]("Loop ended");
}
}
Output:

1
2
Loop ended
continue statement
• Used to skip the current iteration of a loop.
• Control moves to the next iteration of the loop.
Example:

class ContinueExample {
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
if(i == 3) {
continue; // skip when i is 3
}
[Link](i);
}
}
}
Output:

1
2
4 Module-1 Syllabus Page 45
4
5

• Used to exit from a method.


• Can optionally return a value to the caller.
Example:

class ReturnExample {
public static void main(String[] args) {
[Link]("Sum: " + add(10, 20));
}
static int add(int a, int b) {
return a + b; // returns the sum
}
}
Output:

Sum: 30

Module-1 Syllabus Page 46


AccessModifiers
17 October 2025 13:43

Access Modifiers in java


6. Summary Table
Modifie Same Same Subclass Other
r Class Package (different Package
package)
public ✅ ✅ ✅ ✅
protect ✅ ✅ ✅ ❌
ed
default ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌

All modifiers can be accessed within same class


package com.a;
class C1{
public int x=5;
protected int y=45;
int z=6;//default
private int p=78;
public void meth1() {
[Link](x);
[Link](y);
[Link](z);
[Link](p);
}
}
public class Acess {
public static void main(String[]args) {
C1 c=new C1();

Module-1 Syllabus Page 47


c.meth1();
}
}
Private modifier cant be accessed within same pckg
package com.a;
class C1{
public int x=5;
protected int y=45;
int z=6;

private int p=78;


public void meth1() {
[Link](x);
[Link](y);
[Link](z);
[Link](p);

}
}

public class Acess {


public static void main(String[]args) {
C1 c=new C1();
//c.meth1();

[Link](c.x);
[Link](c.y);
[Link](c.z);
[Link](c.p);

Module-1 Syllabus Page 48


}
}
Within subclass:within same package
package myPackage;

public class A {

public int publicNum = 10;


protected int protectedNum = 20;
int defaultNum = 30;
private int privateNum = 40;

public void display() {


[Link]("Inside Class A");
[Link]("Public: " + publicNum);
[Link]("Protected: " + protectedNum);
[Link]("Default: " + defaultNum);
[Link]("Private: " + privateNum);
}
}
package myPackage;

public class A {

public int publicNum = 10;


protected int protectedNum = 20;
int defaultNum = 30;
private int privateNum = 40;

public void display() {


Module-1 Syllabus Page 49
public void display() {
[Link]("Inside Class A");
[Link]("Public: " + publicNum);
[Link]("Protected: " + protectedNum);
[Link]("Default: " + defaultNum);
[Link]("Private: " + privateNum);
}
}

Different package
package anotherPackge;
import myPackage.A;

public class C extends A {


public static void main(String[] args) {
C obj = new C();
[Link]("Accessing from subclass (different
package):");
[Link]("Public: " + [Link]); // ✅
accessible
[Link]("Protected: " + [Link]); //
✅ accessible via inheritance
// [Link]("Default: " + [Link]); // ❌
Not accessible
// [Link]("Private: " + [Link]); // ❌
Not accessible
}
}
Different package
package mypackage;

Module-1 Syllabus Page 50


public class A {
public int publicNum = 10;
protected int protectedNum = 20;
int defaultNum = 30; // no modifier = default
private int privateNum = 40;

public void show() {


[Link]("Inside class A:");
[Link]("Public: " + publicNum);
[Link]("Protected: " + protectedNum);
[Link]("Default: " + defaultNum);
[Link]("Private: " + privateNum);
}
}

package anotherpackage;
import mypackage.A;
public class B {
public static void main(String[] args) {
A obj = new A();
[Link]("Accessing from another package
(non-subclass):");

[Link]("Public: " + [Link]); // ✅


accessible
// [Link]("Protected: " + [Link]);
// ❌ not accessible
// [Link]("Default: " + [Link]); //
❌ not accessible
// [Link]("Private: " + [Link]); //
❌ not accessible

Module-1 Syllabus Page 51


❌ not accessible
}
}

Module-1 Syllabus Page 52


Getter n Setter Method
17 October 2025 13:47

Getter n setter methods in java


In Java, getter and setter methods are used to access and
modify private variables of a class.
They help achieve encapsulation — one of the key principles of
Object-Oriented Programming (OOP).
class Student {
// private variables (data hiding)
private String name;
private int age;

// getter method for name


public String getName() {
return name;
}

// setter method for name


public void setName(String name) {
[Link] = name;
}

// getter method for age


public int getAge() {
return age;
}

// setter method for age (with validation)


public void setAge(int age) {

Module-1 Syllabus Page 53


if (age > 0) {
[Link] = age;
} else {
[Link]("Age cannot be negative!");
}
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student();
[Link]("Shiva");
[Link](21);
[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());
}
}

Module-1 Syllabus Page 54


Array
07 October 2025 19:22

An array is a collection of elements of the same data type, stored in


contiguous memory locations.
It helps to store multiple values in a single variable, instead of declaring
many separate variables.

1)Declaring Array
type arrayname[];
type [] arrayname;

2)Creating Array:
arrayname=new type[size];

3)initializing Array
arrayname[Subscript]=value;

Without array
int a1 = 10, a2 = 20, a3 = 30;

With array
int arr[] = {10, 20, 30};
Program
class ArrayExample {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 92, 88};

[Link]("Marks:");

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


[Link](marks[i]);
}

}
}
o/p
Marks:
85
90
78
92
88

Type Description Example


Single Dimensional Array Normal array with one row int[] arr = new int[5];
Multi Dimensional Array Array inside another array int[][] arr = new int[3][3];

Array Page 55
Multi Dimensional Array Array inside another array int[][] arr = new int[3][3];
Jagged Array Array with different column sizes in each row int[][] arr = new int[3][];

1)Single dimensional array

A 1D array (one-dimensional array) in Java is a collection of elements of the


same data type, stored in a single row (a linear form
class SingleArrayExample {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};

[Link]("Elements in array:");
for(int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}
}
}

o/p
Elements in array:
5
10
15
20
25

Declaration:declaring the array


int[] arr;

Memory Allocation:creating memory location


arr = new int[5]; // 5 elements

Initialization:putting values in memory location


arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

2) 2D Array

class TwoDArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Array Page 56
};

[Link]("2D Array Elements:");

for(int i = 0; i < [Link]; i++) { // rows


for(int j = 0; j < matrix[i].length; j++) { // columns
[Link](matrix[i][j] + " ");
}
[Link](); // new line after each row
}
}
}
2D Array Elements:
123
456
789

Declaration
int[][] arr;

MemoryAllocation
arr = new int[3][3]; // 3 rows, 3 columns

Initialization
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
arr[2][0] = 7;
arr[2][1] = 8;
arr[2][2] = 9;

Array Page 57

You might also like