• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan Question - doubt

 
Agathian Thangavelu
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all , Help mw following code.
class A {
public static void main (String[] args) {
int i = 0,j = 0,m = 0,n = 0,p; <<<<------
label1:
try {
do {
m++;
try {
p = i + j + m + n;
if (p>=5) break label1;
n++;
} finally {i++;}
} while (m++ < 2);
} finally {j++;}
System.out.print(i + "," + j + "," + m + "," + n);
}
}

Above code, No need of initilize the local varible p?
I thought it will compiler error,
Thanks in Advance,
Aga
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Prog Cert forum. Please continue the discussion there.
 
Jay Ashar
Ranch Hand
Posts: 208
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it gives compiler error only if you try to access it before initializing it. Here you are initializing it and then trying to use it so it should work fine.
 
Ruff Young
Ranch Hand
Posts: 513
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your case, it seemed that the variable 'p' didn't initialized at first. However it shows that 'p' is initialized as "p=i+j+m+n" prior to using it in the main block.
When you declare a variable in main or method block, you have to initialize it before using it in main or method block. Otherwise the compiler will complain it.

//
...
p = i + j + m + n; // initialize
if (p>=5) break label1; // This line is first time using the variable 'p'
...
//
One more thing, although you declare a variable 'x', it will compile ok if you don't use it at all.
 
Agathian Thangavelu
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all, Now i understand.
Aga
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic