Java concept – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 10 Mar 2024 17:30:22 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Java concept – Programmerbay https://programmerbay.com 32 32 Multilevel Inheritance in Java with Program Example https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/ https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/#respond Fri, 19 Jan 2024 14:08:35 +0000 https://programmerbay.com/?p=9054 Multilevel inheritance is a type of inheritance where a subclass acts as a superclass of another class. In other words, when a class having a parent class, is extended by another class and forms a sequential chain, then it’s termed Multilevel inheritance. For instance, class A is extended by class B, and further class B is inherited by class C which acquires features of class A and class B.

multilevel inheritance in Java

In multilevel inheritance, a parent can have a single child only and at least require three classes arranged sequentially, forming a chain of parent-child relations.

Syntax:

class A {

}

class B extends A {

}

class C extends B {

}

Multilevel inheritance program in Java

Below are some programs provided to implement multilevel inheritance in Java.

Example 1. Program to implement multilevel Inheritance in Java

Program:

class Person {

    String getName(){
        return "ProgrammerBay";
    }
}

class Programmer extends Person{
    String getCodingLanguage(){
        return "Java";
    }
}

class Program extends  Programmer{
    int getLineOfCode(){
        return 20;
    }
    public static void main(String[] args) {
        Program program = new Program();
        System.out.println(" I am "+program.getName()+" and I code in "+ program.getCodingLanguage()+
                " . This program has "+program.getLineOfCode()+" lines");
    }
}

Output:

I am ProgrammerBay and I code in Java . This program has 20 lines

Explanation:

In the above code, we are having 3 classes named Person, Programmer and Program where class Program is inheriting class Programmer, further, class Programmer is extending class Person. As a result, the Program class’s got the functionalities of class Programmer and also class Person.

Example 2. Program to show real world example of multilevel inheritance in Java

Program:

class iPhone6 {
    void makeCalls(){
        System.out.println("Calling functionality.......");
    }
}

// Getting feature of previous iPhone model
class iPhone10 extends iPhone6{

    void unlockPhoneByFaceId(){
        System.out.println("Unlocking phone by face Id.......");
    }

}
// Getting feature of previous iPhone10
class iPhone12 extends iPhone10{

    void supportFor5GNetwork(){
        System.out.println("5G network support.......");
    }

    public static void main(String[] args) {
        iPhone12 iPhone = new iPhone12();
        iPhone.makeCalls();  // feature reused of iPhone 6 for iPhone 12
        iPhone.unlockPhoneByFaceId(); // feature reused of iPhone 10 for iPhone 12
        iPhone.supportFor5GNetwork(); // additional feature
    }
}

Output:

Calling functionality.......
Unlocking phone by face Id.......
5G network support.......

Explanation:

In the above code, we’ve tried to explain multilevel inheritance using the iPhone Models example. Just similar to the previous example, iPhone12 class is having the functionality of iPhone10 and iPhone6 classes. Because iPhone12 class is inheriting iPhone 10 class, further, iPhone10 is extending iPhone 6 class.

Example 3. Program to print order of constructor calling using multilevel Inheritance in Java

Program:

class Person {
    Person(){
        System.out.println("This is Person's class constructor");
    }

    void printName(){
        System.out.println("ProgrammerBay");
    }
}

class Programmer extends Person{
    Programmer(){
        System.out.println("This is Programmer's class constructor");
    }
    void printCodingLanguage(){
        System.out.println("Java");
    }
}

class Program extends  Programmer{
    Program(){
        System.out.println("This is Program's class constructor");
    }

    void printLineOfCode(){
        System.out.println(20);
    }
    public static void main(String[] args) {
        Program program = new Program();
        program.printName();
        program.printCodingLanguage();
        program.printLineOfCode();
    }
}

Output:

This is Person's class constructor
This is Programmer's class constructor
This is Program's class constructor
ProgrammerBay
Java
20

