Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nameless variable declaration - why does it work?

I am surprised to see this behaviour.

Is it a bug or something?

for(Object obj = new Object(), Integer = new Integer(300);
    obj.toString().length()>3;
    System.out.println("on object's loop")) {

} //causes an infinite loop (not foreach loop, of course)

above code compiles and run fine without any reference to new Integer(300). Why so?

I am only interested in knowing why Integer = new Integer(300); is okay without any reference.

like image 457
Sachin Verma Avatar asked Jul 11 '13 20:07

Sachin Verma


2 Answers

Object obj = new Object(), Integer = new Integer(300);

This creates two variables:

  1. obj of type Object, which gets assigned to new Object().
  2. Integer (yes, that's the name of the variable) also of type Object, which gets assigned to new Integer(300).

By the way this has nothing to do with the for-loop; that line would compile fine on its own. Now, if that , was really a ;, it would be a different story.

In general, we can construct valid statements of the form:

Type t1 = ..., t2 = ..., t3 = ..., ...;

which is equivalent to

Type t1 = ...;
Type t2 = ...;
Type t3 = ...;
...
like image 183
arshajii Avatar answered Oct 01 '22 11:10

arshajii


I think he's asking why Integer = new Integer(300) works. – arshajii 2 mins ago

Integer is valid identifier name and its type is Object because of

Object obj = new Object(), Integer = new Integer(300);

Which is equivalent to

int a=2, b=4;

obj.toString() prints the String (consisting classname and hashcode), which has length > 3 so the infinite loop

like image 25
jmj Avatar answered Oct 01 '22 11:10

jmj