30 Days of Java | Day 3

30 Days of Java | Day 3

·

2 min read

One-line if statements

If the if statement only has one statement you do not need braces, although it can be good to put them anyways.

int score = 250;

if (score > 100 && score <300) System.out.println("You got it!");

Variables in code blocs are not accessible in the outer space:

int score = 250;
if (score > 100 && score < 300) {
    int finalScore = score *2;
    System.out.println("Final Score is: " + finalScore);
}
// The following does not have access to finalScore
System.out.println("Final Score is: " + finalScore);

Ternary Operator

There is a short-hand if else, which is known as the ternary operator because it consists of three operands. This is the structure:

variable = (condition) ? expressionTrue :  expressionFalse;

Let's take a look at an example:

int score = 250;
if (score > 100 && score < 300) {
    System.out.println("You won!");
} else {
    System.out.println("You lose!");
}
// Ternary

int score = 250;
String finalScore = (score > 100 && score < 300) ? "You won!" : "You lose";
System.out.println(finalScore);

Switch Statements

we can use the switch statement instead of writing many if..else statements, .

This statement selects one of many code blocks to be executed based on the initial evaluation:

switch(expression) {
  case 1:
    // code block
    break;
  case 2:
    // code block
    break;
  default:
    // code block
}

The value of the expression is compared with the values of each case. If they match then it will be executed. However, you need a break statement to make sure that it doesn't execute the cases after the correct one as well. The default statement is optional and works like else statement.

int rank = 2;
switch (rank) {
  case 1:
    System.out.println("Gold medal winner!");
    break;
  case 2:
    System.out.println("Silver medal winner!");
    break;
  case 3:
    System.out.println("Bronze medal winner!");
    break;
  default:
    System.out.println("No medals for you!");
}
// Outputs "Silver medal winner!" (case 2)