Explanation:

  1. In the above code, there are three classes named Person, Programmer, Program declared in which Person is extended by Programmer and Programmer is further inherited by Program class.
  2. Each class’s got a default constructor, where we are printing a message to identify the order of invocation.
  3. When the program’s object got created, the very first block executed was the Person class, after the Programmer’s constructor was called and at last Program’s constructor.
  4. In other words, the constructor of the foremost class in the chain is invoked first, then the constructor of immediate next class is called one by one, until it invokes the constructor of the class whose object is created

Frequently Asked Questions

What is multilevel Inheritance in java?

Multilevel Inheritance in java can be defined as an inheritance where a class extends another class, and further, that subclass is become a parent of another class by extending it

How is multilevel Inheritance implemented in Java?

It can be implemented using extends keyword where class A is extended by B, and further, C sequentially extends B.

Is multilevel Inheritance allowed in Java?

Yes, multilevel Inheritance is supported in Java.

What are the types of Inheritance in Java?

There are various types of inheritance supported by Java.
In the case of interfaces, Java supports 5 types of inheritance
which are Single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance.
In the case of classes, it limits to 3 types which are single, multilevel and hierarchical inheritance as hybrid and multiple inheritance is not supported in this.

]]>
https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/feed/ 0
Difference Between Call By Value and Call by Reference in Tabular Form https://programmerbay.com/difference-between-call-by-value-and-call-by-reference-in-tabular-form/ https://programmerbay.com/difference-between-call-by-value-and-call-by-reference-in-tabular-form/#respond Sun, 10 Jul 2022 17:45:13 +0000 https://www.programmerbay.com/?p=4216 In programming, a function is a set of statements that carries out a specific task. It increases the code readability and reusability.
In order to use a function, one requires to invoke it by using its name and parameters.
A function can be called by using two ways :
  1. Call by reference
  2. Call by value

Call by value :  Where a copy of the original value is created and passed in the formal parameters of a method. In this, if any changes are made to formal arguments within the local method would not be reflected in the original data.

Call by Value

Call by reference :  Where a copy of the address is passed to formal argument which points to the address of the original value .

As a result, if any change is made through that copied reference variable would directly reflect on actual data.

call by reference

Difference between call by value and call by reference in Java in tabular form

CALL BY VALUECALL BY REFERENCE
In this, a value of a variable is passed as an argument to a function's formal parametersIn this, an address of a variable is passed as an argument to a function's formal parameters
A separate memory is allocated to a new variable holding copied value in the stack memoryA separate memory is allocated to a new variable pointing to the address of another variable
Changes made to the cloned value within the local function is not reflected outside the methodChanges made to reference variable within the local function is reflected outside the method
Value of a variable is passed to the argumentPointer variable that is used to store the address, is passed to the formal argument
Original value doesn't get changedOriginal value gets changed

Call by Value

In this, a copy of the actual value is generated and passed in the formal parameter of a method. Any change made in those copied value would not affect the original one because both copied and original values are stored in different location.

Original values are copied from the actual parameter to the formal parameter of a function, meaning, variables in both parameters point to different memory spaces. Therefore, if one changes the value of a variable passed to the formal parameter, then it would not be reflected outside the function.

C program to show the working of Call by Value

#include <stdio.h>

void sum (int x);

int main ()
{
  int a = 10;
  printf ("before sum function called : %d \n", a);
  sum (a);
  printf ("After sum function called : %d \n", a);
  return 0;
}

void sum (int x)
{
  x = x + 20;
  printf ("sum : %d \n", x);
}

Output:

before sum function called : 10 
sum : 30 
After sum function called : 10

Call by reference

In this, a copy of the reference variable is generated and passed in the formal parameter of a method. Any change made through that particular copied variable would affect the actual data because both copied and original reference variable are pointing to same memory location where data is located.

An address is passed from the actual parameter to the formal parameter of a function, meaning, variables in both parameters point to the same memory space. Therefore, if one changes the value of a variable passed in a formal parameter would be reflected outside the function.

#include <stdio.h>

void sum (int *x);

int main ()
{
  int a = 10;
  printf ("before sum function called : %d \n", a);
  sum (&a);
  printf ("After sum function called : %d \n", a);
  return 0;
}

void sum (int *x)
{
  (*x) = (*x) + 20;
  printf ("sum : %d \n", (*x));
}

Output:

