Local variable in java - java

All code is in Java.
public class TestLocal
{
public static void main(String [] args)
{
int x;
if (args[0] != null)
{ // assume you know this will
// always be true
x = 7; // statement will run
}
int y = x; // the compiler will choke here
}
}
So, my Question is why does the compiler choke here? Does it bypass the if statement (This look quite horrible...) If I initialize x outside the if statement block then the compiler does not complain, as in this code:
public class TestLocal
{
public static void main(String [] args)
{
int x;
x = 7; // compiler is happy now..:)
if (args[0] != null)
{ // assume you know this will
// always be true
// statement will run
}
int y = x; // the compiler not complain here now.
}
}
Why such a horrible behavior from the compiler?

Java requires you to initialize the local variable as a safety measure. It stops you from accidently reading an odd value. If the compiler didn't complain and you were to read the value of x, it could be anything.

Well, the thing is that args[0] might be null, and then x would not be initialized before use. That is why the compiler is complaining at you.

When you don't pass argument then String[] array has nothing and is uninitialized. so the if condition will not be true in this case and even it will throw Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0.. Now assume you have set args[0] to null value at some place in your code then the if(args[0]) != null) will evaluate to false . In that case you are assigning int y= x; where x is uninitialized. And I think you should know compiler takes these things into account. In java you can not use a local variable until it is initialized.
That's why the smart Java compiler gives you compile time error and tell you code properly.
:-). Hope you got it.

According to java Local variables must be initialized before use.
in your case you are trying to initialize it in condition.Conditions never guaranteed to executes(In run time it may executes or may not execute based on the condition) and trying to assign to y variable.
So compiler warns about it.

Because of performance issues among others, Java doesn't initialize automatically local variables. so here:
int x;
x still have an undefined value. Compiler won't allow you to compile the code because you are referring to x in this line:
int y = x;
It works in the second case because you are initializing x before it is referred elsewehere.
Granted, you are initializing x inside the if statement, but obviously it could be the case that your if evaluates to false, so the compiler takes that into account.

int y = x; // the compiler will choke here
Because in case your if block does not execute(when arg[0] ==null) then x will not be initialized. Java compiler mandates the variable to be initialized before they can be used.

You're declaring x as space to hold an integer, but since you didn't give it any integer to hold, it is still null.
The compiler looks at both the true and false paths of your if statement. If arg[0] contains something, then you're fine. Otherwise, when you try to set y = x, x has nothing to give to y and you get an error.

Related

Variable x might not have have been initialized?

I am having problem with this code, i assigned a value to variable x in if block but compiler throws an error message. I don't get it why?
class psp
{
public static void main(String gg[])
{
int x, y;
y=5;
if(y==5)
{
x=5; // i have assigned a value to x
}
System.out.println(x);
}
}
Because y=5 Is executed at runtime so the compiler doesn't know the value at compile time.
The Java compiler does not take into account possible values of variables when deciding whether a certain execution path will take place. In this case, the compiler will not take into account that y is 5 in deciding whether the if condition will always be true and thus x will always be initialized.
The compiler will only see an if without an else and assume that there is a possibility that the if condition could be false.
You can remove this compiler error by initializing x outside of the if block or by including an else block and also initializing it there.

try catch java -- java complaining that variable may not be initialized [duplicate]

