Java fundamentals, classes and inheritance — Unit 1 Notes (Java Programming)

BCS504 · Unit 1

Java fundamentals, classes and inheritance notes — Unit 1

Free unit-wise study notes on java fundamentals, classes and inheritance for Java Programming, Semester 5 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.

Java fundamentals, classes and inheritance

Notebook — 20 pages

Page 1

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

1. Introduction to Java

Java is a high-level, class-based, object-oriented programming language designed to have as few implementation dependencies as possible.

1.1 The History and Philosophy

Created by James Gosling at Sun Microsystems in 1995. Its core philosophy is WORA (Write Once, Run Anywhere). This means compiled Java code can run on all platforms that support Java without the need for recompilation.

1.2 Key Features

  • Simple: Removes complexities like explicit pointers and operator overloading found in C++.
  • Object-Oriented: Everything (almost) is an object.
  • Robust: Strong memory management (Garbage Collection) and strict compile-time type checking.
  • Secure: Runs inside a virtual machine sandbox.
  • Multithreaded: Built-in support for concurrent execution.

Next — JDK, JRE, and JVM

1 of 20

Page 2

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

2. JDK, JRE, and JVM Architecture

Understanding the Java ecosystem requires distinguishing between these three core components.

2.1 JVM (Java Virtual Machine)

The abstract machine that executes Java Bytecode. It is platform-dependent (there is a different JVM for Windows, Mac, Linux), which is what allows the Java bytecode to be platform-independent.

2.2 JRE (Java Runtime Environment)

Provides the libraries, Java Virtual Machine (JVM), and other components to run applications written in Java. Does not contain development tools like compilers.

2.3 JDK (Java Development Kit)

The complete software development environment. It contains everything in the JRE, plus tools like `javac` (the compiler), `javadoc`, and `jdb` (the debugger).

Next — The Compilation Process

2 of 20

Page 3

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

3. The Compilation and Execution Process

Unlike C++ which compiles directly to machine code, Java uses a two-step process.

3.1 Step 1: Compilation

The developer writes human-readable code in a `.java` file. The `javac` compiler translates this not into machine code, but into Bytecode, saved in a `.class` file. Bytecode is highly optimized and platform-agnostic.

3.2 Step 2: Execution

The JVM loads the `.class` file into memory. The JVM contains a Just-In-Time (JIT) Compiler which translates the Bytecode into native machine code on-the-fly right before execution, optimizing it for the specific hardware it's running on.

Next — Basic Syntax and Structure

3 of 20

Page 4

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

4. Basic Syntax and Structure

4.1 The Main Method

Every standalone Java application must have a `main` method, which serves as the entry point.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

4.2 Understanding the Keywords

  • `public`: Access modifier allowing the JVM to execute the method from anywhere.
  • `static`: Allows the main method to be called without having to instantiate the class first.
  • `void`: The method does not return any value.
  • `String[] args`: An array of strings used to pass command-line arguments to the program.

Next — Data Types

4 of 20

Page 5

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

5. Primitive Data Types

Java is a strongly typed language. Every variable must have a declared type. Java has 8 primitive data types.

5.1 Integer Types

  • `byte`: 8-bit signed. (-128 to 127)
  • `short`: 16-bit signed.
  • `int`: 32-bit signed. (Default for whole numbers)
  • `long`: 64-bit signed. (Requires 'L' suffix: `100000L`)

5.2 Floating-Point Types

  • `float`: 32-bit single-precision. (Requires 'f' suffix: `3.14f`)
  • `double`: 64-bit double-precision. (Default for decimals)

5.3 Other Types

  • `boolean`: Stores `true` or `false`.
  • `char`: 16-bit Unicode character. (Single quotes: `'A'`)

Next — Variables and Type Casting

5 of 20

Page 6

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

6. Variables and Type Casting

6.1 Variable Scope

  • Local: Declared inside a method, block, or constructor. Destroyed when the method exits.
  • Instance: Declared inside a class but outside methods. Each object has its own copy.
  • Static (Class): Declared with the `static` keyword. Shared among all instances of the class.

6.2 Type Casting

Converting a value from one data type to another.

  • Widening (Implicit): Converting a smaller type to a larger type size. Done automatically (e.g., `int` to `double`).
  • Narrowing (Explicit): Converting a larger type to a smaller size type. Must be done manually because data loss may occur (e.g., `double` to `int`).
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: drops the .78

Next — Operators

6 of 20

Page 7

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

7. Operators in Java

