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.
Related
Consider a Java String Field named x.
What will be the initial value of x when an object is created for the class x;
I know that for int variables, the default value is assigned as 0, as the instances are being created. But what becomes of String?
It's initialized to null if you do nothing, as are all reference types.
That depends. Is it just a variable (in a method)? Or a class-member?
If it's just a variable you'll get an error that no value has been set when trying to read from it without first assinging it a value.
If it's a class-member it will be initialized to null by the VM.
There are three types of variables:
Instance variables: are always initialized
Static variables: are always initialized
Local variables: must be initialized before use
The default values for instance and static variables are the same and depends on the type:
Object type (String, Integer, Boolean and others): initialized with null
Primitive types:
byte, short, int, long: 0
float, double: 0.0
boolean: false
char: '\u0000'
An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.
Once the array is created all of its elements are assiged with the default type value. For example:
private boolean[] list; // default value is null
private Boolean[] list; // default value is null
once is initialized:
private boolean[] list = new boolean[10]; // all ten elements are assigned to false
private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)
The answer is - it depends.
Is the variable an instance variable / class variable ? See this for more details.
The list of default values can be found here.
Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.
Is it possible to create an int variable with no value, then quantify it in my code, and then "unquantify" it so that it no longer has a value?
Example:
class Test {
int integer;
public static void main (String[] args) {
integer = 1;
...
//do stuff
...
integer = null; //Does this line set integer's value to nothing?
// I want to be able to reset the value of integer back to what it was when I defined it (the value was nothing, it had no value)
}
}
EDIT: grammar
You cannot assign null to a primitive type.
You could use the Integer object like this:
Integer i = null;
If you have an int as classmember and you access it inside a method the value of the int will be 0.
Also you have to make your variable static to access it in your main.
As an alternative to null you might like to look at the Optional class that was added in Java 8. It is useful for declaring variables that may or may not have a value:
Optional<Integer> value = Optional.empty();
value = Optional.of(4);
value.ifPresent(n -> method(n));
If used well it can make the code handling optional values much more obvious and transparent than using null.
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.
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