Sunday, May 28, 2017

Introduction to Java programming, Part-1 (10)

Conditional operators and control statements


In this section, you learn about the various statements and operators you can use to tell your Java programs how you want them to act based on different input.

Relational and conditional operators

The Java language gives you operators and control statements that you can use to make decisions in your code. Most often, a decision in code starts with a Boolean expression— that is, one that evaluates to either true or false. Such expressions use relational operators, which compare one operand to another, and conditional operators.
Table 3 lists the relational and conditional operators of the Java language.
Table 3. Relational and conditional operators
OperatorUsageReturns true if...
>a > ba is greater than b
>=a >= ba is greater than or equal to b
<a < ba is less than b
<=a <= ba is less than or equal to b
==a == ba is equal to b
!=a != ba is not equal to b
&&a && ba and b are both true, conditionally evaluates b (if a is false, b is not evaluated)
||a || ba or b is true, conditionally evaluates b (if a is true, b is not evaluated)
!!aa is false
&a & ba and b are both true, always evaluates b
|a | ba or b is true, always evaluates b
^a ^ ba and b are different

The if statement

Now that you have a bunch of operators, it's time to use them. This code shows what happens when you add some logic to the Person object's getHeight() accessor:
public int getHeight() {
  int ret = height;
  // If locale of the computer this code is running on is U.S.,
  if (Locale.getDefault().equals(Locale.US))
    ret /= 2.54;// convert from cm to inches
  return ret;
}


In the event that the present district is in the United States (where the metric framework isn't being used), it may bode well to change over the inner estimation of stature (in centimeters) to inches. This (to some degree thought up) case outlines the utilization of the if explanation, which assesses a Boolean expression inside brackets. On the off chance that that expression assesses to genuine, the program executes the following explanation. 
For this situation, you just need to execute one explanation if the Locale of the PC the code is running on is Locale.US. In the event that you have to execute more than one proclamation, you can utilize wavy supports to frame a compound articulation. A compound explanation bunches numerous announcements into one — and compound articulations can likewise contain other compound proclamations.

Variable scope

Every variable in a Java application has scope, or localized namespace, where you can access it by name within the code. Outside that space the variable is out of scope, and you get a compile error if you try to access it. Scope levels in the Java language are defined by where a variable is declared, as shown in Listing 7.
Listing 7. Variable scope
public class SomeClass {
  private String someClassVariable;
  public void someMethod(String someParameter) {
    String someLocalVariable = "Hello";
    if (true) {
      String someOtherLocalVariable = "Howdy";
    }
    someClassVariable = someParameter; // legal
    someLocalVariable = someClassVariable; // also legal
    someOtherLocalVariable = someLocalVariable;// Variable out of scope!
  }
  public void someOtherMethod() {
    someLocalVariable = "Hello there";// That variable is out of scope!
  }
}
Within SomeClasssomeClassVariable is accessible by all instance (that is, nonstatic) methods. WithinsomeMethodsomeParameter is visible, but outside of that method it isn't, and the same is true forsomeLocalVariable. Within the if block, someOtherLocalVariable is declared, and outside of that ifblock it's out of scope. For this reason, we say that Java has block scope, because blocks (delimited by {and }) define the scope boundaries.
Scope has many rules, but Listing 7 shows the most common ones. Take a few minutes to familiarize yourself with them.

The else statement

Sometimes in a program's control flow, you want to take action only if a particular expression fails to evaluate to true. That's when else comes in handy:
public int getHeight() {
  int ret;
  if (gender.equals("MALE"))
    ret = height + 2;
  else {
    ret = height;
    Logger.getLogger("Person").info("Being honest about height...");
  }
  return ret;
}
The else statement works the same way as if, in that the program executes only the next statement that it encounters. In this case, two statements are grouped into a compound statement (notice the curly braces), which the program then executes.
You can also use else to perform an additional if check:
if (conditional) {
  // Block 1
} else if (conditional2) {
  // Block 2
} else if (conditional3) {
  // Block 3
} else {
  // Block 4
} // End
If conditional evaluates to trueBlock 1 is executed and the program jumps to the next statement after the final curly brace (which is indicated by // End). If conditional does not evaluate to true, thenconditional2 is evaluated. If conditional2 is true, then Block 2 is executed, and the program jumps to the next statement after the final curly brace. If conditional2 is not true, then the program moves on to conditional3, and so on. Only if all three conditionals fail is Block 4 executed.

The ternary operator

The Java language provides a handy operator for doing simple if / else statement checks. This operator's syntax is:
(conditional) ? statementIfTrue : statementIfFalse;
If conditional evaluates to truestatementIfTrue is executed; otherwise, statementIfFalse is executed. Compound statements are not allowed for either statement.
The ternary operator comes in handy when you know that you need to execute one statement as the result of the conditional evaluating to true, and another if it doesn't. Ternary operators are most often used to initialize a variable (such as a return value), like so:
public int getHeight() {
  return (gender.equals("MALE")) ? (height + 2) : height;
}
The parentheses following the question mark aren't strictly required, but they do make the code more readable.
Previous Post
Next Post

post written by:

0 coment�rios: