Global Trend Radar
Web: www.w3schools.com US web_search 2026-05-06 16:48

Javaの短縮形If...Else(三項演算子)

原題: Java Short Hand If...Else (Ternary Operator) - W3Schools

元記事を開く →

分析結果

カテゴリ
AI
重要度
54
トレンドスコア
18
要約
Javaの三項演算子は、条件に基づいて値を選択するための短縮形のif-else文です。構文は「条件 ? 値1 : 値2」で、条件が真の場合は値1が、偽の場合は値2が返されます。この演算子を使用することで、コードを簡潔にし、可読性を向上させることができます。
キーワード
Java Short Hand If...Else (Ternary Operator) Menu Search field × See More Sign In ★ +1 Get Certified Upgrade Teachers Spaces Bootcamps Get Certified Upgrade Teachers Spaces Bootcamps ❮ ❯ HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS Java Tutorial Java HOME Java Intro Java Get Started Java Syntax Syntax Statements Code Challenge Java Output Print Text Print Numbers Code Challenge Java Comments Java Variables Variables Print Variables Multiple Variables Identifiers Constants (Final) Real-Life Examples Code Challenge Java Data Types Data Types Numbers Booleans Characters Real-Life Example Non-primitive Types The var Keyword Code Challenge Java Type Casting Java Operators Operators Arithmetic Assignment Comparison Logical Precedence Code Challenge Java Strings Strings Concatenation Numbers and Strings Special Characters Code Challenge Java Math Java Booleans Booleans Real-Life Example Code Challenge Java If...Else if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge Java Switch Switch Code Challenge Java While Loop While Loop Do/While Loop Real-Life Examples Code Challenge Java For Loop For Loop Nested Loops For-Each Loop Real-Life Examples Code Challenge Java Break/Continue Java Arrays Arrays Loop Through an Array Real-Life Examples Multidimensional Arrays Code Challenge Java Methods Java Methods Java Method Challenge Java Method Parameters Parameters Return Values Code Challenge Java Method Overloading Java Scope Java Recursion Java Classes Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers Access Modifiers Non-Access Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java Enum Enums Enum Constructor Java User Input Java Date Java Errors Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources Java File Handling Java Files Java Create Files Java Write Files Java Read Files Java Delete Files Java I/O Streams Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter Java Data Structures Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms Java Advanced Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting Java Projects Java Projects Java Cert Java Certificate Java How To's Java How Tos How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum Java Reference Java Reference Java Keywords assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String Methods charAt() codePointAt() codePointBefore() codePointCount() compareTo() compareToIgnoreCase() concat() contains() contentEquals() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() isEmpty() join() lastIndexOf() length() matches() offsetByCodePoints() regionMatches() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toCharArray() toLowerCase() toString() toUpperCase() trim() valueOf() Java Math Methods abs() acos() addExact() asin() atan() atan2() cbrt() ceil() copySign() cos() cosh() decrementExact() exp() expm1() floor() floorDiv() floorMod() getExponent() hypot() IEEEremainder() incrementExact() log() log10() log1p() max() min() multiplyExact() negateExact() nextAfter() nextDown() nextUp() pow() random() rint() round() scalb() signum() sin() sinh() sqrt() subtractExact() tan() tanh() toDegrees() toIntExact() toRadians() ulp() Java Output Methods print() printf() println() Java Arrays Methods compare() equals() sort() fill() length Java ArrayList Methods add() addAll() clear() clone() contains ensureCapacity() forEach() get() indexOf() isEmpty() iterator() lastIndexOf() listIterator() remove() removeAll() removeIf() replaceAll() retainAll() set() size() sort() spliterator() subList() toArray() trimToSize() Java LinkedList Methods add() addAll() clear() clone() contains forEach() get() getFirst() getLast() indexOf() isEmpty() iterator() lastIndexOf() listIterator() remove() removeAll() removeFirst() removeIf() removeLast() replaceAll() retainAll() set() size() sort() spliterator() subList() toArray() Java HashMap Methods clear() clone() compute() computeIfAbsent() computeIfPresent() containsKey() containsValue() entrySet() forEach() get() getOrDefault() isEmpty() keySet() merge() put() putAll() putIfAbsent() remove() replace() replaceAll() size() values() Java Scanner Methods close() delimiter() findInLine() findWithinHorizon() hasNext() hasNextBoolean() hasNextByte() hasNextDouble() hasNextFloat() hasNextInt() hasNextLine() hasNextLong() hasNextShort() locale() next() nextBoolean() nextByte() nextDouble() nextFloat() nextInt() nextLine() nextLong() nextShort() radix() reset() useDelimiter() useLocale() useRadix() Java File Methods Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter Java Iterator Methods Java Collections Methods Java System Methods Java Errors & Exceptions Java Examples Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Short Hand If...Else (Ternary Operator) ❮ Previous Next ❯ Short Hand if...else There is also a short-hand if else , which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements: Syntax variable = ( condition ) ? expressionTrue : expressionFalse ; Instead of writing: Example int time = 20; if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); } Try it Yourself » You can simply write: Example int time = 20; String result = (time < 18) ? "Good day." : "Good evening."; System.out.println(result); Try it Yourself » You can also use the ternary operator directly inside System.out.println() without a temporary variable: Example int time = 20; System.out.println((time < 18) ? "Good day." : "Good evening."); Try it Yourself » Nested Ternary (Optional) You can nest ternary operators to handle more than two possible outcomes, but this can make your code harder to read: Example int time = 22; String message = (time < 12) ? "Good morning." : (time < 18) ? "Good afternoon." : "Good evening."; System.out.println(message); Try it Yourself » Tip: Use the ternary operator for short, simple choices. For longer or more complex logic, the regular if...else is easier to read. ❮ Previous Next ❯ ★ +1 Sign in to track progress COLOR PICKER REMOVE ADS PLUS SPACES GET CERTIFIED FOR TEACHERS BOOTCAMPS CONTACT US × Contact Sales If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected] Report Error If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected] Top Tutorials HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial Top References HTML Reference CSS Reference JavaScript Reference SQL Reference Python Reference W3.CSS Reference Bootstrap Reference PHP Reference HTML Colors Java Reference AngularJS Reference jQuery Reference Top Examples HTML Examples CSS Examples JavaScript Examples How To Examples SQL Examples Python Examples W3.CSS Examples Bootstrap Examples PHP Examples Java Examples XML Examples jQuery Examples Get Certified HTML Certificate CSS Certificate JavaScript Certificate Front End Certificate SQL Certificate Python Certificate PHP Certificate jQuery Certificate Java Certificate C++ Certificate C# Certificate XML Certificate     FORUM ABOUT ACADEMY W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use , cookies and privacy policy . Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS . -->

類似記事(ベクトル近傍)