Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring a variable inside of if/else construct

I am solving a basic Java string problem on CodingBat.com (extraFront).

The task is to, given a string of any length, return the two first characters repeated three times. This first example is what I ended up doing intuitively:

public String extraFront(String str) {

  if (str.length() <= 2){
    String front = str;
  }else{
    String front = str.substring(0,2);
  }
  return front+front+front;
}

Which gives me an error, front can not be resolved. I guessed that I needed to define the variable outside the loop, so I changed the code to the following, which works without errors:

public String extraFront(String str) {

  String front;

  if (str.length() <= 2){
    front = str;
  }else{
    front = str.substring(0,2);
  }
  return front+front+front;
}

What puzzles me is why this should make a difference, as the variable is going to declared anyway, will it not? Is this a peculiarity of how CodingBat handles the code, or is this actually an error? And if it is, why exactly is this incorrect code? And if it is not incorrect, is it bad style?

like image 726
zxz Avatar asked Jul 05 '26 01:07

zxz


1 Answers

What puzzles me is why this should make a difference, as the variable is going to declared anyway, will it not?

It's a matter of scoping. A variable is only visible within the block where it's declared. This has nothing to do with CodingBat - it's part of the Java language. From section 6.3 of the JLS:

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).
...
The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

I'd also urge you to learn about the conditional operator, which can help in these situations:

String front = str.length() <= 2 ? str : str.substring(0, 2);
like image 91
Jon Skeet Avatar answered Jul 06 '26 14:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!