MacMusic  |  PcMusic  |  440 Software  |  440 Forums  |  440TV  |  Zicos
statement
Recherche

Deciding and iterating with Java statements

mardi 23 juillet 2024, 11:00 , par InfoWorld
Java applications evaluate expressions in the context of statements, which are used for tasks such as declaring a variable, making a decision, or iterating over statements. We can write either simple or compound statements:

A simple statement is a single standalone instruction for performing a task; it must be terminated with a semicolon character (;).

A compound statement is a sequence of simple and other compound statements located between open- and close-brace characters ({...}), which delimit the compound statement’s boundaries. Compound statements can be empty, will appear wherever simple statements appear, and are alternatively known as blocks. A compound statement is not terminated with a semicolon.

In this tutorial, you’ll learn how to use statements in your Java programs. You can use statements such as if, if-else, switch, for, and while to declare variables and specify expressions, make decisions, iterate (or loop) over statements, break and continue iteration, and more.

What you’ll learn in this Java tutorial

How to write declaration statements
How to write assignment statements
About the decision statements: if, if-else, and switch
About loop statements: for, while, and do-while
What are breaking statements in Java?
What are continue statements in Java?
What are empty statements in Java?
Example of statements in a Java program

download
Get the code
Download the source code for example applications in this tutorial. Created by Jeff Friesen.

How to write declaration statements in Java
In a previous article, I introduced variables as a way to store values in your Java code and explained that they must be declared before you can use them. Because a variable declaration is a standalone island of code, it’s effectively a statement—a simple statement, to be exact. All of these are variable declaration statements:

int age = 25;
float interest_rate;
char[] text = { 'J', 'a', 'v', 'a' };
String name;

A variable declaration minimally consists of a type name, optionally followed by a sequence of square-bracket pairs, followed by a name, optionally followed by a sequence of square-bracket pairs, and terminated with a semicolon. A variable may also be explicitly initialized when it is declared.

How to write assignment statements in Java
Now consider the assignment statement, which is closely related to the variable declaration statement. An assignment statement assigns a value (possibly a reference to an array or a reference to an object) to a variable. Here are some examples:

age = 30;
interest_rate = 4.0F;
age += 10;
text[1] = 'A';
text[2] = 'V';
text[3] = 'A';
name = 'John Doe';

An assignment statement is an example of an expression statement, which is an expression that may be used as a statement if it is followed with a semicolon. The following expressions also qualify as expression statements:

Preincrement (e.g., ++x;)
Predecrement (e.g., --y;)
Postincrement (e.g., x++;)
Postdecrement (e.g., y--;)
Method call (e.g., System.out.println('Hello');)
Object creation (e.g., new String('ABC');)

Examples of variable declarations and expression statements

You can use jshell to experiment with variable declarations and expression statements. Here are some examples to get you started (see “Learn Java from the ground up” for an introduction to jshell):

jshell> int age = 25
age ==> 25

jshell> float interest_rate
interest_rate ==> 0.0

jshell> char[] text = { 'J', 'a', 'v', 'a' }
text ==> char[4] { 'J', 'a', 'v', 'a' }

jshell> String name
name ==> null

jshell> age = 30
age ==> 30

jshell> interest_rate = 4.0F
interest_rate ==> 4.0

jshell> age += 10
$7 ==> 40

jshell> text[1] = 'A'
$8 ==> 'A'

jshell> text[2] = 'V'
$9 ==> 'V'

jshell> text[3] = 'A'
$10 ==> 'A'

jshell> name = 'John Doe'
name ==> 'John Doe'

jshell> text
text ==> char[4] { 'J', 'A', 'V', 'A' }

jshell> age++
$13 ==> 40

jshell> age
age ==> 41

Notice that age++ doesn’t appear to have accomplished anything. Here, you see that 40 was assigned to the scratch variable $13. However, the postincrement operator performs the increment after returning the current value. (Actually, it stores the current value somewhere, performs the increment, and then returns the stored value.) Entering age proves that age contains 41, the result of the postincrement operation.

The Java Shell provides various commands and features to simplify working with snippets. For example, the /list command shows all snippets that have been entered in the current session:

jshell> /list

1: int age = 25;
2: float interest_rate;
3: char[] text = { 'J', 'a', 'v', 'a' };
4: String name;
5: age = 30
6: interest_rate = 4.0F
7: age += 10
8: text[1] = 'A'
9: text[2] = 'V'
10: text[3] = 'A'
11: name = 'John Doe'
12: text
13: age++
14: age

The number in the left column uniquely identifies a snippet. You can use this number to re-execute a snippet, list the snippet, drop (delete) a snippet, and so on:

jshell> /12
text
text ==> char[4] { 'J', 'A', 'V', 'A' }

jshell> /list 13

13: age++

jshell> /drop 7
| dropped variable $7

jshell> /list

1: int age = 25;
2: float interest_rate;
3: char[] text = { 'J', 'a', 'v', 'a' };
4: String name;
5: age = 30
6: interest_rate = 4.0F
8: text[1] = 'A'
9: text[2] = 'V'
10: text[3] = 'A'
11: name = 'John Doe'
12: text
13: age++
14: age
15: text

