java basics-páginas-2
java basics-páginas-2
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).
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"
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
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)
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.
/**
* 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
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,
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:
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:
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?
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"
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.
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
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.
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:
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;
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,
Notes:
Prefix operator (e.g., ++i) could be more efficient than postfix operator (e.g., i++)?!
What is i=i++? Try it out!
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.
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
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:
|| Binary x || y Logical OR
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
Examples:
/**
* 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';
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.,
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.
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.
If both operands are Strings, '+' concatenates the two Strings and returns the concatenated String. For examples,
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
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
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 { }
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!");
}
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
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,
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:
switch-case-default
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" 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,
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");
}
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;
}
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
// 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
// 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);
// 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.
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.
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
/**
* 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;
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 52/130