Java provides a rich set of operators to manipulate variables.

CategoryOperatorsDescription
Arithmetic`+ - * / %`Standard math operations. Modulo `%` gives the remainder.
Unary`++ -- !`Increment/Decrement (prefix vs postfix matters), logical NOT.
Relational`== != > < >= <=`Compares values, returns a boolean.
Logical`&& ||`Short-circuit AND, short-circuit OR.
Bitwise`& | ^ ~ << >> >>>`Operates directly on binary bits. `>>>` is unsigned right shift (unique to Java).
Ternary`? :`Shorthand for if-else: `condition ? trueVal : falseVal`.

Next — Control Flow Statements

7 of 20

Page 8

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

8. Control Flow Statements

Java's control flow syntax is identical to C/C++.

8.1 Decision Making

Includes `if`, `else if`, `else`, and the `switch` statement (which in modern Java supports Strings and enums, not just integers).

8.2 Looping

  • `for`: Best when the number of iterations is known.
  • `while`: Best when iterating until a condition turns false.
  • `do-while`: Guarantees the block executes at least once before checking the condition.
  • Enhanced `for` loop (For-Each): Introduced in Java 5 for iterating over arrays and collections easily.
int[] numbers = {1, 2, 3, 4};
for (int n : numbers) {
    System.out.println(n);
}

Next — Arrays

8 of 20

Page 9

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

9. Arrays

Arrays in Java are objects, dynamically allocated, and store a fixed-size sequential collection of elements of the same type.

9.1 Declaration and Instantiation

// Declaration
int[] arr;
// Instantiation (Allocates memory)
arr = new int[5];

// Declaration + Initialization
String[] names = {"Alice", "Bob", "Charlie"};

9.2 Array Properties

  • Arrays are strictly indexed from `0` to `length - 1`.
  • Accessing an out-of-bounds index throws `ArrayIndexOutOfBoundsException`.
  • Every array object has a final `length` property (e.g., `arr.length`). Note it has no parentheses.
  • Multi-dimensional arrays are actually arrays of arrays, meaning sub-arrays can have different lengths (Jagged Arrays).

Next — Classes and Objects

9 of 20

Page 10

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

10. Classes and Objects

A Class is a blueprint or template. An Object is an instance of a class.

10.1 Class Structure

public class Car {
    // Instance Variables (State)
    String color;
    int speed;

    // Method (Behavior)
    void accelerate() {
        speed += 10;
    }
}

10.2 Creating Objects

Objects are created using the `new` keyword, which dynamically allocates memory on the Heap and calls the constructor.

Car myTesla = new Car();
myTesla.color = "Red";
myTesla.accelerate();

Next — Constructors

10 of 20

Page 11

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

11. Constructors

A constructor is a special method used to initialize objects. It is called automatically when an object of a class is created.

11.1 Constructor Rules

  • The constructor name MUST exactly match the class name.
  • It cannot have a return type, not even `void`.
  • If you do not write a constructor, the Java compiler automatically creates a Default Constructor (no arguments, initializes fields to zero/null).

11.2 Parameterized Constructors

public class Person {
    String name;
    
    // Parameterized constructor
    public Person(String n) {
        name = n;
    }
}

Next — The 'this' Keyword

11 of 20

Page 12

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

12. The 'this' Keyword

`this` is a reference variable that refers to the current object invoking the method or constructor.

12.1 Primary Uses

  • Resolving Shadowing: When instance variables and method parameters have the same name, `this` disambiguates them.
  • Constructor Chaining: Invoking another constructor in the same class using `this()`.
  • Returning the current object: Useful for method chaining.
public class Student {
    int id; // instance variable
    
    public Student(int id) {
        // 'this.id' is the instance var, 'id' is the parameter
        this.id = id; 
    }
}

Next — Static Keyword

12 of 20

Page 13

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

13. The 'static' Keyword

The `static` keyword belongs to the class rather than an instance of the class.

13.1 Static Variables

Memory is allocated only once in the Class Area at the time of class loading. Changing a static variable's value changes it for all objects of that class (e.g., a shared counter for total objects created).

13.2 Static Methods

Can be called without creating an object of the class (e.g., `Math.pow(2, 3)`).

  • A static method can ONLY directly access other static data and static methods.
  • It cannot use `this` or `super` because it is not tied to any object.

13.3 Static Blocks

Used to initialize static variables. Executed strictly once when the class is loaded into memory, before `main` runs.

Next — Method Overloading

13 of 20

Page 14

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

14. Method Overloading

