Java Programming Unit-I Notes
Java Programming Unit-I Notes
o In 1991, a small team of engineers at Sun Microsystems led by James Gosling started
a project called “Green Project.”
o The goal was to develop software for digital devices such as televisions, VCRs, and
set-top boxes.
o The first name of the language was “Oak.”
o Later the team selected a new name Java, inspired by Java coffee, which the
developers used to drink while working.
o In 1995, Sun Microsystems officially released Java 1.0.
o The slogan was: “Write Once, Run Anywhere” (WORA).
o Java quickly became popular because programs written in Java could run on any system
using a Java Virtual Machine (JVM).
o In 2010, Oracle Corporation acquired Sun Microsystems.
o Oracle continues to maintain and develop Java.
Java Editions:
Java is available in different editions (or platforms), each designed for a specific type of
application development. The major Java editions are:
o Previously called J2EE, now known as Jakarta EE after Oracle handed over to
Eclipse Foundation
o Used for building enterprise-level and large-scale web applications.
• Java ME (Java Micro Edition)
o Used to develop applications for small, resource-constrained devices.
o It is designed for Embedded systems, Mobile devices, Smart cards, Sensors /
IoT devices
o Used for building rich graphical user interfaces (GUI) with modern features.
o JavaFX replaced the older Swing and AWT GUI technologies in modern Java
development.
1. Encapsulation
Inheritance allows one class to acquire the properties and behaviors of another class.
3. Polymorphism
Polymorphism means one name, many forms. A single method behaves differently
based on the object that calls it.
Types:
4. Abstraction
Abstraction means hiding complex internal details and showing only the necessary
information to the user
What is an Object?
A software object
• Software objects consist of state and related behaviour. An object stores its state
in fields (variables in some programming languages) and exposes its behaviour
through methods (functions in some programming languages).
• Methods operate on an object's internal state and serve as the primary mechanism for
object-to-object communication.
Data encapsulation:
Hiding internal state and requiring all interaction to be performed through an object's
methods is known as data encapsulation — a fundamental principle of object-oriented
programming.
• By attributing state (current speed, current pedal cadence, and current gear) and
providing methods for changing that state, the object remains in control of how the
outside world is allowed to use it. For example, if the bicycle only has 6 gears, a
method to change gears could reject any value that is less than 1 or greater than 6.
• Bundling code into individual software objects provides a number of benefits,
including:
1. Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Once created, an object can
be easily passed around inside the system.
What is a Class?
void printStates() {
[Link]("cadence:" +cadence + " speed:" + speed + " gear:" + gear);
}
}
• You may have noticed that the Bicycle class does not contain a main() method. That
is because it is not a complete application; it is just the blueprint for bicycles that might
be used in an application. The responsibility of creating and using new Bicycle objects
belongs to some other class in your application.
class BicycleDemo {
public static void main(String[] args) {
// Invoke methods on
// those objects
[Link](50);
[Link](10);
[Link](2);
[Link]();
[Link](50);
[Link](10);
[Link](2);
[Link](40);
[Link](10);
[Link](3);
[Link]();
}
}
What is Inheritance?
• Different kinds of objects often have a certain amount in common with each other.
• Ex:
o Mountain bikes, road bikes, and tandem bikes, for example, all share the
characteristics of bicycles (current speed, current pedal cadence, current gear).
o Yet each also defines additional features that make them different: tandem
bicycles have two seats and two sets of handlebars; road bikes have drop
handlebars; some mountain bikes have an additional chain ring, giving
them a lower gear ratio.
• Object-oriented programming allows classes to inherit commonly used state and
behavior from other classes.
Java is the most popular object-oriented programming language. Java has many
advanced features; a list of key features is known as Java Buzz Words. The java team
has listed the following terms as java buzz words.
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Architecture-neutral (or) Platform Independent
• Multi-threaded
• Interpreted and High performance
• Distributed
• Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++. In a java programming language, many
complicated features like pointers, operator overloading, structures, unions, etc.
have been removed. One of the most useful features is the garbage collector it makes
java simpler.
Secure
Java is said to be more secure programming language because it does not have pointers
concept, java provides a feature "applet" which can be embedded into a web
application. The applet in java does not allow access to other parts of the computer,
which keeps away from harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on
any computer or operating system. For example, an applet developed using java runs
on a wide variety of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
Robust
Java is more robust because the java code can be executed on a variety of environments,
java has a strong memory management mechanism (garbage collector), java is a
strictly typed language, it has a strong set of exception handling mechanism, and
many more.
Java has invented to aechieve "write once; run anywhere, any time, forever". The java
provides JVM (Java Virtual Machine) to achieve architectural-neutral or platform-
independent. The JVM allows the java program created using one operating system can
be executed on any other operating system.
Multi-threaded
Distributed
Java programming language supports TCP/IP protocols which enable the java to
support the distributed environment of the Internet. Java also supports Remote Method
Invocation (RMI), this feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on
a running system and it has a dynamic memory allocation and deallocation (objects and
garbage collector).
JVM Architecture
JVM is an abstract machine that provides a runtime environment for executing Java bytecode.
Its architecture consists of Class Loader Subsystem, Runtime Data Areas, and Execution
Engine. The Class Loader loads and verifies classes, memory areas store data during execution,
and the Execution Engine executes bytecode using interpreter and JIT compiler. JVM ensures
portability, security, and efficient memory management.
Overview of JVM Architecture
JVM architecture is broadly divided into three main subsystems:
1. Class Loader Subsystem
2. Runtime Data Areas (Memory Areas)
3. Execution Engine
Additionally, JVM interacts with Native Libraries using JNI.
Class Loader Subsystem:
The Class Loader loads .class files into memory when a program runs.
Types of Class Loaders:
1. Bootstrap Class Loader
o Loads core Java classes ([Link], [Link], etc.)
2. Extension Class Loader
o Loads classes from extension directories ([Link], [Link],
[Link])
3. Application (System) Class Loader
o Loads user-defined classes from classpath
Steps in Class Loading:
• Loading – Reads the .class file
• Linking : The dependencies of all the classes are resolved
o Verification – Ensures bytecode safety
o Preparation – Allocates memory for static variables
o Resolution – Converts symbolic references to direct references
• Initialization – Executes static initializers
Runtime Data Areas (Memory Areas):
These are the memory regions used during program execution.
a) Method Area (Shared)
• Stores class-level data:
o Class metadata
o Static variables
o Method bytecode
• Shared among all threads
b) Heap Area (Shared)
• Stores objects and instance variables
• Managed by Garbage Collector
• Largest memory area
c) Stack Area (Per Thread)
• Stores method calls, local variables and partial results for method execution
• Each thread has its own stack
• Stack Frame contains:
o Local variables
o Operand stack
o Return address
d) PC (Program Counter) Register
• Holds address of the currently executing instruction
• One PC register per thread
e) Native Method Stack
• Stores native code (written in languages like C and C++) that java
programs can interact with.
Execution Engine:
Responsible for executing bytecode.
Components:
1. Interpreter
o Executes bytecode line by line
o Slower execution
2. JIT Compiler (Just-In-Time)
o Converts frequently used bytecode into native machine code
o Improves performance
3. Garbage Collector
o Automatically removes unused objects from heap
o Prevents memory leaks
Java Native Interface (JNI):
• Enables JVM to interact with native libraries written in C/C++
• Used for platform-specific operations
Working of JVM (Flow):
1. Java source code (.java) is compiled by javac
2. Bytecode (.class) is generated
3. Class Loader loads bytecode into JVM
4. Bytecode is verified and stored in memory
5. Execution Engine executes bytecode
6. Output is produced
Java source file structure
A Java source file is a text file with the extension .java. It contains Java program code written
in a well-defined structure.
Documentation Section
Package statements
Import statements
Interface statements
1. Comments
• Used to describe the program.
• Ignored by the compiler.
• Types:
o Single-line //
// This is a simple Java program
o Multi-line /* */
/*
This is a multiline comment.
It is used to write explanations
across multiple lines.
The compiler ignores this block.
*/
o Documentation /** */
Processed by the javadoc tool to create HTML documentation
/**
* This class represents a Student.
*/
class Student {
}
2. Package Statement (Optional)
• Groups related classes into a package.
• Must be the first executable statement in the file.
• Only one package statement is allowed.
package [Link];
3. Import Statements (Optional)
• Used to access predefined classes from other packages.
• Written after the package statement.
import [Link];
4. Class Declaration
• Every Java program must have at least one class.
• The file name must match the public class name.
public class Sample {
}
5. Variables (Fields)
• Used to store data.
• Can be local variables or instance variables or static variables.
int number;
static int count;
6. Methods
• Define behavior of the class.
• main() method is the entry point of the program.
public static void main(String[] args) {
[Link]("Welcome");
}
7. Statements
• Instructions executed by the program.
• Written inside methods.
int a = 10;
[Link](a);
Important Rules to Remember
• Only one public class is allowed in a source file.
• File name must match the public class name.
• Order should be:
1. Package
2. Import
3. Class
• Java is case-sensitive.
• Program execution starts from main().
A First Simple Program:
Java Tokens
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 to name things, such as classes, variables, and methods. An
identifier may be any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters.
Valid Identifiers:
Literals:
A constant value in Java is created by using a literal representation of it.
Comments:
As mentioned, there are three types of comments defined by Java. You have already seen
two: single-line and multiline. The third type is called a documentation comment. This
type
of comment is used to produce an HTML file that documents your program. The
documentation comment begins with a /** and ends with a */.
Separators:
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon.
Java Keywords:
• Keywords in Java are reserved words that have a predefined meaning to the compiler.
• They cannot be used as identifiers (class names, variable names, method names).
show(10); // Valid
show("Ten"); // Compile-time error
e) No Automatic Type Coercion for Conflicting Types
• Java does not automatically convert incompatible types.
• Explicit type casting is required when conversion is necessary.
Example:
int x = (int) 10.5; // Explicit casting required
Without casting:
int x = 10.5; // Compile-time error
Data Types
• Java defines eight primitive types of data: byte, short, int, long, char, float, double,
and boolean.
• The primitive types are also commonly referred to as simple types.
• These eight primitive types can be put in four groups
Integers:
• Java defines four integer types: byte, short, int, and long. All of these are
signed, positive and negative values.
• Java does not support unsigned, positive-only integers
• The width and ranges of these integer types vary widely, as shown in this table:
byte:
• Smallest integer type
• This is a signed 8-bit type that has a range from –128 to 127.
• Useful for file handling, network data, or raw binary data
• Byte variables are declared by use of the byte keyword
byte b, c;
Short:
• short is a signed 16-bit type.
• It has a range from –32,768 to 32,767.
• short variables are declared by use of the short keyword
short s;
short t;
int:
• The int data type is the most commonly used integer type in Java.
• It is a signed 32-bit type that has a range from –2,147,483,648 to
2,147,483,647.
• variables of type int are commonly employed to control loops and to
index arrays.
• When byte and short variables are used in expressions, Java
automatically promotes them to int before performing the operation.
• int variables are declared by use of the int keyword
int i, j;
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 ( –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 )
• This makes it useful when big, whole numbers are needed.
• long variables are declared by use of the long keyword
long i, j;
Floating-Point Types:
• Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision.
• There are two kinds of floating-point types, float and double, which
represent
single- and double-precision numbers, respectively.
• Their width and ranges are
float:
• The type float specifies a single-precision value that uses 32 bits of
storage
• Variables of type float are useful when you need a fractional
component, but don’t require a large degree of precision.
• float can be useful when representing rupees, dollars and cents.
• some example float variable declarations:
float hightemp, lowtemp;
double:
• Double precision, as denoted by the double keyword, uses 64 bits to
store a value
• When you need to maintain accuracy over many iterative calculations,
or are manipulating large-valued numbers, double is the best choice.
• some example double variable declarations:
double hightemp, lowtemp;
Characters:
• In Java, characters are stored using the char data type.
• Java char is different from C/C++ char; C/C++ uses 8 bits, while Java
uses 16 bits.
• Java uses Unicode, a universal character set that supports all human
languages.
• Unicode includes characters from Latin, Greek, Arabic, Cyrillic,
Hebrew, Japanese, Korean, and more.
• The range of char is 0 to 65,536.
• char is an unsigned type, so it cannot store negative values.
• ASCII characters range from 0 to 127 and are part of Unicode.
• Java uses Unicode to ensure internationalization and global
portability, even though it is less memory-efficient for some
languages.
• Although char is designed to hold Unicode characters, it can also be used as an
integer type on which you can perform arithmetic operations
boolean:
• Java provides a primitive data type boolean to represent logical values.
• A boolean variable can have only two values: true or false.
• Boolean values are mainly used in decision-making and control statements.
• Returned by relational operators such as <, >, <=, >=, ==, !=
boolean b = false;
b = (10 > 9); // true
if(b) { }
Literals
• Literals are fixed constant values assigned directly to variables in a Java program.
• They represent constant data and do not change during program execution.
• Different type of Literals are
o Integer Literals
o Floating Point Literals
o Boolean Literals
o Character Literals
o String Literals
Integer Literals:
• Integer literals represent whole number constants in a Java program.
• Common examples: 1, 2, 42 (decimal / base-10 numbers).
Number Systems Used in Integer Literals
1. Decimal (Base 10)
• Default number system.
• Digits: 0–9
• Leading zero is not allowed.
• Example:
int a = 42;
2. Octal (Base 8)
• Digits: 0–7
• Indicated by a leading zero (0).
• Example:
int x = 012; // decimal 10 ( 1*81 + 2*80 = 8+2 =10)
• Invalid example:
int y = 09; // error (9 is not allowed in octal)
3. Hexadecimal (Base 16)
• Digits: 0–9 and A–F / a–f
• Indicated by 0x or 0X.
• Commonly used because it matches 8, 16, 32, 64-bit word sizes.
• Example:
int h = 0x1A; // decimal 26 (1*161 + 10*160 = 16+10 =26)
Type of Integer Literals
• By default, integer literals are of type int (32-bit).
• Range: –2,147,483,648 to 2,147,483,647.
Assigning Integer Literals to Other Types
• An integer literal can be assigned to:
o byte or short → only if value is within range
byte b=16;
o long → always allowed
long l=256;
Long Literals
• Must end with L or l.
• Example:
long n = 9223372036854775807L;
Binary Literals (JDK 7 onwards)
• Binary (base 2) literals are prefixed with 0b or 0B.
• Useful for bit manipulations.
• Example:
int x = 0b1010; // decimal 10 (1*23+0*22 + 1*21 + 0*20 = 8+0+2+0
=10)
Underscores in Integer Literals (JDK 7 onwards)
• Underscores (_) improve readability.
• Ignored by the compiler.
• Can appear between digits only.
• Examples:
int a = 1_23_456;
int b = 123___456___789;
int c = 0b1101_0101_0001_1010;
Floating-Point Literals:
• Floating-point literals represent decimal numbers with a fractional part.
• Used when values require precision beyond integers.
Forms of Floating-Point Literals
1. Standard Notation
• Consists of:
o Whole number part
o Decimal point
o Fractional part
• Examples:
2.0
3.14159
0.6667
2. Scientific Notation
• Written as a decimal number multiplied by a power of 10.
• Uses E or e followed by an exponent.
• Exponent can be positive or negative.
Examples:
6.022E23 (6.022 * 1023)
314159E-05 (314159 * 10-5)
2e+100 (2 * 10100)
Default Type of Floating-Point Literals
• Floating-point literals are double by default.
• double uses 64 bits of memory.
Specifying float and double Literals
• To specify a float literal, append F or f.
• Appending D or d explicitly specifies a double (optional).
Examples:
float f = 3.14f;
double d = 3.14;
Hexadecimal Floating-Point Literals
• Rarely used.
• Use 0x prefix and P or p instead of E.
• P specifies a power of 2 (binary exponent).
Example:
double x = 0x12.2P2; // value is 72.5
(12.2)16 * 22= ( (1*161 + 2*160) . ( 2 * 16-1 ) ) * 4 = (18 + 0.125) * 4 = 18.125 * 4 =
72.5
Underscores in Floating-Point Literals (JDK 7+)
• Improve readability of large numbers.
• Ignored by the compiler.
• Allowed between digits only.
• Can be used in fractional part as well.
Examples:
double num1 = 9_423_497_862.0;
double num2 = 9_423_497.1_0_9; // fractional part is .109
Boolean Literals:
• Boolean literals represent logical constant values in Java.
• There are only two boolean literals:
o true
o false
Key Characteristics
• Boolean literals do not have any numeric representation.
• true is not equal to 1 and false is not equal to 0.
• Java does not allow implicit conversion between boolean and numeric types.
Usage of Boolean Literals
• Can be assigned only to variables of type boolean.
• Can be used in logical and conditional expressions.
• Commonly used with:
o Relational operators (<, >, ==, etc.)
o Logical operators (&&, ||, !)
o Control statements (if, while, for)
Example:
boolean flag = true;
if(flag) {
[Link]("Condition is true");
}
Invalid Usage
int x = true; // Compile-time error
Character Literals:
• Character literals represent single characters in Java.
• Java characters are based on the Unicode character set.
• Each character is a 16-bit value and internally represented as an integer.
• Character values can participate in arithmetic operations like addition and
subtraction.
Representation of Character Literals
• A character literal is written inside single quotes (' ').
• Any visible ASCII character can be written directly.
Examples:
'a'
'z'
'@'
Escape Sequences in Character Literals
• Used for characters that cannot be typed directly.
• Common escape sequences include:
Declaration Rules
• Variables must be declared before they are used.
• A variable declared at the end of a block is practically useless.
• Using a variable before declaration causes a compile-time error.
Lifetime of a Variable
• Variables are created when their scope is entered.
• Variables are destroyed when their scope is exited.
• A variable does not retain its value once it goes out of scope.
Reinitialization of Variables
• Variables declared inside a block with an initializer are reinitialized every time the
block is entered.
• This is common in loops.
Selection statements
Selection statements in Java are used to make decisions in a program and execute different
blocks of code based on conditions. They allow the program to choose one path among multiple
possible paths.
Types of Selection Statements in Java:
Java provides three main types of selection statements:
1. if Statement
Syntax:
if (condition) {
// code to execute if condition is true
}
Example:
int age = 20;
if (age >= 18) {
[Link]("Eligible to vote");
}
2. if-else Statement
Syntax:
if (condition) {
// executed when condition is true
} else {
// executed when condition is false
}
Example:
int num = 5;
if (num % 2 == 0) {
[Link]("Even number");
} else {
[Link]("Odd number");
}
3. else-if Ladder
Used when there are multiple conditions to check.
Syntax:
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else if (condition3) {
// block 3
} else {
// default block
}
Example:
int marks = 72;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 60) {
[Link]("Grade C");
} else {
[Link]("Grade D");
}
4. Nested if Statement
if statements inside another if.
Example:
int a = 10;
int b = 20;
if (a > 0) {
if (b > 0) {
[Link]("Both numbers are positive");
}
}
5. switch Statement
Used when one value needs to be tested against multiple cases.
Works with int, char, String, enum etc.
Syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statements
}
Example:
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}
Iteration Statements
Iteration statements in Java are used to repeat a block of code multiple times. They allow
programs to perform looping, which is essential for tasks like counting, traversing arrays,
repeating operations, etc.
These are also called looping statements or control flow loops.
Operators
• Java provides a rich set of operators to perform operations on variables and values.
Java operators are mainly classified into:
1. Arithmetic Operators
2. Bitwise Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operator
6. Ternary Operator
These operators act on operands and produce a result .
Arithmetic Operators:
• Arithmetic operators are used for mathematical calculations, similar to
algebra.
List of Arithmetic Operators
a = a % 2;
a %= 2;
In Java, increment (++) and decrement (--) operators are unary operators used to
increase or decrease the value of a variable by 1.
b) Post-increment (variable++)
• The current value is used first
• Then the variable is incremented
Example:
int a = 5;
int b = a++;
[Link](a); // 6
[Link](b); // 5
b) Post-decrement (variable--)
• Value is used first
• Then decremented
Example:
int a = 5;
int b = a--;
[Link](a); // 4
[Link](b); // 5
• Increment and decrement operators Works only with variables, not constants
5++; // Error
Bitwise Operators:
• Bitwise operators work on individual bits of integer types (byte, short, int, long, char).
• All of the integer types (except char) are signed integers. This means that they can
represent negative values as well as positive ones.
• Java represents negative numbers using two’s complement encoding. In this method,
all the bits of a number are first inverted (0 becomes 1 and 1 becomes 0), and then 1 is
added to the resulting value.
• Example : -5 ( 11111011 )
5 = 00000101
Invert all the bits (One’s Complement):
00000101
11111010
Add 1 to the inverted bits (Two’s Complement):
11111010
+ 1
------------
11111011
• To decode a negative number, first invert all of the bits, then add 1.
• The high-order bit determines the sign of an integer ( 1 - negative number, 0 – positive
number)
• List of Bitwise Operators
When you are shifting right, the top (leftmost) bits exposed by the right shift are filled
in with the previous contents of the top bit. This is called sign extension and serves to
preserve the sign of negative numbers when you shift them right.
11111111 11111111 11111111 11111000 -8
>>1
11111111 11111111 11111111 11111100 -4
Unsigned Right Shift Operator ( >>> ):
The unsigned right shift operator (>>>) shifts all bits of a number to the right by a
specified number of positions without preserving the sign bit.
General Form
value >>> num
• value → the number whose bits are to be shifted
• num → number of bit positions to shift right
Working of Unsigned Right Shift Operator
When a value is unsigned right shifted:
• Bits are moved right by num positions
• Low-order bits that move beyond the limit are discarded
• Zeros (0) are always filled on the left side, regardless of whether the
number is positive or negative
Important Points
• The unsigned right shift does not preserve the sign
• It treats the number as an unsigned binary value
• It is useful when working with raw binary data, bit masks, and low-level
operations
• Available only for int and long data types in Java
Example with Positive Number
int a = 8; // Binary: 00000000 00000000 00000000 00001000
a = a >>> 2; // Binary: 00000000 00000000 00000000 00000010
Result: 2
Example with Negative Number
int a = -1; // Binary: 11111111 11111111 11111111 11111111
a = a >>> 24; // Binary: 00000000 00000000 00000000 11111111
Result: 255
Relational Operators:
• Relational operators are used to compare two operands and determine the relationship
between them.
• They are mainly used to check equality and ordering.
• The result of any relational operation is always a Boolean value: true or false.
• Relational operators are most commonly used in the expressions that control the if
statement and the various loop statements.
• Only numeric types can be compared using the ordering operators.
Ternary Operator (? :) :
• Java provides a special ternary (three-operand) operator, also called the conditional
operator, which is used as a compact alternative to certain if–else statements.
• This operator is represented by ? :
Syntax:
expression1 ? expression2 : expression3
• Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.
The result of the ? operation is that of the expression evaluated. Both expression2 and
expression3 are required to return the same (or compatible) type, which can’t be void.
Example
int a = 130;
byte b = (byte) a;
This is called a narrowing conversion, because data moves from a larger type to a
smaller type.
Effects of Casting
a) Integer to Byte (Modulo Reduction)
When an integer value exceeds the range of the target type, Java performs
modulo reduction.
Byte range: -128 to 127 (256 values)
int i = 257;
byte b = (byte) i;
Calculation:
257 % 256 = 1
Result:
b=1
b) Floating-Point to Integer (Truncation)
When a floating-point value is cast to an integer:
• Fractional part is discarded
c) Floating-Point to Byte
Two things happen:
1. Fractional part is truncated
2. Value is reduced modulo the byte range
double d = 323.142;
byte b = (byte) d;
Steps:
323 → 323 % 256 = 67
Result:
b = 67
Automatic Type Promotion in Expressions:
• Type promotion also occurs during expression evaluation, as intermediate results may
exceed the range of smaller data types.
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
Here:
• a * b = 2000 → exceeds byte range
• Java promotes byte operands to int automatically
Compile-Time Error Due to Promotion
byte b = 50;
b = b * 2; // Compile-time error
Reason
• b * 2 → operands promoted to int
• Result is int
• Cannot assign int to byte without casting
Correct Code
b = (byte)(b * 2); // correct statement
Arrays
• An array in Java is a collection of elements of the same data type stored in
contiguous memory locations.
• It allows you to store multiple values in a single variable instead of declaring many
separate variables.
Why Do We Use Arrays?
• To store a fixed number of elements.
• Easy to access elements using indexing.
• Useful for loops and data processing.
Types of Arrays
1. One-dimensional array (1D)
2. Two-dimensional array (2D / Matrix)
3. Multi-dimensional array
1. One-Dimensional Array
Declaration :
type var-name[ ];
int[] arr; // preferred style
// or
int arr[];
Memory Allocation:
array-var = new type [size];
arr = new int[5]; // size = 5
▪ Declaration and Memory Allocation can be done in single statement also
int arr[] = new int[5];
[Link]([Link]);
Initialization
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Declaration + Initialization
int[] arr = {10, 20, 30, 40, 50};
Array Indexing
• Index starts from 0
• Last index = size – 1
Example Program: 1D Array
class ArrayExample {
public static void main(String[] args) {
int[] num = {2, 4, 6, 8, 10};
[Link]("Array elements:");
for (int i = 0; i < [Link]; i++) {
[Link](num[i]);
}
}
}
2. Two-Dimensional Array (2D Array)
A 2D array looks like a table or matrix.
Declaration
int[][] matrix;
Allocation
matrix = new int[4][5]; // 4 rows, 5 columns
▪ Declaration and Memory Allocation can be done in single statement also
int matrix[][] = new int[4][5];
Initialization
int[][] matrix = {
{1, 2, 3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20}
};
for(int i=0;i<[Link];i++)
{
for(int j=0;j<twoD[i];j++)
{
twoD[i][j]=[Link]();
}
}
Array Properties in Java
Property Explanation
length stores array size
fixed size size cannot be changed once created
same data type all elements must be of one type
indexed elements accessed by index
Common Array Errors
Error Reason
ArrayIndexOutOfBoundsException accessing invalid index
NullPointerException using an uninitialized array
Useful Programs for Practice
1. Sum of Array Elements
int sum = 0;
int arr={10,20,30,40};
for(int x : arr) {
sum += x;
}
2. Find Largest Element
int arr={30,20,40,10};
int max = arr[0];
for(int x : arr) {
if(x > max) max = x;
}
3. Linear Search
for(int i = 0; i < [Link]; i++) {
if(arr[i] == key) {
[Link]("Found at index " + i);
}
}