Category: Core Java

Methods in Java

Elements of a class-

Java is a class based language where the entire code is written inside a class.

Any class written in Java consists of the following 5 elements-

  1. Variables
  2. Methods
  3. Constructors
  4. Instance blocks
  5. Static blocks

 

In this post, we will discuss about the methods of Java in detail.

 

Methods in Java-

 

Method is an element of a class that is used for writing the logic of the program as it is not allowed to write the logic of the program directly inside a class.

 

Example-

Writing the logic for addition of two numbers as shown below is not allowed-

class Test
{
   int a = 50;
   int b = 100;
   System.out.println(a+b);
}

The logic for addition of two numbers has to be written using a method as shown below-

class Test
{
   int a = 50;
   int b = 100;

   void add( )
   {
      System.out.println(a+b);
   }
}

 

Types of Methods in Java-

 

There are mainly two types of methods in Java-

  1. Instance methods
  2. Static methods

 

1. Instance Methods-

 

  • The methods that are associated with the objects of the class and not to the class as a whole are called as instance methods.
  • Every individual object owns its unique copy of all the instance methods belonging to that class.
  • The call made to the instance methods is resolved at run time through dynamic binding.
  • Overriding of instance methods is allowed.

 

How to access instance methods?

 

Just like instance variables,

  • Instance methods can be called directly inside the instance area.
  • Instance methods can not be called directly inside the static area and necessarily requires an object reference for calling them.

 

2. Static Methods-

 

  • The methods that are associated with the entire class and not to the individual objects are called as static methods.
  • A single copy gets created for the static methods and this single copy is shared by all the objects belonging to that class.
  • Static methods are declared with the ‘static’ modifier.
  • The call made to the static methods is resolved at compile time through static binding by the compiler.
  • Overriding of static methods is not at all allowed.
  • Static methods can be used to write the code that is common and is meant to be shared among all the instances.

 

Since, static methods are associated with the entire class, they are popularly called as class methods.

 

How to access static methods?

 

Just like static variables,

  • Static methods can be called by using class name and dot operator. (Recommended)
  • Static methods can be called directly within the same package.
  • Static methods can be called by using object reference and dot operator.

 

NOTE-

 

  • Although static methods can be accessed using object reference and dot operator but it is not recommended because it does not make it clear that we are talking about the class methods.

Always make a habit of calling the static methods by using class name and dot operator.

 

Difference between Instance methods and Static methods-

 

Instance MethodsStatic Methods
Instance methods are associated with the objects of the class and not to the class as a whole.Static methods are associated with the entire class and not to the individual objects.
Every individual object owns its unique copy of all the instance methods belonging that class.A single copy gets created for the static methods and this single copy is shared by all the objects associated to that class.
The call made to the instance methods is resolved at run time through dynamic binding.The call made to the static methods is resolved at compile time through static binding by the compiler.
Overriding of instance methods is allowed.Overriding of static methods is not at all allowed.

 

Important rules you must know about methods in Java-

 

Rule-01:

As in any other programming language, it is perfectly allowed to define your own methods in Java known as “user defined methods”.

Syntax-

modifiers_list return_type method_name (param_list) throws Exception
{
    //method body
}

 

Rule-02:

It is compulsory to mention the return type when defining methods in Java.

Example- 

 

Rule-03:

Calling a method from another method is perfectly allowed in Java.

Example-

class Test
{
   void m1( )
   {
      m2( );                                      // call to method m2( ) from method m1( ) 
      System.out.println("m1 method called");
   }

   void m2( )
   {
      System.out.println("m2 method called");
   }

   public static void main(String[ ] args)
   {
      Test t = new Test( );                      // Object creation
      t.m1( );                                   // Call to method m1( ) from main method
   }
}

 

Rule-04:

Inside a class, two methods with the same signatures (duplicate methods) are not allowed even if their return types are different.

 

NOTE

Method signature includes only these two things- method name and parameter list.

 

Rule-05:

Declaring a method inside another method is called as inner method. Inner methods are not allowed in Java. However, the concept of Inner classes is fully supported by Java.

 

Rule-06:

