0% found this document useful (0 votes)
3 views26 pages

Memory Allocation in Java (1)

Ppt

Uploaded by

jinni160107
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)
3 views26 pages

Memory Allocation in Java (1)

Ppt

Uploaded by

jinni160107
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
You are on page 1/ 26

Memory Allocation

new, Static Data Members,


Static Methods.
new Keyword/Operator
• When you are declaring a class in java, you are just creating a
new data type. A class provides the blueprint for objects. You
can create an object from a class. However obtaining objects
of a class is a two-step process :
– Declaration : First, you must declare a variable of the class
type. This variable does not define an object. Instead, it is
simply a variable that can refer to an object. Below is
general syntax of declaration with an example :
• Syntax :
• class-name var-name;
• Example :
• Box mybox;
Usage of new Keyword
• It instantiates a class and calls its constructor.
• It initializes an array and allocates memory for
it.
• It is also useful for creating anonymous
objects.
• It can create instances of inner classes.
• When no parameters are passed, it uses the
default constructor.
Example
• public class Main {
• void display()
• {
• System.out.println("Invoking Method");
• }
• public static void main(String[] args) {
• //creating an object of the Main class
• Main obj=new Main();
• //invoking the display() method
• obj.display();
• }
• }
static Keyword in Java
• The static keyword in Java is mainly used
for memory management, allowing variables and
methods to belong to the class itself rather than
individual instances.
• The static keyword is used to share the same
variable or method of a given class.
• The users can apply static keywords with
variables, methods and nested classes.
• The static keyword belongs to the class rather
than an instance of the class.
• The static keyword is used for a constant variable
or a method that is the same for every instance of
a class.
• The static keyword is a non-access modifier used for:
• Variables (class-level, shared across instances)
• Methods (called without object creation)
• Blocks (executed once when the class loads)
• Nested Classes (static inner classes)
• Note: To create a static member(block, variable,
method, nested class), precede its declaration with
the keyword static.
Characteristics of the "static" Keyword
• Static variables and methods use memory only once
when the program runs, and this memory is shared by all
the objects of the class.
• We do not need to create objects of the class to use
static methods
• We can call static members using the class name directly.
• Static members belong to the class, not to any specified
object.
• Static members can not access non-static members.
• Static methods cannot be overridden in subclasses
because they belong to the class, not to an object.
Example: This example demonstrates that a static method can
be called without creating an instance of the class.
• class Student
• {
• // static method
• static void m1()
• {
• System.out.println("from m1");
• }

• public static void main(String[] args)


• {
• // calling m1 without creating
• // any object of class Test
• m1();
• }
• }
• Static Variables
When a variable is declared as static, then a single copy of the
variable is created and shared among all objects at the class
level. Static variables are, essentially, global variables. All
instances of the class share the same static variable.

