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:

    1. Compile-time / StaticMethod Overloading (same method name, different parameter list).

    2. Run-time / DynamicMethod 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:

    1. Source file → javac Sample.java → bytecode (Sample.class).

    2. Execution → java Sample → JVM interprets bytecode.


Java Tokens

Tokens are the smallest individual units in Java source code.

  1. Keywords / Reserved Words – predefined, have special meaning; e.g., int, char, boolean, void, class, static, return.

  2. Identifiers – programmer-defined names (classes, variables, methods).

  3. Literals – constant values written directly in code (numeric, character, string, boolean, null).

  4. Operators – symbols performing operations (+, -, *, &&, etc.).

  5. Separators / Punctuators( ) { } [ ] ; , ..

  6. Comments – single-line //, multi-line /* ... */ & documentation /** ... */.


Primitive & Non-Primitive Data Types

Primitive Types, Size & Range
  • Numerical

    • byte  8\,\text{bits}  -2^{7}\,\text{to}\,2^{7}-1

    • short 16\,\text{bits}  -2^{15}\,\text{to}\,2^{15}-1

    • int  32\,\text{bits}  -2^{31}\,\text{to}\,2^{31}-1

    • long 64\,\text{bits}  -2^{63}\,\text{to}\,2^{63}-1

    • float 32\,\text{bits}  single-precision IEEE-754

    • double 64\,\text{bits}  double-precision IEEE-754

  • Non-Numerical

    • char  16\,\text{bits} (Unicode 0–65,535)

    • boolean 1\,\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

  1. Arithmetic+ − * / %

  2. Unary+ − ++ -- !

  3. Assignment= += -= *= /= %= &= |= ^= <<= >>= >>>=

  4. Relational> < >= <= == !=

  5. Logical&& || !

  6. Bitwise& | ^ ~ << >> >>>


Control Statements

Decision-Making
  • if statement

  if (condition) {
      // statements
  }
  • if-else

  if (condition) {
      // true branch
  } else {
      // false branch
  }
  • if-else-if Ladder

  if (cond1) { }
  else if (cond2) { }
  else if (cond3) { }
  else { }
  • Nested ifif inside another if.

  • switch Statement

  switch (expression) {
      case VALUE1:  ... ; break;
      case VALUE2:  ... ; break;
      default:      ... ;
  }

• Works with byte, short, char, int, enum, String and their wrappers.

Looping / Iterative
  1. while loop – pre-test

   while (condition) {
       ...
   }
  1. do-while loop – post-test (executes at least once)

   do {
       ...
   } while (condition);
  1. for loop – counter-controlled

   for (initialization; condition; increment) {
       ...
   }
Jump Statements
  • break – exits loop or switch.

  • 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 double

  • Casting 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).