CACS204 Object Oriented Programming in Java

Object Oriented Programming in JavaUnit 210 min read

Variables, Data Types & Operators in Java

Unit 2 of Object Oriented Programming in Java covers Java’s primitive data types, variables, operators, and type casting, with visual traces of operations, real-world examples, and exam-focused comparisons.

TAKEAWAYS:

  • Java has 8 primitive types (byte, short, int, long, float, double, char, boolean) and reference types (classes, arrays, interfaces).
  • Variables must be declared with a type and initialized before use; scope rules apply (local, instance, static).
  • Operators include arithmetic (+, -, *, /, %), relational (>, <, ==), logical (&&, ||, !), and bitwise (&, |, ^, ~).
  • Type casting converts between types (e.g., int to double), with implicit and explicit rules.
  • Operator precedence follows PEMDAS/BODMAS; parentheses override defaults.
  • Common pitfalls: integer division truncation, uninitialized variables, and implicit casting losses (e.g., double to int).

1. Data Types in Java

Java divides data types into primitive (built-in) and non-primitive (objects/arrays).

1.1 Primitive Data Types

mindmap
  root((Primitive Types))
    byte
      range: -128 to 127
      size: 1 byte
    short
      range: -32,768 to 32,767
      size: 2 bytes
    int
      range: -2³¹ to 2³¹-1
      size: 4 bytes
    long
      range: -2⁶³ to 2⁶³-1
      size: 8 bytes
    float
      range: ~3.4e-38 to 3.4e+38
      size: 4 bytes
    double
      range: ~1.7e-308 to 1.7e+308
      size: 8 bytes
    char
      range: 0 to 65,535 (Unicode)
      size: 2 bytes
    boolean
      values: true/false
      size: 1 bit (but 1 byte in JVM)

Key Notes:

  • char stores Unicode (e.g., 'A', 'न', '€').
  • boolean cannot be cast to int (unlike C/C++).
  • Default values for primitives:
    • Numeric types: 0
    • char: '\u0000' (null character)
    • boolean: false

Example:

public class DataTypesDemo {
    public static void main(String[] args) {
        byte age = 25;          // Valid
        short salary = 15000;   // Valid
        int population = 30_000_000; // Underscore for readability
        long earthPopulation = 7_800_000_000L; // 'L' suffix
        float pi = 3.14f;       // 'f' suffix
        double avgTemp = 23.5;
        char grade = 'A';
        boolean isPassed = true;
    }
}

1.2 Non-Primitive Data Types

  • Classes (e.g., String, Scanner).
  • Arrays (e.g., int[] marks = new int[5]).
  • Interfaces (e.g., List, Map).

Example:

String name = "Ramesh"; // Object (non-primitive)
int[] scores = {85, 90, 78}; // Array (non-primitive)

2. Variables in Java

Variables store data values. Rules:

  1. Must be declared with a type.
  2. Must be initialized before use (unless static/global).
  3. Names are case-sensitive (age ≠ Age).

2.1 Variable Scope

Scope Lifetime Accessibility
Local Method block Only within the method
Instance Object lifetime Accessible via object
Static Class lifetime Accessible via class name

Example:

public class VariableScope {
    static int staticVar = 10; // Class variable
    int instanceVar = 20;      // Instance variable

    void method() {
        int localVar = 30;     // Local variable
        System.out.println(staticVar + instanceVar + localVar);
    }

    public static void main(String[] args) {
        VariableScope obj = new VariableScope();
        obj.method(); // Output: 60
    }
}

Visual Trace:

sequenceDiagram
    participant Main
    participant obj
    Main->>obj: obj.method()
    obj->>obj: staticVar (10) + instanceVar (20) + localVar (30)
    obj-->>Main: 60

3. Operators in Java

Operators perform operations on variables/values.

3.1 Arithmetic Operators

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 2 2 (int)
% Modulus 5 % 2 1

Note: Division between integers truncates (5/2 = 2, not 2.5). Example:

int a = 5, b = 2;
System.out.println(a / b); // 2 (integer division)
System.out.println((double)a / b); // 2.5 (type casting)

3.2 Relational Operators

Operator Name Example Result
== Equal to 5 == 5 true
!= Not equal 5 != 3 true
> Greater than 5 > 3 true
< Less than 3 < 5 true
>= Greater/equal 5 >= 5 true
<= Less/equal 3 <= 5 true

Example:

int x = 10, y = 20;
boolean isGreater = x > y; // false

3.3 Logical Operators

Operator Name Example Result
&& AND true && false false
|| OR true || false true
! NOT !true false

Example:

int age = 18;
boolean hasID = true;
boolean canVote = age >= 18 && hasID; // true

3.4 Bitwise Operators

