Code:
public class A {
public static void main(String[] args) {
int i;
System.out.println(i);
}
}
When I run this, instead of printing the default value of int i.e, 0, it cries an error that The local variable i may not have been initialized.
How come and if initialization is mandatory, then why do the primitive data types have default values at all? They might as well have garbage values as C++ does.
Default values are used not for a local variables, only for a fields in a class:
public class A {
int i;
public static void main(String[] args) {
System.out.println(i);
}
}
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
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
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
Related
class FinalConcept
{
private final int number = 22;
public static void main(String args[])
{
try{
FinalConcept obj = new FinalConcept();
System.out.println("value of the x variable "+obj.number);
Field obj1 = obj.getClass().getDeclaredField("number");
obj1.setAccessible(true);
obj1.setInt(obj,45);
If I try to access the variable by field function then I get changed value
System.out.println("value of the x variable "+obj1.get(obj));//45
But if I try to access by the name of variable, I get the same value
System.out.println("value of x varialbe "+obj.x);//22
Why is this hapenning ?
Your variable in number is declared final, so it can't be modified. The object itself will keep always the same value.
Its interesting, I tried to dig it out, and found one observation, If we change the filed "number" from int to Integer, then we get the exception:
Exception-> java.lang.IllegalArgumentException: Can not set final java.lang.Integer field HelloTestJava.number to (int)45
One reason which I observed is that, this behavior is with primitives (int, char, byte , short, boolean, float, double, long) only. There is no exception If we try to change the value of a final primitive field through the Field object.
The same exception I got when I take a final Boolean field and tried to change it through reflection(i.e. through Field object)
Exception-> java.lang.IllegalArgumentException: Can not set final java.lang.Boolean field HelloTestJava.number to (boolean)false
But one thing is for sure, that your object will always have the correct(not-changed) value, doesn't matter we are trying to modify the value through reflection.
I was wondering whether I should initialize class members in java with an initial value and then change that value to some other given value in the constructor, or should I avoid doing such a thing?
code example
public class Test {
private int value = 5;
public Test(int value) {
this.value = value;
}
}
If not specified,:
primitive bytes, shorts, ints, longs, floats and doubles are initialized to 0
booleans are initialized to false
Objects are initialized to null
If we are talking about class fields than all unset variables of
primitive types are set to
0 (numeric ones like int, long, double...)
\u0000 (char)
false (boolean).
object types like String, Integer, or AnyOtherClass are set to null
so actually it doesn't matter if you set it explicitly, because
private int x;
private Integer y;
is equivalent of
private int x = 0;
private Integer y = null;
Java give value class variables, I mean they are initialized by JVM and you can use them. But you must to search their default values to use them correctly.
On the other hand, JVM does not initialize the local variables which is created in methods. So if you create any variable on methods you have to assign them to a value before use them.
A not initialized int is always 0 on heap. It can't never be null. Mind: within a method it must be initialized, not only declared.
First, you cannot initialize an int value with null. The default value of an int is zero, but initializing it in both the field declaration and the constructor is pointless. Assuming the compiler does not omit the field initializer completely, it effectively compiles to this:
public class Test {
private int value;
public Test(int value) {
this.value = /* field initializer value */;
this.value = value;
}
}
Unless you want to initialize a field with a non-default value (non-zero, non-null), there is generally no reason to add an initializer. This is especially true if the initializer is redundant, as is the case above. The default value for a field is the "zeroed out" value of the field type, e.g., 0 for numeric types, false for a boolean, and null for objects. Note that there is an exception with respect to fields: final fields must have an initializer if they are not assigned exactly once in every constructor; final fields have no implicit default value.
Now, it may be necessary to initialize method variables to guarantee they have a value by the time they are read, as variables do not have a default/implied initializer as fields do. Whether an explicit initializer is necessary depends on the control flow of your method.
I was confusing since from last several days that how initialization of instance properties through constructor is being done.
Just consider this case
class Demo
{
int a;
int b;
Demo(int a,int b)
{
this.a*=a;//this produces 0 here
this.b*=b;//this produces 0 here
}
public static void main(String[] args)
{
Demo d1=new Demo(20,30);
d1.show();
}
public void show()
{
System.out.println(this.a);
System.out.println(this.b);
}
}
How this is initializing here. As i know constructor initialize a value once.assignments can be possible several times.
The initial value for an integer is 0. Your actual assignment is this:
a = 0 * 20
which will always return 0.
Some documentation:
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
Integral fields are initialized to 0 by default (as per JLS ยง4.12.5), so multiplying this.a (0) and this.b (0) by a and b respectively will not change their value of 0. Zero times any number is still zero.
Initially this.a (the class variable) is zero so it will produce zero when you multiply it by a (the argument). This is your problem here.
Because the default value of int is 0.
So the line
this.a*=a;
is equivalent to
0 * 20
which equals 0.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
The initial value for an integer is 0. Your actual assignment is this:
a = 0 * 20
which will always return 0.
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
My question is: how to assign default zero to an static integer variable?
This is my code:
class Point {
static int i;
public static void main(String[] args) {
System.out.println("" + i);
}
}
The output must be:
0
All class level numbered primitives will be initialized to 0.
All class level Objects will be initialized to null;
Other default values are
byte 0
char '\u0000'
boolean false
Class' primitive members (static or non-static) are set with default value as described here.
int values are set to 0 by default.
Since i is an integer it allocates the default value to zero
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
This happened only if you are doing at class level
If it is a local variable,you have to initalize before you use. Otherwise compile time error.
I am a beginner in Java, struggling to understand the following problem with variable initialisation, would appreciate an expert help.
Given the code from an exam:
public class SimpleCalc {
public int value;
public void calculate() { value += 7; }
}
AND
public class MultiCalc extends SimpleCalc {
public void calculate() { value -= 3; }
public void calculate(int multiplier) {
calculate();
super.calculate();
value *= multiplier;
}
public static void main (String[] args) {
MultiCalc calculator = new MultiCalc ();
calculator.calculate(2);
System.out.println(calculator.value);
}
}
My understanding is that this needs to throw a runtime exception since variable "value" never gets an actual preliminary value assigned to it (public int value;). But, the code works and behaves as if the variable "value" is assigned 0 (same as public int value=0;). Could someone explain please why does this happen? Many thanks
. But, the code works and behaves as if the variable "value" is
assigned 0 (same as public int value=0;).
instance variables in java get default values. i.e, int get 0 as default value, float get 0.0 and so on. thus if you don't initialize, they get default values.
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
My understanding is that this needs to throw a runtime exception since variable "value" never gets an actual preliminary value assigned to it (public int value;).
Failing to initialise a variable which must be initialised is checked by the compiler and is a compile time error.
Runtime errors are thrown at Runtime. i.e. when you run a program which has been successfully compiled. The only runtime error you will get from failing to set a value is a NullPointerException (for accessing a null reference), or rarely an ArithmeticException if you divide by an integer which is zero.
final fields and local variables must be initialised, but non final fields will value their default value.
Primitive types in Java always get assigned a default value. For an int this is always 0.
If you were to use a Integer object (rather than int) you would see a null pointer exception being thrown if it wasn't initialised.
This kind of initializations happen for instance variables, in java. The variable 'value' is an instance variable which exists in each of the object of that class. Instance variables of data type int have default value 0 assigned to it. Different data types(of instance variables) have different default values.
Example