Method Overloading allows a class to have more than one method with the same name, provided their parameter lists are different. This is a form of Compile-Time Polymorphism.

14.1 Rules for Overloading

The methods must differ in:

  • Number of parameters.
  • Data types of parameters.
  • Order of parameters.

CRITICAL: You cannot overload a method based purely on changing the return type. It will cause a compile-time error.

class MathUtil {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
}

Next — Inheritance

14 of 20

Page 15

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

15. Inheritance

Inheritance is the mechanism where one class acquires the properties and behaviors of a parent class, promoting code reusability.

15.1 Basics

The class that inherits is the Subclass (Child), and the class being inherited is the Superclass (Parent). Implemented using the `extends` keyword.

class Animal {
    void eat() { System.out.println("Eating"); }
}
class Dog extends Animal {
    void bark() { System.out.println("Barking"); }
}

15.2 Types of Inheritance in Java

  • Single, Multilevel, and Hierarchical inheritances are supported.
  • Multiple Inheritance (via classes) is NOT supported in Java to avoid the 'Diamond Problem' of ambiguity. (It is supported via Interfaces).

Next — The 'super' Keyword

15 of 20

Page 16

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

16. The 'super' Keyword

The `super` keyword is a reference variable used to refer to immediate parent class objects.

16.1 Primary Uses

  • `super.variable`: Access the parent's instance variable if the child class shadowed it.
  • `super.method()`: Invoke the parent class's method if the child class overrode it.
  • `super()`: Invoke the parent class's constructor.

Constructor Rule: If a child constructor does not explicitly call `super()`, the Java compiler automatically inserts an invisible `super()` call to the parent's default (no-arg) constructor at the very first line.

Next — Method Overriding

16 of 20

Page 17

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

17. Method Overriding

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. This is the basis for Runtime (Dynamic) Polymorphism.

17.1 Rules for Overriding

  • Method name and parameter list must be identical.
  • Return type must be the same or a covariant (a subclass of the original return type).
  • The access modifier cannot be more restrictive than the parent's (e.g., if parent is `protected`, child can be `protected` or `public`, but not `private`).
  • `static` methods cannot be overridden (they are hidden instead).
  • Methods marked `final` or `private` cannot be overridden.

It is best practice to use the `@Override` annotation to let the compiler verify you are actually overriding a method correctly.

Next — Dynamic Method Dispatch

17 of 20

Page 18

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

18. Dynamic Method Dispatch

This is the mechanism by which a call to an overridden method is resolved at runtime, rather than compile time.

18.1 Upcasting

A superclass reference variable can refer to a subclass object. The JVM determines exactly which version of the method to run based on the actual object in memory, not the reference type.

Animal myDog = new Dog(); // Upcasting

// If both Animal and Dog have a makeNoise() method, 
// the JVM runs Dog's version at runtime.
myDog.makeNoise(); 

This is the cornerstone of extensible design in Java, allowing developers to write generic code that handles base classes, but magically executes subclass-specific behaviors.

Next — The 'final' Keyword

18 of 20

Page 19

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

19. The 'final' Keyword

The `final` keyword is used to restrict the user, essentially making something immutable or unchangeable.

19.1 Three Usages

  • Final Variables: The value cannot be changed once initialized (creates a constant). Examples: `final double PI = 3.14159;`
  • Final Methods: The method cannot be overridden by any subclasses. Used to lock down critical behaviors (like authentication checks in a base class).
  • Final Classes: The class cannot be inherited at all. Examples: The built-in `String` class is final to ensure strings remain strictly immutable and secure.

Next — The Object Class

19 of 20

Page 20

Wink Notes

B.Tech CSE — 5th Semester

Java Programming

Unit - 1

20. The Root: java.lang.Object

In Java, the `Object` class (in the `java.lang` package) is the cosmic superclass of all classes. If a class does not explicitly extend another class, it implicitly extends `Object`.

20.1 Important Object Methods

Because every class inherits from `Object`, every object automatically has the following methods, which developers frequently override:

  • `toString()`: Returns a string representation of the object. Often overridden to print meaningful field data instead of memory hashes.
  • `equals(Object obj)`: Compares two objects for logical equivalence, rather than strict memory reference equality (which is what `==` does).
  • `hashCode()`: Returns an integer hash code value for the object, crucial for placing the object in HashMaps.
  • `clone()`: Creates and returns a copy of the object.
  • `getClass()`: Returns the runtime class of the object (used heavily in Reflection).

20 of 20

Continue in this subject