← Back to Courses
© 2025 sampathirao yoganandh
Week 3 · CO-1

Java Language Basics

Buzzwords, Data Types, Variables, Operators, Control Structures, Arrays, Console I/O, Type Casting, Wrapper Classes  CO-1

Java Buzzwords

Java was designed with specific goals that make it unique. These goals are described as Java's Buzzwords:

BuzzwordMeaning
SimpleSyntax similar to C/C++ but without complex features like pointers and operator overloading
Object-OrientedEverything in Java is an object; supports all OOP features
Platform IndependentWrite Once, Run Anywhere (WORA) — bytecode runs on any JVM
SecuredNo explicit pointers; bytecode verification; security manager
RobustStrong exception handling; no pointer arithmetic; automatic garbage collection
Architecture NeutralBytecode is not specific to any processor architecture
PortablePlatform-independent + architecture-neutral = portable
High PerformanceJIT (Just-In-Time) compiler converts bytecode to native code at runtime
DistributedSupports networking protocols; RMI; enterprise distribution
Multi-threadedBuilt-in support for multithreading
DynamicClasses loaded dynamically at runtime; supports runtime polymorphism
📌 Key PointThe most important buzzword is Platform Independence. Java achieves this via the JVM — Java source → javac compiler → bytecode (.class) → JVM → executes on any OS.

Data Types

Java is a strongly typed language — every variable must have a declared type.

Primitive Data Types (8 types)

TypeSizeRangeDefaultExample
byte1 byte (8 bits)-128 to 1270byte b = 10;
short2 bytes-32768 to 327670short s = 500;
int4 bytes-2^31 to 2^31-10int i = 1000;
long8 bytes-2^63 to 2^63-10Llong l = 100L;
float4 bytes~±3.4×10^380.0ffloat f = 3.14f;
double8 bytes~±1.8×10^3080.0ddouble d = 3.14;
char2 bytes0 to 65535 (Unicode)'\u0000'char c = 'A';
boolean1 bittrue / falsefalseboolean flag = true;
💡 Did You KnowJava uses Unicode for char (2 bytes), unlike C/C++ which uses ASCII (1 byte). This is why Java supports international character sets.

Variables

Types of Variables in Java

TypeDeclared InsideDefault ValueLifetime
Local VariableMethod / BlockNo default — must initializeUntil method exits
Instance VariableClass (no static)Has default (0, null, false)Until object is GC'd
Static VariableClass (with static)Has defaultUntil class is unloaded
class Example {
    static int count = 0;     // static variable — shared by all objects
    int id;                    // instance variable — per object

    void show() {
        int local = 10;          // local variable — must be initialized
        System.out.println(local);
    }
}
⚠️ ImportantLocal variables have NO default value. Using an uninitialized local variable causes a compile-time error.

Operators

CategoryOperatorsExample
Arithmetic+ - * / %a + b, a % b
Relational== != < > <= >=a == b, a < b
Logical&& || !a&&b, !flag
Bitwise& | ^ ~ << >> >>>a & b, a << 2
Assignment= += -= *= /= %=a += 5
Ternary? :max = (a>b) ? a : b
Increment/Decrement++ --a++, --b
📌 Key PointShort-circuit evaluation: In &&, if the left operand is false, the right side is NOT evaluated. In ||, if left is true, right is skipped.

Control Structures

// if-else
if (marks >= 60) {
    System.out.println("Pass");
} else if (marks >= 35) {
    System.out.println("Compartment");
} else {
    System.out.println("Fail");
}

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

// for loop
for (int i = 0; i < 5; i++) { System.out.print(i + " "); }

// while
while (n > 0) { sum += n % 10; n /= 10; }

// do-while (executes at least once)
do { System.out.println("Entered"); } while (false);

Arrays

An array is a collection of elements of the same type stored in contiguous memory locations.

// 1D Array
int[] marks = new int[5];         // declaration + creation
int[] scores = {85, 92, 78, 95, 88}; // declaration + init

// Enhanced for loop
for (int s : scores) {
    System.out.print(s + " ");
}

// 2D Array
int[][] matrix = new int[3][3];
int[][] grid = {{1,2,3}, {4,5,6}, {7,8,9}};
📌 Key PointArrays in Java are objects, not primitives. array.length gives the size. Array index starts at 0.

Console I/O

import java.util.Scanner;

public class ConsoleDemo {
    public static void main(String[] args) {
        // Input using Scanner
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter name: ");
        String name = sc.nextLine();
        System.out.print("Enter age: ");
        int age = sc.nextInt();

        // Output
        System.out.println("Hello, " + name + "! Age: " + age);
        System.out.printf("Formatted: %s is %d years old%n", name, age);

        sc.close();
    }
}

Type Casting

Type casting is converting a value from one data type to another. Java supports two kinds of casting:

1. Widening Conversion (Implicit / Automatic)

The smaller type is automatically promoted to a larger type. No data loss occurs. Java does this automatically.

// Widening: byte → short → int → long → float → double
byte b = 10;
short s = b;       // byte to short — automatic
int i = s;         // short to int — automatic
long l = i;        // int to long — automatic
float f = l;       // long to float — automatic
double d = f;      // float to double — automatic
System.out.println(d);  // Output: 10.0

2. Narrowing Conversion (Explicit / Manual)

The larger type must be explicitly cast to a smaller type. Data loss may occur. You must use the cast operator (type).

// Narrowing: double → float → long → int → short → byte
double d = 9.99;
int i = (int) d;     // explicit cast — fractional part lost
System.out.println(i); // Output: 9 (not 10 — truncated, not rounded)