before sum function called : 10 
sum : 30 
After sum function called : 30

Call by reference and Call by value in Java

In C++, Call by reference can be achieved using pointers that can be defined as a variable that is capable of storing an address of other variables.

Unlike C++, Java doesn’t support pointers due to security reasons. likewise, call-by-reference is not possible in Java.

Java only supports “call by value”, in the case of objects, it acts differently.

In Java, there are two types of arguments.

  1. Primitive data type : In this, a primitive datatype is passed as an argument to a method’s formal parameters
  2. Object reference type: In this, a reference type is passed as an argument to a method’s formal parameters

Object reference :

An object reference can be defined as memory location which refers to the actual object’s information i.e methods, and variables. The variable that holds it is termed an object reference variable.

In Java, a copy of an object reference is passed from the actual parameter to the formal parameter where both variables passed in the arguments are pointing to the same object. As a result, changes made on the passed variable inside the method is reflected in an actual variable.

In Java, Call by value works by copying the value of an actual parameter to the formal parameter of a method. In this, the value of an actual argument is copied to a different memory space and assigned to the formal argument of a method.

In call by value, any operation performed on the received value, which is a copy, inside a method would not impact the original value residing in the caller method. This is also termed “pass by value”.

Java program to demonstrate how call by value and call by reference works?

Program:

public class callme{int x;
callme(){

x=20;
}
void callByValue(int x)
{
x=x+10; // try to make changes
}
void callByReference( callme obj)
{
obj.x = obj.x + 10; // try to make changes
}

public static void main(String[] args) {
callme o = new callme(); // to demonstrate how call by reference works
int data=10; // to demonstrate how call by value works
System.out.println("Actual Value of 'data' variable before passing it as a parameter = "+data);
System.out.println("Actual Value of object that 'o' reference variable pointing to before passing it as a parameter = "+o.x);
o.callByValue(data); // passing permitive type
o.callByReference(o); // getting reference type

System.out.println("Actual Value of 'data' variable after changes = "+data);
System.out.println("Actual Value of object that 'o' reference variable pointing to after passing it as a parameter = "+o.x);

}

}

Output:

Actual Value of 'data' variable before passing it as a parameter = 10
Actual Value of object that 'o' reference variable pointing to before passing it as a

parameter = 20

Actual Value of 'data' variable after changes = 10
Actual Value of object that 'o' reference variable pointing to after passing it as a

parameter = 30

]]>
https://programmerbay.com/difference-between-call-by-value-and-call-by-reference-in-tabular-form/feed/ 0
Java Garbage Collection And its Working With Program Example https://programmerbay.com/java-garbage-collection-and-its-working-with-program-example/ https://programmerbay.com/java-garbage-collection-and-its-working-with-program-example/#respond Sat, 09 Jul 2022 11:07:37 +0000 https://www.programmerbay.com/?p=4186 Introduction:

Terms:

Reachable & unreachable objects: Objects that can be accessed by a reference variable are known as reachable object. When there is no reference available to access an object, in any way,  it is called unreachable.

Garbage: Useless objects or unreachable objects or objects that can no longer be referenced.

Garbage collector: A program that takes care of memory and manages it automatically.

Garbage collection: It is a process of reclaiming already occupied memory referenced by unreachable objects.

finalization: A process of releasing resources held by the unreachable object and invoked just before destruction.

 Journey of an Object

1. We use new keyword to create an object  and its reference gets stored in a reference variable of same class type.

2. Once the object finishes all its assigned tasks, it is highly recommended to make that object eligible for gc. So, that memory can be freed and used for further activities.

3. After making it eligible for gc, it is very important to release all the resources that are held by that object. For this intent, the finalize method is invoked.

4. And lastly, gc destroys that object and release the memory occupied by that object.

What is the need of Garbage Collector in Java ?

In C++, objects that are allocated using new operator should be destroyed manually using delete operator.

So, it is the programmer’s responsibility to remove that object from the heap memory. However, if one shows carelessness to do this job, the memory would become filled with unreachable objects.

As a result, a situation would arrive, where no further allocation of an object could be made and the most common error called ‘out of memory’ would be triggered.

