Module 1 – Java Basics, OOP & Control Structures
Programming Paradigms
Imperative (Procedural) Programming
Focuses on how to perform tasks — gives step-by-step instructions.
Uses in-built language features to manipulate state.
Example language: C.
Object-Oriented Programming (OOP)
Models programs as collections of interacting objects.
Examples: Java, Python.
Functional Programming
Emphasises immutable data and pure functions.
Examples: Haskell, JavaScript (functional style).
Logical Programming
Describes problems as facts & rules; the engine deduces results.
Classic example: Prolog.
Descriptive / Declarative Programming
Focuses on what to achieve, not how to do it.
SQL is a common declarative language.
Principles & Features of OOP
Six fundamental features ("Pillars")
Class
Object
Abstraction
Encapsulation
Inheritance
Polymorphism
Object
Real-world entity; instance of a class.
Composition: Data Members + Member Functions \text{object}={\text{fields}}+{\text{methods}}
Has physical existence at runtime (memory allocated).
Class
Blueprint / template that defines attributes (variables) and behaviour (methods).
No physical existence until objects are created.
Syntax (Java):
java class ClassName { // data members (variables) // methods (functions) }
Abstraction
Process of exposing only relevant details & hiding implementation.
Goal: reduce complexity, improve maintainability.
Encapsulation
Bundling data & code operating on that data inside one unit (class).
Achieved with access modifiers (private, public, protected).
Inheritance
Mechanism for a class (child / subclass) to acquire members of another class (parent / superclass).
Promotes code reuse and hierarchical classification.
Common forms in Java:
Single (one parent, one child)
Multilevel (A → B → C)
Hierarchical (one parent, many children)
Hybrid & Multiple are conceptual but not directly supported in Java (can be simulated via interfaces).
Polymorphism
Ability of one interface to represent many forms.
Two major manifestations in Java:
Compile-time / Static — Method Overloading (same method name, different parameter list).
Run-time / Dynamic — Method Overriding (subclass re-defines superclass method).
Example hierarchy (illustrates overriding):
text Shape (area(), perimeter()) ├── Circle (radius) ├── Square (side) ├── Rectangle (length, breadth) └── Triangle (base, height)
Java Development Kit (JDK)
Provides compiler (
javac), runtime (java), libraries & tools.Compilation flow:
Source file →
javac Sample.java→ bytecode (Sample.class).Execution →
java Sample→ JVM interprets bytecode.
Java Tokens
Tokens are the smallest individual units in Java source code.
Keywords / Reserved Words – predefined, have special meaning; e.g.,
int,char,boolean,void,class,static,return.Identifiers – programmer-defined names (classes, variables, methods).
Literals – constant values written directly in code (numeric, character, string, boolean, null).
Operators – symbols performing operations (
+,-,*,&&, etc.).Separators / Punctuators –
(){}[];,..Comments – single-line
//, multi-line/* ... */& documentation/** ... */.
Primitive & Non-Primitive Data Types
Primitive Types, Size & Range
Numerical
byte8\,\text{bits} -2^{7}\,\text{to}\,2^{7}-1short16\,\text{bits} -2^{15}\,\text{to}\,2^{15}-1int32\,\text{bits} -2^{31}\,\text{to}\,2^{31}-1long64\,\text{bits} -2^{63}\,\text{to}\,2^{63}-1float32\,\text{bits} single-precision IEEE-754double64\,\text{bits} double-precision IEEE-754
Non-Numerical
char16\,\text{bits} (Unicode 0–65,535)boolean1\,\text{bit (conceptually)} values:true,false
Non-Primitive Types
String, Arrays, Classes, Interfaces, Enums – all reference types, store memory address of actual object.
Variables
Declaration syntax:
DataType variableName;e.g.,int score;Case-sensitive; cannot start with a digit; cannot be a keyword; no spaces or special symbols except
_and$.Assigning value:
int a = 10;
Literals
Integer (
123,0x7B), Floating (3.14,2.0e5), Character ('A'), String ("Hello"), Boolean (true), Null (null).
Operators
Arithmetic
+ − * / %Unary
+ − ++ -- !Assignment
= += -= *= /= %= &= |= ^= <<= >>= >>>=Relational
> < >= <= == !=Logical
&& || !Bitwise
& | ^ ~ << >> >>>
Control Statements
Decision-Making
ifstatement
if (condition) {
// statements
}
if-else
if (condition) {
// true branch
} else {
// false branch
}
if-else-ifLadder
if (cond1) { }
else if (cond2) { }
else if (cond3) { }
else { }
Nested
if–ifinside anotherif.switchStatement
switch (expression) {
case VALUE1: ... ; break;
case VALUE2: ... ; break;
default: ... ;
}
• Works with byte, short, char, int, enum, String and their wrappers.
Looping / Iterative
whileloop – pre-test
while (condition) {
...
}
do-whileloop – post-test (executes at least once)
do {
...
} while (condition);
forloop – counter-controlled
for (initialization; condition; increment) {
...
}
Jump Statements
break– exits loop orswitch.continue– skips remaining loop body, proceeds to next iteration.return– exits from a method, optionally returning a value.
Type Conversion
1. Implicit Conversion (Widening)
Smaller → larger datatype, no data loss.
short s = 10; // 16-bit
float f = s; // 32-bit
long l = 100L;
double d = l; // 64-bit
General rule: \text{byte} \rightarrow \text{short} \rightarrow \text{int} \rightarrow \text{long} \rightarrow \text{float} \rightarrow \text{double}
2. Explicit Conversion (Narrowing / Casting)
Programmer casts larger → smaller; possible data loss.
float f = 159.56f;
int a = (int) f; // truncates decimal part→159
Syntax:
targetType variable = (targetType) value;
Sample Code Snippets
Basic Java Program Skeleton
class Sample {
public static void main(String[] args) {
System.out.println("Hello Java");
}
}
Compile: javac Sample.java Run: java Sample
while Loop Example (print 1-5)
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
do-while Example
do {
System.out.println(i);
i++;
} while (i <= 5);
for Loop Example
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
switch Example with char
char c = 'D';
switch (c) {
case 'A': System.out.println("Sunday"); break;
case 'B': System.out.println("Monday"); break;
case 'C': System.out.println("Tuesday"); break;
case 'D': System.out.println("Wednesday");break;
default: System.out.println("Invalid");
}
Addition Using Scanner
import java.util.Scanner;
class Add {
public static void main(String[] args) {
int a, b, c;
Scanner s = new Scanner(System.in);
System.out.print("Enter value of a: ");
a = s.nextInt();
System.out.print("Enter value of b: ");
b = s.nextInt();
c = a + b;
System.out.println("c = " + c);
}
}
// Sample I/O
// Enter value of a : 4
// Enter value of b : 4
// c = 8
Arithmetic Operator Demo
int a = 10;
int b = 20;
float c = a + b; // 30.0
Ethical & Practical Notes
Encapsulation aids in information hiding, which prevents unintended access & misuse of data.
Abstraction allows APIs to expose contract while shielding complexity, improving security & usability.
Inheritance Misuse can lead to fragile base-class problem; favour composition where appropriate.
Type Casting must be performed carefully to avoid precision loss and runtime
ClassCastException.
Quick Reference Formulas & Sizes
Memory sizes:
\text{byte}=8\;\text{bits},\;\text{short}=16\;\text{bits},\;\text{int}=32\;\text{bits},\;\text{long}=64\;\text{bits}
\text{float}=32\;\text{bits},\;\text{double}=64\;\text{bits}Implicit widening chain:
byte \rightarrow short \rightarrow int \rightarrow long \rightarrow float \rightarrow doubleCasting syntax:
\text{targetVariable} = (\text{TargetType})\;\text{sourceValue}
Connections & Real-World Relevance
Paradigm knowledge guides choosing the right approach (e.g., OOP for GUI apps, functional for concurrency).
OOP principles underpin frameworks like Spring, Android SDK.
Control statements map directly to real-world decision logic (e.g., ATM withdrawal limits →
if-else).Type conversion crucial when reading sensor data (int) and processing in analytics (double).