0% found this document useful (0 votes)
22 views12 pages

Java Module 2 Notes

The document provides an overview of Java programming concepts, including classes, methods, constructors, and garbage collection. It explains key topics such as the garbage collection mechanism, class structure, access specifiers, method overloading, recursion, command line arguments, and nested classes. Additionally, it includes example programs to illustrate these concepts and their practical applications.

Uploaded by

Amogh B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views12 pages

Java Module 2 Notes

The document provides an overview of Java programming concepts, including classes, methods, constructors, and garbage collection. It explains key topics such as the garbage collection mechanism, class structure, access specifiers, method overloading, recursion, command line arguments, and nested classes. Additionally, it includes example programs to illustrate these concepts and their practical applications.

Uploaded by

Amogh B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MODULE 2

QUESTION AND ANSWERS

Introducing Classes: Class Fundamentals, Declaring Objects, Assigning Object Reference Variables,
Introducing Methods, Constructors, The this Keyword, Garbage Collection. Methods and Classes:
Overloading Methods, Objects as Parameters, Argument Passing, Returning Objects, Recursion, Access
Control, Understand ing static, Introducing final, Introducing Nested and Inner Classes.

1. Examine Java Garbage collection mechanism in JAVA.

Java’s Garbage Collection (GC) mechanism is a powerful memory management system that automatically
reclaims memory occupied by objects no longer in use. It operates primarily within the Java heap. Java
relieves developers from the burden of manually handling memory allocation and deallocation.

 When objects are created using new, they are stored in heap memory.
 If an object is no longer referenced, it becomes eligible for garbage collection.
 Garbage Collector identifies and these unreachable objects.

2. Interpret the general form of a class with an example.


Object is any real world entity and group of objects with similar properties and behaviour is called class.

General Form of a class :

class ClassName {
// Fields (attributes)
dataType field1;
dataType field2;

// Constructor
ClassName(parameters) {
// Initialization code
}

// Methods (behaviors)
returnType method1(parameters) {
// Method logic
}

returnType method2(parameters) {
// Method logic
}
}

Key Components:
 class ClassName: Defines the class.
 Fields: Variables that hold the state of the object.
 Constructor: Special method that runs when an object is created.
 Methods: Define behaviors or actions the object can perform.

Example :

Defining a class :

import [Link].*;
class Rectangle {
private float length;
private float breadth;
private float area;

public Rectangle() {
length = 0.0f;
breadth = 0.0f;
}
public Rectangle(float l, float b) {
length = l;
breadth = b;
}
public void acceptData()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter length ");
length = [Link]();
[Link]("Enter breadth ");
breadth = [Link]();
}
public void area() {
area = length * breadth;
}
public void display()
{
[Link]("Area of rectangle " + area);
}
}

Creating an object of above class

class RectangleDemo {

public static void main(String args[]) {

Rectangle r1 = new Rectangle(2.0f, 3.5f); // calls parameterized constructor


[Link]();
[Link]();

Rectangle r2 = new Rectangle(); // calls default constructor


[Link]();
[Link]();
[Link]();
}
}

3. Outline the following keywords with an example:


i this
ii static
this Keyword
 Refers to the current object or invoking object of the class.
 Used to distinguish between instance variables and parameters when they have the same name.
 Can also be used to call other constructors in the same class.

Example :

public class Student {


String name;

// Constructor with parameter


// here parameter and data member has same name ‘name’
public Student(String name) {
[Link] = name; // '[Link]' refers to the instance variable
}

public void display() {


[Link]("Student name: " + [Link]);
}
}

static keyword :

static keyword can be used before instance variable, member function or method, block and in nested
class.

static data member:


 static data member can be referred using class name or object name.
 static data member are essentially global variables. Memory is allocated when class is loaded.
 Memory for static data member is allocated only once, irrespective of how many ever objects are
created. All objects refer to same copy.

static methods:
 static methods can be called using class name or object name.
 static methods can access only static data members and cannot access non static data members.
 static methods cannot use this or super keyword
static block :
 static block inside a class is used to initialize the static data members of a class
 static block is executed when the class is loaded

Example :

public class StaticExample {

// Static data member


static int count;

// Static block (executed once when the class is loaded)


static {
count = 10;
[Link]("Static block executed. Initial count set to " + count);
}

// Constructor
StaticExample() {
count++;
[Link]("Constructor called. Count is now: " + count);
}

// Static method
static void displayCount() {
[Link]("Current count: " + count);
}

public static void main(String[] args) {


StaticExample obj1 = new StaticExample();
StaticExample obj2 = new StaticExample();

// Call static method


[Link]();
}
}

