0% found this document useful (0 votes)
12 views

java basics-páginas-2

Uploaded by

Johnson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

java basics-páginas-2

Uploaded by

Johnson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

double ⊕ double ⇒ double

int Division
It is important to take note int division produces an int, i.e., int / int ⇒ int, with the result truncated. For example, 1/2 ⇒ 0 (int), but 1.0/2.0 ⇒ 0.5 (double
/ double ⇒ double).

Same-Type Operands of byte, short, char: Convert to int


If BOTH operands are byte, short or char, the binary operations are carried out in int, and evaluate to a value of int. A char is treated as an integer of its underlying
Unicode number in the range of [0, 65535]. That is,
byte ⊕ byte ⇒ int ⊕ int ⇒ int, where ⊕ denotes a binary arithmetic operators such as +, -, *, /, %.
short ⊕ short ⇒ int ⊕ int ⇒ int
char ⊕ char ⇒ int ⊕ int ⇒ int

Take note that NO arithmetic operations are carried out in byte, short or char.

For examples,

byte b1 = 5, b2 = 9, b3;
// byte + byte -> int + int -> int
b3 = b1 + b2; // error: RHS is "int", cannot assign to LHS of "byte"
b3 = (byte)(b1 + b2); // Need explicit type casting (to be discussed later)

However, if compound arithmetic operators (+=, -=, *=, /=, %=) (to be discussed later) are used, the result is automatically converted to the LHS. For example,

byte b1 = 5, b2 = 9;
b2 += b1; // Result in "int", but automatically converted back to "byte"

Mixed-Type Arithmetic Operations


If the two operands belong to different types, the value of the smaller type is promoted automatically to the larger type (known as implicit type-casting). The operation is then
carried out in the larger type, and evaluated to a value in the larger type.
byte, short or char is first promoted to int before comparing with the type of the other operand. (In Java, no operations are carried out in byte, short or char.)
The order of promotion is: int ⇒ long ⇒ float ⇒ double.