Inside static methods, ‘this‘ keyword is not allowed (static area) as there is no instance for ‘this’ to refer to inside static methods.

 

Rule-07:

Static methods must be given implementation (at least empty implementation) otherwise compile time error will be generated.

Example-

 

Examples based on using methods in Java-

 

Example-01:

class Test
{
   void m1( )                                 // Instance Method
   {                                                                         
      System.out.println("m1 method called");                               
   }                                                                                

   static void m2( )                          // Static Method
   {
      System.out.println("m2 method called");
   }

   public static void main(String[ ] args)
   {
      Test t = new Test( );                    // Object Creation
      t.m1( );                                 // Call to instance method m1( ) using object reference
      Test.m2( );                              // Call to static method m2( ) using class name and dot operator
   }
}

OUTPUT-

m1 method called

m2 method called

 

Example-02:

class Test
{
   void m1(int a , char ch)                 // Instance Method
   {
      System.out.println("m1 method called");
      System.out.println(a);
      System.out.println(ch);
   }

   static void m2(String str , double d)    // Static Method
   {
      System.out.println("m2 method called");
      System.out.println(str);
      System.out.println(d);
   }

   public static void main(String[ ] args)
   {
      Test t = new Test( );                 // Object Creation
      t.m1(50,'G');                         // Call to instance method m1( ) using object reference
      Test.m2("Gate Vidyalay",50.5);        // Call to static method m2( ) using class name and dot operator
   }
}

OUTPUT-

m1 method called

50

G

m2 method called

Gate Vidyalay

50.5

 

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.

Garbage Collection in Java | How to make object eligible for Garbage Collection

Garbage Collection in Java-

 

  • It is recommended that if there exist some objects which are not required anymore, programmers make those objects eligible for garbage collection.

 

Thumb rule

An object qualifies for garbage collection if and only if it does not contain any external reference to it.

 

  • So, an object can be made eligible for garbage collection be removing all the external references pointing to it.

 

Ways to make an object eligible for garbage collection in Java-

 

There are 4 different ways in which an object can be made eligible for the purpose of garbage collection-

 

 

  1. By nullifying the reference variable
  2. By reassigning the reference variable
  3. By creating objects inside a method
  4. Island of Isolation

 

1. By nullifying the reference variable-

 

As the name suggests,

In this method, programmer assigns null to the reference variables of all those objects which are no longer required. This makes the useless objects automatically eligible for the purpose of garbage collection.

 

Example-

Consider the following lines of code-

1. Student s1 = new Student( );
2. Student s2 = new Student( );
3.            .
4.            .
5.            .
6.            .
7.         s1 = null;
8.            .
9.            .
10.           .
11.           .
12.        s2 = null;
13.           .
14.           .
15.           .
16.           .

Now, let us perform the analysis of the above lines of code-

Analysis-

 

  • Statement-1 and Statement-2 create two Student objects where reference variable s1 references the first object and reference variable s2 references the second object as shown-

 

 

  • Till statement-6, there exists no object which is eligible for garbage collection.
  • After the execution of statement-7, the first object referenced by s1 becomes eligible for garbage collection as the null reference gets assigned to it as shown-

 

 

  • After the execution of statement-12, the second object referenced by s2 also becomes eligible for garbage collection as the null reference gets assigned to it as shown-

 

 

2. By reassigning the reference variable-

 

As the name suggests,

In this method, programmer reassigns the reference variables of all those objects which are no longer needed to some other objects. This makes the useless objects automatically eligible for the purpose of garbage collection.

 

Example-

Consider the following lines of code-

1. Student s1 = new Student( );
2. Student s2 = new Student( );
3.            .
4.            .
5.            .
6.            .
7.         s1 = new Student( );
8.            .
9.            .
10.           .
11.           .
12.        s2 = s1;
13.           .
14.           .
15.           .
16.           .

Now, let us perform the analysis of the above lines of code-

Analysis-

 

  • Statement-1 and Statement-2 create two Student objects where reference variable s1 references the first object and reference variable s2 references the second object as shown-

 

 

  • Till statement-6, there exists no object which is eligible for garbage collection.
  • Statement-7 creates a new Student object and reassigns the reference variable s1 to this new object. As a result, first object loses its reference and becomes eligible for garbage collection.

 

 

  • Statement-12 makes the second object also eligible for garbage collection as it makes the reference variable s2 point to the object to which the reference variable s1 points.

 

 