When I try to compile this:
public static Rand searchCount (int[] x)
{
int a ;
int b ;
...
for (int l= 0; l<x.length; l++)
{
if (x[l] == 0)
a++ ;
else if (x[l] == 1)
b++ ;
}
...
}
I get these errors:
Rand.java:72: variable a might not have been initialized
a++ ;
^
Rand.java:74: variable b might not have been initialized
b++ ;
^
2 errors
It seems to me that I initialized them at the top of the method. What's going wrong?
You declared them, but you didn't initialize them. Initializing them is setting them equal to a value:
int a; // This is a declaration
a = 0; // This is an initialization
int b = 1; // This is a declaration and initialization
You get the error because you haven't initialized the variables, but you increment them (e.g., a++) in the for loop.
Java primitives have default values but as one user commented below
Their default value is zero when declared as class members. Local variables don't have default values
Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.
If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.
If they were declared as fields of the class then they would be really initialized with 0.
You're a bit confused because if you write:
class Clazz {
int a;
int b;
Clazz () {
super ();
b = 0;
}
public void printA () {
sout (a + b);
}
public static void main (String[] args) {
new Clazz ().printA ();
}
}
Then this code will print "0". It's because a special constructor will be called when you create new instance of Clazz. At first super () will be called, then field a will be initialized implicitly, and then line b = 0 will be executed.
You declared them, but not initialized.
int a; // declaration, unknown value
a = 0; // initialization
int a = 0; // declaration with initialization
You declared them, but you didn't initialize them with a value. Add something like this:
int a = 0;
You declared them but did not provide them with an intial value - thus, they're unintialized. Try something like:
public static Rand searchCount (int[] x)
{
int a = 0 ;
int b = 0 ;
and the warnings should go away.
Since no other answer has cited the Java language standard, I have decided to write an answer of my own:
In Java, local variables are not, by default, initialized with a certain value (unlike, for example, the field of classes). From the language specification one (§4.12.5) can read the following:
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)).
Therefore, since the variables a and b are not initialized :
for (int l= 0; l<x.length; l++)
{
if (x[l] == 0)
a++ ;
else if (x[l] == 1)
b++ ;
}
the operations a++; and b++; could not produce any meaningful results, anyway. So it is logical for the compiler to notify you about it:
Rand.java:72: variable a might not have been initialized
a++ ;
^
Rand.java:74: variable b might not have been initialized
b++ ;
^
However, one needs to understand that the fact that a++; and b++; could not produce any meaningful results has nothing to do with the reason why the compiler displays an error. But rather because it is explicitly set on the Java language specification that
A local variable (§14.4, §14.14) must be explicitly given a value (...)
To showcase the aforementioned point, let us change a bit your code to:
public static Rand searchCount (int[] x)
{
if(x == null || x.length == 0)
return null;
int a ;
int b ;
...
for (int l= 0; l<x.length; l++)
{
if(l == 0)
a = l;
if(l == 1)
b = l;
}
...
}
So even though the code above can be formally proven to be valid (i.e., the variables a and b will be always assigned with the value 0 and 1, respectively) it is not the compiler job to try to analyze your application's logic, and neither does the rules of local variable initialization rely on that. The compiler checks if the variables a and b are initialized according to the local variable initialization rules, and reacts accordingly (e.g., displaying a compilation error).
You declared them at the start of the method, but you never initialized them. Initializing would be setting them equal to a value, such as:
int a = 0;
int b = 0;
Imagine what happens if x[l] is neither 0 nor 1 in the loop. In that case a and b will never be assigned to and have an undefined value.
You must initialize them both with some value, for example 0.
It's a good practice to initialize the local variables inside the method block before using it. Here is a mistake that a beginner may commit.
public static void main(String[] args){
int a;
int[] arr = {1,2,3,4,5};
for(int i=0; i<arr.length; i++){
a = arr[i];
}
System.out.println(a);
}
You may expect the console will show '5' but instead the compiler will throw 'variable a might not be initialized' error. Though one may think variable a is 'initialized' inside the for loop, the compiler does not think in that way. What if arr.length is 0? The for loop will not be run at all. Hence, the compiler will give variable a might not have been initialized to point out the potential danger and require you to initialize the variable.
To prevent this kind of error, just initialize the variable when you declare it.
int a = 0;
You haven't initialised a and b, only declared them. There is a subtle difference.
int a = 0;
int b = 0;
At least this is for C++, I presume Java is the same concept.
Set variable "a" to some value like this,
a=0;
Declaring and initialzing are both different.
Good Luck

Why attempt to print uninitialized variable does not always result in an error message