For examples,
1. int / double ⇒ double / double ⇒ double. Hence, 1/2 ⇒ 0, 1.0/2.0 ⇒ 0.5, 1.0/2 ⇒ 0.5, 1/2.0 ⇒ 0.5
2. 9 / 5 * 20.1 ⇒ (9 / 5) * 20.1 ⇒ 1 * 20.1 ⇒ 1.0 * 20.1 ⇒ 20.1 (You probably don't expect this answer!)
3. char '0' + int 2 ⇒ int 48 + int 2 ⇒ int 50 (Result is an int, need to explicitly cast back to char '2' if desired.)
4. char ⊕ float ⇒ int ⊕ float ⇒ float ⊕ float ⇒ float
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 27/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
5. byte ⊕ double ⇒ int ⊕ double ⇒ double ⊕ double ⇒ double

Summary: Type-Conversion Rules for Binary Operations


The type-promotion rules for binary operations can be summarized as follows:
1. If one of the operand is double, the other operand is promoted to double;
2. else if one of the operand is float, the other operand is promoted to float;
3. else if one of the operand is long, the other operand is promoted to long;
4. else both operands are promoted to int.

Summary: Type-Conversion Rules for Unary Operations


The type-promotion rules for unary operations (e.g., negate '-') can be summarized as follows:
1. If the operand is double, float, long or int, there is no promotion;
2. else the operand is byte, short, char, the operand is promoted to int.

More on Arithmetic Operators

Modulus (Remainder) Operator


To evaluate the remainder for negative and floating-point operands, perform repeated subtraction until the absolute value of the remainder is less than the absolute value of
the second operand.

For example,
-5 % 2 ⇒ -3 % 2 ⇒ -1
5.5 % 2.2 ⇒ 3.3 % 2.2 ⇒ 1.1

Exponent?
Java does not have an exponent operator. (The ^ operator denotes exclusive-or, NOT exponent). You need to use JDK method Math.exp(x, y) to evaluate x raises to
power y; or write your own code.

Overflow/Underflow
Study the output of the following program:

/**
* Illustrate "int" overflow
*/
public class OverflowTest {
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 28/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
public static void main(String[] args) {
// Range of int is [-2147483648, 2147483647]
int i1 = 2147483647; // maximum int
System.out.println(i + 1); //-2147483648 (overflow)
System.out.println(i + 2); //-2147483647 (overflow)
System.out.println(i + 3); //-2147483646 (overflow)
System.out.println(i * 2); //-2 (overflow)
System.out.println(i * i); //1 (overflow)

int i2 = -2147483648; // minimum int


System.out.println(i2 - 1); //2147483647 (overflow)
System.out.println(i2 - 2); //2147483646 (overflow)
System.out.println(i2 * i2); //0 (overflow)
}
}

In arithmetic operations, the resultant value wraps around if it exceeds its range (i.e., overflow). Java runtime does NOT issue an error/warning message but produces an
incorrect result.

On the other hand, integer division produces a truncated integer and results in so-called underflow. For example, 1/2 gives 0, instead of 0.5. Again, Java runtime does
NOT issue an error/warning message, but produces an imprecise result.

It is important to take note that checking of overflow/underflow is the programmer's responsibility. i.e., your job!!!

Why computer does not flag overflow/underflow as an error? This is due to the legacy design when the processors were very slow. Checking for overflow/underflow
consumes computation power. Today, processors are fast. It is better to ask the computer to check for overflow/underflow (if you design a new language), because few
humans expect such results.

To check for arithmetic overflow (known as secure coding) is tedious. Google for "INT32-C. Ensure that operations on signed integers do not result in overflow" @
www.securecoding.cert.org.

More on Integer vs. Floating-Point Numbers


Integers (byte, short, int, long) are precise (exact). But float and double are not precise but close approximation. Study the results of the following program:

/**
* Test preciseness for int/float/double
*/
public class TestPreciseness {
public static void main(String[] args) {
// doubles are NOT precise
System.out.println(2.2 + 4.4); //6.6000000000000005

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 29/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.println(6.6 - 2.2 - 4.4); //-8.881784197001252E-16 (NOT Zero!)
// Compare two doubles
System.out.println((6.6) == (2.2 + 4.4)); //false

// int is precise, float/double are NOT!


int i1 = 123456789;
System.out.println(i1*10); //1234567890 (exact within the range)

float f1 = 123456789.0f; // float keeps 6-7 significant digits


System.out.println(f1); //1.23456792E8 (=123456792 close but not exact)
System.out.println(f1*10); //1.23456794E9 (=1234567940)
}
}

Always use int if you do not need the fractional part, although double can also represent most of the integers (e.g., 1.0, 2.0, 3.0). This is because:
int is more efficient (faster) than double in arithmetic operations.
32-bit int takes less memory space than 64-bit double.
int is exact (precise) in representing ALL integers within its range. double is an approximation - NOT ALL integer values can be represented by double.

Type Casting
In Java, you will get a compilation "error: incompatible types: possible lossy conversion from double|float|long to int" if you try to assign a double, float, or long
value of to an int variable. This is because the fractional part would be truncated and lost. For example,

// Assign a "double" value to an "int" variable


double d = 3.5;
int i = d; //Compilation error: incompatible types: possible lossy conversion from double to int

// Assign a "float" value to an "int" variable


int sum = 55.66f; //Compilation error: incompatible types: possible lossy conversion from float to int

// Assign a "long" value to an "int" variable


long lg = 123;
int count = lg; //Compilation error: incompatible types: possible lossy conversion from long to int

Explicit Type-Casting and Type-Casting Operator


To assign the a double value to an int variable, you need to invoke the so-called type-casting operator - in the form of (int)doubleOperand - to operate on the
double operand and return a truncated value in int. In other words, you tell the compiler you consciously perform the truncation and you are fully aware of the "possible

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 30/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
lossy conversion". You can then assign the truncated int value to the int variable. For example,

double d = 3.5;
int i;
i = (int)d; // Cast "double" value of 3.5 to "int" 3. Assign the resultant value 3 to i
// Casting from "double" to "int" truncates.

Type casting is an operation which takes one operand. It operates on its operand, and returns an equivalent value in the specified type. The syntax is:

(type)variable // e.g., (int)height


(type)literal // e.g., (int)55.66

There are two kinds of type-casting in Java:


1. Explicit type-casting via a type-casting operator, as described above, and
2. Implicit type-casting performed by the compiler automatically, if there is no loss of precision.

Implicit Type-Casting in Assignment


Explicit type-casting is not required if you assign an int value to a double variable, because there is no loss of precision. The compiler will perform the type-casting
automatically (i.e., implicit type-casting). For example,,

int i = 3;
double d;
d = i; // OK, no explicit type casting required
// d = 3.0
d = (double)i; // Explicit type casting operator used here
double aDouble = 55; // Compiler auto-casts int 55 to double 55.0
double nought = 0; // Compiler auto-casts int 0 to double 0.0
// int 0 and double 0.0 are different.

The following diagram shows the order of implicit type-casting performed by compiler. The rule is to promote the smaller type to a bigger type to prevent loss of precision,
known as widening conversion. Narrowing conversion requires explicit type-cast to inform the compiler that you are aware of the possible loss of precision. Take note that
char is treated as an integer in the range of [0, 65535]. boolean value cannot be type-casted (i.e., converted to non-boolean).

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 31/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

Example: Suppose that you want to find the average (in double) of the running integers from 1 and 100. Study the following code:

/** Compute the average of running numbers 1 to 100 */


public class Average1To100 {
public static void main(String[] args) {
int sum = 0;
double average;
for (int number = 1; number <= 100; ++number) {
sum += number; // Final sum is int 5050
}
average = sum / 100; // Won't work (average = 50.0 instead of 50.5)
System.out.println("Average is " + average); //Average is 50.0
}
}

The average of 50.0 is incorrect. This is because both the sum and 100 are int. The result of int/int is an int, which is then implicitly casted to double and assign to
the double variable average. To get the correct answer, you can do either:

average = (double)sum / 100; // Cast sum from int to double before division, double / int -> double / double -> double
average = sum / (double)100; // Cast 100 from int to double before division, int / double -> double / double -> double
average = sum / 100.0; // int / double -> double / double -> double
average = (double)(sum / 100); // Won't work. why?

Compound Assignment Operators


Besides the usual simple assignment operator (=) described earlier, Java also provides the so-called compound assignment operators as listed:

Operation Mode Usage Description Example


= Binary var = expr Assignment x = 5;
Assign the LHS value to the RHS variable
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 32/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

+= Binary var += expr Compound addition and assignment x += 5;


same as: var = var + expr same as: x = x + 5

-= Binary var -= expr Compound subtraction and assignment x -= 5;


same as: var = var - expr same as: x = x - 5

*= Binary var *= expr Compound multiplication and assignment x *= 5;


same as: var = var * expr same as: x = x * 5

/= Binary var /= expr Compound division and assignment x /= 5;


same as: var = var / expr same as: x = x / 5

%= Binary var %= expr Compound modulus (remainder) and assignment x %= 5;


same as: var = var % expr same as: x = x % 5

One subtle difference between simple and compound operators is in byte, short, char binary operations. For examples,

byte b1 = 5, b2 = 8, b3;
b3 = (byte)(b1 + b2); // byte + byte -> int + int -> int, need to explicitly cast back to "byte"
b3 = b1 + b2; // error: RHS is int, cannot assign to byte
b1 += b2; // implicitly casted back to "byte"

char c1 = '0', c2;


c2 = (char)(c1 + 2); // char + int -> int + int -> int, need to explicitly cast back to "char"
c2 = c1 + 2; // error: RHS is int, cannot assign to char
c1 += 2; // implicitly casted back to "char"

Increment/Decrement
Java supports these unary arithmetic operators: increment (++) and decrement (--) for all primitive number types (byte, short, char, int, long, float and double,
except boolean). The increment/decrement unary operators can be placed before the operand (prefix), or after the operands (postfix). These operators were introduced in
C++ to shorthand x=x+1 to x++ or ++x.

Operator Mode Usage Description Example


++ Unary Prefix ++x Increment the value of the operand by 1. int x = 5;
(Increment) Unary Postfix x++ x++ or ++x is the same as x += 1 or x = x + 1 x++; // x is 6
++x; // x is 7

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 33/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

-- Unary Prefix --x Decrement the value of the operand by 1. int y = 6;


(Decrement) Unary Postfix x-- x-- or --x is the same as x -= 1 or x = x - 1 y--; // y is 5
--y; // y is 4

The increment (++) and decrement (--) operate on its sole operand and store the result back to its operand. For example, ++x retrieves x, increment and stores the result
back to x.

In Java, there are 4 ways to increment/decrement a variable:

int x = 5;
// 4 ways to increment by 1
x = x + 1; // x is 6
x += 1; // x is 7
x++; // x is 8
++x; // x is 9
// 4 ways to decrement by 1
x = x - 1; // x is 8
x -= 1; // x is 7
x--; // x is 6
--x; // x is 5

Unlike other unary operator (such as negate (-)) which promotes byte, short and char to int, the increment and decrement do not promote its operand because there is
no such need.

The increment/decrement unary operator can be placed before the operand (prefix), or after the operands (postfix), which may affect the outcome.
If these operators are used by themselves (standalone) in a statement (e.g., x++; or ++x;), the outcomes are the SAME for pre- and post-operators. See above
examples.
If ++ or -- involves another operation in the SAME statement, e.g., y = x++; or y = ++x; where there are two operations in the same statement: assignment and
increment, then pre- or post-order is important to specify the order of these two operations, as tabulated below:

Operator Description Example Same As


++var Increment var, and return the incremented var y = ++x; x = x + 1;
(Pre-Increment) for the other operation in the same statement. y = x;

var++ Return the old value of var for the other operation y = x++; oldX = x;
(Post-Increment) in the same statement, then increment var. x = x + 1;
y = oldX;

--var Decrement var, and return the decremented var y = --x; x = x - 1;


(Pre-Decrement) for the other operation in the same statement. y = x;

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 34/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

var-- Return the old value of var for the other operation y = x--; oldX = x;
(Post-Decrement) in the same statement, then decrement var. x = x - 1;
y = oldX;

For examples,

// Two operations in the statement: increment and assignment


x = 5;
y = ++x; // Increment x (=6), then assign x to y (=6). (++x returns x+1)
x = 5;
y = x++; // Assign x to y (=5), then increment x (=6). (x++ returns the oldX)
// After the operations, x gets the SAME value, but the other operation has different outcomes

// Two operations in the statement: increment and println()


x = 5;
System.out.println(++x); // Increment x (=6), then print x (=6). (++x returns x+1)
x = 5;
System.out.println(x++); // Print x (=5), then increment x (=6). (x++ returns the oldX)

Notes:
Prefix operator (e.g., ++i) could be more efficient than postfix operator (e.g., i++)?!
What is i=i++? Try it out!

Relational and Logical Operators


Very often, you need to compare two values before deciding on the action to be taken, e.g. if mark is more than or equals to 50, print "PASS!".

Java provides six comparison operators (or relational operators). All these operators are binary operators (that takes two operands) and return a boolean value of either
true or false.

Operator Mode Usage Description Example (x=5, y=8)


== Binary x == y Equal to (x == y) ⇒ false

!= Binary x != y Not Equal to (x != y) ⇒ true

> Binary x > y Greater than (x > y) ⇒ false

>= Binary x >= y Greater than or equal to (x >= 5) ⇒ true

< Binary x < y Less than (y < 8) ⇒ false

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 35/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

<= Binary x <= y Less than or equal to (y <= 8) ⇒ true

Take note that the comparison operators are binary infix operators, that operate on two operands with the operator in between the operands, e.g., x <= 100. It is invalid to
write 1 < x < 100 (non-binary operations). Instead, you need to break out the two binary comparison operations x > 1, x < 100, and join with a logical AND operator,
i.e., (x > 1) && (x < 100), where && denotes AND operator.

Java provides four logical operators, which operate on boolean operands only, in descending order of precedence, as follows:

Operator Mode Usage Description Example


! Unary !x Logical NOT

&& Binary x && y Logical AND

|| Binary x || y Logical OR

^ Binary x ^ y Logical Exclusive-OR (XOR)

The truth tables are as follows:

NOT (!) true false


Result false true

AND (&&) true false

true true false

false false false

OR (||) true false

true true true

false true false

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 36/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

XOR (^) true false

true false true

false true false

Examples:

// Return true if x is between 0 and 100 (inclusive)


(x >= 0) && (x <= 100)
// wrong to use 0 <= x <= 100

// Return true if x is outside 0 and 100 (inclusive)


(x < 0) || (x > 100)
// or
!((x >= 0) && (x <= 100))

// Return true if year is a leap year


// A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

Exercise: Study the following program, and explain its output.

/**
* Test relational and logical operators
*/
public class RelationalLogicalOpTest {
public static void main(String[] args) {
int age = 18;
double weight = 71.23;
int height = 191;
boolean married = false;
boolean attached = false;
char gender = 'm';

System.out.println(!married && !attached && (gender == 'm')); //true


System.out.println(married && (gender == 'f')); //false
System.out.println((height >= 180) && (weight >= 65) && (weight <= 80)); //true
System.out.println((height >= 180) || (weight >= 90)); //true

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 37/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
}

Write an expression for all unmarried male, age between 21 and 35, with height above 180, and weight between 70 and 80.

Exercise: Given the year, month (1-12), and day (1-31), write a boolean expression which returns true for dates before October 15, 1582 (Gregorian calendar cut-over
date).

Ans: (year < 1582) || (year == 1582 && month < 10) || (year == 1582 && month == 10 && day < 15)

Equality Comparison ==
You can use == to compare two integers (byte, short, int, long) and char. But do NOT use == to compare two floating-point numbers (float and double) because
they are NOT precise. To compare floating-point numbers, set a threshold for their difference, e.g.,

public class FloatComparisonTest {


public static void main(String[] args) {
// floating-point numbers are NOT precise
double d1 = 2.2 + 4.4;
double d2 = 6.6;
System.out.println(d1 == d2); //false
System.out.println(d1); //6.6000000000000005

// Set a threshold for comparison with ==


final double EPSILON = 1e-7;
System.out.println(Math.abs(d1 - d2) < EPSILON); //true
}
}

You also CANNOT use == to compare two Strings because Strings are objects. You need to use str1.equals(str2) instead. This will be elaborated later.

Logical Operator Precedence


The precedence from highest to lowest is: '!' (unary), '^', '&&', '||'. But when in doubt, use parentheses!

System.out.println(true || true && false); //true (same as below)


System.out.println(true || (true && false)); //true
System.out.println((true || true) && false); //false

System.out.println(false && true ^ true); //false (same as below)


System.out.println(false && (true ^ true)); //false
System.out.println((false && true) ^ true); //true

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 38/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

Short-Circuit Operations
The binary AND (&&) and OR (||) operators are known as short-circuit operators, meaning that the right-operand will not be evaluated if the result can be determined by the
left-operand. For example, false && rightOperand gives false and true || rightOperand give true without evaluating the right-operand. This may have
adverse consequences if you rely on the right-operand to perform certain operations, e.g. false && (++i < 5) but ++i will not be evaluated.

String and '+' Concatenation Operator


In Java, '+' is a special operator. It is overloaded. Overloading means that it carries out different operations depending on the types of its operands.
If both operands are numeric (byte, short, int, long, float, double, char), '+' performs the usual addition. For examples,

1 + 2 ⇒ 3 // int + int ⇒ int


1.2 + 2.2 ⇒ 3.4 // double + double ⇒ double
1 + 2.2 ⇒ 1.0 + 2.2 ⇒ 3.2 // int + double ⇒ double + double ⇒ double
'0' + 2 ⇒ 48 + 2 ⇒ 50 // char + int ⇒ int + int ⇒ int (need to cast back to char '2')

If both operands are Strings, '+' concatenates the two Strings and returns the concatenated String. For examples,

"Hello" + "world" ⇒ "Helloworld"


"Hi" + ", " + "world" + "!" ⇒ "Hi, world!"

If one of the operand is a String and the other is numeric, the numeric operand will be converted to String and the two Strings concatenated, e.g.,
"The number is " + 5 ⇒ "The number is " + "5" ⇒ "The number is 5"
"The average is " + average + "!" (suppose average=5.5) ⇒ "The average is " + "5.5" + "!" ⇒ "The average is 5.5!"
"How about " + a + b (suppose a=1, b=1) ⇒ "How about 1" + b ⇒ "How about 11" (left-associative)
"How about " + (a + b) (suppose a=1, b=1) ⇒ "How about " + 2 ⇒ "How about 2"

We use String concatenation operator '+' frequently in the print() and println() to produce the desired output String. For examples,

System.out.println("The sum is: " + sum); // Value of "sum" converted to String and concatenated
System.out.println("The square of " + input + " is " + squareInput);

Flow Control
There are three basic flow control constructs - sequential, conditional (or decision), and loop (or iteration), as illustrated below.

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 39/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

Sequential Flow Control


A program is a sequence of instructions executing one after another in a predictable manner. Sequential flow is the most
common and straight-forward, where programming statements are executed in the order that they are written - from top to
bottom in a sequential manner.

Conditional Flow Control


There are a few types of conditionals, if-then, if-then-else, nested-if, switch-case-default, and conditional expression.

if-then and if-then-else

Syntax Example Flowchart

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 40/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

// if-then int mark = 80;


if (booleanTest) { if (mark >= 80) {
trueBlock; System.out.println("Well Done!");
} System.out.println("Keep it up!");
// next statement }
System.out.println("Life goes on!);

double temperature = 80.1;


if (temperature > 80) {
System.out.println("Too Hot!");
}
System.out.println("yummy!");

// if-then-else int mark = 50; // Assume that mark is [0, 100]


if (booleanTest) { if (mark >= 50) { // [50, 100]
trueBlock; System.out.println("Congratulation!");
} else { System.out.println("Keep it up!");
falseBlock; } else { // [0, 49]
} System.out.println("Try Harder!");
// next statement }
System.out.println("Life goes on!");

double temperature = 80.1;


if (temperature > 80) {
System.out.println("Too Hot!");
} else {
System.out.println("Too Cold!");
}
System.out.println("yummy!");

Braces: You could omit the braces { }, if there is only one statement inside the block. For example,

// if-then
int absValue = -5;
if (absValue < 0) absValue = -absValue; // Only one statement in the block, can omit { }

int min = 0, value = -5;


if (value < min) { // More than one statements in the block, need { }
min = value;
System.out.println("Found new min");

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 41/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}

// if-then-else
int mark = 50;
if (mark >= 50)
System.out.println("PASS"); // Only one statement in the block, can omit { }
else { // More than one statements in the block, need { }
System.out.println("FAIL");
System.out.println("Try Harder!");
}

// Harder to read without the braces


int number1 = 8, number2 = 9, absDiff;
if (number1 > number2) absDiff = number1 - number2;
else absDiff = number2 - number1;

However, I recommend that you keep the braces to improve the readability of your program, even if there is only one statement in the block.

Nested-if

Syntax Example Flowchart


// nested-if int mark = 62; // Assume that mark is [0, 100]
if (booleanTest1) { if (mark >= 80) { // [80, 100]
block1; System.out.println("A");
} else if (booleanTest2) { } else if (mark >= 65) { // [65, 79]
block2; System.out.println("B");
} else if (booleanTest3) { } else if (mark >= 50) { // [50, 64]
block3; System.out.println("C");
} else if (booleanTest4) { } else { // [0, 49]
...... System.out.println("F");
} else { }
elseBlock; System.out.println("Life goes on!");
}
// next statement double temperature = 61;
if (temperature > 80) { // > 80
System.out.println("Too Hot!");
} else if (temperature > 75) { // (75, 80]
System.out.println("Just right!");
} else { // <= 75

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 42/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.println("Too Cold!");
}
System.out.println("yummy!");

Java does not provide a separate syntax for nested-if (e.g., with keywords like eif, elseif), but supports nested-if with nested if-else statements, which is interpreted as
below. Take note that you need to put a space between else and if. Writing elseif causes a syntax error.

if ( booleanTest1 ) {
block1;
} else { // This else-block contains a if-else statement
if ( booleanTest2 ) {
block2;
} else { // This else-block also contains a if-else statement
if (booleanTest3) {
block3;
} else { // This else-block also contains a if-else statement
if ( booleanTest4 ) {
......
} else {
elseBlock;
}
}
}
}
// This alignment is hard to read!

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 43/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
However, for readability, it is recommended to align the nest-if statement as written in the syntax/examples.

Take note that the blocks are exclusive in a nested-if statement; only one of the blocks will be executed. Also, there are two ways of writing nested-if, for example,

// Assume that mark is [0, 100]


if (mark >= 80) { // [80, 100]
System.out.println("A");
} else if (mark >= 65) { // [65, 79]
System.out.println("B");
} else if (mark >= 50) { // [50, 64]
System.out.println("C");
} else { // [0, 49]
System.out.println("F");
}
// OR
if (mark < 50) { // [0, 49]
System.out.println("F");
} else if (mark < 65) { // [50, 64]
System.out.println("C");
} else if (mark < 80) { // [65, 79]
System.out.println("B");
} else { // [80, 100]
System.out.println("A");
}

Dangling-else Problem
The "dangling-else" problem can be illustrated as follows:

int i = 0, j = 0;
if (i == 0) // outer-if
if (j == 0) // inner-if
System.out.println("i and j are zero");
else System.out.println("xxx"); // This else can pair with the inner-if and outer-if?!

The else clause in the above code is syntactically applicable to both the outer-if and the inner-if, causing the dangling-else problem.

Java compiler resolves the dangling-else problem by associating the else clause with the innermost-if (i.e., the nearest-if). Hence, the above code shall be interpreted
as:

int i = 0, j = 0;
if (i == 0)

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 44/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
if (j == 0)
System.out.println("i and j are zero");
else // associated with if (j == 0) - the nearest if
System.out.println("xxx");

Dangling-else can be prevented by applying explicit parentheses. For example, if you wish to associate the else clause with the outer-if, do this:

// Force the else-clause to associate with the outer-if with parentheses


int i = 0, j = 0;
if (i == 0) {
if (j == 0)
System.out.println("i and j are zero");
} else {
System.out.println("i is not zero"); // non-ambiguous for outer-if
}

// Force the else-clause to associate with the inner-if with parentheses


int i = 0, j = 0;
if (i == 0) {
if (j == 0) {
System.out.println("i and j are zero");
} else {
System.out.println("i is zero, j is not zero"); // non-ambiguous for inner-if
}
}

Nested-if vs. Sequential-if


Study the following code:

// Assume mark is between 0 and 100


// This "sequential-if" works but NOT efficient!
// Try mark = 81, which will run thru ALL the if's.
int mark = 81;
if (mark > 80) { // [81, 100]
grade = 'A';
}
if (mark > 65 && mark <= 80) { // [66, 80]
grade = 'B';
}
if (mark >= 50 && mark <= 65) { // [50, 65]
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 45/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
grade = 'C';
}
if (mark < 50) { // [0, 49]
grade = 'F';
}

// This "nested-if" is BETTER


// Try mark = 81, which only run thru only the first if.
int mark = 81;
if (mark > 80) { // [81, 100]
grade = 'A';
} else if (mark > 65 && mark <= 80) { // [66, 80]
grade = 'B';
} else if (mark >= 50 && mark <= 65) { // [50, 65]
grade = 'C';
} else {
grade = 'F'; // [0, 49]
}

// This "nested-if" is the BEST with fewer tests


int mark = 81;
if (mark > 80) { // [81, 100]
grade = 'A';
} else if (mark > 65) { // [66, 80]
grade = 'B';
} else if (mark >= 50) { // [50, 65]
grade = 'C';
} else { // [0, 49]
grade = 'F';
}

switch-case-default

Syntax Example Flowchart

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 46/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

// switch-case-default // Print number in word


switch (selector) { int number = 3;
case value1: switch (number) { // "int" selector
block1; break; case 1: // "int" value
case value2: System.out.println("ONE"); break;
block2; break; case 2:
case value3: System.out.println("TWO"); break;
block3; break; case 3:
...... System.out.println("THREE"); break;
case valueN: default:
blockN; break; System.err.println("OTHER");
default: // not the above }
defaultBlock;
} // Select arithmetic operation
// next statement char operator = '*';
int num1 = 5, num2 = 8, result;
// Selector Types: switch (operator) { // "char" selector
// byte, short, int, case '+': // "char" value
// char, String result = num1 + num2; break;
case '-':
result = num1 - num2; break;
case '*':
result = num1 * num2; break;
case '/':
result = num1 / num2; break;
default:
System.out.println("Unknown operator);
}

"switch-case-default" is an alternative to the "nested-if" for fixed-value tests (but not applicable for range tests). You can use an int, byte, short, or char variable
as the case-selector, but NOT long, float, double and boolean. JDK 1.7 supports String as the case-selector.

In a switch-case statement, a break statement is needed for each of the cases. If break is missing, execution will flow through the following case, which is typically a
mistake. However, we could use this property to handle multiple-value selector. For example,

// Converting Phone keypad letter to digit


char inChar = 'x';
switch (inChar) {
case 'a': case 'b': case 'c': // 'a' and 'b' (without break) fall thru 'c'
System.out.print(2); break;

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 47/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
case 'd': case 'e': case 'f':
System.out.print(3); break;
case 'g': case 'h': case 'i':
System.out.print(4); break;
case 'j': case 'k': case 'l':
System.out.print(5); break;
......
default:
System.out.println("Invalid Input");
}

Conditional Expression ( ... ? ... : ... )


A conditional operator is a ternary (3-operand) operator, in the form of booleanExpr ? trueExpr : falseExpr. Depending on the booleanExpr, it evaluates and
returns the value of trueExpr or falseExpr.

Syntax Examples
// Conditional Expression int num1 = 9, num2 = 8, max;
booleanExpr ? trueExpr : falseExpr max = (num1 > num2) ? num1 : num2; // RHS returns num1 or num2
// An expression that returns // same as
// the value of trueExpr if (num1 > num2) {
// or falseExpr max = num1;
} else {
max = num2;
}

int value = -9, absValue;


absValue = (value > 0) ? value : -value; // RHS returns value or -value
// same as
if (value > 0) absValue = value;
else absValue = -value;

int mark = 48;


System.out.println((mark >= 50) ? "PASS" : "FAIL"); // Return "PASS" or "FAIL"
// same as
if (mark >= 50) System.out.println("PASS");
else System.out.println("FAIL");

Conditional expression is a short-hand for if-else. But you should use it only for one-liner, for readability.

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 48/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

Exercises on Getting Started and Conditional


LINK

Loop Flow Control


Again, there are a few types of loops: for, while-do, and do-while.

Syntax Example Flowchart


// while-do loop // Sum from 1 to upperbound
while (booleanTest) { int sum = 0;
body; final int UPPERBOUND = 100;
} int number = 1; // init
// next statement while (number <= UPPERBOUND) {
// number = 1, 2, 3, ..., UPPERBOUND
//for each iteration
sum += number;
++number; // update
}
System.out.println("sum is: " + sum);

// Factorial of n (=1*2*3*...*n)
int n = 5;
int factorial = 1;
int number = 1; // init
while (number <= n) {
// num = 1, 2, 3, ..., n for each iteration
factorial *= number;
++num; // update
}
System.out.println("factorial is: " + factorial);

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 49/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

// do-while loop // Sum from 1 to upperbound


do { int sum = 0;
body; final int UPPERBOUND = 100;
} while (booleanTest; int number = 1; // init
// next statement do {
// Need a semi-colon to // number = 1, 2, 3, ..., UPPERBOUND
// terminate statement // for each iteration
sum += number;
++number; // update
} while (number <= UPPERBOUND);
System.out.println("sum is: " + sum);

// Factorial of n (=1*2*3*...*n)
int n = 5;
int factorial = 1;
int number = 1; // init
do {
// num = 1, 2, 3, ..., n for each iteration
factorial *= number;
++number; // update
} while (number <= n);
System.out.println("factorial is: " + factorial);

// for-loop // Sum from 1 to upperbound


for (init; booleanTest; update) { int sum = 0;
body; final int UPPERBOUND = 100;
} for (int number = 1; number <= UPPERBOUND; ++number) {
// next statement // num = 1, 2, 3, ..., UPPERBOUND
sum += number;
}
System.out.println("sum is: " + sum);

// Factorial of n (=1*2*3*...*n)
int n = 5;
int factorial = 1;
for (int number = 1; number <= n; ++number) {
// number = 1, 2, 3, ..., n
factorial *= number;

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 50/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
System.out.println("factorial is: " + factorial);

The difference between while-do and do-while lies in the order of the body and test. In while-do, the test is carried out first. The body will be executed if the test is true and
the process repeats. In do-while, the body is executed and then the test is carried out. Take note that the body of do-while is executed at least once (1+); but the body of
while-do is possibly zero (0+). Similarly, the for-loop's body could possibly not executed (0+).

For-loop is a shorthand for while-do with fewer lines of code. It is the most commonly-used loop especially if the number of repetitions is known. But its syntax is harder to
comprehend. Make sure that you understand for-loop by going through the flow-chart and examples.

Loop's Index/Counter Variable


A loop is typically controlled by an index or counter variable. For example,

// Sum from 1 to UPPERBOUND using for-loop


int sum = 0
final int UPPERBOUND = 100;
for (int number = 1; number <= UPPERBOUND; ++number) { // number = 1, 2, 3, ..., UPPERBOUND for each iteration
sum += num;
}

// Sum from 1 to UPPERBOUND using while-loop


int sum = 0
final int UPPERBOUND = 100;
int number = 1;
while (number <= UPPERBOUND) { // number = 1, 2, 3, ..., UPPERBOUND for each iteration
sum += number;
++number;
}

In the above examples, the variable number serves as the index variable, which takes on the values 1, 2, 3, ..., UPPERBOUND for each iteration of the loop. You need to
increase/decrease/modify the index variable explicitly (e.g., via ++number). Otherwise, the loop becomes an endless loop, as the test (number <= UPPERBOUND) will
return the same outcome for the same value of number.

Observe that for-loop is a shorthand of while-loop. Both the for-loop and while-loop have the same set of statements, but for-loop re-arranges the statements.

For the for-loop, the index variable number is declared inside the loop, and therefore is only available inside the loop. You cannot access the variable after the loop, as It is
destroyed after the loop. On the other hand, for the while-loop, the index variable number is available inside and outside the loop.

For the for-loop, you can choose to declare the index variable inside the loop or outside the loop. We recommend that you declare it inside the loop, to keep the life-span of
this variable to where it is needed, and not any longer.

[TODO] Animated GIF??

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 51/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

Code Example: Sum and Average of Running Integers


The following program sums the running integers from a given lowerbound to an upperbound. Also compute their average.

/**
* Sum the running integers from lowerbound to an upperbound.
* Also compute the average.
*/
public class SumAverageRunningNumbers {
public static void main(String[] args) {
// Declare variables
int sum = 0; // store the accumulated sum
final int LOWERBOUND = 1;
final int UPPERBOUND = 1000;
double average;

// Use a for-loop to accumulate the sum


for (int number = LOWERBOUND; number <= UPPERBOUND; ++number) {
// number = LOWERBOUND, LOWERBOUND+1, LOWERBOUND+2, ..., UPPERBOUND for each iteration
sum += number;
}
average = (double)sum / (UPPERBOUND - LOWERBOUND + 1); // need to cast int to double first
// Print results
System.out.println("The sum from " + LOWERBOUND + " to " + UPPERBOUND + " is: " + sum);
//The sum from 1 to 1000 is: 500500
System.out.println("The average is: " + average);
//The average is: 500.5

// Sum only the ODD numbers


int count = 0; // counts of odd numbers
sum = 0; // reset sum for accumulation again
// Adjust the LOWERBOUND to the next odd number if it is a even number
final int ADJUSTED_LOWERBOUND = LOWERBOUND % 2 == 0 ? LOWERBOUND+1 : LOWERBOUND;
// Use a for-loop to accumulate the sum with step size of 2
for (int number = ADJUSTED_LOWERBOUND; number <= UPPERBOUND; number += 2) {
// number = ADJUSTED_LOWERBOUND, ADJUSTED_LOWERBOUND+2, ADJUSTED_LOWERBOUND+4,
// ..., UPPERBOUND for each iteration
++count;
sum += number;
}

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 52/130

You might also like