Sitemap
Deepaksingh

Deepaksingh

Java Notes(Part 1)

11 min readMar 14, 2026

--

What is Java

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

-Developed by Sun Microsystems (1995)

-Now owned by Oracle

-Used for web, mobile, desktop, and enterprise applications

-Principle: Write Once, Run Anywhere (WORA)

History of Java

  • Created by James Gosling
  • First name was Oak
  • Later renamed to Java
  • Released in 1995

Features of Java

  • Platform Independent
  • Object Oriented
  • Secure
  • Robust
  • Multithreaded
  • Portable
  • Automatic Garbage Collection

Platform Independent

  • Java program runs on any operating system
  • Because of JVM
  • Code is compiled into Bytecode, not machine code

ByteCode

  • Intermediate code generated by Java compiler
  • File extension: .class
  • Executed by JVM

JVM (Java Virtual Machine)

  • Executes Java Bytecode
  • Converts bytecode into machine code
  • Provides platform independence
  • Manages memory and security

JDK, JRE, JVM

  • JDK (Java Development Kit) → tools to develop Java programs
  • JRE (Java Runtime Environment) → environment to run Java programs
  • JVM → executes bytecode

Difference: Java vs C/C++

  • Java is platform independent
  • Java uses JVM
  • Java supports automatic garbage collection
  • Java does not use pointers
  • C/C++ are platform dependent

JVM (Java Virtual Machine)

  • Virtual machine that runs Java Bytecode
  • Converts bytecode → machine code
  • Provides platform independence
  • Handles memory management

JRE (Java Runtime Environment)

  • Environment to run Java programs
  • Contains JVM + libraries
  • Does not include development tools

JDK (Java Development Kit)

  • Used to develop Java programs
  • Contains JRE + development tools
  • Tools: javac, java, debugger

Difference: JVM, JRE, JDK

  • JVM → Executes bytecode
  • JRE → Provides runtime environment
  • JDK → Full toolkit for development

JSE (Java Standard Edition)

  • Core Java platform
  • Used for desktop and basic applications
  • Contains basic libraries and APIs

JEE (Java Enterprise Edition)

  • Used for large-scale enterprise applications
  • Supports web apps, distributed systems
  • Includes Servlet, JSP, etc.

JME (Java Micro Edition)

  • Used for small devices
  • Example: mobile phones, embedded systems

Platform Independence

  • Java code compiled into Bytecode
  • Bytecode runs on JVM
  • JVM available for different OS

First Java Program (Hello World)

  • Create HelloWorld.java
  • Write main method
  • Print using System.out.println()

Compiling Java Code

  • Use javac command
  • Converts .java → .class (Bytecode)

Running Java Program

  • Use java command
  • JVM executes .class file

Variables in Java

  • Variables store data values
  • Must declare with data type
  • Value can change during program

Identifiers

  • Names of variables, methods, classes
  • Must start with letter, _ or $
  • Cannot start with number
  • Cannot use Java keywords

Primitive Data Types

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

Literals

  • Fixed values assigned to variables
  • Types: Integer, Floating, Character, String, Boolean

Java Reserved Keywords

  • Reserved words used by Java
  • Cannot be used as identifiers
  • Examples: class, public, static, void, if, else, return

Naming Conventions (Best Practices)

  • Class → PascalCase (StudentData)
  • Variable → camelCase (studentName)
  • Method → camelCase (calculateTotal)
  • Constant → UPPER_CASE (MAX_VALUE)

Negative Numbers using 2’s Complement

  • Computers store negative numbers using 2’s complement
  • MSB (leftmost bit) indicates sign
  • 0 → positive
  • 1 → negative

Example (8-bit):

+5 →

00000101

2’s Complement Conversion (Step Example)

Example: Convert -5 to binary

Step 1: Write binary of 5

00000101

Step 2: Invert bits (1↔0)

11111010

Step 3: Add 1

11111010
+ 1
---------
11111011

Final Answer:

-5 = 11111011

Why 2’s Complement is Used

  • Makes addition & subtraction easy
  • Same circuit used for positive and negative numbers
  • Only one zero representation

Example

5 + (-5) = 0

Binary:

00000101
+11111011
---------
00000000

Floating Point Number Storage

Used to store decimal numbers

Example numbers:

  • 3.14
  • 0.5
  • 12.75

Floating point has 3 parts

Sign | Exponent | Mantissa

Example structure (32-bit float)

1 bit   8 bits   23 bits

Exponent Representation & Normalization

