Consider the following code snippet in Java. It won't compile.
package temppkg;
final public class Main
{
private String x;
private int y;
private void show()
{
String z;
int a;
System.out.println(x.toString()); // Causes a NullPointerException but doesn't issue a compiler error.
System.out.println(y); // Works fine displaying its default value which is zero.
System.out.println(z.toString()); // Causes a compile-time error - variable z might not have been initialized.
System.out.println(a); // Causes a compile-time error - variable a might not have been initialized.
}
public static void main(String []args)
{
new Main().show();
}
}
Why do the class members (x and y) declared in the above code snippet not issue any compile-time error even though they are not explicitly initialized and only local variables are required to be initialized?
When in doubt, check the Java Language Specification (JLS).
In the introduction you'll find:
Chapter 16 describes the precise way in which the language ensures
that local variables are definitely set before use. While all other
variables are automatically initialized to a default value, the Java
programming language does not automatically initialize local variables
in order to avoid masking programming errors.
The first paragraph of chapter 16 states,
Each local variable and every blank final field must have a definitely
assigned value when any access of its value occurs....A Java compiler
must carry out a specific conservative flow analysis to make sure
that, for every access of a local variable or blank final field f, f
is definitely assigned before the access; otherwise a compile-time
error must occur.
The default values themselves are in section 4.12.5. The section opens with:
Each class variable, instance variable, or array component is
initialized with a default value when it is created.
...and then goes on to list all the default values.
The JLS is really not that hard to understand and I've found myself using it more and more to understand why Java does what it does...after all, it's the Java bible!
Why would they issue a compile warning?, as instance variables String will get a default value of null, and int will get a default value of 0.
The compiler has no way to know that x.toString(), will cause a runtime exception, because the value of null is not actually set till after runtime.
In general the compiler couldn't know for sure if a class member has or has not been initialized before. For example, you could have a setter method that sets the value for a class member, and another method which accesses that member. The compiler can't issue a warning when accessing that variable because it can't know whether the setter has been called before or not.
I agree that in this case (the member is private and there is no single method that writes the variable) it seems it could raise a warning from the compiler. Well, in fact you are still not sure that the variable has not been initialized since it could have been accessed via reflexion.
Thins are much easier with local variables, since they can't be accessed from outside the method, nor even via reflexion (afaik, please correct me if wrong), so the compiler can be a bit more helpful and warn us of uninitialized variables.
I hope this answer helps you :)
Class members could have been initialized elsewhere in your code, so the compiler can't see if they were initialized at compilation time.
Member variables are automatically initialized to their default values when you construct (instantiate) an object. That holds true even when you have manually initialized them, they will be initialized to default values first and then to the values you supplied.
This is a little little lengthy article but it explains it: Object initialization in Java
Whereas for the local variables (ones that are declared inside a method) are not initialized automatically, which means you have to do it manually, even if you want them to have their default values.
You can see what the default values are for variables with different data types here.
The default value for the reference type variables is null. That's why it's throwing NullPointerException on the following:
System.out.println(x.toString()); // Causes a NullPointerException but doesn't issue a compiler error.
In the following case, the compiler is smart enough to know that the variable is not initialized yet (because it's local and you haven't initialized it), that's why compilation issue:
System.out.println(z.toString()); // "Cuases a compile-time error - variable z might not have been initialized.
Related
Does it have a value?
I am trying to understand what is the state of a declared but not-initialized variable/object in Java.
I cannot actually test it, because I keep getting the "Not Initialized" compile-error and I cannot seem to be able to suppress it.
Though for example, I would guess that if the variable would be an integer it could be equal to 0.
But what if the variable would be a String, would be it be equal to null or the isEmpty() would return true?
Is the value the same for all non-initialized variables? or every declaration (meaning, int, string, double etc) has a different value when not explicitly initialized?
UPDATE
So as I see now, it makes a big difference if the variable is declared locally or in the Class, though I seem to be unable to understand why when declaring as static in the class it gives no error, but when declaring in the main it produces the "Not Initialized" error.
How exactly a JVM does this is entirely up to the JVM and shouldn't matter for a programmer, since the compiler ensures that you do not read uninitialized local variables.
Fields however are different. They need not be assigned before reading them (unless they are final) and the value of a field that has not been assigned is null for reference types or the 0 value of the appropriate primitive type, if the field has a primitive type.
Using s.isEmpty() for a field String s; that has not been assigned results in a NullPointerException.
So as I see now, it makes a big difference if the variable is declared locally or in the Class, though I seem to be unable to understand why when declaring in the class it gives no error, but when declaring in the main it produces the "Not Initialized" error.
In general it's undesirable to work with values that do not have a value. For this reason the language designers had 2 choices:
a) define a default value for variables not yet initialized
b) prevent the programmers from accessing the variable before writing to them.
b) is hard to achieve for fields and therefore option a) was chosen for fields. (There could be multiple methods reading/writing that could be valid or invalid depending on the order of calls, which could only be determined at runtime).
For local variables option b) is viable, since all possible paths of the execution of the method can be checked for assignment statements. This option was chosen during the language design for local variables, since it can help to find many easy mistakes.
Fabian already provided a very clear answer, I just try to add the specification from the official documentation for reference.
Fields in Class
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.
If not specified the default value, it only be treated as a bad style, while it's not the same case in local variables.
Local Variables
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.
The default value will be based on the type of the data and place where you are using initialized variable . Please refer below for Primitive default.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
I'm indebted to this answer for the idea.
The following code compiles, but certainly shouldn't. It uses the value of x before it's been initialised. If you remove the StaticAssign. qualifier then it no longer compiles.
public class StaticAssign {
public static final int x;
static {
System.out.println(StaticAssign.x);
x = 5;
}
public static void main(String[] args) {}
}
On my machine, this consistently prints 0. If I change the type of x to String, it consistently prints null.
The question is: will it definitely print 0 or null, or might it access uninitialised memory and print out something else?
And even if this code gets through the compiler, why isn't it picked up by the JVM?
Is there a way to do nasty things based on this?
It actually has been initialized. Variables in the global scope are initialized automatically. Variables of Object type will be initialized to null primitive like int will be initialized to 0. A variable declared not in the global scope must be initialized ie. declared in a method. Another problem is declaring it as final this is telling the compiler it must be explicitly initialized. So by adding the x=5 you are bypassing the compiler error saying it must be explicitly initialized. When you access it before this line at run-time it is initialized to 0 like any other primitive int type variable in the global scope.
This is due to the way in which the classes are loaded.
First the class StaticAssign definition is loaded and the fields are initialized to default values:
StaticAssign.x = 0;
Then the initalization block is executed.
System.out.println(StaticAssign.x);
x = 5;
There is a reference to StaticAssign.x, the current class. As recursive initialization attempts are simply ignored, value of x is still 0.
This means that:
System.out.println(StaticAssign.x)
is valid because StaticAssign.x is a reference to field of an allready loaded class.
But if yo do:
System.out.println(x)
then x is a reference to a final uninitalized field.
On the other hand, you never will access uninitialised memory. When the class definition is loaded variables are initialized to default values, before the initalization block is executed.
EDIT:
There is a nice video "Elvis Lives Again" from Java Puzzlers that shows this much more better than I can explain
In Java, what is the difference and best way to do?
Integer x = null; // x later assign some value.
Integer y; // y later initialize and use it.
The answer depends on what type of variable are you referring.
For class variables, there's no difference, see the JLS - 4.12.5. Initial Values of Variables:
... Every variable in a program must have a value before its value is
used:
For all reference types (§4.3), the default value is null.
Meaning, there is no difference, the later is implicitly set to null.
If the variables are local, they must be assigned before you pass them to a method:
myMethod(x); //will compile :)
myMethod(y) //won't compile :(
Local variables must be assigned to something before they are used.
Integer x = null;
myFunction(x);
// myFunction is called with the argument null
Integer y;
myFunction(y);
// This will not compile because the variable has not been initialised
Class variables are always initialised to a default value (null for object types, something like zero for primitives) if you don't explicitly initialise them. Local variables are not implicitly initialised.
Its better to not set it to null, otherwise you can by accident use it and cause NPE. Compiler wont help you with compile error. Only set to null if you want to have logic like if ( x != null ) { /use it/ }
No difference at all. Both cases when ever you want to use it, local variable must be in initialized form(must have a value).
From Java doc
Similar to how an object stores its state in fields, a method will
often store its temporary state in local variables. The syntax for
declaring a local variable is similar to declaring a field (for
example, int count = 0;). There is no special keyword designating a
variable as local; that determination comes entirely from the location
in which the variable is declared — which is between the opening and
closing braces of a method. As such, local variables are only visible
to the methods in which they are declared; they are not accessible
from the rest of the class.
Internally there is no difference. Also it is a debatable topic.
Use the local variable only if it is really required. Local variables are mostly in the following scenarios (I may be missing few other).
As a shorthand or for Readability
Integer myObject = someObject.someFunction().someOtherFunction();
If we use the syntax like that in many places, code will become clumsy.
For accessibility
Object returnObject = null;
if(mycondition)
{
returnObject = value1;
}
else if(secondCondition)
{
returnObject = value2;
}
return returnObject;
The caller of the above code snippet will take decision based on the return value.
Honestly speaking i am not seeing other valid use case to declare a variable without initial value.
Conclusion (Best Practice):
Declare local variable only if required
Always create local variable with default value.
No differences at all expect for one thing, if you don't initialize it and later on you try to use this variable (without changing the reference) means an error at compilation time, but if you initialize it and you use it later on (without changing the reference) means a NullPointerException.
I show you with an example.
Without initializing
Integer y;
y.intValue(); // Compilation error
With initializing
Integer x = null;
x.intValue(); // You are able to compile it but NullPointerException
class TestMe{
public static void main (String args[]){
String s3;
System.out.print(s3);
}
}
why the compiler is giving a error,refernce object has a default value of null,why it is not the output...??
error: variable s3 might not have been initialized
It's an error because the JLS says so in §14.4.2. Execution of Local Variable Declarations:
If a declarator does not have an initialization expression, then every reference to the variable must be preceded by execution of an assignment to the variable, or a compile-time error occurs by the rules of §16.
local variables should be initialized before using them, local vars dont get default values in java, thus your string s3 doesn't get default value null as it is a local variable , thus the compiler error.
Fom JLS:
If a declarator does not have an initialization expression, then every
reference to the variable must be preceded by execution of an
assignment to the variable, or a compile-time error occurs by the
rules of §16.
The default value of null only applies to non-final fields of a class.
All other cases require initialisation before first use
Yes, it's necessary.
String s3;
s3 = "Something....";
System.out.print(s3); // prints "Something..."
Before you use a local variable, you have to initialize it.
what i know about local variables is:
Local variables are declared mostly to do some calculation.So it is the programmer's decision to give the value to the variable and it should not take default value. If programmer by mistake did not initialize a local variable, then it takes default value, then the output goes wrong. so local variables will ask programmer to initialize before he uses the variable to avoid making mistake.
The unique scenarios where defaut values are used are the cases where the concerned variables are object's fields or array's components even local. Indeed, arrays ALWAYS initializes their cells with their appropriate default values.
Thus, in your case, your variable doesn't come from a field ( since local to the method) and hasn't participated with an array initialization. So compiler logically complains ..
Consider this:
public class TestClass {
private String a;
private String b;
public TestClass()
{
a = "initialized";
}
public void doSomething()
{
String c;
a.notify(); // This is fine
b.notify(); // This is fine - but will end in an exception
c.notify(); // "Local variable c may not have been initialised"
}
}
I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?
Edit: making the members private was my initial intention, and the question still stands...
The language defines it this way.
Instance variables of object type default to being initialized to null.
Local variables of object type are not initialized by default and it's a compile time error to access an undefined variable.
See section 4.12.5 for SE7 (same section still as of SE14)
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5
Here's the deal. When you call
TestClass tc = new TestClass();
the new command performs four important tasks:
Allocates memory on the heap for the new object.
Initiates the class fields to their default values (numerics to 0, boolean to false, objects to null).
Calls the constructor (which may re-initiate the fields, or may not).
Returns a reference to the new object.
So your fields 'a' and 'b' are both initiated to null, and 'a' is re-initiated in the constructor. This process is not relevant for method calling, so local variable 'c' is never initialized.
For the gravely insomniac, read this.
The rules for definite assignment are quite difficult (read chapter 16 of JLS 3rd Ed). It's not practical to enforce definite assignment on fields. As it stands, it's even possible to observe final fields before they are initialised.
The compiler can figure out that c will never be set. The b variable could be set by someone else after the constructor is called, but before doSomething(). Make b private and the compiler may be able to help.
The compiler can tell from the code for doSomething() that c is declared there and never initialized. Because it is local, there is no possibility that it is initialized elsewhere.
It can't tell when or where you are going to call doSomething(). b is a public member. It is entirely possible that you would initialize it in other code before calling the method.
Member-variables are initialized to null or to their default primitive values, if they are primitives.
Local variables are UNDEFINED and are not initialized and you are responsible for setting the initial value. The compiler prevents you from using them.
Therefore, b is initialized when the class TestClass is instantiated while c is undefined.
Note: null is different from undefined.
You've actually identified one of the bigger holes in Java's system of generally attempting to find errors at edit/compile time rather than run time because--as the accepted answer said--it's difficult to tell if b is initialized or not.
There are a few patterns to work around this flaw. First is "Final by default". If your members were final, you would have to fill them in with the constructor--and it would use path-analysis to ensure that every possible path fills in the finals (You could still assign it "Null" which would defeat the purpose but at least you would be forced to recognize that you were doing it intentionally).
A second approach is strict null checking. You can turn it on in eclipse settings either by project or in default properties. I believe it would force you to null-check your b.notify() before you call it. This can quickly get out of hand so it tends to go with a set of annotations to make things simpler:
The annotations might have different names but in concept once you turn on strict null checking and the annotations the types of variables are "nullable" and "NotNull". If you try to place a Nullable into a not-null variable you must check it for null first. Parameters and return types are also annotated so you don't have to check for null every single time you assign to a not-null variable.
There is also a "NotNullByDefault" package level annotation that will make the editor assume that no variable can ever have a null value unless you tag it Nullable.
These annotations mostly apply at the editor level--You can turn them on within eclipse and probably other editors--which is why they aren't necessarily standardized. (At least last time I check, Java 8 might have some annotations I haven't found yet)