Skip to main content

Short Hand If Else Statement


Introduction:
This tutorial page will talk about the short hand version of an if else statement.

Important:
I highly recommend you read through the If Else tutorial page before reading this tutorial.

How is the short hand if else statement structured?
The short hand version of an if else statement is used through a couple of symbols, here is the layout of the statement;
Action (setting a variable, function or method, etc.) - condition - "?" - What to do if the condition is true - ":" - What to do if the condition is false.

When is a short hand if else statement used?
This can be used for simple if else statements which only perform one line of script for each condition while still having the following benefits;
- Saves space
- Can make the script look more organised
- Makes the script easier to read

Example:
Here is an example of giving the output of "Hey" if the variable is true, and "Hi" if the variable is false;

  1. boolean klo = true;
  2. System.out.println(klo ? "Hey" : "Hi");

Which gives the output:

Hey

And here is an example of setting the value of an integer in relative to a boolean variable ("klo"):

  1. boolean klo = true;
  2. int lok = klo ? 1 : 2;
  3. System.out.println(lok);

Which gives the output:

1

Finished!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.