Floating numbers stored in scientific binary form

Example:

Decimal:

10.5

Binary:

1010.1

Normalize:

1.0101 × 2³

Where

  • 1.0101 → Mantissa
  • 3 → Exponent

Bias in Floating Point

Exponent stored using Bias

Formula

Stored Exponent = Actual Exponent + Bias

Example (32-bit float)

Bias = 127

If exponent = 3

Stored exponent = 3 + 127 = 130

Normal vs Edge Cases

Normal Numbers

  • Valid exponent and mantissa

Example

5.25
2.75

Edge Cases

  • 0
  • Infinity (∞)
  • NaN (Not a Number)

Example

0 / 0 → NaN
10 / 0 → Infinity

Why Exact Values Are Not Retrieved

Some decimal numbers cannot be represented exactly in binary

Example

0.1 (decimal)

Binary representation becomes infinite repeating

0.0001100110011...

So computer rounds the value.

Precision Errors

Because floating numbers have limited bits

Example

0.1 + 0.2

Expected

0.3

Computer result sometimes

0.30000000000000004

This is called floating point precision error.

Type Conversion & Type Casting in Java

Implicit Type Conversion (Widening)

  • Automatic conversion by Java compiler
  • Converts smaller data type → larger data type
  • No data loss

Order:

byte → short → int → long → float → double

Example

int a = 10;
double b = a;
System.out.println(b);

Output

10.0

Explanation
int automatically converted to double.

Explicit Type Casting (Narrowing)

  • Done manually by programmer
  • Converts larger type → smaller type
  • May cause data loss

Syntax

datatype variable = (datatype) value;

Example

double a = 10.75;
int b = (int) a;
System.out.println(b);

Output

10

Explanation
Decimal part 0.75 removed.

Data Loss & Truncation

When converting larger type → smaller type, extra data is lost.

Example

int a = 130;
byte b = (byte) a;
System.out.println(b);

Output

-126

Explanation
byte range = -128 to 127
So value overflows.

Why boolean Cannot Be Converted

  • boolean represents true or false
  • It is not numeric
  • Cannot convert to int, float, etc.

Invalid Example

boolean b = true;
int a = (int) b; // ERROR

Reason
Java does not allow boolean conversion.

How Java Handles Arithmetic Internally

During arithmetic operations Java automatically promotes types.

Small data types become int.

Example

byte a = 10;
byte b = 20;
int result = a + b;

Explanation

byte + byte → int

Type Promotion Rules

Java promotes smaller types during expressions.

Rules:

byte, short, char → promoted to int

If one operand is long, result → long

If one operand is float, result → float

If one operand is double, result → double

Example

int a = 10;
double b = 5.5;
double result = a + b;

Result type → double

Why char + char Becomes int

char stores ASCII/Unicode numeric value.

Example

char a = 'A';
char b = 'B';
int result = a + b;System.out.println(result);

ASCII values

A = 65
B = 66

Result

65 + 66 = 131

So result type → int

Java Operators

Arithmetic Operators

Used to perform mathematical operations

Operators

+   Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

Example

int a = 10;
int b = 3;
System.out.println(a + b); //13
System.out.println(a % b); //1

Unary Operators

Operate on one operand

Operators

+   Positive
- Negative
++ Increment
-- Decrement
! Logical NOT

Example

int a = 5;
a++;

Result

a = 6

Increment & Decrement

Pre-Increment

Value increases before use

int a = 5;
int b = ++a;

Result

a = 6
b = 6

Post-Increment

Value increases after use

int a = 5;
int b = a++;

Result

a = 6
b = 5

Same rule for — operator

Assignment Operators

Used to assign values

=   Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign

Example

int a = 10;
a += 5;

Result

a = 15

Relational Operators

Used for comparison

==   Equal to
!= Not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal

Example

int a = 5;
int b = 3;
System.out.println(a > b);

Output

true

Logical Operators

Used with boolean values

&&   AND
|| OR
! NOT

Example

boolean a = true;
boolean b = false;
System.out.println(a && b);

Output

false

Short-Circuit Evaluation

Java stops evaluation when result is already known

Example

int a = 10;
if(a > 5 || a++ > 20)
{
}

Explanation

First condition true → second not checked
a remains 10

Bitwise Operators

Work on binary bits

&   AND
| OR
^ XOR
~ NOT

Example

5 = 0101
3 = 0011
5 & 3 = 0001 = 1

Shift Operators

Used to shift bits left or right

<<  Left shift
>> Right shift
>>> Unsigned right shift

