Why is a colon operator used?
Question mark and colon in Java
- Use question marks and colon operators in Java
- Use nested question marks and colon operators in Java
This tutorial introduces the use of question marks and colon operators in Java and lists some sample code to help understand the subject.
The question mark and colon operators are collectively referred to as ternary operators in Java because they work with three operands.
It is the shorthand version of the instruction in Java and can be used as a one-line instruction for decision making. Let's look at some examples.
Use question marks and colon operators in Java
The ternary operator consists of three segments. The first is a conditional expression that returns a Boolean value. The second and third values are the values before and after the colon. It returns the value before the colon when the conditional expression is evaluated as. Otherwise the value is returned after. The syntax is below.
See the example below.
We can get the return value of any type from the ternary operator. In the following example, we pass string values and get a returned string value based on the condition.
The following example is a use case of the ternary operator in Java. We use this one-line conditional statement to check that the given string is in lowercase and convert it to uppercase if the string is in lowercase. Otherwise the original string is returned.
This is another use case of the ternary operator where we check whether the given integer is a positive integer or not and return a string value. See the example below.
Use nested question marks and colon operators in Java
In this example, we're using the nested ternary operator to see if we can do it like with the statement. Here we first check whether the given integer is a positive integer, then check whether it is between a given range and return a string value. See the example below.
Related Article - Java Operator
- Which films were almost entirely improvised
- The Minoans were the first civilization
- If log x 400 what is x
- According to which criteria are YouTubers paid
- What kind of wine is Stella Rosa
- What is a power shopper
- Is religion a construct of the mind
- What is an integer value
- What was the first article on Wikipedia
- A computer virus can infect itself
- Why is defense important to our survival?
- Why did Dooku not expose Palpatine
- What makes short stories so powerful
- Why is Gurdaas Maan a great singer
- What are some treatments for breathing problems
- Can Comedy Central Hurt Stephen Colbert Amazon
- What is the drinking age in the Czech Republic
- There are two auli
- What does learning material teach
- Which universities offer ASL interpreting degrees?
- Are cufflinks business casual clothing
- What is the ultimate goal of Judaism
- Music gets old
- What is your dream boat