Java


Default Value of Data Types in Java :
Data Type
Default Value (for fields)
byte
0
short
0
int
0
long
0L
float
0.0f
double
0.0d
char
‘u0000’
String (or any object)
null
boolean
false
Live Example : Default value of Data Type
Sample Program that will illustrate Default Value Stored in Each Primitive Data Type Variable
public class DefaultValue {
  static boolean bool;
  static byte by;
  static char ch;
  static double d;
  static float f;
  static int i;
  static long l;
  static short sh;
  static String str;

  public static void main(String[] args) {
    System.out.println("Bool :" + bool);
    System.out.println("Byte :" + by);
    System.out.println("Character:" + ch);
    System.out.println("Double :" + d);
    System.out.println("Float :" + f);
    System.out.println("Integer :" + i);
    System.out.println("Long :" + l);
    System.out.println("Short :" + sh);
    System.out.println("String :" + str);
  }
}
Output :
[468×60]
Bool     :false
Byte     :0
Character:
Double   :0.0
Float    :0.0
Integer  :0
Long     :0
Short    :0
String   :null

Output of Java Program

Question 1

class Base { 
    public void Print() { 
        System.out.println("Base"); 
    }          
  
class Derived extends Base {     
    public void Print() { 
        System.out.println("Derived"); 
    } 
  
class Main{ 
    public static void DoPrint( Base o ) { 
        o.Print();    
    } 
    public static void main(String[] args) { 
        Base x = new Base(); 
        Base y = new Derived(); 
        Derived z = new Derived(); 
        DoPrint(x); 
        DoPrint(y); 
        DoPrint(z); 
    } 
}
Output:

Base
Derived
Derived
--------------------------------------------------------------------------
Question 2

class Test1 {   
    Test1(int x) {
        System.out.println("Constructor called " + x);
    }
}
   
// This class contains an instance of Test1 
class Test2 {    
    Test1 t1 = new Test1(10);   
   
    Test2(int i) { t1 = new Test1(i); } 
   
    public static void main(String[] args) {    
         Test2 t2 = new Test2(5);
    }
}

Output:
The output of the program is Constructor called 10 Constructor called 5.
-----------------------------------------------------------------------------------------

public class Main
{
    public static void gfg(String s)
    {    
        System.out.println("String");
    }
    public static void gfg(Object o)
    {
        System.out.println("Object");
    }
 
    public static void main(String args[])
    {
        gfg(null);
    }
} //end class
Output:
 String
Explanation: In case of method overloading, the most specific method is chosen at compile time.

No comments:

Post a Comment