• Post Reply Bookmark Topic Watch Topic
  • New Topic

what an empty curly braces will do in an if statement  RSS feed

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i created a class and a constructor for the class. then i used getters and setters.
in the setters i'm trying to write a line that will be -

if (num < 0|| num>120) {
dont change value and do nothing
}
else{
num1 = num
}
how can i do this ? i tried to put an empty curly braces but it gives me an error.
 
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What was the error? One approach would be to negate the condition, and thus not have an else branch:
 
Dan D'amico
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my mistake . it didnt give me an error . its ok .
but will it work ? it will do nothing if i put empty curly braces ?

and i understand . yea thats will work too.
 
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dan D'amico wrote:it will do nothing if i put empty curly braces ?

Yes it will do nothing. If you do go down this route rather than taking Ulf's suggestion I would suggest you add a comment to the empty braces explaining why they are empty. Otherwise at some future time you (or somebody else) will look at the code and wonder why there is an empty code block.
 
Dan D'amico
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes . ok. and actually i liked more what Ulf's suggested. i just wanted to know what empty curly braces will do.
thanks.
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also to this - although there could be some argument about it being good style or not:
 
Dan D'amico
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok. thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!