Conditionals in Java
import java.util.Scanner;
public class guess {
static final int N = 42;
public static void main (String[] arg) {
int h = 0;
Scanner in = new Scanner(System.in);
System.out.print ("Guess the number ? ");
int v = in.nextInt();
if (v < 0) {
System.err.println ("Only positive numbers.");
return;
}
if (v == N)
System.out.println ("Well Done!");
else {
System.out.println ("Keep Trying!");
System.out.println ("The number is " + ((v < n) ? "HIGHER" : "LOWER"));
// As we failed, let's generate a hint
h = Math.abs (v - n);
System.out.print ("HINT : ");
if (h < 5) System.out.println ("TOO HOT!!!");
else if (h < 10) System.out.println ("HOT");
else if (h < 15) System.out.println ("WARM");
else System.out.println ("COLD");
}
}
}The Java version of our small program is, syntactically speaking,
practically the same as the C version. It’s just a bit more
verbose. The if statement takes the following
form:
if (condicion) SentenciaTrue else SentenciaFalseWhere a statement can be a single instruction, or a block of instructions between curly braces, as we already know.
Java offers a ternary operator with the classic syntax used by most languages that support this type of operator.
(condition) ? expressionTrue : expressionFalse;In this case, the ternary operator cannot be used as a statement or instruction and can only be used as an expression. That is, we cannot write expressions like:
(a < 10) ? System.out.println ("LOWER") : System.out.println("HIGHER");DID YOU KNOW…
The
errobject of theSystemclass is associated with the standard error outputstderr. Thus,System.err.printin Java is equivalent in C tofprintf (stderr,...
Java requires that variables be declared before they are used,
following the standard format of type variable [= value],
where the initial value assignment is optional.
I’M NEW
Java is an object-oriented language and does not provide functions like C. Most general-purpose functions that we find in C and other languages (such as
absin this case) are implemented as static methods of some class. In this case, the mathematical functions in Java (abs,cos,tan,…) are static methods of the classMathand therefore we have to execute them asMath.abs(number).The
Mathclass works on native types in a similar way to the C math library, not like the more formal OO model of Ruby.
Java offers a switch statement with the following
format:
switch (val) {
case CONTANTE1: instruction1
case CONTANTE2: instruction2
...
}In Java, break can be used to prematurely exit a case,
and it is necessary to prevent the cases defined below from being
executed, and the default case will be executed when none
of the other cases are met. In the previous example, if
val == CONSTANTE1, the instruction1 and
instruction2 will be executed. To avoid this behavior, it
is necessary to add a break statement at the end of each
case.
More modern versions of Java have introduced improvements to the
switch command:
- Java 8 allows the use of
Stringsin the cases in addition to integer values. - Java 14 introduces new features such as: returning a value using
yieldor the->operator, and allowing cases with multiple labels, and automatically terminating cases without needing to include thebreakstatement. Starting with Java 14, theswitchstatement can be used as an expression that returns parameters. - Java 17 adds the following additional functions: checking types,
guard cases which allow us to add additional conditions in each case,
and null conditions to handle
nullpointers.
As an example of all these features described above, in Java 17 you can write code like the following:
//Integer v = new Integer(11);
//String v = new String("Hello World");
//Boolean v = new Boolean (true);
Object v = null;
System.out.println (switch ((Object)v) {
case Boolean i -> "Is a Boolean";
case String s -> "Is a String";
case Integer i && ((i % 2) == 0) -> "Is an even number";
case null -> "Invalid Object";
default -> "What!?";
});DID YOU KNOW
There are different ways to read user input from Java. One of them is to use the
Scannerclass, which offers convenient methods for reading different data types. As it is aScannerclass, it offers many more facilities than the native methods offered by other languages. For example, we can specify which character (or regular expression) we want to use as a delimiter (by default it is the space), check the type of the next value without consuming it, etc… ThenextIntmethod attempts to read an integer from the user input and moves to the next value,nextdoes the same withStrings,nextLinewill read the whole line. Check the documentation to know all the options.
Java allows you to define constants using the keywords
static and final, and since they are static
values, they must be defined as members of a class, record, or
interface. We cannot declare a constant within a method, although we can
declare a final variable within a method that cannot be modified.
Something like a local constant. Another thing is whether that can be
useful in some case.
As is often the case, the convention for naming constants is to use
uppercase letters and separate words using the _
(underscore) character. For example:
class MiClase {
static final int MY_COOL_CONSTANT = 42;
static final double NUMBER_PI = 3.14159
(...)
}Within the MiClase class, we can use the constant
directly, exactly as we do in the example code. But we can also use the
constant from other modules (unless we declare it private within the
class) as follows:
System.out.println ("The value of PI is : " + MiClase.NUMERO_PI);Summary
- Supports
if ... [else if] ...[else] ... - Supports ternary operator
(cond) ? valor_Verdad : Valor_Falso - Supports booleans natively
- Supports
switch - Does not natively support constants (with
staticandfinal)