But unlike C++, Java follows a different approach, it provides garbage collector whose purpose is to reclaim memory occupied by objects.

Therefore, there is no need to handle this situation manually as Garbage collector keeps monitoring memory for useless objects.

Garbage collector always run in the background to fulfill the need for memory management. It can’t be anticipated when would GC actually perform the cleaning task of memory as it depends on the approach that JVM follows.

However, it is certain that if a program is running in a low memory then JVM definitely going to execute GC.

How Does Garbage Collection in Java Work?

Unlike C++, the programmer doesn’t require to remove unused objects from heap memory in Java. Java provides a garbage collector that automates this process and its implementation lives in JVM.

How java Objects are stored in memory

Java garbage collection is a mechanism of identifying reachable & unreachable objects in heap memory, and cleaning unused ones for future allocation purpose. It’s the garbage collector’s responsibility to manage and reclaim the objects which can no longer be referenced.

What is GC root?

GC roots are the special objects to which all other objects are referenced from it and considered alive.

The garbage collector starts its process from the GC root and tracks all the objects that are directly or indirectly accessible through it on the heap. If an object can’t be referenced through GC root, then GC considers that object as a valid candidate for garbage collection

Garbage Collection Stages in Java

1) First, Garbage collector traverses each and every accessible object in the memory array through GC root. Objects that are accessible, considered as alive and inaccessible objects are considered as dead.

2) The marked dead objects occupy memory in the heap, which is then reclaimed by the Garbage collector for future object allocation.

When an object doesn’t have a reference variable, then it automatically becomes eligible for garbage collection.

Methods to run GC explicitly  a brief Article on Method to run GC explicitly ]

Using system class

System class supports a static method called gc() to run the garbage collector. gc() method does not essentially run the Garbage collector, indeed, it requests JVM to execute it. Execution of gc totally depends on the approach that JVM follows.

By using runtime class

Runtime class also supports gc() method to make a call by requesting JVM to invoke gc. It is a singleton class that consists only a single object.

As a result, new instance can’t be created, instead, we use a factory method to get the reference of runtime class.

Before destroying an object, GC invokes finalize method in order to resource deallocation and perform cleaning operation.

Finalize method   a brief Article on Finalize() ]

It allows us to perform some action before destroying a particular object.

There may be a situation where an object holds system resources and it is needed to be freed before the object gets destroyed. This is said to be finalization.

This method invokes beforehand reclaiming an object.

protected void finalize() { 
// action 
}

 

]]>
https://programmerbay.com/java-garbage-collection-and-its-working-with-program-example/feed/ 0
How to Call a Method in Java ? https://programmerbay.com/how-to-call-a-method-in-java/ https://programmerbay.com/how-to-call-a-method-in-java/#respond Sun, 05 Dec 2021 04:19:56 +0000 https://programmerbay.com/?p=8365 In this article, we’ll be discussing meaning of method, how to call a method of different types such as instance method, static method, predefined method and more.

What is a Method ?

A method is a block of code that performs a particular task.  It can be invoked anywhere in a program . It increases code readability and reusability.

What is method

When a compiler encounters a method name, it executes its body. After finishing the method execution, the control is sent back to the caller method’s immediate next statement.

How to create a method in java? 

In order to create a method, the below syntax should be considered :

public static void methodName(int x, int y) {
   // body
}
  • public : access modifier
  • static : non-access modifier
  • void : return type
  • methodName : name of the method
  • int x, int y : method arguments or parameters

A method can be divided into two parts : method header and method body, method header is like signature with description which is defined at very beginning, and method body is, where your logic resides.

For example : 

void sum(int a, int b){   // method header
   int result = a + b;                   // method body
  System.out.println("Sum : "+ result);
    
}

How to Call a Method in Java ?

Calling method using object or calling an Instance method

An instance method is a method that requires an object in order to get called. In other words, we need to create an object of a class in which the method resides and then using the object name followed by dot operator, we can call it.

Syntax:

ObjectName.methodName();

Program:

public class InstanceMethodExample {

private void getMessage(){
System.out.println("Hi this is an example of Instance withod ");
}

public static void main(String[] args) {
InstanceMethodExample obj = new InstanceMethodExample();
obj.getMessage();
}
}

