Java
September 26, 2025
Java September 26, 2025 1 / 79
History of Java Programming Language
Key Milestones: Original Purpose:
1991: The Green Project started by Designed for interactive
James Gosling at Sun Microsystems television and digital
1992: Originally called ”Oak” after an devices
oak tree outside Gosling’s office Too advanced for cable
1995: Renamed to ”Java” (after Java TV industry at that time
coffee from Indonesia) Shifted focus to web
1995: Java 1.0 officially released (May programming
23, 1995)
Famous Quote
2010: Oracle acquired Sun
Microsystems and Java ”Write Once, Run Anywhere”
(WORA) - Java’s core
Present: Java continues to evolve with
philosophy
regular updates
Java September 26, 2025 2 / 79
Java Features and Characteristics
Core Features: Key Characteristics:
Platform Independent: ”Write Compiled & Interpreted: Uses
Once, Run Anywhere” bytecode
Object-Oriented: Everything is Architecture Neutral: Runs on
an object any platform
Simple: Easy to learn and use Portable: Code can run on
syntax different systems
Secure: Built-in security High Performance: JVM
features optimizations
Robust: Strong memory Distributed: Network-oriented
management programming
Multithreaded: Supports Dynamic: Supports runtime
concurrent programming modifications
Java September 26, 2025 3 / 79
Java Compilation Process
Step 1: Compilation Phase
What Happens During
Compilation Steps:
Compilation:
1 Write Java source code (.java file)
Source code is parsed
2 Java Compiler (javac) processes the and analyzed
source code
Syntax and semantic
3 Parser creates Abstract Syntax Tree errors are detected
(AST)
Bytecode is generated
4 Type checking and error validation (machine-independent)
5 Generates platform-independent .class files contain
bytecode (.class file) executable bytecode
Command Line Compilation: Key Point
1 javac HelloWorld . java // Bytecode is
Compile to bytecode platform-independent - same
2 // C r e a t e s H e l l o W o r l d . c l a s s f i l e .class file runs on any system
Java with JVM September 26, 2025 4 / 79
Java Execution Process
Step 2: Execution Phase
Execution Steps: JVM Components:
1 JVM (Java Virtual Machine) starts ClassLoader: Loads
2 ClassLoader loads bytecode into classes into memory
memory Bytecode Verifier:
3 Bytecode Verifier checks code safety Ensures code safety
and security JIT Compiler:
4 JIT Compiler converts frequently used Optimizes performance
bytecode to machine code Memory Manager:
5 Program executes on target platform Handles garbage
collection
Command Line Execution: JVM Benefits
1 java HelloWorld // ”Write Once, Run Anywhere”
Execute bytecode - JVM acts as intermediary
2 // JVM i n t e r p r e t s and r u n s t h e layer enabling cross-platform
program execution September 26, 2025
Java 5 / 79
Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming approach
that models real-world entities as ”objects” in code. Instead of
writing separate functions and data, OOP combines related data and
actions together into single units called objects.
Understanding OOP principles is not just beneficial, but essential for
writing effective, scalable, and maintainable Java applications, even
for the simplest programs.
At its core, OOP is about modeling real-world entities as ”objects”
within your code.
Instead of focusing solely on actions or procedures (what is
happening), OOP shifts the focus to the data itself and the objects
that operate on that data (who or what is being affected).
Java September 26, 2025 6 / 79
Why is OOP Important?
Modularity: Programs are broken down into smaller, self-contained
objects, making them easier to understand and manage.
Reusability: Objects can be reused in different parts of a program or
in entirely new projects, saving time and effort.
Maintainability: Changes in one part of the program are less likely to
affect other parts, simplifying debugging and updates.
Scalability: It’s easier to add new features or expand functionality by
creating new objects or extending existing ones.
Java September 26, 2025 7 / 79
Procedural vs. Object-Oriented Thinking
Procedural Programming Object-Oriented Programming
Focuses on a sequence of Combines data and the
instructions functions that operate on that
(procedures/functions) that data into self-contained units
operate on data. called ”objects”.
Data and functions are typically Objects protect their data and
separate, leading to potential expose controlled ways to
issues as data can be modified interact with it.
by any function. Example: A smart system (has
Example: A cooking recipe internal state/data and defined
(steps to transform ingredients). actions it can perform).
Java September 26, 2025 8 / 79
Procedural vs Object-Oriented: Simple Calculator Example
Procedural Approach Object-Oriented Approach
Step 1: Get first number Create a Calculator object
Step 2: Get operation (+, -, *, Calculator has:
/) Data: current result, memory
Actions: add(), subtract(),
Step 3: Get second number multiply(), divide()
Step 4: Perform calculation Use the calculator:
Step 5: Display result [Link](5)
Think like: Following a recipe Think like: Using a real calculator
Data (numbers) and functions Data and functions bundled
(add, subtract) are separate together
Focus on ”what steps to follow” Focus on ”what the object can
Linear execution from top to do”
bottom Object maintains its own state
Procedural: ”Follow these steps to calculate”
Object-Oriented: ”Ask the calculator to do the calculation”
Java September 26, 2025 9 / 79
Basic OOP Terminology
Before diving into code, let’s define some key terms you’ll encounter:
Class: A blueprint or template for creating objects. It defines the
properties (data) and behaviors (methods) that objects of that type
will have. Think of it like a cookie cutter.
Object: An instance of a class. It’s a real-world entity created from
the class blueprint. Think of it like an actual cookie made from the
cutter.
Method: A function or procedure associated with a class or object,
defining its behavior. These are actions an object can perform.
Attribute/Field: A variable that is part of a class or object, defining
its characteristics or state. These are the properties an object has.
Java September 26, 2025 10 / 79
Basic Java Program Structure
Simple Java Program Example:
1 p u b l i c c l a s s HelloWorld {
2 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( ” H e l l o , World ! ” ) ;
4 // V a r i a b l e d e c l a r a t i o n
5 i n t number = 4 2 ;
6 S t r i n g message = ”Welcome t o J a v a ! ” ;
7 // Method c a l l
8 System . o u t . p r i n t l n ( ”Number : ” + number ) ;
9 System . o u t . p r i n t l n ( message ) ;
10 }
11 }
File Naming Rule
Every Java program must have at least one class, and the filename must
exactly match the public class name (case-sensitive). This file must be
saved as [Link]
Java September 26, 2025 11 / 79
Essential Java Syntax Rules
Basic Syntax Rules:
Class name must match
Data Type Syntax:
filename exactly
Strings use double quotes (””)
main() method is program
entry point Characters use single quotes (”)
Statements end with semicolon Numbers don’t need quotes
(;) Boolean values: true or false
Code blocks use curly braces {} Variables must be declared
Case-sensitive language before use
Comments: // or /* */
Always follow Java naming conventions: class names start with uppercase,
variable and method names start with lowercase (camelCase).Java is
case-sensitive! MyClass and myclass are different identifiers.
Java September 26, 2025 12 / 79
Your First Java Class and Object
Let’s write a simple Java class and create an object from it. This example
introduces a Dog class.
1 // 1. Define a Class
2 class Dog {
3 // Attributes ( properties ) of a Dog
4 String name ;
5 String breed ;
6 int age ;
7
8 // Method ( behavior ) of a Dog
9 void bark () {
10 System . out . println ( name + " says Woof ! " ) ;
11 }
12
13 // Another method to display dog ’s details
14 void displayDetails () {
15 System . out . println ( " Name : " + name +
16 " , Breed : " + breed +
17 " , Age : " + age ) ;
18 }
19 } Java September 26, 2025 13 / 79
Creating Objects from the Class
1 // 2. Create Objects from the Class in your main program
2 public class MyFirstObject {
3 public static void main ( String [] args ) {
4 // Create an object ( instance ) of the Dog class
5 Dog myDog = new Dog () ; // myDog is an object
6 // Set the attributes of myDog
7 myDog . name = " Buddy " ;
8 myDog . breed = " Golden Retriever " ;
9 myDog . age = 3;
10 // Call a method on myDog
11 myDog . bark () ; // Buddy says Woof !
12 // Call another method
13 myDog . displayDetails () ;
14 // Create another Dog object
15 Dog anotherDog = new Dog () ;
16 anotherDog . name = " Lucy " ;
17 anotherDog . breed = " Poodle " ;
18 anotherDog . age = 5;
19 anotherDog . bark () ; // Lucy says Woof !
20 anotherDog . displayDetails () ;
21 }}
Java September 26, 2025 14 / 79
Code Explanation - Part 1
class Dog { ... }: This defines a new class named Dog. It’s the
blueprint.
String name; String breed; int age;: These are the attributes
(or fields) that every Dog object will have.
void bark() { ... }: This is a method. It defines an action a
Dog can perform.
public class MyFirstObject { ... }: This is our main
program where we will create and use Dog objects. The main method
is the entry point for execution.
Java September 26, 2025 15 / 79
Code Explanation - Part 2
Dog myDog = new Dog();: This line creates a new Dog object
named myDog. new Dog() calls a constructor to build the object.
[Link] = "Buddy";: We are setting the name attribute for the
myDog object.
[Link]();: We are calling the bark() method on the myDog
object, making it ”bark”.
Notice that myDog and anotherDog are distinct objects, each with
their own name, breed, and age, demonstrating how objects created
from the same class maintain independent states.
Java September 26, 2025 16 / 79
Output
Expected Output
Buddy says Woof!
Name: Buddy, Breed: Golden Retriever, Age: 3
Lucy says Woof!
Name: Lucy, Breed: Poodle, Age: 5
Practical Exercise
Try creating a new class called Car with attributes like make, model, and
year, and a method like startEngine(). Then, create two Car objects in
your main method, set their properties, and call their methods.
Common Beginner Mistake
One common mistake is confusing a class with an object. Remember: A
class is the blueprint (the idea of a dog), and an object is a specific
instance created from that blueprint (your actual dog, Buddy). You cannot
”bark” with a class; you can only ”bark” with an object (a specific dog).
Java September 26, 2025 17 / 79
Abstraction: Managing Complexity in Java
Abstraction is one of the foundational pillars of Object-Oriented
Programming (OOP) and a crucial concept for any aspiring Java
developer.
At its core, abstraction is about managing complexity by hiding
unnecessary details and showing only the essential features of an
object.
Think about how humans deal with complex systems in everyday life.
When you drive a car, you interact with the steering wheel,
accelerator, and brakes. You don’t need to understand the intricate
mechanics of the engine, transmission, or braking system to drive
effectively.
The car abstracts away these complexities, providing you with a
simple, intuitive interface.
Java September 26, 2025 18 / 79
Car Abstraction Example
Subsystems
Car Object Components
Internal systems like the
A single, unified entity Detailed parts like spark
Engine, Steering, or
that you interact with plugs, pistons, hydraulic
Braking system that
directly. lines, or brake pads.
work together.
This hierarchical approach allows us to think about a system at different
levels of detail, making complex systems manageable. In computer
programming, abstraction applies this same principle to code, letting us
build robust applications without getting overwhelmed by every tiny detail.
Java September 26, 2025 19 / 79
Why is Abstraction Important in Java?
1 Reduces Complexity: By showing only relevant information,
abstraction simplifies the view of a system, making it easier to
understand and use.
2 Enhances Maintainability: If the internal implementation of an
abstracted component changes, the external code that uses it (the
”user” of the abstraction) doesn’t need to be modified, as long as the
essential interface remains the same.
3 Promotes Reusability: Abstract components can be reused in
different parts of a program or even in other programs.
4 Improves Security: Abstraction allows you to hide sensitive data and
implementation details, exposing only what’s necessary, thus
protecting the integrity of your code.
Java September 26, 2025 20 / 79
How Java Achieves Abstraction
Java provides two main mechanisms to achieve abstraction:
Interfaces
Abstract Classes Blueprint of a class
Cannot be instantiated directly Contains abstract methods (and
Can contain both abstract default/static methods from
methods (no implementation) Java 8+)
and concrete methods (with Classes implement interfaces by
implementation) providing implementations for
Subclasses must implement all all abstract methods
abstract methods A class can implement multiple
interfaces
Java September 26, 2025 21 / 79
When to Use Each Approach
Choose an Abstract Class
When you want to define a common base for a group of closely related
classes, sharing some implementation details and common state. It allows
for partial implementation and strong ”is-a” relationships (e.g., a ”Car” is
a ”Vehicle”).
Opt for an Interface
When you want to define a contract for what a class can do, regardless of
its class hierarchy. It promotes flexibility, enabling unrelated classes to
share functionality and supports ”can-do” relationships (e.g., a ”Dog” can
”Barkable”, a ”Phone” can ”RingtonePlayer”). Interfaces are ideal for
achieving multiple inheritance of type.
Java September 26, 2025 22 / 79
Practical Example: RemoteControl Interface
Let’s create a simple system for controlling electronic devices with a
remote.
Define the Interface
1 public interface RemoteControl {
2 void turnOn () ; // Abstract method : turns the device on
3 void turnOff () ; // Abstract method : turns the device off
4 }
Key Points:
public interface RemoteControl: Declares a public interface
void turnOn() and turnOff(): Abstract methods that define
WHAT can be done, not HOW
This is the core of abstraction: we define the contract, not the
implementation
Any device controlled by our remote must implement this interface
Java September 26, 2025 23 / 79
The Three OOP Principles: An Overview
Object-Oriented Programming (OOP) is a powerful paradigm that helps
developers design software using a modular and flexible approach. At its
core, OOP is built upon three fundamental principles that are supported
by almost all object-oriented programming languages, including Java.
These principles allow us to structure our code in a way that mimics
real-world entities and their interactions, making programs easier to
understand, maintain, and extend.
Java September 26, 2025 24 / 79
Encapsulation
Encapsulation is like putting related data and the methods that
operate on that data inside a protective capsule.
It’s the mechanism of binding together code and the data it
manipulates, preventing direct access from outside the bundle.
This creates a ”black box” where you only interact with a well-defined
public interface, keeping the internal workings safe and hidden.
It ensures data integrity and helps manage complexity by hiding
implementation details.
Key Benefits: Data security, controlled access, easier maintenance.
Java September 26, 2025 25 / 79
Understanding Encapsulation Through Visual Layers
Visual Layer Explanation:
Innermost Circle: Private
Methods - Most protected,
completely hidden from outside
Image not available: Middle Circle: Private Instance
Screenshot (134).png Variables - Protected data only
the class can access
Outer Circle: Public Methods
& Variables - Interface for
external interaction
Java September 26, 2025 26 / 79
Encapsulation Principles and Real-World Analogy
Real-World Analogy Core Encapsulation Principles
Like a security system: Data Hiding: Private elements
Core: Private elements in inner circles
completely protected Controlled Access: Only public
Middle Layer: Controlled methods accessible from outside
access zone Interface Design: Clean public
Outer Layer: Public interface interface hiding implementation
for external interaction details
Key Insight
Outside code can only interact with the outermost public layer, ensuring
data integrity and security within the class.
Java September 26, 2025 27 / 79
Inheritance
Inheritance is a powerful feature that allows a new class (subclass or
child class) to inherit properties and behaviors (methods and fields)
from an existing class (superclass or parent class).
This mechanism promotes code reuse, reduces redundancy, and
establishes a natural ”is-a” relationship between classes, forming a
hierarchy.
For example, a ”Car” is a type of ”Vehicle”, inheriting general vehicle
characteristics while adding its own unique features.
Key Benefits: Code reusability, hierarchical organization, easier
maintenance.
Java September 26, 2025 28 / 79
Inheritance: ”Is-A” Relationship
In this example:
Animal is the parent
class
Image not available: Dog and Cat are child
[Link] classes
Both Dog and Cat
inherit common animal
traits
Java September 26, 2025 29 / 79
Inheritance Benefits
Key Benefits
Code Reuse: Common attributes like name, age, eat(), sleep() are
defined once in Animal class.
Specialization: Dog can have bark() method, Cat can have meow()
method.
Maintainability: Changes to common behavior only need to be made in
the parent class.
Java September 26, 2025 30 / 79
Polymorphism
Polymorphism means ”many forms.” In OOP, it allows objects of
different classes to be treated as objects of a common superclass.
This principle enables a single interface to represent different
underlying forms or types.
It means you can call a method on an object without knowing its
exact class at compile time, and the correct method implementation
will be executed based on the object’s actual type at runtime.
This provides flexibility and extensibility in your code.
Key Benefits: Flexibility, extensibility, simplified code maintenance.
Java September 26, 2025 31 / 79
Polymorphism Example
Image not available:
1 [Link]
Java September 26, 2025 32 / 79
Understanding Code Blocks in Java
In Java, just like in many other programming languages, we often need to
group multiple instructions together so they can be treated as a single
unit. This is where code blocks come in. A code block is a fundamental
building block of Java programming, allowing you to organize your code,
control execution flow, and manage variable scope.
They are essential for creating structured and readable programs, ensuring
that your code behaves exactly as you intend. Think of them as logical
containers for your statements.
Java September 26, 2025 33 / 79
What is a Code Block?
A code block, also known as a compound statement, is a collection of zero
or more statements enclosed within curly braces { }. These braces define
the beginning and end of the block. All statements inside these braces are
executed sequentially as a single unit.
Why are Code Blocks Important?
Grouping: They allow you to group related statements together
logically.
Control Flow: They are used with control statements (like if, for,
while) to specify which statements should execute under certain
conditions or repeatedly.
Scope Management: They define the scope of variables, meaning
where variables are accessible within your program.
Java September 26, 2025 34 / 79
The Basic Structure
Here’s how a code block looks in its simplest form:
1 {
2 // Statement 1
3 // Statement 2
4 // ...
5 // Statement N
6 }
Anywhere Java expects a single statement, you can substitute it with a
code block containing multiple statements. The Java compiler treats the
entire block as one single instruction.
Java September 26, 2025 35 / 79
Practical Example: Using Blocks with ’if’ Statements
Let’s look at a concrete example using an if statement. Suppose we want
to perform two actions only if a certain condition is true.
1 public class CodeBlockDemo {
2 public static void main ( String [] args ) {
3 int temperature = 28;
4
5 if ( temperature > 25) { // Beginning of code block
6 System . out . println ( " It ’s a hot day ! " ) ;
7 System . out . println ( " Remember to hydrate . " ) ;
8 } // End of code block
9
10 System . out . println ( " Program finished . " ) ;
11 }
12 }
Expected Output:
It’s a hot day!
Remember to hydrate.
Program finished.
Java September 26, 2025 36 / 79
Code Explanation
public class CodeBlockDemo: This line declares a new class
named CodeBlockDemo. In Java, all code resides within classes.
public static void main(String[] args): This is the main
method, the entry point of our Java program.
int temperature = 28;: We declare an integer variable
temperature and initialize it to 28.
if (temperature > 25) { ... }: This is an if statement. The
condition is temperature ¿ 25. Since 28 is greater than 25, this
condition is true.
The two println statements are inside the curly braces { }, forming a
code block. Because the if condition was true, both these statements
will execute.
[Link]("Program finished.");: This line is
outside the if statement’s block and will always execute, regardless of
the temperature.
Java September 26, 2025 37 / 79
Java Lexical Elements
Java programs are composed of atomic elements:
Core Elements:
Whitespace Key Properties:
Identifiers Java is a free-form language
Literals Case-sensitive
Comments Uses Unicode character set
Operators Whitespace includes: space, tab,
Separators newline.
Keywords
Free-Form Language
Java doesn’t require special indentation rules - you can write code on one
line or format it any way, as long as tokens are properly separated.
Java September 26, 2025 38 / 79
Identifiers and Literals
Identifiers (Names):
Name classes, variables,
methods
Can contain: letters, numbers,
,$
Literals (Constants):
Must NOT start with a number
Integer: 100
Case-sensitive
Floating-point: 98.6
Valid Examples:
Character: ’X’
1 AvgTemp
2 count String: "This is a test"
3 a4
4 $test
Invalid Examples:
1 2 count // s t a r t s w i t h number
2 h i g h−temp // c o n t a i n s hyphen
3 Not / ok // c o n t a i n s s l a s h
Java September 26, 2025 39 / 79
Comments and Separators
Common Separators:
( ) - Parentheses (parameters,
precedence)
Three Types of Comments: { } - Braces (code blocks)
Single-line: // comment [ ] - Brackets (arrays)
Multi-line: /* comment */ ; - Semicolon (terminates
Documentation: /** comment statements)
*/ , - Comma (separates
identifiers)
. - Period (package/method
separation)
Documentation Comments
Documentation comments (/** */) are used to generate HTML
documentation files for your program.
Java September 26, 2025 40 / 79
Java Keywords
67 Reserved Keywords in Java:
Common Keywords:
public, private,
protected
class, interface, extends
Reserved Values:
static, final, abstract
true, false, null
if, else, for, while
int, double, boolean,
char
return, void, new, this
Important
Keywords cannot be used as identifiers (variable names, class names,
method names).
Java September 26, 2025 41 / 79
Java Class Libraries
Java Environment = Language + Built-in Libraries
Standard Libraries Provide: Examples We’ve Used:
Input/Output (I/O) [Link]()
String handling [Link]()
Networking System - predefined class
Graphics Learning Path
GUI support Part of becoming a Java programmer
Mathematical operations is learning to use the standard Java
Data structures classes and methods.
Key Insight
Java’s power comes from combining the core language syntax with
extensive built-in class libraries.
Java September 26, 2025 42 / 79
Understanding Java’s Primitive Data Types
In Java, primitive data types are the most basic types of data available.
They are fundamental because they represent single, straightforward values
and are optimized for efficiency. Think of them as the atoms of your
program – simple, powerful, and essential for storing different kinds of
information. Java defines eight primitive types, categorized into four main
groups:
1. Integer Types
byte (1 byte)
short (2 bytes) 3. Character Type
int (4 bytes) char (2 bytes)
long (8 bytes) 4. Boolean Type
2. Floating-Point Types boolean (1 bit)
float (4 bytes)
double (8 bytes)
Java September 26, 2025 43 / 79
Integer Types: Working with Whole Numbers
Java provides four integer types for different ranges and memory needs:
1 byte: 1 byte, range -128 to 127, for small values
2 short: 2 bytes, range -32,768 to 32,767, rarely used
3 int: 4 bytes, range approx. -2 billion to 2 billion, most common
4 long: 8 bytes, very large numbers, needs ’L’ suffix
1 public class IntegerDemo {
2 public static void main ( String [] args ) {
3 byte myByte = 100;
4 int myInt = 1500000;
5 long myLong = 1234567890123 L ; // Note the ’L ’ suffix
6
7 System . out . println ( " byte : " + myByte ) ;
8 System . out . println ( " int : " + myInt ) ;
9 System . out . println ( " long : " + myLong ) ;
10 }
11 }
Java September 26, 2025 44 / 79
Integer Overflow
When working with integer types, be mindful of their range. Using a value
outside of a type’s range will result in an ”integer overflow” or
”underflow,” where the number wraps around to the opposite end of its
range, leading to unexpected behavior.
Java September 26, 2025 45 / 79
Floating-Point Types: Working with Decimal Numbers
Floating-point types handle numbers with decimal places:
float: 4 bytes, 6-7 decimal digits precision, needs ’f’ suffix
double: 8 bytes, 15-16 decimal digits precision, default for decimals
1 public class Float ingPointDemo {
2 public static void main ( String [] args ) {
3 float myFloat = 3.14159 f ; // Note the ’f ’ suffix
4 double myDouble = 3.1415926535;
5
6 double radius = 5.0;
7 double area = myDouble * radius * radius ;
8
9 System . out . println ( " float : " + myFloat ) ;
10 System . out . println ( " double : " + myDouble ) ;
11 System . out . println ( " Circle area : " + area ) ;
12
13 // Precision demonstration
14 System . out . println ( " 0.1 + 0.2 = " + (0.1 + 0.2) ) ;
15 }
16 }
Java September 26, 2025 46 / 79
Character and Boolean Types
The remaining two primitive types handle characters and logical values:
Character Type (char)
Stores a single Unicode character (16-bit)
Range: ‘\u0000‘ to ‘\uffff‘ (0 to 65535)
Uses single quotes: ’A’, ’7’, ’&’
Can be treated as integers (ASCII/Unicode values)
Boolean Type (boolean)
Only two values: true or false
Essential for conditional logic and decision-making
Cannot be converted to/from numbers (unlike some languages)
Java September 26, 2025 47 / 79
Character and Boolean Demo Program
1 public class CharBooleanDemo {
2 public static void main ( String [] args ) {
3 // Character examples
4 char initial = ’J ’;
5 char digit = ’7 ’;
6 char unicodeChar = ’\ u00A9 ’; // Copyright symbol ( c )
7 // Boolean examples
8 boolean isJavaFun = true ;
9 boolean h a sF inishedHomework = false ;
10 boolean canVote = (18 >= 18) ; // Result of
comparison
11 System . out . println ( " Initial : " + initial ) ;
12 System . out . println ( " Unicode char : " + unicodeChar ) ;
13 System . out . println ( " ASCII value of ’A ’: " + ( int ) ’A ’
);
14 if ( isJavaFun && canVote ) {
15 System . out . println ( " Ready to code and vote ! " ) ;
16 }
17 }
18 }
Java September 26, 2025 48 / 79
What are Reference Data Types?
Simple Explanation: Reference data types are like ”addresses” that point
to where the actual data is stored, rather than storing the data directly.
Real-World Analogy: Simple Example:
Think of a house address 1 // C r e a t i n g a S t r i n g o b j e c t
The address itself isn’t the house2 S t r i n g myName = ” A l i c e ” ;
3
The address tells you WHERE
4 // myName s t o r e s t h e ADDRESS
the house is 5 // where ” A l i c e ” i s l o c a t e d
Reference variables work the 6 // i n memory , n o t ” A l i c e ”
same way! itself
Default Value:
Key Point
Reference = Address to memory 1 S t r i n g name ; // D e f a u l t i s
null
location
2 // n u l l means ” no a d d r e s s ”
Not the actual data itself
Java September 26, 2025 49 / 79
Types of Reference Data Types
Main Categories with Easy Examples:
1. Strings (Text data)
What makes them ”Reference”?
1 S t r i n g f i r s t N a m e = ” John ” ;
2 S t r i n g l a s t N a m e = ” Smith ” ; All created with new keyword
(except String literals)
2. Arrays (Lists of data)
All can be null
1 i n t [ ] ages = {20 , 25 , 30};
All store memory addresses
2 S t r i n g [ ] names = { ” A l i c e ” , ”
Bob” } ; All are objects in memory
3. Objects (Class instances) Remember
1 // R e q u i r e s : i m p o r t j a v a . If it’s not one of the 8 primitive types
u t i l . Scanner ; (int, double, boolean, etc.), it’s a
2 S c a n n e r i n p u t = new S c a n n e r ( reference type!
System . i n ) ;
Java September 26, 2025 50 / 79
Reference vs Primitive - Simple Comparison
Reference Types:
Primitive Types: 1 S t r i n g name = ” A l i c e ” ;
2 i n t [ ] s c o r e s = {90 , 85 , 92};
1 i n t age = 2 5 ; 3 // R e q u i r e s : i m p o r t j a v a .
2 double p r i c e = 99.99; u t i l . ArrayList ;
3 boolean isStudent = true ; 4 A r r a y L i s t <S t r i n g > l i s t =
4 c h a r g r a d e = ’A ’ ; 5 new A r r a y L i s t <>() ;
What happens: What happens:
Value is stored directly in the Variable stores memory address
variable
name contains address, not
age actually contains 25 ”Alice”
Fast access Actual data is elsewhere in
Fixed size memory
Dynamic size
Easy Rule
Primitive: ”The box contains the actual
Java
thing” September 26, 2025 51 / 79
What are Literals? - Definition
Definition: A literal is a source code representation of a fixed value that
can be assigned to variables without requiring computation or memory
references.
Key Characteristics:
Compile-time constants
Direct representation of data values
Type-specific formatting rules
Immutable values in source code
No calculation or method calls needed
Purpose: Provide a way to directly specify values in program source code
for immediate use or assignment to variables.
Java September 26, 2025 52 / 79
Integer Literals - Detailed Definition
Definition: Integer literals represent whole number values without
fractional components, expressed in various number bases.
Default Type: 32-bit signed int (-2,147,483,648 to 2,147,483,647)
Number Base Systems:
Decimal (Base 10): Standard counting system using digits 0-9
Octal (Base 8): Uses digits 0-7, prefixed with leading zero
Hexadecimal (Base 16): Uses 0-9 and A-F, prefixed with 0x/0X
Binary (Base 2): Uses only 0 and 1, prefixed with 0b/0B
Type Suffixes: L or l for long (64-bit) integers
Java September 26, 2025 53 / 79
Integer Literals - Examples and Rules
Valid Examples:
Decimal: 42, 1000, -255
Octal: 077 (equals 63 decimal), 0123 (equals 83 decimal)
Hexadecimal: 0xFF (equals 255), 0x7A (equals 122)
Binary: 0b1010 (equals 10), 0b11111111 (equals 255)
Long: 123456789L, 0xFFFFFFFFL
Readability Enhancement:
Underscores allowed between digits: 1 000 000
Multiple underscores permitted: 123 456
Cannot start or end with underscore
Useful for phone numbers, IDs: 555 123 4567
Java September 26, 2025 54 / 79
Floating-Point Literals - Definition
Definition: Floating-point literals represent real numbers with fractional
components using IEEE 754 standard.
Default Type: double (64-bit, 15-17 decimal digits precision)
Notation Types:
Standard: Whole number + decimal point + fraction (3.14159)
Scientific: Mantissa + E/e + exponent (6.022E23)
Hexadecimal: 0x + hex digits + P/p + binary exponent
Type Suffixes:
F or f: float (32-bit, 6-7 decimal digits)
D or d: double (explicit, but redundant)
Java September 26, 2025 55 / 79
Floating-Point Examples and Precision
Standard Notation:
2.0, 3.14159, 0.6667, -45.67
9 423 497.1 0 9 (with underscores)
Scientific Notation:
6.022E23 (Avogadro’s number)
314159E-05 (equals 3.14159)
2e+100, 1.5e-10
Type Examples:
float: 3.14F, 2.5f, 1.0E10F
double: 3.14159D, 2.718281828 (default)
Hexadecimal: 0x12.2P2 = 18.125 × 22 = 72.5
Java September 26, 2025 56 / 79
Character Literals - Detailed Definition
Definition: Character literals represent single Unicode characters as 16-bit
unsigned integers (0 to 65,535).
Representation: Single quotes enclosing one character or escape sequence
Unicode Support: Full Unicode character set access via \u notation
Character Categories:
Printable ASCII: ’A’, ’z’, ’7’, ’@’, ’ ’
Escape sequences: Special characters requiring backslash
Unicode notation: \uxxxx format for any Unicode character
Octal notation: \ddd format (0-377 octal range)
Conversion: Can be converted to int for arithmetic operations
Java September 26, 2025 57 / 79
Character Escape Sequences - Complete List
Escape Description Unicode
\n Line feed (newline) \u000A
\r Carriage return \u000D
\t Horizontal tab \u0009
\b Backspace \u0008
\f Form feed \u000C
\’ Single quote \u0027
\” Double quote \u0022
\\ Backslash \u005C
\s Space (JDK 15+) \u0020
\ddd Octal character 0-377 range
\uxxxx Unicode character Any Unicode
Java September 26, 2025 58 / 79
Character Examples and Unicode
Basic Characters:
’A’, ’z’, ’5’, ’@’, ’ ’ (space)
Escape Sequences:
’\n’ (newline), ’\t’ (tab), ’\r’ (carriage return)
’\b’ (backspace), ’\f’ (form feed)
’\\’ (backslash), ’\” (single quote), ’\”’ (double quote)
Unicode Examples:
’\u0041’ (Latin ’A’), ’\u0061’ (Latin ’a’)
’\u03B1’ (Greek alpha), ’\u4E2D’ (Chinese)
’\u3042’ (Japanese Hiragana)
Octal Examples:
’\141’ (equals ’a’), ’\101’ (equals ’A’)
Java September 26, 2025 59 / 79
Boolean Literals - Definition
Definition: Boolean literals represent logical truth values in binary logic
operations and conditional statements.
Values: Only two possible values - true and false
Key Properties:
No numeric conversion: true is not 1, false is not 0
Type safety: Cannot be cast to integers
Memory: Typically 1 byte storage
Usage: Control structures, logical operations
Applications:
Conditional statements (if, while, for)
Method return values for yes/no questions
Flag variables for state tracking
Java September 26, 2025 60 / 79
String Literals - Detailed Definition
Definition: String literals represent sequences of characters as immutable
object instances of the String class.
Syntax: Double quotes enclosing character sequence
Key Characteristics:
Object type: Not primitive arrays like in C/C++
Immutable: Cannot be modified after creation
Unicode support: Full Unicode character set
Escape sequences: Same as character literals
Line constraint: Must begin and end on same line
Memory Management: Stored in string pool for optimization
Java September 26, 2025 61 / 79
String Examples and Features
Basic Strings:
"Hello World", "Java Programming", ""
With Escape Sequences:
"Line 1\nLine 2" (multi-line effect)
"Tab\tseparated\tvalues"
"She said, \"Hello!\""
"File path: C:\\Users\\Documents"
Unicode in Strings:
"Café" (accented characters)
"Price: \u00A5100" (Yen symbol)
"Greek: \u03B1\u03B2\u03B3" (alpha, beta, gamma)
Special Cases:
"" (empty string), " " (space string)
Java September 26, 2025 62 / 79
Literal Type Assignment Rules
Integer Literal Assignment:
int literals can go into byte, short, char (if within range)
int literals can go into int (direct assignment)
int literals can go into long (automatic widening)
long literals (L suffix) can go into long only
Floating-Point Assignment:
double literals go into double (default)
float literals (F suffix) go into float
double to float requires an explicit cast
Type Safety: Java’s strong typing prevents automatic narrowing
conversions that might lose data.
Java September 26, 2025 63 / 79
Summary - All Literal Types
Integer: Whole numbers in decimal, octal, hex, binary
Floating-point: Real numbers with decimal points
Character: Single Unicode characters in single quotes
Boolean: Logical true/false values
String: Character sequences in double quotes
Common Features:
Compile-time constants
Type-specific rules and constraints
Escape sequence support (where applicable)
Unicode support for internationalization
Java September 26, 2025 64 / 79
What are Variables?
Think of Variables Like Boxes:
Variables are containers that store data in memory.
Like labeled boxes that hold different types of items.
Each box has a name (identifier) and a type (what it can hold).
Real-World Analogy:
String name = "John"; → Box labeled ”name” contains text
”John”
int age = 25; → Box labeled ”age” contains number 25
double salary = 50000.50; → Box labeled ”salary” contains
decimal 50000.50
Java September 26, 2025 65 / 79
Variable Declaration - Step by Step
Three Steps to Create a Variable:
1 Choose a Type: What kind of data? (int, String, double, etc.)
2 Give it a Name: Follow naming rules (myAge, studentName)
3 Assign a Value: Use = sign (optional at first)
Basic Syntax:
type variableName = value;
Step-by-Step Example:
Step 1: int (type - whole numbers)
Step 2: myAge (name - camelCase style)
Step 3: = 20; (value - assign number 20)
Result: int myAge = 20;
Java September 26, 2025 66 / 79
Common Data Types with Examples
Text Data:
String name = "Alice"; // Stores text/words
char grade = ’A’; // Stores single character
Number Data:
int age = 18; // Whole numbers (-2, -1, 0, 1, 2...)
double price = 19.99; // Decimal numbers
float height = 5.8f; // Smaller decimal numbers
True/False Data:
boolean isStudent = true; // Only true or false
Java September 26, 2025 67 / 79
Two Ways to Create Variables
Method 1: Declare and Initialize Together
int score = 100; // Create and assign value immediately
String city = "New York"; // Most common way
Method 2: Declare First, Assign Later
int score; // Create empty box first
score = 100; // Put value in later
Multiple Variables of Same Type:
int a, b, c; // Three empty int boxes
int x = 5, y = 10, z = 15; // Three with values
Java September 26, 2025 68 / 79
Real-Life Student Record Example
Complete Student Information System:
String studentName = "John Doe";
int studentID = 12345;
int studentAge = 20;
double studentFee = 1250.75;
char studentGrade = ’B’;
boolean isFullTime = true;
Printing the Information:
[Link]("Name: " + studentName);
[Link]("Age: " + studentAge);
[Link]("Grade: " + studentGrade);
Java September 26, 2025 69 / 79
Dynamic Initialization - Advanced Example
Using Variables to Calculate Other Variables:
int length = 8;
int width = 5;
int area = length * width; // Calculated automatically!
Real Math Example:
double a = 3.0, b = 4.0;
double c = [Link](a*a + b*b); // Pythagorean theorem
[Link]("Hypotenuse: " + c); // Output: 5.0
Key Point: Variables can use other variables and calculations!
Java September 26, 2025 70 / 79
Variable Scope - Where Can You Use Variables?
Scope = ”Where the variable lives”
Variables only work within their {} curly braces.
Think of it like room boundaries in a house.
Example - Variable Lives in Method:
public static void main(String[] args) {
int x = 10; // x lives here
[Link](x); // Works - same room
}
// [Link](x); // Error - x doesn’t exist here!
Java September 26, 2025 71 / 79
Nested Scope Example
Nested Scopes - Boxes Inside Boxes:
int x = 5; // Outer box - everyone can see
if(x > 0) { // Start inner box
int y = 10; // Inner box - only inner code sees this
[Link](x); // Can see outer variable
[Link](y); // Can see inner variable
} // End inner box
[Link](x); // Still can see outer
// [Link](y); // Error! Inner variable gone
Rule: Inner can see outer, but outer cannot see inner.
Java September 26, 2025 72 / 79
Variable Lifetime - When Variables Die
Variables are Born and Die with Their Scope:
Created when scope starts ({ appears)
Destroyed when scope ends (} appears)
Like lights turning on/off when entering/leaving rooms
Loop Example - Variable Reborn Each Time:
for(int i = 0; i < 3; i++) {
int temp = 100; // Born with value 100
[Link](temp); // Prints: 100
temp = 200; // Changed to 200
} // Dies here, forgets it was 200
Each loop iteration creates fresh temp = 100 again!
Java September 26, 2025 73 / 79
Common Beginner Mistakes
Mistake 1: Using Before Declaring
x = 10; // Error! What is x?
int x = 10; // Correct - declare first
Mistake 2: Same Name in Nested Scope
int score = 10;
if(true) {
int score = 20; // Error! Name already used
}
Mistake 3: Wrong Data Type
int name = "John"; // Error! int cannot hold text
String name = "John"; // Correct data type
Java September 26, 2025 74 / 79
Java Arrays: Storing Collections of Data
In programming, we often need to store multiple pieces of data that are
related to each other. Instead of creating a separate variable for each item,
which can become messy and unmanageable, Java provides a powerful and
fundamental data structure called an array.
What is an Array? An array is a data structure that allows you to store a
fixed-size sequential collection of elements of the same data type. Think of
it like a row of identical boxes, where each box can hold one item, and all
items are of the same type (e.g., all numbers, all words, all true/false
values).
Example: Seating Arrangement in a Theater: The seats in a single row
of a theater can be represented as an array. Each seat is an element, and
its position in the row is its index. This can be extended to a 2D array (a
matrix) to represent all seats in the entire theater, with rows and columns.
Java September 26, 2025 75 / 79
Why are Arrays Important?
Efficient Storage: Stores multiple related values under a single
variable name.
Organized Data: Helps manage large amounts of data
systematically.
Foundation: Many other complex data structures (like ArrayLists)
are built upon arrays.
Repetitive Tasks: Simplifies operations on multiple data items using
loops.
Java September 26, 2025 76 / 79
Declaring and Creating Arrays
Before you can use an array, you need to declare it (tell Java what type of
data it will hold) and then create it (allocate memory for it). You can do
these steps separately or combine them.
1. Declaration: Telling Java About Your Array Declaration simply tells
the compiler that you’re going to use an array and what type of data it
will contain. It doesn’t allocate any memory yet.
1 // Syntax 1: Recommended ( type [] variableName )
2 dataType [] arrayName ;
3
4 // Syntax 2: Also valid , but less common
5 dataType arrayName [];
Example:
1 int [] studentAges ; // Declares an array for integers
2 String [] studentNames ; // Declares an array for Strings
Java September 26, 2025 77 / 79
Array Creation (Instantiation)
2. Creation (Instantiation): Allocating Memory After declaration, you
need to create the array using the new keyword. This allocates memory for
the specified number of elements and initializes them to default values.
1 arrayName = new dataType [ size ];
Here, size specifies how many elements the array can hold. Remember,
array size is fixed once created!
Example:
1 // Creating an array to hold 5 integer ages
2 int [] studentAges ;
3 studentAges = new int [5]; // Now can hold 5 integers
Java September 26, 2025 78 / 79
Array Default Values
Default Values: When you create an array using new, Java automatically
initializes its elements:
Numeric types (int, double, float, etc.): 0 or 0.0
boolean: false
char: ’\u0000’ (null character)
Object references: null
Important Note
These default values are automatically assigned when you create an array
with the new keyword. You don’t need to explicitly initialize each element
unless you want specific values different from the defaults.
Java September 26, 2025 79 / 79