• Static Methods
• When a method is declared with the static keyword, it is
known as the static method. The most common example of a
static method is the main() method. As discussed above, Any
static member can be accessed before any objects of its class
are created, and without reference to any object.
• Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.
• Example: This example demonstrates the restriction that static
methods cannot access instance variables, instance methods, or
use super in a static context.
• class Student {
• String name;
• int rollNo;

• // static variable
• static String cllgName;

• // static counter to set unique roll no


• static int counter = 0;
• public Student(String name)
• {
• this.name = name;

• this.rollNo = setRollNo();
• }

• // getting unique rollNo


• // through static variable(counter)
• static int setRollNo()
• {
• counter++;
• return counter;
• }

• // static method
• static void setCllg(String name)
• {
• cllgName = name;
• }
• // instance method
• void getStudentInfo()
• {
• System.out.println("name : " + this.name);
• System.out.println("rollNo : " + this.rollNo);

• // accessing static variable


• System.out.println("cllgName : " + cllgName);
• }
• }
• public class StaticDemo {
• public static void main(String[] args)
• {
• // calling static method
• // without instantiating Student class
• Student.setCllg("XYZ");

• Student s1 = new Student(“ABC");


• Student s2 = new Student(“XYZ");

• s1.getStudentInfo();
• s2.getStudentInfo();
• }
• }
Static Classes
• A class can be made static only if it is a nested class. We cannot
declare a top-level class with a static modifier but can
declare nested classes as static. Such types of classes are called
Nested static classes. Nested static class doesn’t need a reference
of Outer class. In this case, a static class cannot access non-static
members of the Outer class.
• public class Student{
• private static String str = “My Class";

• // Static class
• static class MyNestedClass {

• // non-static method
• public void disp(){
• System.out.println(str);
• }
• }
• public static void main(String args[])
• {
• Student.MyNestedClass obj
• = new Student.MyNestedClass();
• obj.disp();
• }
Static vs Non-Static
• Static :
• Static members have one copy shared across the class.
• Static members are accessed via the class name.
• Static members cannot be overridden.
• Static members cannot use this or super keyword.
• Static members exist for the duration of the class's lifecycle.
• Non-Static/Instance :
• Non-static members have a separate copy for each instance
of the class.
• Non-static members are accessed via an object reference.
• Non-static members can be overridden in subclasses.
• Non-static members can use this and super keyword.
• Non-static members exist as long as the object they belong to
is alive.
Advantages of Static Keyword
• Static members use the memory only once and this helps save
memory when we have to deal with big programs.
• Static members provide fast access because static members
belong to the class not to an object and that's why they can
be access faster than regular member.
• We can access static members from anywhere, whether an
object of the class has been created or not.
• We can use static final variables to create constant that stays
the same throughout the program.
Disadvantages of Static Keyword
• Static members can't be overridden or dynamically bound like
instance members.
• Static methods and variables make unit testing difficult due to
tight coupling.
• Static variables create a global state, which can lead to
unwanted side effects across different parts of the program.
• Static variables stay in memory as long as the program runs,
which might cause memory to be used longer than needed.
• Using too many static members can reduce the benefits of
object-oriented programming, like hiding data and using
inheritance.
Garbage Collection:Destructors and
Finalizers
• In programming, a destructor is a method called when an
object is destroyed, typically to release resources like
memory, file handles, or network connections. In languages
like C++, destructors are explicitly used to manage resource
cleanup. However, Java takes a different approach due to its
automatic memory management system powered by garbage
collection.
• Java does not have explicit destructors like C++ because the
garbage collector automatically manages Java’s
memory. Garbage collection tracks objects in memory, and
when they are no longer referenced, it automatically reclaims
the memory.
• Although Java does not provide destructors, it used
to have a method called finalize() that could be
overridden to define cleanup operations before an
object is garbage collected. The finalize() method
has been deprecated since Java 9 and removed
in Java 18 due to its unpredictability and
performance overhead. Instead, modern Java
programs rely on other mechanisms for resource
management, such
as AutoCloseable and try-with-resources.
• Advantages of Destructors
• Automatic Resource Management: By automating
the process of freeing up memory and other
resources, Java's garbage collector lowers the
possibility of memory leaks and improper resource
management.
• Simplifies Programming: By eliminating the need for
developers to manually monitor and release memory,
programming becomes simpler and less prone to error.
• Enhances Performance: By effectively handling memory
allocation and deallocation, automated memory
management can aid in performance optimization.
• Memory Management in Java
• Java’s garbage collector automatically manages the
lifecycle of objects.
• When no references point to an object, it becomes
eligible for garbage collection.
• The garbage collector reclaims memory at its
discretion, making memory management automated
and simplifying development.
Why Java Doesn’t Need Destructors?
• In languages like C++, destructors are essential
because programmers manually manage memory
allocation and deallocation.
• In contrast, Java developers don’t have to worry
about this due to its automatic garbage collection
system.
• Instead of destructors, developers in Java can handle
resource management using
the try-with-resources statement
and AutoCloseable interface, ensuring resources like
files, database connections, or sockets are properly
closed.
Alternatives to Finalization in Java
• AutoCloseable and try-with-resources:
– This is the preferred method for managing resources
that require cleanup, such as file streams, database
connections, or network sockets.
– The try-with-resources statement ensures that
resources are automatically closed after usage,
without relying on the garbage collector's
unpredictable behavior.
• java.lang.ref.Cleaner Class:
– For advanced cleanup tasks where AutoCloseable is
not sufficient, Java 9 introduced the Cleaner class as a
replacement for finalize().
– Cleaner allows you to register cleanup actions that are
invoked once the object becomes unreachable,
without the issues associated with finalize().
Example Using AutoCloseable and try-with-resources
• public class Resource implements AutoCloseable {

• public Resource() {
• System.out.println("Resource acquired.");
• }

• @Override
• public void close() {
• System.out.println("Resource released.");
• }

• public static void main(String[] args) {


• try (Resource resource = new Resource()) {
• System.out.println("Using the resource.");
• } // close() is automatically called here
• System.out.println("End of program.");
• }
• }
• Output :
• Resource acquired.
• Using the resource.
• Resource released.
• End of program.
• Explanation:
• The class Resource implements AutoCloseable,
meaning it has a close() method that is automatically
called when the resource goes out of scope.
• The try-with-resources statement ensures the
resource is properly closed without relying on the
garbage collector.
Why finalize() Is Deprecated?
• The finalize() method, which was once used to
clean up before garbage collection, has been
deprecated since Java 9 and removed in Java
18 for several reasons:
• Unpredictable Timing: The garbage collector may
never call finalize(), or it may be delayed, making
resource management unreliable.
• Performance
Overhead: Implementing finalize() incurs a
significant performance penalty since objects
with finalize() are handled separately by the
garbage collector.
• Better Alternatives: Java provides better
mechanisms for resource management
(try-with-resources, Cleaner),
making finalize() obsolete.

You might also like