4. Interpret with an example, types of constructors.


Constructor is a method in a class which is used to initialize data members of a class.

 Constructor has same name as class name.


 It is automatically called when object is created.
 Constructor does not have return type.

There are three types of constructors:


Default constructor – constructor without arguments or parameters.
Parameterized constructor – constructor with arguments or parameters.
Copy constructor – constructor works by taking an object of the same class as a parameter.

import [Link].*;
class Rectangle {
private float length;
private float breadth;
private float area;
// default constructor
public Rectangle() {
length = 0.0f;
breadth = 0.0f;
}
// parameterized constructor
public Rectangle(float l, float b) {
length = l;
breadth = b;
}
// copy constructor
public Rectangle(Rectangle r)
{
[Link] = [Link];
[Link] = [Link];
}
public void acceptData()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter length ");
length = [Link]();
[Link]("Enter breadth ");
breadth = [Link]();
}
public void area() {
area = length * breadth;
}
public void display()
{
[Link]("Area of rectangle " + area);
}
}

class RectangleDemo {

public static void main(String args[]) {

Rectangle r1 = new Rectangle(2.0f, 3.5f); // calls parameterized constructor


[Link]();
[Link]();

Rectangle r2 = new Rectangle(); // calls default constructor


[Link]();
[Link]();
[Link]();

Rectangle r3 = new Rectangle(r2); // calls copy constructor


[Link]();
[Link]();

}
}

5. Explain different access specifiers Java with example-program.


Java Access Modifiers and their scope:

Modifier Other class or


Within the In Subclasses in other Any class in other
subclass within same
Class packages packages
Package
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ✘
default ✔ ✔ ✘ ✘
private ✔ ✘ ✘ ✘

Explanation:

1 public: Accessible everywhere inside a class


2 protected: Accessible by classes in same package, sub classes in same and other packages.
3 default (no modifier): Accessible by class in same package, subclass in same package.
4 private: Accessible only inside the class

Example:

class Test {
public int x;
private int y;

public void sety(int a)


{
y = a;
}
public void display()
{
[Link]("x " + x);
[Link]("y " + y);
}

class AccessControlDemo {
public static void main(String args[])
{
Test obj = new Test();

obj.x = 10;
obj.y = 20; // not accessible
[Link](20);
[Link]();

}
}

6. What is method overloading? Illustrate the concept of method overloading


using java program.
Method overloading is feature in OOP which allows two or more methods to have same name. This is
possible only if
 No. of parameters are different
 Data type of parameters is different
 Return type is different

Example 1:
class MethodOverload {
void test(float f)
{
[Link]("Test with one float argument ");
}
void test(int i, float f)
{
[Link]("Test with one int and one float argument ");
}
void test(int i, double d)
{
[Link]("Test with one int and one double argument ");
}
}
class Overload {
public static void main(String args[])
{
MethodOverload obj = new MethodOverload();

[Link](10.23f); // exact match


[Link](10, 34.23f); // exact match
[Link](10); // no exact match of test method with int argument
// widening happens here
//[Link](10.23); // error – no exact match of test method narrowing cannot happen
}
}

Example 2:

import [Link];
class Triangle {
// method area is overloaded
public static float area(float b, float h) {
return 0.5f * b * h;
}
public static float area(float s1, float s2, float s3) {
float s = (s1 + s2 + s3) / 2;
float area = (float) ([Link](s * (s - s1) * (s - s2) * (s - s3)));
return area;
}
}

class TriangleDemo {
public static void main(String args[]) {

[Link]([Link](6.0f, 10.0f)); // calls method area() with two parameters


[Link]([Link](6.0f, 9.0f, 12.0f)); // calls method area() with
three parameters
}
}

Above class has two methods with same name but different parameters. One has two parameters and other
has three parameters.

7. Write a java program to illustrate:

 Passing object as parameters


