[Go to site: main page, start]

0% found this document useful (0 votes)
2 views24 pages

Java Unit-II Notes

The document explains argument passing mechanisms in Java, emphasizing that Java is always pass-by-value, where primitives pass their actual value and objects pass a reference copy. It also covers wrapper classes, their utility in collections, and the concept of the 'this' keyword for referencing the current object. Additionally, it discusses intra-class constructor chaining and method chaining, highlighting their significance in code organization and readability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Java Unit-II Notes

The document explains argument passing mechanisms in Java, emphasizing that Java is always pass-by-value, where primitives pass their actual value and objects pass a reference copy. It also covers wrapper classes, their utility in collections, and the concept of the 'this' keyword for referencing the current object. Additionally, it discusses intra-class constructor chaining and method chaining, highlighting their significance in code organization and readability.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

Argument Passing Mechanisms


In Java, argument passing mechanisms define how values are transferred from a
calling method to a called method. This is a fundamental concept for understanding
how Java programs behave.

1. The Core Principle: Java is Always Pass-by-Value

No matter what you pass—primitive or object—Java always passes a copy of the


value.

There is no pass-by-reference in Java.

However, what gets copied differs:

• For primitives → actual value is copied

• For objects → reference (address) is copied

2. Passing Primitive Arguments

✔ How it Works

• A copy of the actual value is passed

• Method works on its own independent variable

✔ Example

void increment(int x) {

x = x + 1;

int a = 10;

increment(a);

[Link](a); // Output: 10

✔ Explanation

• a → value = 10

• Method receives x = 10 (copy)

• Changing x does not affect a


2

3. Passing Object Arguments (Reference Types)

Objects include:

• Classes

• Arrays

• Strings

✔ How it Works

• The reference (memory address) is copied

• Both original and method parameter point to the same object

✔ Example 1: Modifying Object State

class Box {

int value;

void change(Box b) {

[Link] = 20;

Box obj = new Box();

[Link] = 10;

change(obj);

[Link]([Link]); // Output: 20

✔ Explanation

• Copy of reference is passed

• Both obj and b refer to same object

• So changes affect original object


3

✔ Example 2: Reassigning Object Reference

void reassign(Box b) {

b = new Box();

[Link] = 50;

Box obj = new Box();

[Link] = 10;

reassign(obj);

[Link]([Link]); // Output: 10

✔ Explanation

• New object is assigned only to local b

• Original obj remains unchanged

4. Key Insight: Why Confusion Happens

Java appears to behave like pass-by-reference for objects because:

• You can modify object data inside methods

But in reality:

• You are modifying the object via a copied reference

• Not passing the original reference itself

5. Memory-Level Understanding

Primitive Case:

a = 10

method(x = 10) // copy

Change x → no effect on a
4

Object Case:

obj → [value = 10]

method(b → same object)

Change [Link] → affects [Link]

6. Comparison Table

Feature Primitive Types Object Types

What is passed Value copy Reference copy

Memory shared? No Yes (same object)

Can modify original? No Yes (state only)

Can reassign? No effect No effect on original

Wrapper Classes
In Java, wrapper classes are used to convert primitive data types into objects. They are
part of the [Link] package and play a key role in collections, utilities, and object-
oriented features.

1. What are Wrapper Classes?

A wrapper class “wraps” a primitive data type into an object.

For example:

• int → Integer

• double → Double
5

2. Primitive → Wrapper Mapping

Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

3. Why Wrapper Classes are Needed

1. Collections Framework

Java collections (like ArrayList) work only with objects:

ArrayList<Integer> list = new ArrayList<>();

[Link](10); // primitive int converted to Integer

2. Utility Methods

Wrapper classes provide useful methods:

• parseInt()

• toString()

• compareTo()

3. Object Features

• Required for null values

• Used in generics

• Enable synchronization and reflection


6

4. Autoboxing and Unboxing

Autoboxing

Automatic conversion of primitive → object

int x = 10;

Integer obj = x; // autoboxing

Unboxing

Object → primitive

Integer obj = 20;

int y = obj; // unboxing

5. Manual Conversion

int x = 5;

Integer obj = [Link](x); // boxing

int y = [Link](); // unboxing

6. Important Features of Wrapper Classes

✔ Immutable

Objects of wrapper classes cannot be changed once created.

Integer a = 10;

a = 20; // new object created

✔ Comparable

Wrapper classes implement comparison methods:

Integer a = 10;

Integer b = 20;

[Link]([Link](b)); // -1
7

✔ Useful Constants

[Link](Integer.MAX_VALUE);

[Link](Integer.MIN_VALUE);

7. Example Program

public class WrapperDemo {

public static void main(String[] args) {

// Autoboxing

int num = 100;

Integer obj = num;

// Unboxing

int value = obj;

// Using methods

String str = "123";

int parsed = [Link](str);

[Link]("Object: " + obj);

[Link]("Primitive: " + value);

[Link]("Parsed: " + parsed);

}
8

8. Key Differences

Feature Primitive Wrapper Class

Type Basic data Object

Memory Less More

Speed Faster Slower

Null allowed No Yes

Methods No Yes

9. Important Notes (Exam/Interview)

• Wrapper classes are immutable

• Stored in heap memory

• Used heavily in collections and generics

• Enable autoboxing/unboxing

Final Summary

Wrapper classes allow primitives to behave like objects, enabling:

• Use in collections

• Utility operations

• Object-oriented programming features

this keyword
In Java, the this keyword is a reference variable that refers to the current object (the
object whose method or constructor is being called).

1. What is this?

this refers to the current instance of a class.


9

• It is automatically available inside non-static methods and constructors

• Used to access current object’s variables and methods

2. Why this is Needed

Mainly used to:

• Resolve naming conflicts

• Access current object

• Call constructors

• Pass current object as argument

3. Common Uses of this

1. To Refer Current Instance Variables

Used when local variables and instance variables have the same name.

class Student {

int marks;

void setMarks(int marks) {

[Link] = marks; // distinguishes instance variable

✔ Without this, Java would confuse local and instance variables.

2. To Call Current Class Methods

class Demo {

void display() {

[Link]("Hello");

}
10

void show() {

[Link](); // calling method

✔ this is optional here, but improves clarity.

3. To Call Another Constructor (Constructor Chaining)

class Test {

Test() {

this(10); // calls parameterized constructor

[Link]("Default constructor");

Test(int x) {

[Link]("Parameterized constructor: " + x);

✔ Must be the first statement in constructor.

4. To Pass Current Object as Argument

class A {

void show(A obj) {

[Link]("Method called");

void display() {

[Link](this);

}
11

✔ Useful in callbacks and method chaining.

5. To Return Current Object

class Demo {

Demo getObject() {

return this;

✔ Used in method chaining / fluent APIs

6. To Pass Current Object to Constructor

class B {

B(A obj) {

[Link]("Constructor called");

class A {

void create() {

B b = new B(this);

4. Where this Cannot Be Used

Inside static methods

static void show() {

// this.x = 10; Error


12

✔ Because static methods don’t belong to an object.

5. Complete Example

class Person {

String name;

int age;

Person(String name, int age) {

[Link] = name; // instance variable

[Link] = age;

void display() {

[Link]([Link] + " " + [Link]);

Person getPerson() {

return this;

void show() {

display(); // internally [Link]()

public class Main {

public static void main(String[] args) {


13

Person p = new Person("Rahul", 25);

[Link]();

Person p2 = [Link]();

[Link]([Link]);

6. Key Points

• this refers to current object

• Cannot be used in static context

• Helps in constructor chaining

• Used for method chaining and passing objects

7. One-Line Summary

this = reference to the current object

Referencing Instance Members


In Java, referencing instance members means accessing the variables (fields) and
methods that belong to an object (instance of a class).

1. What are Instance Members?

Instance members are:

• Instance variables (non-static fields)

• Instance methods (non-static methods)

They belong to an object, not the class itself.


14

2. How to Reference Instance Members

There are two main ways:

1. Using Object Reference

This is the most common way.

✔ Syntax:

[Link]

[Link]()

✔ Example:

class Student {

int marks;

void display() {

[Link]("Marks: " + marks);

public class Main {

public static void main(String[] args) {

Student s = new Student();

[Link] = 90; // accessing variable

[Link](); // calling method

2. Using this Keyword (Inside Class)

Inside a class, you can use this to refer to instance members.

✔ Example:
15

class Student {

int marks;

void setMarks(int marks) {

[Link] = marks; // refers to instance variable

void show() {

[Link]([Link]);

✔ Useful when:

• Local and instance variables have the same name

• You want to explicitly refer to the current object

3. Accessing Instance Members from Static Context

Direct access is NOT allowed in static methods.

class Test {

int x = 10;

static void show() {

// [Link](x); Error

✔ Correct way:

static void show() {

Test obj = new Test();


16

[Link](obj.x);

5. Key Rules

• Instance members belong to objects

• Must use object reference or this

• Cannot be accessed directly from static context

• Each object has its own copy of instance variables

6. Complete Example

class Car {

String brand;

int speed;

void setDetails(String brand, int speed) {

[Link] = brand;

[Link] = speed;

void display() {

[Link]("Brand: " + brand);

[Link]("Speed: " + speed);

public class Main {

public static void main(String[] args) {


17

Car c1 = new Car();

[Link]("BMW", 200);

Car c2 = new Car();

[Link]("Audi", 180);

[Link]();

[Link]();

7. Important Difference

Feature Instance Members Static Members

Belongs to Object Class

Accessed using Object reference Class name

Memory Separate per object Shared

Intra-Class Constructor Chaining


In Java, intra-class constructor chaining refers to calling one constructor from
another constructor within the same class using the this() keyword.

1. What is Intra-Class Constructor Chaining?

It is a mechanism where:

• One constructor calls another constructor

• Both constructors belong to the same class

✔ Done using:

this();
18

this(parameters);

2. Why It is Used

• To reuse code

• To avoid duplication

• To initialize objects in a structured way

3. Important Rule

this() must be the first statement in the constructor

this(); // must be first line

4. Basic Example

class Demo {

Demo() {

this(10); // calling parameterized constructor

[Link]("Default constructor");

Demo(int x) {

[Link]("Parameterized constructor: " + x);

public static void main(String[] args) {

Demo d = new Demo();

}
19

✔ Output:

Parameterized constructor: 10

Default constructor

5. Step-by-Step Flow

1. new Demo() → calls default constructor

2. Default constructor calls this(10)

3. Parameterized constructor executes first

4. Control returns to default constructor

6. Multiple Constructor Chaining

class Test {

Test() {

this(5);

[Link]("Constructor 1");

Test(int x) {

this(10, 20);

[Link]("Constructor 2: " + x);

Test(int x, int y) {

[Link]("Constructor 3: " + x + ", " + y);

public static void main(String[] args) {


20

new Test();

✔ Output:

Constructor 3: 10, 20

Constructor 2: 5

Constructor 1

7. Key Rules

✔ Use this() to call another constructor


✔ Must be first statement
✔ Cannot call multiple constructors at the same time
✔ Helps in constructor reuse

9. Real-Life Analogy

Think of it like:

• One constructor says: “Before I work, let me reuse another constructor’s setup.”

10. Final Summary

Intra-class constructor chaining = calling one constructor from another within the
same class using this()
21

Method Chaining
In Java, method chaining is a technique where multiple methods are called in a single
statement, one after another.

1. What is Method Chaining?

Method chaining means:

Calling one method after another on the same object in a single line.

✔ This is possible when:

• Each method returns the current object (this) or another object

2. Basic Syntax

object.method1().method2().method3();

3. Simple Example

class Demo {

Demo show() {

[Link]("Show method");

return this;

Demo display() {

[Link]("Display method");

return this;

void print() {

[Link]("Print method");

public static void main(String[] args) {

new Demo().show().display().print();
22

✔ Output:

Show method

Display method

Print method

4. How It Works

Step-by-step:

1. new Demo() → creates object

2. .show() → executes and returns this

3. .display() → executes on same object

4. .print() → final method call

5. Real-World Example

Java commonly uses method chaining in classes like:

• StringBuilder

StringBuilder sb = new StringBuilder();

[Link]("Hello ")

.append("World")

.append("!");

✔ Each append() returns the same object → enabling chaining

6. Example with Data Setting (Fluent Style)

class Student {
23

String name;

int age;

Student setName(String name) {

[Link] = name;

return this;

Student setAge(int age) {

[Link] = age;

return this;

void display() {

[Link](name + " " + age);

public static void main(String[] args) {

new Student()

.setName("Rahul")

.setAge(20)

.display();

}
24

7. Advantages

✔ Cleaner and more readable code


✔ Reduces number of lines
✔ Useful in builder patterns and APIs

8. Conditions for Method Chaining

• Methods must return:

o this (current object), or

o Another object

If method returns void, chaining stops

9. Important Notes

• Works only with non-static methods

• Uses this internally

• Common in fluent APIs

10. Method Chaining vs Constructor Chaining

Feature Method Chaining Constructor Chaining

Uses this this()

Purpose Call methods Call constructors

Return type needed Yes (this) No

Final Summary

Method chaining = calling multiple methods on the same object by returning this

You might also like