Example

5 << 1

Binary

00000101 → 00001010

Result

10

Unsigned Right Shift (>>>)

  • Shifts bits to the right
  • Left side always filled with 0
  • Ignores sign bit

Example

int a = -8;
System.out.println(a >>> 1);

Explanation

Negative number becomes large positive value

Example Output

2147483644

Ternary Operator

Short form of if-else

Get Deepaksingh’s stories in your inbox

Join Medium for free to get updates from this writer.

Syntax

condition ? value1 : value2;

Example

int a = 10;
String result = (a > 5) ? "Yes" : "No";

Operator Precedence

Order in which operations execute

High → Low

1  ++ --
2 * / %
3 + -
4 < > <= >=
5 == !=
6 &&
7 ||
8 = += -=

Example

int result = 10 + 5 * 2;

Result

10 + 10 = 20

Edge Case / Interview Trap

Example

int a = 5;
System.out.println(a++ + ++a);

Step

a++  → 5 (a becomes 6)
++a → 7

Result

12

Internal Evaluation Order

Java evaluates left → right

Example

int a = 5;
int result = a++ + a++;

Steps

First a++ → 5 (a=6)
Second a++ → 6 (a=7)

Result

11

Flow of Control

  • Determines order of execution of statements
  • Controls which code runs and when

Types:

  • Sequential
  • Decision Making
  • Looping

Example

int a = 5;
int b = 3;
int sum = a + b;

Execution order: top → bottom

Decision Making in Programming

  • Used to choose between multiple paths
  • Program executes code based on conditions

Example

if(age >= 18)

if Statement

  • Executes block only if condition is true

Syntax

if(condition){
// code
}

Example

int age = 20;
if(age >= 18){
System.out.println("Eligible to vote");
}

if-else Statement

  • Executes one block if true
  • Executes another block if false

Syntax

if(condition){
// true block
}else{
// false block
}

Example

int number = 10;
if(number % 2 == 0){
System.out.println("Even");
}else{
System.out.println("Odd");
}

if-else-if Ladder

  • Used when multiple conditions exist
  • Conditions checked top → bottom

Syntax

if(condition1){
}
else if(condition2){
}
else{
}

Example

int marks = 75;
if(marks >= 90)
System.out.println("Grade A");
else if(marks >= 70)
System.out.println("Grade B");
else
System.out.println("Grade C");

Nested if

  • if inside another if

Example

int age = 20;
boolean id = true;
if(age >= 18){
if(id){
System.out.println("Allowed");
}
}

switch Statement

  • Used to check multiple fixed values
  • Works with int, char, String, enum

Syntax

switch(expression){
case value1:
break;
case value2:
break;
default:
}

Example

int day = 2;
switch(day){case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid");
}

When to Use switch vs if-else-if

Use switch when:

  • Comparing single variable
  • Checking fixed constant values

Use if-else-if when:

  • Conditions use ranges
  • Complex logical expressions

Example

marks > 70 && marks < 90

Switch cannot handle ranges

Why switch Can Be More Optimized

  • Compiler may convert switch into jump table
  • Direct jump to case block
  • Faster than checking multiple conditions

Internal Working (Simple Idea)

if-else ladder

Check condition1
Check condition2
Check condition3

switch

Jump directly to matching case

Iteration

  • Iteration = repeating a block of code
  • Used when task must run multiple times
  • Implemented using loops

Example use cases:

  • Printing numbers
  • Processing arrays
  • Calculations

for Loop

Structure

for(initialization; condition; update){
// code
}

Flow

Initialization executes once

Condition checked

Loop body runs

Update executes

Repeat until condition false

Example

for(int i = 1; i <= 5; i++){
System.out.println(i);
}

Output

1 2 3 4 5

while Loop

  • Used when number of iterations unknown
  • Condition checked before execution

Syntax

while(condition){
// code
}

Example

int i = 1;
while(i <= 5){
System.out.println(i);
i++;
}

do-while Loop

  • Loop executes at least once
  • Condition checked after execution

Syntax

do{
// code
}while(condition);

Example

int i = 1;
do{
System.out.println(i);
i++;
}while(i <= 5);

Difference: while vs do-while

whiledo-whileCondition checked firstCode executes firstMay execute 0 timesExecutes at least once

Infinite Loop

  • Loop that never stops
  • Happens when condition never becomes false

Example

while(true){
System.out.println("Hello");
}

Common cause

Missing update statement

Nested Loops

  • Loop inside another loop

