Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Bootcamps Get Certified Upgrade Teachers Spaces Bootcamps
   ❮     
     ❯   

Java Tutorial

Java HOMEJava IntroJava Get StartedJava SyntaxJava OutputJava CommentsJava VariablesJava Data TypesJava Type CastingJava OperatorsJava StringsJava MathJava BooleansJava If...ElseJava SwitchJava While LoopJava For LoopJava Break/ContinueJava Arrays

Java Methods

Java MethodsJava Method ChallengeJava Method ParametersJava Method OverloadingJava ScopeJava Recursion

Java Classes

Java OOPJava Classes/ObjectsJava Class AttributesJava Class MethodsJava Class ChallengeJava ConstructorsJava this KeywordJava ModifiersJava EncapsulationJava Packages / APIJava InheritanceJava PolymorphismJava super KeywordJava Inner ClassesJava AbstractionJava InterfaceJava AnonymousJava EnumJava User InputJava Date

Java Errors

Java ErrorsJava DebuggingJava ExceptionsJava Multiple ExceptionsJava try-with-resources

Java File Handling

Java FilesJava Create FilesJava Write FilesJava Read FilesJava Delete Files

Java I/O Streams

Java I/O StreamsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriter

Java Data Structures

Java Data StructuresJava CollectionsJava ListJava ArrayListJava LinkedListJava List SortingJava SetJava HashSetJava TreeSetJava LinkedHashSetJava MapJava HashMapJava TreeMapJava LinkedHashMapJava IteratorJava Algorithms

Java Advanced

Java Wrapper ClassesJava GenericsJava AnnotationsJava RegExJava ThreadsJava LambdaJava Advanced Sorting

Java Projects

Java Projects

Java How To's

Java How Tos

Java Reference

Java ReferenceJava KeywordsJava String MethodsJava Math MethodsJava Output MethodsJava Arrays MethodsJava ArrayList MethodsJava LinkedList MethodsJava HashMap MethodsJava Scanner MethodsJava File MethodsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriterJava Iterator MethodsJava Collections MethodsJava System MethodsJava Errors & Exceptions

Java Examples

Java ExamplesJava VideosJava CompilerJava ExercisesJava QuizJava Code ChallengesJava ServerJava SyllabusJava Study PlanJava Interview Q&AJava Certificate


JavaIf ... Else


Java Conditions and If Statements

Conditions and if statements let you control the flow of your program - deciding which code runs, and which code is skipped.

Think of it like real life:If it rains, take an umbrella. Otherwise, do nothing.

Everyif statement needs a condition that results intrue orfalse.

This meansif statements work hand-in-hand withboolean values:

Example

boolean isRaining = true;if (isRaining) {  System.out.println("Bring an umbrella!");}

Try it Yourself »

Most often, conditions are created using comparison operators, like the ones below:

  • Less than:a < b
  • Less than or equal to:a <= b
  • Greater than:a > b
  • Greater than or equal to:a >= b
  • Equal to:a == b
  • Not equal to:a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

  • Useif to specify a block of code to be executed, if a specified condition is true
  • Useelse to specify a block of code to be executed, if the same condition is false
  • Useelse if to specify a new condition to test, if the first condition is false
  • Useswitch to specify many alternative blocks of code to be executed

The if Statement

Theif statement specifies a block of code to be executed if a condition istrue:

Syntax

if (condition) {  // block of code to be executed if the condition is true}

Thecondition inside theif statement must result in aboolean value - it can be either a boolean expression (likex > y) or a boolean variable (likeisLightOn).

Also note thatif is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition istrue, print some text:

Example

if (20 > 18) {  System.out.println("20 is greater than 18");}

Try it Yourself »

You can also compare variables:

Example

int x = 20;int y = 18;if (x > y) {  System.out.println("x is greater than y");}

Try it Yourself »

Example explained

In the example above we use two variables,x andy, to test whether x is greater than y (using the> operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

Comparison is also often used to check if two values areequal, using the== operator:

Example

int x = 20;int y = 20;if (x == y) {  System.out.println("x is equal to y");}

Try it Yourself »

Here the conditionx == y is true, because bothx andy are 20, so the message "x is equal to y" is printed.



Using Boolean Variables

You can also test boolean variables directly in anif statement:

Example

boolean isLightOn = true;if (isLightOn) {  System.out.println("The light is on.");}

Try it Yourself »

Note: Writingif (isLightOn) is the same as writingif (isLightOn == true), but shorter and easier to read.

Here is the same example with the valuefalse to see that the program continues even when the code block does not run:

Example

boolean isLightOn = false;if (isLightOn) {  System.out.println("The light is on.");  // This will not be printed}System.out.println("This line runs no matter what, because it is outside the if statement.");

Try it Yourself »


If Without Braces

If anif statement has only one line of code, you can write it without curly braces{ }:

Example

if (20 > 18)  System.out.println("20 is greater than 18");

Try it Yourself »

Potential Problem

Without braces, only thefirst line after theif belongs to it. Any other lines will run no matter what, which can lead to unexpected results:

Example

int x = 20;int y = 18;if (x > y)  System.out.println("x is greater than y");  // Belongs to if  System.out.println("This line runs no matter what (not part of the if statement)");// Output:// x is greater than y// This line runs no matter what (not part of the if statement)

Try it Yourself »

The Safe Way

To avoid mistakes, always use curly braces{ }. This makes it clear which lines belong to theif statement:

Example

int x = 20;int y = 18;if (x > y) {  System.out.println("x is greater than y");  System.out.println("Both lines are part of the if");}// Some code outside ifSystem.out.println("I am outside if, not part of if!");

Try it Yourself »

Tip: Always using braces{ } makes your code clearer, easier to read, and prevents subtle bugs.


In the next chapters, you will also learn how to handleelse (when the condition is false),else if (to test multiple conditions), andswitch (to handle many possible values).





×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

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 ourterms of use,cookies andprivacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.

-->
[8]ページ先頭

©2009-2026 Movatter.jp