Some may find it similar to the SO question Will Java Final variables have default values? but that answer doesn't completely solve this, as that question doesn't directly print the value of x within instance initializer block.
The problem arises when I try to print x directly inside the instance initializer block, while having assigned a value to x before the end of the block :
Case 1
class HelloWorld {
final int x;
{
System.out.println(x);
x = 7;
System.out.println(x);
}
HelloWorld() {
System.out.println("hi");
}
public static void main(String[] args) {
HelloWorld t = new HelloWorld();
}
}
This gives a compile time error stating that variable x might not have been initialized.
$ javac HelloWorld.java
HelloWorld.java:6: error: variable x might not have been initialized
System.out.println(x);
^
1 error
Case 2
Instead of directly printing, I am calling a function to print:
class HelloWorld {
final int x;
{
printX();
x = 7;
printX();
}
HelloWorld() {
System.out.println("hi");
}
void printX() {
System.out.println(x);
}
public static void main(String[] args) {
HelloWorld t = new HelloWorld();
}
}
This compiles correctly and gives output
0
7
hi
What is the conceptual difference between the two cases?
In the JLS, §8.3.3. Forward References During Field Initialization, its stated that there's a compile-time error when:
Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables
are in scope. Specifically, it is a compile-time error if all of the
following are true:
The declaration of an instance variable in a class or interface C appears textually after a use of the instance variable;
The use is a simple name in either an instance variable initializer of C or an instance initializer of C;
The use is not on the left hand side of an assignment;
C is the innermost class or interface enclosing the use.
The following rules come with a few examples, of which the closest to yours is this one:
class Z {
static int peek() { return j; }
static int i = peek();
static int j = 1;
}
class Test {
public static void main(String[] args) {
System.out.println(Z.i);
}
}
Accesses [to static or instance variables] by methods are not checked in this way, so the code above produces output 0, because the variable initializer for i uses the class method peek() to access the value of the variable j before j has been initialized by its variable initializer, at which point it still has its default value (§4.12.5 Initial Values of Variables).
So, to summarize, your second example compiles and executes fine, because the compiler does not check if the x variable was already initialized when you invoke printX() and when printX() actually takes place at Runtime, the x variable will be assigned with its default value (0).
Reading the JLS, the answer appears to be in section 16.2.2:
A blank final member field V is definitely assigned (and moreover is not definitely unassigned) before the block (§14.2) that is the body of any method in the scope of V and before the declaration of any class declared within the scope of V.
This means that when a method is called, the final field is assigned to its default value 0 before invoking it, so when you reference it inside the method, it compiles successfully and prints the value 0.
However, when you access the field outside of a method, it is considered unassigned, hence the compilation error. The following code will also not compile:
public class Main {
final int x;
{
method();
System.out.println(x);
x = 7;
}
void method() { }
public static void main(String[] args) { }
}
because:
V is [un]assigned before any other statement S of the block iff V is [un]assigned after the statement immediately preceding S in the block.
Since the final field x is unassigned before the method invocation, it is still unassigned after it.
This note in the JLS is also relevant:
Note that there are no rules that would allow us to conclude that V is definitely unassigned before the block that is the body of any constructor, method, instance initializer, or static initializer declared in C. We can informally conclude that V is not definitely unassigned before the block that is the body of any constructor, method, instance initializer, or static initializer declared in C, but there is no need for such a rule to be stated explicitly.
The difference is that in the first case you are calling System.out.println from initializer block so the block which is invoked before constructor. In the first line
System.out.println(x);
variable x is not yet initialized so that you get compilation error.
But in the second case you call instance method which doesn't know if variable has already been initialized so you don't have compilation error and you can see the default value for x
Ok, here is my 2 cents.
We all know that final variables can be initialized only While declaring or later on in constructors. Keeping that fact in mind, let see what happened here so far.
No errors Case:
So when you use inside a method, it have already a value.
1) If you initialize it, that value.
2) If not, the default value of data type.
Error case :
When you do that in an initialization block, which you are seeing errors.
If you look at the docs of initialization block
{
// whatever code is needed for initialization goes here
}
and
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
In compiler's eye, your code is literally equals to
class HelloWorld {
final int x;
HelloWorld() {
System.out.println(x); ------------ ERROR here obviously
x = 7;
System.out.println(x);
System.out.println("hi");
}
public static void main(String[] args) {
HelloWorld t = new HelloWorld();
}
}
You are using it before even initializing it.
Case 1 :
Gives you a compile-error,
Because at System.out.println(x);
you are trying to print x which was never initialized.
Case 2:
Works because you are not directly using any literal values, instead you are calling some method, which is correct.
General Rule is,
If you are trying to access any variable which is never initialized
then it will give a compilation error.
We deal here with initializer block. The Java compiler copies initializer blocks into every constructor.
The compiler error don't occure in second example, because printing x is in another Frame, please refer to spec.

Java initialising a static field to itself

