0% found this document useful (0 votes)
8 views3 pages

Java Methods and Memory Management Guide

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Java Methods and Memory Management Guide

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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 [Link] whereas
if heap memory is full, it throws [Link]: 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.

[Link]

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)

[Link]
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 [Link].*;

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

// Parameterized Constructor
Geek(String name, int id)
{
[Link] = name;
[Link] = id;
}

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

[Link]();

// This would invoke the copy constructor.


Geek geek2 = new Geek(geek1);
[Link](
"Copy Constructor used Second Object");
[Link]("GeekName :" + [Link]
+ " and GeekId :" + [Link]);
}
}

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.

Common questions

Powered by AI

Encapsulation in Java is supported by access modifiers that control visibility and restrict external access to class members, thereby protecting data integrity. Private, protected, and package-private modifiers prevent unauthorized manipulation, while public access enables interaction only through controlled interfaces. Constructors further facilitate encapsulation by initializing objects with controlled access and specified initial states, enabling secure and modular design architectures .

Constructor chaining in Java refers to the sequence of calls to parent and child class constructors during the instantiation of an object, ensuring the initialization of all fields in the inheritance hierarchy. For example, when a subclass object is created, the superclass constructor is invoked first, followed by the subclass constructors. This contrasts with method calls, which depend on explicit invocations but do not enforce hierarchical order. Constructor chaining promotes code reuse and ensures comprehensive initialization .

Garbage collection in the JVM is essential for reclaiming memory by identifying and disposing of objects that are no longer in use, thus preventing memory leaks. The primary algorithm used is mark and sweep, where live objects are marked, and unreachable ones are swept away. Minor garbage collection occurs in the young generation when eden space fills, while major garbage collection happens in the old generation upon memory saturation. This automated memory management aids efficient heap space utilization and ensures application performance .

Heap memory is utilized by all parts of the application, allowing objects to be globally accessible, while stack memory is used only by a single thread containing local variables and references to heap objects. Stack memory operates in a Last-In-First-Out (LIFO) manner, making it fast and short-lived, whereas heap memory, being globally used, requires complex management with garbage collection mechanisms like mark and sweep algorithms. Stack memory is limited in size compared to heap memory, which can be adjusted with JVM options like -Xms and -Xmx .

Improper memory management in the heap can lead to issues such as memory leaks, where unused objects are not freed, causing memory exhaustion and eventual application failure. Java's garbage collection mitigates these problems by automatically reclaiming memory through the mark and sweep algorithms, which target objects no longer in use. This reduces developer burden for manual memory management, ensuring more efficient resource utilization and stability in long-running applications .

Constructors in Java must have the same name as their class and do not have a return type, unlike methods that can return values or be void. Constructors are called when an object is created using the 'new' keyword and cannot be abstract, final, static, or synchronized. Access modifiers can restrict the calling of constructors, although methods can be called repeatedly. Constructors differ from methods as they initialize objects, and constructor overloading is determined by parameter types, counts, and orders .

Stack memory allocation is faster than heap memory due to its simple Last-In-First-Out (LIFO) management, where memory is allocated and deallocated in a predictable order without complex tracking of objects. This speed benefits application performance by allowing swift execution of methods and management of local variables. In contrast, heap memory requires elaborate garbage collection routines for memory management, which can introduce delays in execution, particularly under heavy load .

Java's constructor overloading allows for the creation of objects with varying initial states by defining multiple constructors with different parameter lists within the same class. The differentiation based on the number, types, and order of parameters helps the compiler determine which constructor to invoke, thus providing flexibility in object instantiation. This supports diverse initialization scenarios and enhances the reusability and scalability of code .

Heap memory in Java supports global access, making it shared across multiple threads, which can lead to concurrency issues such as race conditions if access is not properly synchronized. In contrast, stack memory is thread-specific, ensuring that local variables and references are isolated per thread. This inherent isolation simplifies concurrency management for stack memory, whereas heap memory requires careful synchronization or the use of thread-safe constructs to prevent conflicts in multithreaded applications .

Access modifiers in Java, including private, default, protected, and public, serve to control the accessibility of classes, methods, and variables, thus supporting encapsulation and information hiding. Private modifiers restrict access to within the class itself, while default (package-private) allows access within the same package. Protected access extends to subclasses even outside the package. Public modifiers permit access from any class or package. These control mechanisms enhance data protection and modular design .

You might also like