Here, we’ve entered /12 to re-execute snippet #12, which outputs the contents of text. We then entered /list 13 to list snippet #13, which increments age. Next, we entered /drop 7 to delete snippet #7 (no more age += 10 snippet). Finally, we entered /list to re-list all snippets. Notice that snippet #7 has been removed, and a snippet #15 has been added thanks to the /12 command.

About the decision statements: if, if-else, switch

Decision statements let applications choose between multiple paths of execution. For example, if a salesperson sells more than 500 items this month, give the salesperson a bonus. Also, if a student’s grade on an algebra test is greater than 85 percent, congratulate the student for doing well; otherwise, recommend that the student study harder for the next test.

Java supports the if, if-else, and switch decision statements, along with the switch expressions feature.

Writing if statements

The simplest of Java’s decision statements is the if statement, which evaluates a Boolean expression and executes another statement when this expression evaluates to true. The if statement has the following syntax:

if (Boolean expression)
statement

The if statement starts with reserved word if and continues with a parenthesized Boolean expression, which is followed by the statement to execute when the Boolean expression evaluates to true.

The following example demonstrates the if statement. When the age variable contains a value of 55 or greater, if executes System.out.println(...); to output the message:

if (age >= 55)
System.out.println('You are or were eligible for early retirement.');

Many developers prefer to wrap any simple statement that follows the if statement in braces, effectively converting it to an equivalent compound statement:

if (age >= 55)
{
System.out.println('You are or were eligible for early retirement.');
}

Although the braces clarify what is being executed by the if statement, I believe that the indentation provides this clarity, and that the braces are unnecessary.

Example if statements in jshell

Let’s try out this example usingjshell. Restart jshell and then introduce an age variable (of type int) that’s initialized to 55:

jshell> int age = 55

Next, enter the first example if statement (without the curly braces surrounding its body):

jshell> if (age >= 55)...> System.out.println('You are or were eligible for early retirement.');

You are or were eligible for early retirement.

jshell>

Notice that the jshell> prompt changes to the...> continuation prompt when you enter a multiline snippet. Pressing Enter after the last snippet line causes jshell to immediately execute the snippet.

Execute /list to list all snippets. I observe that the if statement snippet has been assigned 2 in my session. Executing /2 causes jshell to list and then execute this snippet, and the same message is output.

Now, suppose you assign 25 to age and then re-execute /2 (or the equivalent snippet number in your session). This time, you should not observe the message in the output.

Writing if-else statements

The if-else statement evaluates a Boolean expression and executes a statement. The statement executed depends on whether the expression evaluates to true or false. Here’s the syntax for the if-else statement:

if (Boolean expression)
statement1
else
statement2

The if-else statement is similar to the if statement, but it includes the reserved word else, followed by a statement to execute when the Boolean expression is false.

The following example demonstrates an if-else statement that tells someone who is less than 55 years old how many years are left until early retirement:

if (age >= 55)
System.out.println('You are or were eligible for early retirement.');
else
System.out.println('You have ' + (55 - age) + ' years to go until early retirement.');


The conditional operator

The conditional operator (?:) is similar to an if-else statement. However, this operator cannot be used to execute alternate statements. Instead, it can only return one of two values of the same type. (The conditional operator is also sometimes known as the ternary operator.)

Chaining if-else statements

Java lets you chain multiple if-else statements together for situations where you need to choose one of multiple statements to execute:

if (Boolean expression1)
statement1
else
if (Boolean expression2)
statement2
else...
else
statementN

Chaining works by executing a subsequent if-else statement whenever the current if statement’s Boolean expression evaluates to false. Consider this demonstration:

if (temperature < 0.0)
System.out.println('freezing');
else
if (temperature > 100.0)
System.out.println('boiling');
else
System.out.println('normal');

The first if-else statement determines if temperature‘s value is negative. If so, it executes System.out.println('freezing');. If not, it executes a second if-else statement.

The second if-else statement determines if temperature‘s value is greater than 100. If so, it executes System.out.println('boiling');. Otherwise, it executes System.out.println('normal');.

The dangling-else problem

When if and if-else are used together, and the source code isn’t properly indented, it can be difficult to determine which if associates with the else. You can see the problem in the code below:

int x = 0;
int y = 2;
if (x > 0)
if (y > 0)
System.out.println('x > 0 and y > 0');
else
System.out.println('x 0 and y > 0');
else
System.out.println('x 0 and y > 0');
}
else
System.out.println('x prompt to run the application. When you finish with the application, enter q and you’ll be returned to the jshell> prompt.

Conclusion
Along with Java expressions and operators, statements are the workhorses of a Java application. Mastering these three basic language features gives you a solid foundation for exploring more advanced aspects of programming with Java. In this article, you’ve learned about Java statements and how to use them in your Java programs.

Jump to: Classes and objects in Java.
https://www.infoworld.com/article/2245414/java-101-deciding-and-iterating-with-java-statements.html

Voir aussi

News copyright owned by their original publishers | Copyright © 2004 - 2024 Zicos / 440Network
Date Actuelle
dim. 22 déc. - 13:35 CET