2

I wrote this code in the main:

if (startAmount>0) //create new cashier object with or without a start amount
    Cashier newCashier = new Cashier(startAmount);
else Cashier newCashier = new Cashier();

and got an compile error for the second and third lines:

Multiple markers at this line
    - Cashier cannot be resolved to a variable
    - Syntax error on token "newCashier", delete

and:

Multiple markers at this line
    - Cashier cannot be resolved to a variable
    - Syntax error, insert "AssignmentOperator Expression" to complete 
     Assignment
    - Syntax error, insert ";" to complete Statement

but when i write the code like this with brackets:

if (startAmount>0)//create new cashier object with or without a start amount
{
    Cashier newCashier = new Cashier(startAmount);
}
else{ Cashier newCashier = new Cashier();}

it seems to be okay, no compile errors. can someone help me understand why?

3
  • Which version of Java and what IDE you use? Commented Mar 31, 2014 at 14:19
  • 1
    remove the assignment, you don't use the variable newCashier anyway. Commented Mar 31, 2014 at 14:20
  • version:Version: Kepler Service Release 2 Commented Mar 31, 2014 at 14:26

2 Answers 2

3

Why are you creating shadow variable for newCachier reference, you could rather do this

Cashier newCashier = null;
if (startAmount>0) //create new cashier object with or without a start amount
    newCashier = new Cashier(startAmount);
else 
     newCashier = new Cashier();
Sign up to request clarification or add additional context in comments.

2 Comments

What is the difference between what you wrote and what i wrote? In both cases was created one object no?
what do you mean "shadow variable"? it will create only once dependent on the if statement
0

It's always better to add those curly braces. Cause you won't forget to add them when you extend your code, which leads to strange behavior otherwise.

I think your exception of the first might came cause you forgot to put your else statement in a new line, but I am not sure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.