3. By creating objects inside a method-

 

As the name suggests,

In this method, programmer creates the objects inside the methods because after the method gets executed completely, objects present inside the method body automatically becomes eligible for the purpose of garbage collection.

The reason behind it is that the reference variables are the local variables of the method and after the method has executed completely, all the local variables are automatically destroyed.

 

Example-

Consider the following lines of code-

1. class Test
2. {
3.    public static void main(String[ ] args)
4.    {
5.        m1( );
6.    }
7.    
8.    public static void m1( )
9.    {
10.       Student s1 = new Student( );
11.       Student s2 = new Student( );
12.   }
13.}

Now, let us perform the analysis of the above lines of code-

Analysis-

 

After the execution of method m1( ) in the main method i.e. after executing statement-5, both the objects becomes eligible for garbage collection and can be collected by the garbage collector.

 

4. Island of Isolation-

 

  • Island of Isolation describes the situation where there exists one or more objects in the program which are not accessible from anywhere in the application as they contain no external reference to them.
  • It is not possible to access such objects through any means as they have no external reference to them and thus they become eligible for garbage collection.
  • So, it appears as if the objects are stuck on some isolated island and they can not be accessed through any means. Hence, the name “Island of Isolation” is quite apt.

 

NOTE-

It is interesting to note that a single object having no reference to it is also an island of isolation.

 

Example-

Consider the following lines of code-

1. class Demo
2. {
3.    Demo d;
4.
5.    public static void main(string[ ] args)
6.    {
7.        Demo d1 = new Demo( );
8.        Demo d2 = new Demo( );
9.        Demo d3 = new Demo( );
10.               .
11.               .
12.               .
13.               .
14.          d1.d = d2;
15.          d2.d = d3;
16.          d3.d = d1;
17.               .
18.               .
19.               .
20.               .
21.            d1 = null;
22.            d2 = null;
23.            d3 = null;
24.   }
25. }

Now, let us perform the analysis of the above lines of code-

Analysis-

 

  • Statement-7, statement-8 and statement-9 create three Student objects which are referenced by the reference variables d1, d2 and d3 respectively as shown-

 

 

Till now, each object is having exactly one reference variable and no object is eligible for garbage collection.

  • Statement-14 assigns a copy of d2 to d1.d. So, now d1.d points to the object of d2.
  • Statement-15 assigns a copy of d3 to d2.d. So, now d2.d points to the object of d3.
  • Statement-16 assigns a copy of d1 to d3.d. So, now d3.d points to the object of d1.

 

 

Till now, each object is having exactly two reference variables and no object is eligible for garbage collection.

 

  • Statement-21 assigns null to the reference variable d1. Thus, now d1 references to no one. Still, no object is eligible for garbage collection.
  • Statement-22 assigns null to the reference variable d2. Thus, now d2 references to no one. Still, no object is eligible for garbage collection.
  • Statement-23 assigns null to the reference variable d3. Thus, now d3 references to no one.

 

Now, all the three objects become eligible for garbage collection as now there does not exist even one external reference to them.

 

An isolated island is created where all the three objects are stuck and there is no communication with any active part of the application.

All the three objects internally references each other but there is no external reference which makes the three objects eligible for garbage collection.

 

Island of Isolation

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.

Garbage Collection in Java

What is Garbage Collection in Java?

 

In Java, the unreferenced objects not having any reference to them are referred to as garbage as they are useless.

The process of collecting the unreferenced objects (garbage) to free up the unnecessarily occupied memory for efficient memory usage is called as garbage collection.

In Java, there is a program called as Garbage Collector which has been assigned the responsibility of Garbage Collection.

 

 

This ignorance of destruction of useless objects often fills the memory unnecessarily and as a result of which at certain point of time, sufficient memory does not remain available for the creation of new objects and the performance of entire application goes down due to memory problems like OutOfMemoryError.

To avoid such problems, it is very important to perform garbage collection from time to time.

 