Explanation:

In the above code, we defined an instance method to print a simple message. In main(), we first created the object in which the method was defined  and then after we invoked it using “obj” object.

Calling a Static method

A static method is a method that doesn’t depend on the object of a class in which it resides. It uses static keyword before return type while declaration. In Java, main() is a good example of a static method.

Syntax:

ClassName.methodName();

Program:

public class StaticMethodExample {

private static void getMessage(){

System.out.println("Hi this is an example of Static method ");

}

public static void main(String[] args) {
StaticMethodExample.getMessage();
}
}

However, when we are calling it from the same class, we don’t mandatorily to put className.

Explanation:

In the above code, we defined a static method to display a message. In main(), we are directly calling it without using any object.

Calling pre-defined Method in Java

In Java, standard libraries provide helpful predefined methods. In other words, these are prewritten classes consisting of utility methods, for example, the String class offers methods like trim(),toLowerCase(). These classes can be imported and directly used in our program without the need to write them from Scratch.

If a method in the utility class is an instance method then we would call it ObjectName.methodName(). In case of static, ClassName.methodName();

Program:

class PreDefinedMethodExample {


public static void main(String[] args) {
String str = " Called my utility method ";

System.out.println(" Lower Case : "+str.toLowerCase());
}
}

Explanation:

In above code, we are importing String Class and using the method name toLowerCase() which converts a string to lower-case in our code.

Calling an Abstract Method

A method defined with abstract keyword is termed as Abstract method. It comes with only declaration part and the body is provided by the implementing or child class. In this, the concept of inheritance is come into picture.

An abstract method is defined in an abstract classes and another class that extends it would need to implement its abstract method.

Syntax:

abstract returnType methodName();

Program :

public abstract class AbstractClassExample {

abstract void getMessage();
}


class ChildClass extends AbstractClassExample{
@Override
void getMessage() {
System.out.println("Defining Abstract class method");
}

public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.getMessage();
}
}

 

]]>
https://programmerbay.com/how-to-call-a-method-in-java/feed/ 0
What is the Purpose of Finalize Method in Java ? https://programmerbay.com/what-is-the-purpose-of-finalize-method-in-java/ https://programmerbay.com/what-is-the-purpose-of-finalize-method-in-java/#respond Thu, 09 Jul 2020 11:06:03 +0000 https://www.programmerbay.com/?p=4192 finalize method is a method of Object class. It is invoked by GC just before the destruction of an object. It is used to free all the system resources held by the object .

It must be overridden by a class in order to perform deallocation of resources of related objects. It is preceded with protected access specifier and doesn’t perform any special action. If there is an exception occurred it would be handled by throwable.

Syntax:

protected void finalize() throws Throwable 
{ 
}

When does Java finalize method come into the picture? [ A brief Article on GC ]

  • As we know object gets its memory in Heap and the variable reference to that object gets memory in the stack.
  • Each object gets spaces depending on their size.
  • When an object is no longer in use and present in heap memory, then that object becomes eligible for garbage collection
  • Garbage collector wipes up all unreachable objects and reclaims the occupied memory
  • Lastly, this reclaimed memory once again can be used.

Before destroying an object GC invokes finalize method with the purpose of resource deallocation and perform cleaning operation.

Finalize method & Finalization

It allows us to perform some action before destroying a particular object. There may be a situation where an object is holding some resources and it is needed to be freed before the object gets destroyed.

So, a process of releasing resources held by the unreachable object and invoked just before the object’s destruction is called finalization. This method invokes beforehand reclaiming an object.

protected void finalize() { 
// action 
}

Java finalize method example:

class Sample
{
  @Override protected void finalize ()
  {
    System.out.println ("I am in Finalize Method");
  }
}

public class FinalizeExample
{
  public static void main (String[]args)
  {
    Sample obj = new Sample ();
      obj = null;
      System.gc ();
  }
}

Output:

I am in Finalize Method

]]>
https://programmerbay.com/what-is-the-purpose-of-finalize-method-in-java/feed/ 0