1.
Introduction to Java — deep view
What is Java?
• Java is an object-oriented, class-based, platform-independent programming
language designed for reliability, portability, and security.
• Motto: WORA — Write Once, Run Anywhere (Java source → bytecode → runs on any
JVM).
Java History & Ecosystem
• History
o Developed by James Gosling at Sun Microsystems in 1995.
o Originally designed for embedded systems, later became popular for web and
enterprise applications.
o "Write Once, Run Anywhere" philosophy – portability across platforms.
o Acquired by Oracle Corporation in 2010, which now maintains Java.
• Ecosystem Components
1. JDK (Java Development Kit):
▪ Tools for developers (compiler javac, debugger, libraries).
▪ Used for writing and compiling programs.
2. JRE (Java Runtime Environment):
▪ Provides libraries, class loader, and JVM.
▪ Runs already compiled Java applications.
3. JVM (Java Virtual Machine):
▪ Executes Java bytecode.
▪ Ensures platform independence by acting as an interpreter between
bytecode and OS.
Java architecture
1. Source code (.java) → compiled by javac into bytecode (.class).
2. JVM executes bytecode (interprets or JIT-compiles to native code).
3. Classloader loads classes at runtime; bytecode verifier enforces security.
JDK vs JRE vs JVM
• JDK: tools for development (javac, jar, etc.) + JRE.
• JRE: JVM + standard class libraries (required to run Java programs).
• JVM: executes bytecode, manages memory (heap/stack), GC.
Basic Java program structure
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java!");
• public static void main(String[] args) is the program entry point.
• System.out.println prints to console.
Java features (explain)
• Simple: syntax largely like C/C++ but without complex features like pointers.
• Object-oriented: encapsulation, inheritance, polymorphism, abstraction.
• Platform-independent: bytecode + JVM.
• Robust: exception handling, type checking, garbage collection.
• Secure: classloader sandboxing, no raw pointers.
• Multithreaded: built-in language support (Thread, Runnable).
• High performance: JIT compilers and optimizations.
Data Types in Java
Java is a strongly typed language, meaning every variable must have a declared data type.
Data types specify the kind of values a variable can hold and the operations allowed on
them.
Java data types are divided into two categories:
1. Primitive Data Types (built-in, 8 types)
• Integral Types
o byte → 8-bit, range: −128 to 127. Used to save memory.
o short → 16-bit, range: −32,768 to 32,767.
o int → 32-bit, commonly used for integers.
o long → 64-bit, larger integer values.
• Floating-Point Types
o float → 32-bit, single precision, for decimal values.
o double → 64-bit, double precision, default for decimals.
• Other Types
o char → 16-bit Unicode character, range: '\u0000' to '\uffff'.
o boolean → stores true or false.
2. Non-Primitive (Reference) Data Types
• Not defined by the language, but by the programmer or Java libraries.
• Examples: Strings, Arrays, Classes, Interfaces, Objects.
• Store references (memory addresses) of actual objects.
• More flexible but require more memory compared to primitive types.
Primitive types — table (size, default, range)
Type Size (bits) Default value Typical use
byte 8 0 small integers (-128..127)
short 16 0 small integers (-32,768..32,767)
int 32 0 default integer type
long 64 0L large integers (use L suffix)
float 32 0.0f single-precision decimal (use f)
double 64 0.0d double-precision decimal (default for decimals)
char 16 '\u0000' single Unicode character (0..65535)
boolean 1 (logical) false true / false
3. What is a variable?
• Named storage location with a type. Holds values or references.
Categories
1. Local variables
o Declared inside methods or blocks.
o Must be initialized before use.
o Lifetime: method execution; memory on the stack.
2. Instance variables (fields)
o Declared in class outside methods (no static).
o Each object has its own copy.
o Default values provided by JVM if not explicitly initialized.
3. Static (class) variables
o Declared with static.
o Single copy shared across all instances.
o Initialized at class loading.
Example
public class Student {
static String college = "VKSU"; // static
int rollNo; // instance
void method() {
int marks = 90; // local
4. Operators — exhaustive
Categories
1. Arithmetic: +, -, *, /, %
o Integer division truncates: 5/2 == 2.
o Use casting for float division: 5/2.0 or (double)5/2.
2. Unary: +, -, ++, --, !
o Prefix ++i increments then yields value; postfix i++ yields old value then
increments.
3. Relational (comparison): ==, !=, >, <, >=, <=
o For objects == compares references; use .equals() for logical equality (String
equals).
4. Logical: &&, ||, !
o Short-circuit behavior: && stops if left is false; || stops if left is true.
5. Bitwise: &, |, ^, ~ (operate on integer bit patterns).
o & & | with booleans behave like logical but no short-circuit when used as
boolean operators.
6. Shift: <<, >>, >>>
o << left shift, >> arithmetic right shift (preserves sign), >>> logical right shift
(fills with zero).
7. Assignment: =, compound +=, -=, *=, /=, %=
o a += b is roughly a = (typeOfA)(a + b) — implicit cast may happen.
8. Ternary (conditional): condition ? valueIfTrue : valueIfFalse
o Example: int m = (a > b) ? a : b;
9. Instanceof: obj instanceof ClassName returns boolean.
Operator precedence
• Highest: ++, --, unary +/-, !
• Multiplicative * / %
• Additive + -
• Shift << >> >>>
• Relational < > <= >=
• Equality == !=
• Bitwise & ^ |
• Logical &&, ||
• Ternary ?:
• Assignment =, +=, et
5. Control Structures — selection & looping (complete)
Selection statements (decision making)
if statement
if (condition) {
// executed when condition true
if–else
if (marks >= 35) {
System.out.println("Pass");
} else {
System.out.println("Fail");
if–else if–else ladder
• Use for multiple mutually exclusive conditions.
if (marks >= 85) System.out.println("Distinction");
else if (marks >= 60) System.out.println("First class");
else if (marks >= 35) System.out.println("Pass");
else System.out.println("Fail");
switch statement
• Evaluates an expression and matches case labels. break prevents fall-through.
switch (day) {
case 1: System.out.println("Mon"); break;
case 2: System.out.println("Tue"); break;
default: System.out.println("Invalid day");
Looping statements
for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
• Initialization → condition → body → update.
Enhanced for (for-each)
int[] arr = {1,2,3};
for (int x : arr) {
System.out.println(x);
• Read-only style: cannot change array length; modifying loop variable doesn't change
original array element (except mutating object contents).
while loop
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
do–while loop
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
• Ensures body executes at least once.
break and continue
• break exits nearest loop/switch.
• continue skips to next iteration.
• Labelled break/continue can exit/continue outer loops:
outer:
for (int i=0;i<3;i++)
for (int j=0;j<3;j++) {
if (i == 1 && j == 1) break outer;
Infinite loops
• for(;;) { }
• while(true) { }
• Use carefully; typically controlled by break.
6. Java Methods — fully explained
What is a method?
• Named block of code that performs action; promotes modularity and reuse.
Method structure
[modifier] returnType methodName([parameterList]) {
// body
return value; // if returnType not void
Example
public int add(int a, int b) {
return a + b;
Return type
• void if no value returned.
• Other types return corresponding values.
Parameters
• Methods can have zero or more parameters.
• Varargs (variable number of arguments): void print(int... nums) {}.
• Parameter types determine overload resolution.
Method signature
• Method name + parameter types (order matters). Return type is not part of signature
for overloading.
Access modifiers
• public, protected, default (package), private control visibility.
static methods
• Belong to class, not instance. Can be called without creating an object.
• Cannot access instance variables directly (this unavailable).
final methods
• Cannot be overridden in subclasses.
Recursion
• A method calling itself. Must have base condition to terminate.
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
• Recursion depth limited by stack size.
Pass-by-value reminder
• Primitive arguments are copied. For object references the reference is copied
(method can change object state but cannot reassign caller’s reference).
Overloading vs Overriding (short)
• Overloading: same method name, different parameters within same class (compile-
time polymorphism).
• Overriding: subclass provides implementation for parent class method with same
signature (run-time polymorphism).
7. Method Overloading — in depth
Method overloading: multiple methods in same class with same name but different
parameter lists (number, type, or order).
Rules
• Signature must differ (parameter list). Return type alone isn’t enough.
• Access modifiers can vary.
• static and instance methods can both be overloaded.
Overloading resolution
• Compiler chooses best match at compile time using most specific applicable method.
• Autoboxing and varargs influence resolution; exact match preferred; then widening;
then boxing; varargs last.
• Ambiguity example:
• void m(Integer i) {}
• void m(int... i) {}
• m(10); // ambiguous? compiler chooses best match based on rules
Examples
int add(int a, int b) { return a+b; }
double add(double a, double b) { return a+b; }
int add(int a, int b, int c) { return a+b+c; }
Common exam points
• Overloaded methods can differ only by parameter order if types differ: f(int a, double
b) vs f(double a, int b) are valid.
• Overloading across inheritance: subclass can overload parent method — still
overload in subclass scope.
8. Math class — full details & examples
java.lang.Math — static methods for common mathematical operations.
Important constants
• Math.PI — 3.141592653589793
• Math.E — Euler’s number
Common methods
• Math.abs(x) — absolute value
• Math.max(a,b), Math.min(a,b)
• Math.sqrt(x) — square root
• Math.pow(a,b) — a^b
• Math.exp(x), Math.log(x) (natural)
• Math.log10(x) — base-10 log
• Math.sin(x), Math.cos(x), Math.tan(x) — trig (radians)
• Math.toDegrees(radians), Math.toRadians(degrees)
• Math.ceil(x) — smallest integer ≥ x
• Math.floor(x) — largest integer ≤ x
• Math.round(x) — nearest long/int depending on input type
• Math.random() — returns double in [0.0, 1.0)
Generate random integer in range [min, max]
int rand = (int)(Math.random() * (max - min + 1)) + min;
Note: For better randomness and features, use java.util.Random or
java.security.SecureRandom (for crypto).
Precision & money
• Floating point (float/double) can have rounding errors — for financial calculations
use BigDecimal.
9. Arrays in Java — exhaustive
What is an array?
• Contiguous collection of elements of same type.
• Indexing starts at 0.
Declaration & initialization
int[] a; // declaration
a = new int[5]; // instantiation (default zeros)
int[] b = {1,2,3}; // declaration + initialization
int c[] = new int[3]; // alternate syntax
Access & length
• Access element: a[0] = 10;
• Length: a.length (no parentheses; method only for Strings length()).
Default values
• numeric → 0, char → '\u0000', boolean → false, reference → null.
Multidimensional arrays
• 2D (matrix):
• int[][] mat = new int[3][4];
• int[][] ragged = { {1,2}, {3,4,5} }; // jagged array
• Access mat[i][j].
Traversal
• for index loop
• Enhanced for for convenience (read-only form for element variable)
Passing arrays to methods
• Arrays are passed by value of the reference — method can modify elements.
void incrementFirst(int[] arr) { arr[0]++; }
Common utilities (java.util.Arrays)
• Arrays.toString(arr) — printable form of 1D array.
• Arrays.deepToString(objArr) — for nested arrays.
• Arrays.sort(arr) — sorts (primitives ascending).
• Arrays.binarySearch(arr, key) — requires sorted array.
• Arrays.copyOf(arr, newLen), System.arraycopy(src, srcPos, dest, destPos, length)
Cloning arrays
• int[] copy = arr.clone(); — shallow copy (elements copied for primitives; reference
copies for objects).
Arrays vs Collections
• Array fixed size; Collections (ArrayList, LinkedList) dynamic sizing and richer APIs.
• ArrayList<Integer> cannot hold primitives (autoboxing to Integer occurs).
Example: find largest element
int max = arr[0];
for (int i=1; i<arr.length; i++) {
if (arr[i] > max) max = arr[i];
Sorting example (bubble sort simple)
for (int i=0; i < n-1; i++)
for (int j=0; j < n-1-i; j++)
if (arr[j] > arr[j+1]) {
int t = arr[j]; arr[j] = arr[j+1]; arr[j+1] = t;
(But prefer Arrays.sort(arr) in real code.)
10. Practical examples & sample programs (useful for labs & exams)
Hello World with comments
public class Hello {
public static void main(String[] args) {
// Print a message
System.out.println("Hello, Java!");
Sum of two numbers (method + overloading)
public class Calc {
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; } // overloaded
public static void main(String[] args) {
Calc c = new Calc();
System.out.println(c.add(2,3));
System.out.println(c.add(2.5,3.1));
}
Array: find max & average
public class ArrayOps {
public static void main(String[] args) {
int[] arr = {5, 3, 9, 1};
int max = arr[0], sum = 0;
for (int v : arr) { if (v > max) max = v; sum += v; }
double avg = (double) sum / arr.length;
System.out.println("Max: " + max + ", Avg: " + avg);
Method: factorial (recursion)
public static int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);