 Returning objects
An argument of a method can be an object and a method can also return objects.

Passing object as parameters:

When object is passed as parameter, it is passed by reference and NOT by value.

Call by value : Changes made to formal parameter does not affect actual argument.
Call by Reference : Changes made to formal parameter affects actual argument.

Example :

class B{
int x;
B()
{
x = 10;
}
public void assign1(int x) // call by value
{
x = x * 10;
}
public void assign2(B obj) // call by reference
{
obj.x = obj.x * 10;
}
public B assign3()
{
B temp = new B();
temp.x = 99;
return temp;
}
public void display()
{
[Link]("x = " + x);
}
}

class ObjectAsParameter {
public static void main(String args[])
{
B obj2 = new B();

[Link]();
obj2.assign1(obj2.x); // this passes x of obj2 by value and hence value of x does not change
[Link]();
obj2.assign2(obj2); // this passes obj2 by reference and hence value of x changes
[Link]();
obj2 = obj2.assign3(); // returns an object and hence obj2 now points to memory allocated in
//assign3
[Link]();

}
}

8. Illustrate Recursion with an example


A method which calls itself is called recursion. Every recursive function or method must have a base case
to avoid infinite loops. A base case is a condition that stops recursion.

Example program for recursion:

class Factorial {
public static int fact(int n) {
if (n < 0) // base case 1
{
[Link]("Factorial cannot be found for negative number");
return -1;
}
else if (n == 0 || n == 1) // base case 2
return 1;
else
return n * fact(n-1); // here function is calling itself
}

public static void main(String args[])


{
[Link]("Factorial of 6 = " + [Link](6));
}

9. Explain Command line arguments in Java with example.

Command line arguments are values passed to a Java program when it starts. These arguments are passed
as strings to the main() method via the String[] args parameter.

Example ([Link]):

public class CommandLineExample {


public static void main(String[] args) {
[Link]("Number of arguments: " + [Link]);

for (int i = 0; i < [Link]; i++) {


[Link]("Argument " + i + ": " + args[i]);
}
}
}

After compiling above program, executing it with following command

java CommandLineExample Java 42 true

results in following output –

Number of arguments: 3
Argument 0: Java
Argument 1: 42
Argument 2: true

10. Explain the concept of nested class.


A nested class in Java is a class defined within another class.

Types of Nested Classes

Java offers two main types of nested classes:


a) Static Nested Class
 Declared with the static keyword.
 Can access static members of the outer class.
 Doesn’t need an object of the outer class to be created.
b) Non-static (Inner) Class
 Associated with an instance of the outer class.
 Can access both static and non-static members of the outer class.
 Requires an object of the outer class to be created.

Why Use Nested Classes?


 Encapsulation: Keeps related classes together.
 Readability: Improves code organization.
 Logical grouping: Useful when one class is only relevant to another.

Example 1:

class Outer {
void display()
{
[Link]("display method of Outer class");
}
class Inner()
{
void display()
{
[Link]("display method of Inner class");
}
}
}
class OuterInnerDemo {
public static void main(String args[])
{
Outer obj1 = new Outer();
[Link]();
[Link] obj2 = [Link] Inner();
[Link]();
}

Example 2:

public class OuterClass {


static int outerData1 = 100;
int outerData2 = 200;

// Static nested class


static class staticInnerClass {
void display() {
outerData1 = 150;
//outerData2 = 250; // error - non static member cannot be accessed
[Link]("Static Inner class : ");
[Link]("Accessing static outerData1 : " + outerData1);
}
}

// Non-static inner class


class nonStaticInnerClass {
void display() {
outerData1 = 175;
outerData2 = 275;
[Link]("non Static Inner class : ");
[Link]("Accessing static outerData1 : " + outerData1);
[Link]("Accessing non static outerData2 : " + outerData2);
}
}

public static void main(String[] args) {


// Creating an instance of the static nested class - outerclass instance not required
[Link] nested1 = new [Link]();
[Link]();

// Creating an instance of the non static nested class - outerclass instance not required
OuterClass o = new OuterClass();
//[Link] nested2 = new [Link](); // error
[Link] nested2 = [Link] nonStaticInnerClass();

[Link]();
}

11. What happens when final keyword is used before a variable.


final keyword when used with a variable or data member cannot be changed in the program.

Programs

1 Design a class called "Employee" with fields 10, Name and Salary. Write a suitable constructor, a method
to raise salary and a static method to display the number of employee objects. Write suitable Main method
for illustration.

2 Design a stack class to hold maximum of N numbers with a constructor, push, POP and Display methods.
Develop Java main method to illustrate stack operations.

3 Create a class called Rectangle with suitable data members and member functions.

You might also like