Return types in Java

class A < public void message() < System.out.println("Hello"); return 1; //Returning an int value from a method with void return type. >public static void main(String. ar) < A ob = new A(); ob.message(); >>

Output-

Return9.java:6: error: incompatible types: unexpected return value return 1; ^ 1 error 
class A < public void message() < System.out.println("Hello"); return; // empty return statement is perfectly fine in a void method >public static void main(String. ar) < A ob = new A(); ob.message(); >> 

Output-

Hello
class A < byte b= 10; public int returnValue() < System.out.println("Hello"); return b; >public static void main(String. ar) < A ob= new A(); System.out.println(ob.returnValue()); >>

Output-

class A < public double returnValue() < char c ='a'; return c; >public static void main(String. ar) < A ob = new A(); System.out.println(ob.returnValue()); >>

Output-

class A < public long returnValue() < float f = 10.5f; return f; >public static void main(String. ar) < A ob = new A(); System.out.println(ob.returnValue()); >>

Output-

Return10.java:8: error: incompatible types: possible lossy conversion from float to long return f; ^ 1 error

To return a float out of a method with a long return type, the float value must be converted to long. When converting a float value to long, the decimal value of a float will be truncated, leading to a loss in the value of float, which is not allowed by the compiler, hence, a compile error.

class A < >class B extends A < public A message() < System.out.println("Hello"); return this; //currently executing object of B type is returned from a method with superclass return type. >public static void main(String. ar) < B ob = new B(); // an object of B is created ob.message(); //method message() is called on this object of B >> 

Output-

Hello 
class A < public Object message() //Method with Object class return type < int arr[] = new int[]; return arr; //returning an int array, which is also an object. > public static void main(String. ar) < A ob = new A(); int arr2[]=(int[])ob.message(); //casting the Object reference back to int array for(int i=0;i>

Output-

1 2 3 4 
class A < public A message() < System.out.println("Hello"); return null; >public static void main(String. ar) < A ob = new A(); ob.message(); >>