Purpose of Garbage Collector-

 

  • Unlike in old programming languages like C++ where programmer has the responsibility of both creating as well as destroying the objects, in Java, programmers are allowed to create as many objects as they want without any overhead of destroying the useless objects.
  • Garbage Collector takes up the responsibility of cleaning up the memory by destroying the useless objects.
  • Garbage Collector runs from time to time in the background silently to clean up the memory.

 

Eligibility Criteria for Garbage Collection-

 

  • Although, programmers have no responsibility of destroying the useless objects, it is highly recommended that if there are some existing objects which are no longer required, programmers make those objects eligible for the garbage collection so that they can be easily identified by the garbage collector for garbage collection.

 

An object qualifies for garbage collection if and only if it does not contain any external reference to it

 

 

Requesting JVM to run Garbage Collector-

 

  • We can not predict when JVM will perform the garbage collection by running its garbage collector. It entirely depends on the JVM and varies from JVM to JVM.
  • So, an object may not be destroyed immediately after it has qualified for the garbage collection. It will be collected only when the JVM will run its garbage collector.
  • Instead of keep waiting for the JVM to run the garbage collector by itself, we can manually make a request to the JVM for collecting the garbage.
  • However, it totally depends on the JVM whether it accepts the request or not. However, JVM mostly accepts the request for running the garbage collector.

 

Ways to request JVM for running Garbage Collector-

 

There are 2 ways in which the JVM can be requested to run its garbage collector-

 

 

1. By using System class-

 

  • System class contains a static method gc( ) which can be used to request the JVM  to run its garbage collector.
  • Syntax-

System.gc( ) ;

 

2. By using Runtime class-

 

  • Runtime class is a singleton class contained in a java.lang package.
  • It is possible for a java application to communicate with the JVM by making use of a Runtime object which can be created by using getRuntime( ) method as-

Runtime obj = Runtime.getRuntime( ) ;

  • Once we have created a Runtime object, the methods given below can be called on it-

 

a. freeMemory( )-

  • This method returns the amount of free space in the heap in bytes.

b. totalMemory( )-

  • This method returns the total heap size in bytes.

c. gc( )-

  • This method requests the JVM to perform the garbage collection by running its garbage collector.

 

NOTE-

 

  • gc( ) method contained in System class is static in nature i.e. it is a static method whereas gc( ) method contained in Runtime class is an instance method.

 

Which of the above two ways is recommended?

 

As per the convenience, it is recommended to use System.gc( ) method when compared to Runtime class gc( ) method.

As per the performance performance, it is recommended to use Runtime class gc( ) method when compared with System class gc( ) method because Runtime class gc( ) method calls System.gc( ) method internally.

 

class System
{
   public static void gc( )
   {
      Runtime.getRuntime( ).gc( );
   }
}

 

By using Runtime class gc( ) method directly, a method call is saved which contributes towards improving the performance.

 

EXAMPLE-

import java.util.Date; 
class RuntimeExample
{
   public static void main (String[ ] args)
   {
      Runtime obj = Runtime.getRuntime( ); 
      System.out.println(obj.totalMemory( ));
      System.out.println(obj.freeMemory( )); 

      for(int j=0 ; j<10000 ; j++)
      {
         Date d = new Date( ); 
         d = null; 
      }

      System.out.println(obj.freeMemory( ));
      obj.gc( );
      System.out.println(obj.freeMemory( ));
   }
}

OUTPUT-

5177344

4945200

4714464

5059352

 

PROBLEM BASED ON GARBAGE COLLECTION IN JAVA-

 

Problem-

A student learning Java states the following 4 ways in which the JVM can be requested for running its Garbage Collector-

  1. Runtime.getRuntime( ).gc( );
  2. Runtime.gc( );
  3. (new Runtime( )).gc( );
  4. System.gc( );

Which of the above four ways is / are correct?

  1. Only I and IV
  2. Only I
  3. Only IV
  4. All are correct

 

Solution-

Option (A) is correct.

  • II is incorrect because gc( ) method contained in Runtime class is not static in nature.
  • III is incorrect because Runtime class is a singleton class, so an object can not be created for it by using the new operator.

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.