Default initialization in java - java

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
}

Related

Will volatile variables in a class be set to 0 by default?

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.

Default Primitive Values in Java - Memory Allocation?

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.

Are default field values assigned by the compiler or the JVM?

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.

Java check to see if a variable has been 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.

java basics about String

To what value is a variable of the String type automatically initialized?
null
Unless it's inside a method (local variable), in which case it's not declared to anything.
Here's a summary of the answers posted by Martin v. Löwis and silky.
We can say the following about the initialization of a String object:
If the String is a local variable, it will not be initialized.
If the String is a class variable, instance variable, or an array component, then it will be initialized to null.
The reasoning is as follows:
As a variable with the type of String is a reference type, according to The Java Language Specification, Third Edition, Section 4.12.5: Initial Values of Variables says the following:
Every variable in a program must have
a value before its value is used
It goes on to say the following about the initialization of reference types:
Each class variable, instance variable, or array component is
initialized with a default value when
it is created (§15.9, §15.10):
[removed information on irrelevant information]
For all reference types (§4.3), the default value is null.
And finally, the follow about local variables:
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 by the
compiler using the rules for definite
assignment (§16).
If the variable is a class variable, instance variable, or array component, it is initialized to null (since the default value for a reference type is null)
If the variable is a local variable, then it must be given a value explicitly (i.e. it has no default value in this case).
A variable of type String is a reference variable. As an instance variable, it gets initialized to null, see the specification for the discussion of other cases.
It's null unless it's local, in which case it is technically uninitialized, but in fact you can't use it, for that reason, so the language is still type-safe. You can't deref a garbage pointer.
null
String str=null means that the str is a object of String class which is not pointing to anything...but when we talk abt memory allocation,memory will be allocated to str as soon as it comes into existence....u can check the amount of memory by using the profiling option in netbeans..
the string value should be NULL in default , no need to initialize it.
string class objects are NULL by default only if they are defined as class level atttributes, otherwise string objects don't have any default value they need to be explicity initialized.
If the variable of type String is within a method, it would not automatically initialise. Otherwise it would be initialised with null as a value.
Any variable that is declared within a class is automatically initialized.
Any variable that is declared within a method must be initialized otherwise it will generate an error.
Strings are initialized to null,ints to 0 and so on..
Check this page for more information...

Categories

Resources