0% found this document useful (0 votes)
0 views

Class2

The document discusses Java methods, memory management, and constructors, highlighting the differences between stack and heap memory, including their allocation and accessibility. It also covers the advantages of methods, access modifiers, and the characteristics of constructors, including constructor overloading and chaining. Additionally, it provides examples of copy constructors and the use of init blocks in Java.

Uploaded by

Praveen Karoshi
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Class2

The document discusses Java methods, memory management, and constructors, highlighting the differences between stack and heap memory, including their allocation and accessibility. It also covers the advantages of methods, access modifiers, and the characteristics of constructors, including constructor overloading and chaining. Additionally, it provides examples of copy constructors and the use of init blocks in Java.

Uploaded by

Praveen Karoshi
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

Java Methods

<access_modifier> <return_type> <method_name>( list_of_parameters) throws


<Exception>
{
//body
int i = 50 / 0;
}

Arithmetic Exception to be handled inside the method

Common methods - Swap two numbers


Lets say a method swap number 5 times

Two types of memory in Java - Stack and Heap

When main method is executed - main is attached to a single thread


For main method - stack memory is allocated

local variables are stored on the stack


Objects are allocated memory in heap and a reference to the objects are stored on
stack
All methods get memory allocated in the stack and it LIFO - Last In First Out
Methods called later are allocated memory on the stack and they get destroyed first
when stack unwinds
Based on the above explanations, we can easily conclude the following differences
between Heap and Stack memory.

Heap memory is used by all the parts of the application whereas stack memory is
used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack
memory contains the reference to it. Stack memory only contains local primitive
variables and reference variables to objects in heap space.
Objects stored in the heap are globally accessible whereas stack memory can’t be
accessed by other threads.
Memory management in stack is done in LIFO manner whereas it’s more complex in Heap
memory because it’s used globally. Heap memory is divided into Young-Generation,
Old-Generation etc, more details at Java Garbage Collection.
Stack memory is short-lived whereas heap memory lives from the start till the end
of application execution.
We can use -Xms and -Xmx JVM option to define the startup size and maximum size of
heap memory. We can use -Xss to define the stack memory size.
When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas
if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space
error.
Stack memory size is very less when compared to Heap memory. Because of simplicity
in memory allocation (LIFO), stack memory is very fast when compared to heap
memory.

https://www.digitalocean.com/community/tutorials/java-heap-space-vs-stack-memory

Garbage Collection - Mark and sweep algorithm to clean up the memory in heap
Whichever variable is alive, it is marked by refrence count
Whichever variable goes out of scope, or dies, it is swept

Mark(reference count) and Sweep (Clean up operation)

https://medium.com/@khurshidbek-bakhromjonov/java-memory-management-understanding-
the-jvm-heap-method-area-stack-24a4d4fa2363
In young generation of memory, when eden space is full minor garbage collection
algorithm is run
In old generation of memory, when space is full major garbage collection algorithm
is run

Advantages of methods in Java -


Reusability
Abstraction
Improved Readability
Encapsulation
Separation of concern
Improved modularity
Improved Testability
Improved Performance

Modifiers -
default access - Only accessible within the current package and not outside of the
package
private - only accessible inside the class where it is defined and no other class
in the package can access
protected - accessible within the class and the derived (Child) classes of the
parent class even if its outside package
public - accessible across multiple packages

Java Constructors-
Constructors have the same name as the Class name
Constructors do not have return value
We have two types - Parametrized and Non-parameterized constructors
Default constructor is non-parameterized constructors
Constructors implement Method overloading

The compiler differentiates constructors on the basis of the number of parameters,


types of parameters, and order of the parameters.

How Java Constructors are Different From Java Methods?


Constructors must have the same name as the class within which it is defined it is
not necessary for the method in Java.
Constructors do not return any type while method(s) have the return type or void if
does not return any value.
Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.

When Java Constructor is called?


Each time an object is created using a new() keyword, at least one constructor (it
could be the default constructor) is invoked to assign initial values to the data
members of the same class. Rules for writing constructors are as follows:

The constructor(s) of a class must have the same name as the class name in which it
resides.
A constructor in Java can not be abstract, final, static, or Synchronized.
Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.

Copy constructor by default is not provided in Java. However, we can implement a


copy constructor when a object is passed call-by-value and a new object is created

Java program for copy constructor


// Java Program for Copy Constructor
import java.io.*;

class Geek {
// data members of the class.
String name;
int id;

// Parameterized Constructor
Geek(String name, int id)
{
this.name = name;
this.id = id;
}

// Copy Constructor
Geek(Geek obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);

System.out.println();

// This would invoke the copy constructor.


Geek geek2 = new Geek(geek1);
System.out.println(
"Copy Constructor used Second Object");
System.out.println("GeekName :" + geek2.name
+ " and GeekId :" + geek2.id);
}
}

Constructor Chaining -
Class A {}
Class B extends Class A {}
Class C extends Class B {}
Class D extends Class C {}

D obj = new D()


//default constructor of Class A is called first
//default constructor of Class B is called
//default constructor of Class C is called
//Constructor of Class D is called

Java provides init block


using Init block :
When we want certain common resources to be executed with every constructor we can
put the code in the init block. Init block is always executed before any
constructor, whenever a constructor is used for creating a new object.

You might also like