Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Ternary Operator | Deep Java Structure
Java Classes and Core Mechanics
セクション 1.  6
single

single

bookTernary Operator

メニューを表示するにはスワイプしてください

How to Shorten an If-Else Statement in Java

The if-statement may not always look elegant, but Java provides a faster and more convenient way to check conditions. It is called the ternary operator, and it has the following syntax:

condition ? expression_for_true : expression_for_false

First, we define a condition, such as 10 > 5, followed by a question mark ?. If the condition is true, the true expression is executed, for example System.out.println("That's true");. If the condition is false, the false expression runs instead, such as System.out.println("That's not true");.

Let’s look at a more practical example:

Main.java

Main.java

copy
12345678
package com.example; public class Main { public static void main(String[] args) { System.out.println(10 > 5 ? "That's true" : "That's false"); System.out.println(5 > 6 ? "That's true" : "That's false"); } }

You may have noticed that the ternary operator is used inside the System.out.println() statement. This is its main advantage—it helps reduce the amount of code, especially in output statements.

The ternary operator can also be used when initializing or returning values. You’ll learn more about returning values in the next section when studying methods.

Here’s an example of using the ternary operator during initialization:

Main.java

Main.java

copy
12345678910
package com.example; public class Main { public static void main(String[] args) { final int a = 10 > 2 ? 5 : 2; final int b = 10 < 2 ? 5 : 2; System.out.println("Variable 'a' has value: " + a); System.out.println("Variable 'b' has value: " + b); } }

Below is an example code where the ternary operator is replaced with a regular if-statement to help you better understand how it works:

Main.java

Main.java

copy
1234567891011121314151617181920
package com.example; public class Main { public static void main(String[] args) { int a = 0; int b = 0; if (10 > 2) { a = 5; } else { a = 2; } if (10 < 2) { b = 5; } else { b = 2; } System.out.println("Variable 'a' has value: " + a); System.out.println("Variable 'b' has value: " + b); } }

The result is the same, but you can see how much space we save by using the ternary operator.

タスク

スワイプしてコーディングを開始

  1. Write a code that prints "The string contains Florida" if the string contains the word Florida, or "Florida is not found" if it does not.

  2. Use the ternary operator to practice with it.

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  6
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt