-4

I got errors in this program to find the default values of all data types in Java.

import java.lang.*;

class Datatypesvalues
{
    public static void main(String var[])
    {
        int i;
        long l;
        float f;
        double d;
        char ch;
        boolean bool;
        System.out.println(+ by);
        System.out.println(+ sh);
        System.out.println(+ i);
        System.out.println(+ l);
        System.out.println(+ f);
        System.out.println(+ d);
        System.out.println(+ ch);
        System.out.println(bool);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sasi kanth
  • 23
  • 1
  • 4

3 Answers3

1

How can I find the default values of all data types in Java?

Read The Java® Language Specification, e.g., JLS §4.12.5. Initial Values of Variables:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
    • For type byte, the default value is zero, that is, the value of (byte)0.
    • For type short, the default value is zero, that is, the value of (short)0.
    • For type int, the default value is zero, that is, 0.
    • For type long, the default value is zero, that is, 0L.
    • For type float, the default value is positive zero, that is, 0.0f.
    • For type double, the default value is positive zero, that is, 0.0d.
    • For type char, the default value is the null character, that is, '\u0000'.
    • For type boolean, the default value is false.
    • For all reference types (§4.3), the default value is null.

It goes on to say:

  • A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Which is the problem with your code. You didn't explicitly assign a value to your local variables.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

Declare a variable as an instance variable and print it in the function to get the default value.

A local variable will not be initialized to the default value.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sumit Kumar
  • 375
  • 1
  • 11
0

You defined your variables inside the main function which makes them local variables and they don't have initial values. You have to initialize them before using. Otherwise you'll get the not initialized error.

You have to use instance variables declared outside any method to have initial values. Study the scope of variables. This page is helpful: Java - Variable Types

class example
{
    public static int a; 

    public static void main (String[] args) 
    {
        System.out.println(a);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Batman
  • 105
  • 6