Example

for(int i = 1; i <= 3; i++){
for(int j = 1; j <= 2; j++){
System.out.println(i + " " + j);
}
}

Outer loop controls rows
Inner loop controls columns

Jump Statements

Used to change normal flow

Types

break
continue
return

break Statement

  • Terminates loop immediately
  • Control moves outside the loop

Example

for(int i=1; i<=10; i++){
    if(i==5)
break;
System.out.println(i);
}

Output

1 2 3 4

continue Statement

  • Skips current iteration
  • Next iteration begins

Example

for(int i=1; i<=5; i++){
    if(i==3)
continue;
System.out.println(i);

Output

1 2 4 5

What are Arrays

  • Array = collection of similar data types
  • Stored in continuous memory locations
  • Accessed using index
  • Index starts from 0

Example

int[] numbers = {10,20,30,40};

Why Arrays are Needed

  • Store multiple values in one variable
  • Avoid creating many variables

Without array

int a = 10;
int b = 20;
int c = 30;

With array

int[] arr = {10,20,30};

Array Declaration

Syntax

datatype[] arrayName;

Example

int[] marks;

Array Initialization

Syntax

arrayName = new datatype[size];

Example

int[] marks = new int[5];

Memory created for 5 integers

Different Ways to Create Arrays

Method 1

int[] arr = new int[3];

Method 2

int[] arr = {10,20,30};

Method 3

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

Default Values in Arrays

When array created with new

Data TypeDefault Valueint0double0.0booleanfalsechar’\u0000'Objectnull

Example

int[] arr = new int[3];

Stored values

0 0 0

Traversing Arrays

Accessing elements using loop

Example

int[] arr = {10,20,30};
for(int i=0;i<3;i++){
System.out.println(arr[i]);
}

Array length Property

Used to get size of array

Syntax

arrayName.length

Example

int[] arr = {10,20,30,40};
System.out.println(arr.length);

Output

4

Loop using length

for(int i=0;i<arr.length;i++)

Common Beginner Mistakes

Array index out of bounds

arr[5]

When size is 5, max index = 4

Using wrong loop condition

Wrong

i <= arr.length

Correct

i < arr.length

Accessing uninitialized array

int[] arr;
arr[0] = 5; // error

Must create array first

Introduction to Strings

  • String = sequence of characters
  • Used to store text data

Example

String name = "Java";

String Example

String s = "Hello";
System.out.println(s);

Output

Hello

Why Arrays Use Contiguous Memory

  • Array elements stored in continuous memory locations
  • Allows fast access using index
  • CPU can calculate address directly

Example

Array: [10, 20, 30, 40]
Index: 0 1 2 3

Memory

Address → Value
1000 → 10
1004 → 20
1008 → 30
1012 → 40

Each element stored next to each other.

Arrays Stored in Heap Memory

  • Arrays are objects in Java
  • Objects stored in Heap memory

Example

int[] arr = new int[5];

Memory

Stack → reference variable
Heap → actual array object

What Happens Inside JVM When Array is Created

Example

int[] arr = new int[5];

Steps

JVM allocates memory in Heap

Size for 5 integers reserved

Default values assigned

Reference stored in Stack

Memory idea

Stack
arr → reference
Heap
[0,0,0,0,0]

Stack vs Heap for Arrays

Stack

  • Stores reference variable
  • Faster memory
  • Stores method variables

Example

arr → address of array

Heap

  • Stores actual array data
  • Larger memory
  • Shared by objects

Example

[10,20,30]

How Memory Indexing Works

Formula

Address = Base Address + (Index × Size of datatype)

Example

Array

int arr[ ]

Assume

Base address = 1000
int size = 4 bytes

Index 3

Address = 1000 + (3 × 4)
Address = 1012

Why Array Access is O(1)

  • Index gives direct memory location
  • No need to search elements

Example

arr[3]

JVM directly calculates memory address.

So time complexity

O(1) → constant time

Performance Implications of Arrays

Advantages

  • Fast access
  • Cache friendly
  • Memory efficient

Disadvantages

  • Fixed size
  • Insert/delete operations slow
  • Need shifting elements

Example

Insert at index 2
Shift elements right

What Happens in new int[5]

Code

int[] arr = new int[5];

Steps inside JVM

new keyword allocates Heap memory

JVM creates array object

Memory for 5 integers reserved

All elements set to default value (0)

Reference returned to arr variable

Memory view

Stack
arr → 2000
Heap
2000 → [0,0,0,0,0]

--

--