Variable declaration in Java – if clause

if(someCondition)
if(someCondition)
  int a=10;//Compilation Error
else if(SomeOtherCondition){
int b=10;//no compilation Error
}

Why did this happen Why do compile errors occur in the first case If I put parentheses, there is no compilation error, but if statement parentheses are optional if it is a statement

Solution

You need to define the scope of int a in the if statement and define it with curly braces {}

if(someCondition){
  int a=10; // works fine
}else if(SomeOtherCondition){
  int b=10; //works fine
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>