I know java will have a default constructor to initialize variables to 0, but how about volatile variables?
class Test {
volatile long a;
volatile double b;
volatile int c;
}
and I print them and every time result is 0, but is it guaranteed ?
The Java Language Specifiction, section 4.12.5, says:
Each class variable, instance variable, or array component is initialized with a default value when it is created:
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.
As you can see, this rule applies to all fields, regardless of their volatility.
Related
I have scoured the Internet and have not found satisfying answers to my question. In a localized instance, if I have the code:
public static void main (String args[])
{
int x;
System.out.println(x);
}
...it will not compile, because the Java compiler will warn me that x should be initialized. I understand that.
My question is, will Java actually set aside 4 bytes of memory for the integer x? And if so, does it wipe out that block of memory? Does it define it as NULL (I don't think so because NULL and an int are incompatible types)? Or does the memory address of int x still retain the value last stored in memory, or does x just simply have "no value?"
I know that the above works in C, and that in C, it would just print out whatever is in that memory block. I want to know how Java handles this.
===EDIT===
Okay, okay. For some reason, my basic knowledge of programming had entirely exited my mind, as when a program does not compile, the question of memory allocation is irrelevant, as pointed out by both of the members who posted the answers. (Cue facepalm)
So what if I had the code:
public static void main (String args[])
{
int x;
}
How is the integer x resolved in memory then?
It's not a warning; it's a compiler error. That code won't compile, so no bytecode is generated. The question of whether memory is set aside is irrelevant, because there is no program to run.
However, if the x variable is not local, then Java will assign a default value of 0.
Section 4.12.5 of the JLS states:
Every variable in a program must have a value before its value is used:
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.
Each method parameter (§8.4.1) is initialized to the corresponding argument value provided by the invoker of the method (§15.12).
Each constructor parameter (§8.8.1) is initialized to the corresponding argument value provided by a class instance creation expression (§15.9) or explicit constructor invocation (§8.8.7).
An exception parameter (§14.20) is initialized to the thrown object representing the exception (§11.3, §14.18).
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)).
Given that your questions are:
[W]ill Java actually set aside 4 bytes of memory for the integer x?
And if so, does it wipe out that block of memory?
The answer you seek is in JLS 4.12.3.8:
A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment (§16 (Definite Assignment)) prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or for statement is complete.
So the answers are:
Maybe. The value will be stored somewhere.
Yes. No uninitialized values are allowed by the JLS.
Nothing happens to the local variable until it is assigned. It is impossible to use the value until it has been assigned, however, so you can never use an uninitialized value. At the point of initialization, some sort of storage location must be used (obviously). However, nothing about the JLS requires the JVM to allocate memory.
Whether memory is allocated would be determined at runtime based on the execution context, whether the value needed to be pushed onto a stack frame to make a method call, whether an unused CPU register was available, etc. A naive JVM implementation might just always allocate memory, but that would be slow, and as such I would expect most real-world JVMs to try something more optimized.
I have one question: in java we declare int,long,double etc.,(primitive data)
or non primitive (object data), not initialized with default values, but at run
time it will take default values. Now my question is which one assigns
default values: java compiler or Java Virtual Machine (JVM)?
For Example:
int x;
System.out.println(x) //Result is 0;
There are three different types of declared variables in Java. They are instance, class and local variables.
Instance Variables
Instance variables are the non-static fields of your class, often referred to simply as fields.
Primitive numeric fields initialize to 0. This includes byte, short, int, long, float and double.
booleans initialize to false .
chars initialize to the null character \u0000.
Reference types initialize to null.
Class Variables
A class variable is a field within a class declared as static, often referred to as a static variable or static field. It is also same initialize as instance variable.
Local Variables
A local variable is a variable defined within a method, which includes any method
parameters.
Local variables must be initialized before use. They do not have a default value.
Initialization process is done by JVM when method is create.
The default values for fields are assigned by the JVM at runtime. From JLS 15.9.4 (emphasis mine):
The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value.
Of course, given that this behavior is standardized in the JLS, a compiler could conceivably take advantage of that to perform certain optimizations based on the assumption that uninitialized fields start with their default value.
Fields are initialized to the equivalent of 0 in whatever type they are (null for reference types). This article gives a nice list:
Data Type: Default Value:
boolean false
char \u0000
int,short,byte / long 0 / 0L
float / double 0.0f / 0.0d
any reference type null
Local variables are not given an initial value, and it is a compiler error to use them if they are not assigned a value through all possible code paths prior to use.
Note that array elements are automatically initialized to default values as well when a new array is created (e.g. each element of new int[100] will be initialized to 0). This applies to both field and local array variables.
I have a confusion about variable initialization in Java. As I understand, class variables get default initialization while local variables are not initialized by default. However, if I create an array inside a method using the new keyword, it does get initialized by default. Is this true of all objects? Does using the new keyword initialize an object regardless of whether it's a class variable or local variable?
From Java Language Specification
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
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
After further investigation, primitives will always initialize to the default only when they are member variables, local variables will throw a compile error if they are not initialized.
If you create an array of primitives they will all be initialized by default (this is true for both local and member arrays), an array of objects you will need to instantiate each one.
Is this true of all objects? Does using the new keyword initialize an
object regardless of whether it's a class variable or local variable?
When you use new keyword. it means that you have initialized your Object. doesn't matter if its declared at method level or instance level.
public void method(){
Object obj1;// not initialized
Object obj2 = new Object();//initialized
}
I need to use something similar to php's isset function. I know php and java are EXTREMELY different but php is my only basis of previous knowledge on something similar to programming. Is there some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not. For example...
if(box.isset()) {
box.removeFromCanvas();
}
So far I've had this problem where I am getting a run-time error when my program is trying to hide or remove an object that hasn't been constructed yet.
Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
int: 0
char: \u0000 or 0
double: 0.0
boolean: false
reference: null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
What are the default values of boolean (primitive) and Boolean (primitive wrapper) in Java?
The default value for a Boolean (object) is null.
The default value for a boolean (primitive) is false.
The default value of any Object, such as Boolean, is null.
The default value for a boolean is false.
Note: Every primitive has a wrapper class. Every wrapper uses a reference which has a default of null. Primitives have different default values:
boolean -> false
byte, char, short, int, long -> 0
float, double -> 0.0
Note (2): void has a wrapper Void which also has a default of null and is it's only possible value (without using hacks).
boolean
Can be true or false.
Default value is false.
(Source: Java Primitive Variables)
Boolean
Can be a Boolean object representing true or false, or can be null.
Default value is null.
If you need to ask, then you need to explicitly initialize your fields/variables, because if you have to look it up, then chances are someone else needs to do that too.
The value for a primitive boolean is false as can be seen here.
As mentioned by others the value for a Boolean will be null by default.
Boolean is an Object. So if it's an instance variable it will be null. If it's declared within a method you will have to initialize it, or there will be a compiler error.
If you declare as a primitive i.e. boolean. The value will be false by default if it's an instance variable (or class variable). If it's declared within a method you will still have to initialize it to either true or false, or there will be a compiler error.
An uninitialized Boolean member (actually a reference to an object of type Boolean) will have the default value of null.
An uninitialized boolean (primitive) member will have the default value of false.
There is no default for Boolean. Boolean must be constructed with a boolean or a String. If the object is unintialized, it would point to null.
The default value of primitive boolean is false.
http://download.oracle.com/javase/6/docs/api/java/lang/Boolean.html
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
class BooleanTester
{
boolean primitive;
Boolean object;
public static void main(String[] args) {
BooleanTester booleanTester = new BooleanTester();
System.out.println("primitive: " + booleanTester.getPrimitive());
System.out.println("object: " + booleanTester.getObject());
}
public boolean getPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
}
output:
primitive: false
object: null
This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.
Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.
I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.