int big = 130;
byte small = (byte) big; // 130 overflows byte range (-128 to 127)
System.out.println(small); // Output: -126 (bit truncation)

3. Type Promotion in Expressions

Java automatically promotes smaller types to int when used in arithmetic expressions.

byte a = 40, b = 50;
byte c = (byte)(a + b);  // a+b produces int, so explicit cast needed

char ch = 'A';
int val = ch + 1;          // 'A' (65) + 1 = 66 — char promoted to int
System.out.println(val);   // Output: 66
System.out.println((char) val); // Output: B

4. Casting Between char and int

char and int are interchangeable via casting — Java stores characters as their Unicode (ASCII) numeric values.

// char → int (widening, automatic)
char ch = 'A';
int code = ch;
System.out.println(code);       // Output: 65 (ASCII of 'A')

// int → char (narrowing, explicit)
int n = 66;
char c = (char) n;
System.out.println(c);          // Output: B

// Alphabet traversal using int-to-char casting
for (int i = 65; i <= 90; i++) {
    System.out.print((char) i + " ");
}
// Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

5. Real-World Example — Grade Calculator

public class GradeCalc {
    public static void main(String[] args) {
        int totalMarks = 456;
        int subjects    = 5;

        // int division gives int — fractional part lost
        int wrongAvg = totalMarks / subjects;
        System.out.println("Wrong avg: " + wrongAvg);   // 91 (not 91.2)

        // Cast one operand to double to get accurate result
        double correctAvg = (double) totalMarks / subjects;
        System.out.println("Correct avg: " + correctAvg); // 91.2

        // Narrow back to int for display (truncates decimal)
        int displayAvg = (int) correctAvg;
        System.out.println("Display avg: " + displayAvg);  // 91
    }
}

6. Overflow Behaviour During Narrowing

When a value is too large for the target type, Java wraps around (modulo arithmetic) — it does NOT throw an exception.

int val = 257;
byte b = (byte) val;
System.out.println(b);   // Output: 1  (257 % 256 = 1)

int val2 = 300;
byte b2 = (byte) val2;
System.out.println(b2);  // Output: 44  (300 - 256 = 44)

double pi = 3.99999;
int i = (int) pi;
System.out.println(i);   // Output: 3 (truncated, NOT rounded)

7. Casting in Mixed-Type Arithmetic

int a = 7, b = 2;

// Both int — result is int
System.out.println(a / b);              // 3

// Cast numerator — result is double
System.out.println((double) a / b);    // 3.5

// Cast denominator — result is double
System.out.println(a / (double) b);    // 3.5

// Cast result (wrong!) — division already done as int
System.out.println((double)(a / b));   // 3.0 (NOT 3.5)
⚠️ Common MistakeCasting the result (double)(a/b) does NOT give a decimal result — the integer division happens first, then the result is cast. Always cast at least one operand: (double)a / b.
📌 Key PointWidening is safe (no data loss) and done automatically. Narrowing requires explicit cast and may lose data. In expressions, byte and short are always promoted to int.
TypeDirectionCast Required?Data Loss?
Wideningsmall → large (e.g. int→long)No — automaticNo
Narrowinglarge → small (e.g. double→int)Yes — explicit (type)Possible

Wrapper Classes

Java primitives (int, char, etc.) are not objects. Wrapper classes wrap a primitive value inside an object, making them compatible with Java's object-oriented features (Collections, Generics, etc.).

Primitive vs Wrapper Class

PrimitiveWrapper ClassPackage
byteBytejava.lang
shortShortjava.lang
intIntegerjava.lang
longLongjava.lang
floatFloatjava.lang
doubleDoublejava.lang
charCharacterjava.lang
booleanBooleanjava.lang

Autoboxing and Unboxing

Autoboxing is the automatic conversion of a primitive to its wrapper object. Unboxing is the reverse — wrapper object to primitive. Java does both automatically (since Java 5).

// Autoboxing — primitive int automatically wrapped into Integer object
int x = 42;
Integer obj = x;          // autoboxing: int → Integer

// Unboxing — Integer object automatically unwrapped to int
int y = obj;              // unboxing: Integer → int

// Common use: storing primitives in a Collection
java.util.ArrayList<Integer> list = new java.util.ArrayList<>();
list.add(10);             // autoboxing happens here automatically
int val = list.get(0);    // unboxing happens here automatically

Useful Wrapper Class Methods

// Parsing strings to primitives
int a = Integer.parseInt("123");       // String → int
double d = Double.parseDouble("3.14"); // String → double
boolean b = Boolean.parseBoolean("true");

// Converting primitives to String
String s1 = Integer.toString(42);       // int → String
String s2 = String.valueOf(3.14);       // any type → String

// Useful constants
System.out.println(Integer.MAX_VALUE);  // 2147483647
System.out.println(Integer.MIN_VALUE);  // -2147483648
System.out.println(Integer.toBinaryString(10)); // "1010"
System.out.println(Integer.toHexString(255));   // "ff"
System.out.println(Character.isDigit('5'));     // true
System.out.println(Character.isLetter('A'));    // true
System.out.println(Character.toUpperCase('a')); // A
💡 Why Wrapper Classes?Collections like ArrayList and HashMap can only store objects, not primitives. Wrapper classes bridge this gap — ArrayList<Integer> works; ArrayList<int> does not.
⚠️ Null Pointer RiskWrapper objects can be null. Unboxing a null wrapper causes a NullPointerException at runtime. Always check for null before unboxing.
📄

Download PDF Notes

Save these notes as a PDF for offline reference

View / Download PDF