This code compiles (using Java 8), giving the warning The assignment to variable value has no effect:
package test;
public class Test {
private static int value;
static {
value = Test.value;
}
public static void main(String[] args) {
System.out.println(value);
}
}
The program outputs 0 as expected. But why does the compiler allow this, what is the use case?
Because variables in Java have a default value which is initialized before any other initialization, unless the initialization happens directly when declaring the variable. Indeed value is 0.
The warning seems reasonable, assigning a variable to itself has no apparent effect but I don't think it should be considered a compile type error since it's syntactically and semantically correct.
If as variable is assigned to itself, the compiler issues a warning, as in the following:
int x = 2;
x = x;
This warning is usually a sign of a programming problem, so for itself it is a good thing to have it, yet in the case that the variable is volatile, which will be the ONLIEST useful Use Case I can think off, the warning is incorrect.
int y = 0;
volatile int x = 2;
y = 3;
x = x;
The java memory model enforces that every thread reading x and y in that order is guaranteed to see the value 3 for y. This is because assigning to x in one thread and reading x in the other establishes a happens-before-ordering.
The assignment has no effect to the value of the variable but it does have a huge effect for concurrency.
Note that in the example above the warning can be suppressed by using
x = x + 0;
Yet there is no such hack for references. One Use Case that will hit you is when trying to sync the content of a int[]. One thread reads a member:
myarray[3]
and another thread writes the member:
myarray[3] = 2;
Because array members themselfes cannot be volatile, you have to make myarray volatile and add the following to the writing thread:
myarrray = myarray;

What is called a forward reference in Java?

I have been through this question on legality of forward references but not clear as to what is meant by forward references in Java language . Can someone please explain with the help of an example ?
This is specifically a compilation error. And its all about ordering of class variable declarations. Let's use some code for illustrative purposes:
public class ForwardReference {
public ForwardReference() {
super();
}
public ForwardReference echoReference() {
return this;
}
public void testLegalForwardReference() {
// Illustration: Legal
this.x = 5;
}
private int x = 0;
// Illustration: Illegal
private ForwardReference b = a.reference();
private ForwardReference a = new ForwardReference();
}
As you can see, Java allows you to reference a class variable in a class method, even if the declaration of the variable comes after the method. This is an example of a (legal) forward reference, and support for this is built into the Java compiler.
What you cannot do though, is declare a class variable 'a' that depends on another class variable 'b' that has not been declared yet. Dependent class variable declarations must appear in reverse order of their dependency.
On a tangent, Most, if not all IDE's will warn you if your code contains illegal reference errors.
Illegal forward references are covered in section 8.3.2.3 of the JLS.
It's basically just the order that things are read by the compiler, if you have
int c = 3
int a = b;
int b = 5;
the compiler will read it from top to bottom, so it will se the first line, which declares a variable 'c', and assigns it to 3, and that is fine, then it will encounter the second line, which declares a variable 'a', and then tries to assign it to 'b'.
But now, the compiler has a problem: What is this 'b' thing? It has only yet learned about 'c', and just recently 'a', but it has no knowledge anything called 'b', since to the compiler, it has not yet been declared. So then, since the compiler can't handle all the confusion, it stops, and leaves you to figure what you have done to anger it.
So, the forward reference part would be a reference to something that does not yet exist. Forward in time perhaps..
In simple terms it means referencing (accessing a variable, calling a function) that is further down in the code file.
static int x=getY();
static int y=5;
static int getY() { return y; }
x's value is set to the result of getY()
getY() is called before y's value is set to 5
x's value is therefore 0 (default integer)
y's value is 5
public class AnyCode {
void print() {
System.out.println("Value of j - " + j); // legal
System.out.println("Value of i - " + i); // legal
}
// CASE - 1
int k = i; // illegal
int i;
// CASE - 2
int l = j; // legal
static int m = j; // illegal
static int j;
// CASE - 3
A aObj = bObj; // illegal
B bObj = new B();
public static void main(String[] args) {
/*
Note :- here anyCode act as a local variable and get space on stack
whereas the object it is referring to is present on heap. And you
cannot forward reference a local variable.
*/
anyCode.print(); // 'Cannot find symbol' error
AnyCode anyCode = new AnyCode();
}
}
class A {
}
class B {
}
*********Refer CASE - 1*********
Forward referencing instance variable is not allowed as compiler is not sure of the type of value we are forward referencing or it might even be possible that no such variable exist.
Consider an example :-
int a = b;
boolean b = false;
If forward referencing is allowed in above case then it might create a havoc.
int a = b; // What is b? is it a primitive variable or a value or a object reference
in the above example i have decided not to declare b and now if such assignment were allowed by java, then it will be a nightmare.
**********Refer CASE - 2*********
Static variables are loaded before instance variables and hence forward referencing static variables and assigning them to instance variable is perfectly fine

Categories