Java Unassigned Variables


Unassigned Local and Instance Variables

Summary:

In this "Java unassigned variables" tutorial, you will learn Java nature of unassigned variables which quiet contract to C/C++.

One of the features of Java is "Java does not support garbage values". If a variable is used without a value assigned, it is either compilation error or takes a default value. If a local variable is not given a value and still used in the program it is a compilation error. But in case of an instance variable, it takes a default value. For example, an integer variable takes 0 by default. A novice should remember the nature of this Java unassigned variables.

Following program illustrates.

public class Values
{
  int price;
  double rate;
  boolean raining;

  public static void main(String args[])
  {
    int marks;

    // System.out.println(marks);                  // raises compilation error
    Values v1 = new Values();  
    System.out.println(v1.price);                 // prints 0
    System.out.println(v1.rate);                  // prints 0.0
    System.out.println(v1.raining);              // prints false
  }
}

Java Unassigned Variables

Output screen of Values.java of Java Unassigned Variables

In the above code, price, rate and raining are unassigned instance variables and printed default values. But unassigned local variable marks is placed in comments. If comments are removed and compiled the program, it raises compilation error.

The following table gives the default values for Java unassigned variables (instance variables)

.

Date type Default value
byte
0
short
0
int
0
long
0
float
0.0
double
0.0
char
\u0000 (does not print any value)
boolean
false

On Java unassigned variables, more discussion is available at Data Types Default Values – No Garbage.

Explanation for calling Java unassigned variables from methods is discussed in Using Variables from Methods.

1 thought on “Java Unassigned Variables”

  1. Binary options: The shortest route to the world of trading. $ 154 900 Paid to our traders yesterday. Register now and get 10.000 virtual FUNDS in case of right forecast! This is FREE! далее вот nnzcq.tk

Leave a Comment

Your email address will not be published.