Object-Oriented Programming in Java

Introduction to Java


Module I: Introduction to Java. This module builds the foundation of Java programming by covering data types, variables, arrays, strings, operators, and control statements. These are the building blocks required before learning classes, inheritance, or advanced concepts.


Primitive Data Types

Java has eight primitive data types used for basic storage needs. They differ in size, range, and typical usage.

  • byte – 1 byte, integer range -128 to 127
  • short – 2 bytes, small integer values
  • int – 4 bytes, default integer type
  • long – 8 bytes, larger numeric values
  • float – 4 bytes, decimal numbers (single precision)
  • double – 8 bytes, decimal numbers (double precision)
  • char – 2 bytes, Unicode character
  • boolean – true or false
Code Example
int age = 19;
double gpa = 8.6;
char grade = 'A';
boolean isValid = true;

Diagram to add: java-primitive-sizes.png


Variables, Type Conversion and Casting

Java automatically performs widening conversions (small to large type), while narrowing conversions require explicit casting.

  • Widening: int to long, float to double (automatic)
  • Narrowing: double to int, long to short (explicit cast)
int a = 10;
double b = a;        // widening

double x = 9.76;
int y = (int) x;     // narrowing, y = 9

Arrays

Arrays store multiple values of the same type. They are objects and have fixed length determined at creation.

int[] marks = {85, 90, 75};
for (int i = 0; i < marks.length; i++) {
  System.out.println(marks[i]);
}

Diagram to add: java-array-memory.png


Strings

Strings are immutable objects. Java stores them in a special "String pool" for memory optimization.

String s = "openCSE";
System.out.println(s.length());
System.out.println(s.toUpperCase());

Operators and Precedence

Java provides arithmetic, relational, logical, bitwise and assignment operators. Parentheses improve readability and override precedence.

int a = 2 + 3 * 4;     // 14
int b = (2 + 3) * 4;   // 20

boolean result = (a < b) && (b < 50);

Diagram: operator-precedence-java.png


Control Statements

Control statements determine program flow. Java provides selection, iteration, and jump statements.

  • Selection: if, if-else, switch
  • Iteration: for, while, do-while, enhanced for
  • Jump: break, continue
int n = 7;

// if-else
if (n > 0) System.out.println("positive");

// switch
switch (n) {
  case 1: System.out.println("one"); break;
  default: System.out.println("other");
}

// loop
for (int i = 0; i < 5; i++) {
  if (i == 3) continue;
  System.out.println(i);
}

Diagram: loop-flowcharts.png