void and Void

void is a keyword which is used to specify the return type of a method.When a method return type is void,it means,the method is not going to return anything

Void is a class with private constructor,Hence we cannot create the object of such class.

What is the Use of Void class?
It is use to know the return type of a method,via reflection api.
Assume you have a Demo class with a show() method

public class Demo
{
public void show(){}
}


Now Based on the return type(If return type is void do something) else do someother thing
So the code to find out the return type is

Class c1 =Demo.class.getMethod("show",null).getReturnType();
 if(c1 == Void.TYPE)
{
//Some Business logic when return type is void
}



The complete program is
VoidDemo.java

import java.util.List;

class Demo
{
    public void show()
    {
       
    }
}


public class VoidDemo {
    public static void main(String[] args) throws NoSuchMethodException,SecurityException {
        Class c1 = Demo.class.getMethod("show",null).getReturnType();
       
        if(c1 == Void.TYPE){
        System.out.println("Void return type");}
        else{
        System.out.println("Something was returned");}
       
    }
}
Output:-
Void return type

Note:You change the return type of show() to any other datatype,and you can see the else block getting executed

Comments

Popular posts from this blog

How to know which liferay version we are using

Viewing the SQL Query in liferay : debugging the SQL Query in Hibernate

Opening portlet in popup