Operator Name Example Result (Binary)
& AND 5 & 3 101 & 011 → 001 (1)
| OR 5 | 3 101 | 011 → 111 (7)
^ XOR 5 ^ 3 101 ^ 011 → 110 (6)
~ NOT ~5 ~101 → 010 (-6)
<< Left Shift 5 << 1 101 << 1 → 1010 (10)
>> Right Shift 5 >> 1 101 >> 1 → 010 (2)

Example:

int num1 = 5; // 0101
int num2 = 3; // 0011
System.out.println(num1 & num2); // 1 (0001)

3.5 Operator Precedence

Java follows PEMDAS/BODMAS rules. Parentheses have the highest precedence. Example:

int result = 10 + 5 * 2; // 20 (multiplication first)
int result2 = (10 + 5) * 2; // 30 (parentheses first)

Visual Trace:

flowchart TD
    A["10 + 5 * 2"] --> B["5 * 2 = 10"]
    B --> C["10 + 10 = 20"]
    D[(10 + 5) * 2] --> E["10 + 5 = 15"]
    E --> F["15 * 2 = 30"]

4. Type Casting

Converts one data type to another.

4.1 Implicit Casting (Widening)

Automatic (smaller to larger type). Example:

int num = 10;
double d = num; // int → double (implicit)
System.out.println(d); // 10.0

4.2 Explicit Casting (Narrowing)

Manual (larger to smaller type; may lose data). Example:

double pi = 3.14159;
int intPi = (int) pi; // double → int (explicit)
System.out.println(intPi); // 3 (truncated)

Visual Trace:

sequenceDiagram
    participant doublePi
    participant intPi
    doublePi->>intPi: (int) 3.14159
    intPi-->>doublePi: 3 (truncated)

5. Real-World Applications

Example 1: eSewa Transaction Fees

eSewa calculates transaction fees using percentage operators:

double amount = 5000;
double fee = amount * 0.025; // 2.5% fee
System.out.println("Fee: " + fee); // Fee: 125.0

Visual:

flowchart TD
    A["Amount: 5000"] --> B["Fee = 5000 * 0.025"]
    B --> C["Fee: 125.0"]

Example 2: Ncell Data Usage

Ncell tracks data usage with bitwise operations for efficient storage:

int usedData = 1024; // 1KB in bytes
int totalData = 2048; // 2KB
boolean isOverLimit = usedData > totalData; // false

Visual:

pie
    title Data Usage
    "Used: 1KB" : 50
    "Remaining: 1KB" : 50

Example 3: Daraz Discount Calculation

Daraz applies discounts using arithmetic and relational operators:

int originalPrice = 1000;
int discount = 20;
int finalPrice = originalPrice - (originalPrice * discount / 100);
System.out.println("Final Price: " + finalPrice); // 800

Visual:

flowchart TD
    A["Original: 1000"] --> B["Discount: 20%"]
    B --> C["Discounted: 1000 - 200 = 800"]

6. Common Pitfalls & Best Practices

Pitfall Solution
Uninitialized variables Always initialize (int x = 0;)
Integer division truncation Use (double) casting for decimals
Operator precedence errors Use parentheses to clarify order
Mixing == and .equals() Use .equals() for String comparisons
Bitwise vs. logical operators Use & for bitwise, && for logical

Example of Pitfall:

int a = 5, b = 2;
System.out.println(a / b == 2.5); // false (2 == 2.5 is false)
System.out.println(a / (double)b == 2.5); // true

7. Exam Tip

  1. Memorize Primitive Types:

    • Know ranges/sizes (e.g., int is 4 bytes, -2³¹ to 2³¹-1).
    • Exam Question: "What is the range of a short?" → -32,768 to 32,767.
  2. Operator Precedence:

    • Always use parentheses in complex expressions.
    • Exam Question: "What is the output of 5 + 3 * 2?" → 11 (not 16).
  3. Type Casting:

    • Differentiate implicit (automatic) vs. explicit casting.
    • Exam Question: "Convert double to int in Java." → (int) d.
  4. Variable Scope:

    • Local variables must be initialized before use.
    • Exam Question: "Where can a static variable be accessed?" → Via class name.
  5. Real-World Scenarios:

    • Relate to apps like eSewa (fees), Ncell (data limits), or Daraz (discounts).
    • Exam Question: "How would you calculate a 10% discount on a product priced at ₹500?"
      double price = 500;
      double discount = price * 0.10;
      double finalPrice = price - discount;
      
  6. Common Mistakes:

    • Avoid == for String comparisons (use .equals()).
    • Watch for integer division truncation (e.g., 5/2 = 2).
    • Initialize variables to avoid NullPointerException or NumberFormatException.

Final Note: Practice coding snippets for operator precedence, type casting, and variable scope to score full marks in TU/PU exams. Use real-world examples (e.g., eSewa fees, Ncell data) to remember concepts.

Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 2.

Discussion

Loading…