3 - Java Basics - Java Programming Tutorial
3 - Java Basics - Java Programming Tutorial
İçindekiler (Gizle)
1. Temel Söz Dizimleri
1.1 Java Programı Yazma Adımları
1.2 Java Program Şablonu
[Link] 1/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
3
*/ 9.2 Converting char to int
4
public class Classname { // Choose a meaningful Classname. Save as "[Link] 9.3 String Operations
5
public static void main(String[] args) { // Entry point of the program 9.4 Converting String to Primitive
6
// Your programming statements here!!! 9.5 Converting Primitive to String
7
} 9.6 Formatting Strings - [Link]
8
} 9.7 Code Example: Reverse String
9.8 Code Example: Validating Binary
9.9 Code Example: Binary to Decim
9.10 Code Example: Hexadecimal to
1.3 A Sample Program Illustrating Sequential, Decision and Loop Constructs 9.11 Exercises on String and char
Below is a simple Java program that demonstrates the three basic programming constructs: sequential, 10. Arrays
10.1 Array Index
loop, and conditional. Read "Introduction To Java Programming for First-time Programmers" if you need
help in understanding this program. 10.2 Array's length
10.3 Array and Loop
10.4 Enhanced for-loop (or "for-eac
1 /**
* Find the sums of the running odd numbers and even numbers from a given lowerbound 10.5 Code Example: Read and Print
2
10.6 Code Example: Horizontal and
3 * to an upperbound. Also compute their absolute difference.
10.7 Code Example: Hexadecimal to
4 */
5 public class OddEvenSum { // Save as "[Link]" 10.8 Code Example: Decimal to Hex
1.4 Comments
Comments are used to document and explain your code and your program logic. Comments are not programming statements. They are ignored by
the compiler and have no consequences to the program execution. Nevertheless, comments are VERY IMPORTANT for providing documentation
and explanation for others to understand your programs (and also for yourself three days later).
I recommend that you use comments liberally to explain and document your code.
[Link] 2/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
During program development, instead of deleting a chunk of statements irrevocably, you could comment-out these statements so that you could
get them back later, if needed.
For examples,
// Each of the following lines is a programming statement, which ends with a semi-colon (;).
// A programming statement performs a piece of programming action.
int number1 = 10;
int number2, number3 = 99;
int product;
number2 = 8;
product = number1 * number2 * number3;
[Link]("Hello");
Block: A block is a group of programming statements surrounded by a pair of curly braces { }. All the statements inside the block is treated as one
single unit. Blocks are used as the body in constructs like class, method, if-else and loop, which may contain multiple statements but are treated as
one unit (one body). There is no need to put a semi-colon after the closing brace to end a compound statement. Empty block (i.e., no statement
inside the braces) is permitted.
For examples,
// Each of the followings is a "compound" statement comprising one or more blocks of statements.
// No terminating semi-colon needed after the closing brace to end the "compound" statement.
// Take note that a "compound" statement is usually written over a few lines for readability.
if (mark >= 50) { // A if statement
[Link]("PASS");
[Link]("Well Done!");
[Link]("Keep it Up!");
}
i = 1;
while (i < 8) { // A while-loop statement
[Link](i + " ");
++i;
}
int sum = 0; // Cannot write "intsum". Need at least one white space between "int" and "sum"
double average; // Again, need at least a white space between "double" and "average"
Java, like most of the programming languages, ignores extra white spaces. That is, multiple contiguous white spaces are treated as a single white
space. Additional white spaces and extra lines are ignored, e.g.,
double
average
;
// Also same as above with minimal white space. Also hard to read
int sum=0;double average;
[Link] 3/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
Formatting Source Code: As mentioned, extra white spaces are ignored and have no computational significance. However, proper indentation
(with tabs and blanks) and extra empty lines greatly improves the readability of the program. This is extremely important for others (and yourself
three days later) to understand your programs.
For example, the following one-line hello-world program works. But can you read and understand the program?
Braces: Java's convention is to place the beginning brace at the end of the line, and to align the ending brace with the start of the statement. Pair-
up the { } properly. Unbalanced { } is one of the most common syntax errors for beginners.
Indentation: Indent each level of the body of a block by an extra 3 or 4 spaces according to the hierarchy of the block. Don't use tab because tab-
spaces is editor-dependent.
/**
* Recommended Java programming style (Documentation comments about the class)
*/
public class ClassName { // Place the beginning brace at the end of the current line
public static void main(String[] args) { // Indent the body by an extra 3 or 4 spaces for each level
// A if-else statement
if (test) {
true-statements;
} else {
false-statements;
}
// A loop statement
init;
while (test) {
body-statements;
update;
}
}
} // Ending brace aligned with the start of the statement
"Code is read much more often than it is written." Hence, you have to make sure that your code is readable (by others and yourself 3 days
later), by following convention and recommended coding style.
More precisely, a variable is a named storage location, that stores a value of a particular data type. In other words, a variable has a name, a type
and stores a value.
A variable has a name (aka identifier), e.g., radius, area, age, height and numStudents. The name is needed to uniquely identify and reference
each variable. You can use the name to assign a value to the variable (e.g., radius = 1.2), and to retrieve the value stored (e.g.,
radius*radius*3.1419265).
A variable has a data type. The frequently-used Java data types are:
int: meant for integers (whole numbers) such as 123 and -456.
double: meant for floating-point number (real numbers) having an optional decimal point and fractional part, such as 3.1416, -55.66,
1.2e3, or -4.5E-6, where e or E denotes exponent of base 10.
String: meant for texts such as "Hello" and "Good Morning!". Strings are enclosed within a pair of double quotes.
char: meant for a single character, such as 'a', '8'. A char is enclosed by a pair of single quotes.
In Java, you need to declare the name and the type of a variable before using a variable. For examples,
int sum; // Declare an "int" variable named "sum"
double average; // Declare a "double" variable named "average"
String message; // Declare a "String" variable named "message"
char grade; // Declare a "char" variable named "grade"
A variable can store a value of the declared data type. It is important to take note that a variable in most programming languages is associated
with a type, and can only store value of that particular type. For example, an int variable can store an integer value such as 123, but NOT
floating-point number such as 12.34, nor string such as "Hello".
The concept of type was introduced in the early programming languages to simplify interpretation of data made up of binary sequences (0's
and 1's). The type determines the size and layout of the data, the range of its values, and the set of operations that can be applied.
[Link] 4/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
The following diagram illustrates three types of variables: int, double and String. An int variable stores an integer (or whole number or fixed-
point number); a double variable stores a floating-point number (or real number); a String variable stores texts.
Examples: abc, _xyz, $123, _1_2_3 are valid identifiers. But 1abc, min-value, surface area, ab@c are NOT valid identifiers.
Caution: Programmers don't use blank character in any names (filename, project name, variable name, etc.). It is either not supported (e.g., in Java
and C/C++), or will pose you many more challenges.
Recommendations
1. It is important to choose a name that is self-descriptive and closely reflects the meaning of the variable, e.g., numberOfStudents or
numStudents, but not n or x, to store the number of students. It is alright to use abbreviations.
2. Do not use meaningless names like a, b, c, i, j, k, n, i1, i2, i3, j99, exercise85 (what is the purpose of this exercise?), and example12 (What is
this example about?).
3. Avoid single-letter names like i, j, k, a, b, c, which are easier to type but often meaningless. Exceptions are common names like x, y, z for
coordinates, i for index. Long names are harder to type, but self-document your program. (I suggest you spend sometimes practicing your
typing.)
4. Use singular and plural nouns prudently to differentiate between singular and plural variables. For example, you may use the variable row to
refer to a single row number and the variable rows to refer to many rows (such as an array of rows - to be discussed later).
Syntax Example
// Declare a variable of a specified type int sum;
type identifier; double average;
String statusMsg;
[Link] 5/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
type identifier1 = initValue1, ..., identifierN = String greetingMsg = "hi!", quitMsg =
initValueN; "bye!";
Constant Naming Convention: Use uppercase words, joined with underscore. For example, MIN_VALUE, MAX_SIZE, and INTEREST_RATE_6_MTH.
2.5 Expressions
An expression is a combination of operators (such as '+' and '-') and operands (variables or literals), that can be evaluated to yield a single value
of a certain type.
For example,
// "int" literals
((1 + 2) * 3 / 4) % 6 // This expression is evaluated to an "int" value
// "double" literals
3.45 + 6.7 // This expression is evaluated to a "double" value
Syntax Example
// Assign the RHS literal value to the LHS variable int number;
variable = literalValue; number = 9;
// Evaluate the RHS expression and assign the result to the LHS int sum = 0, number = 8;
variable sum = sum + number;
variable = expression;
The assignment statement should be interpreted this way: The expression on the RHS is first evaluated to produce a resultant value (called r-value
or right-value). The r-value is then assigned to the variable on the left-hand-side (LHS) or l-value. Take note that you have to first evaluate the RHS,
before assigning the resultant value to the LHS. For examples,
[Link] 6/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
int number;
number = 8; // Assign RHS literal value of 8 to the LHS variable number
number = number + 1; // Evaluate the RHS expression (number + 1),
// and assign the resultant value back to the LHS variable number
Note that x = x + 1 is valid (and often used) in programming. It evaluates the RHS expression x
+ 1 and assigns the resultant value to the LHS variable x. On the other hand, x = x + 1 is illegal
in Mathematics.
While x + y = 1 is allowed in Mathematics, it is invalid in programming because the LHS of an assignment statement shall be a variable.
Some programming languages use symbol ":=", "->" or "<-" as the assignment operator to avoid confusion with equality.
We shall describe the primitive types here. We will cover the reference types (classes and objects) in the later chapters on "Object-Oriented
Programming".
TYPE DESCRIPTION
byte Integer 8-bit signed integer
The range is [-27, 27-1] = [-128, 127]
char Character
Represented in 16-bit Unicode '\u0000' to '\uFFFF'.
Can be treated as integer in the range of [0, 65535] in arithmetic operations.
(Unlike C/C++, which uses 8-bit ASCII code.)
boolean Binary
Takes a literal value of either true or false.
The size of boolean is not defined in the Java specification, but requires at least one bit.
booleans are used in test in decision and loop, not applicable for arithmetic operations.
(Unlike C/C++, which uses integer 0 for false, and non-zero for true.)
Primitive type are built-into the language for maximum efficiency, in terms of both
space and computational efficiency.
[Link] 7/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
standard). Take note that not all real numbers can be represented by float and double. This is because there are infinite real numbers even in
a small range of say [1.0, 1.1], but there is a finite number of patterns in a n-bit representation. Most of the floating-point values are
approximated to their nearest representation.
The type char represents a single character, such as '0', 'A', 'a'. In Java, char is represented using 16-bit Unicode (in UCS-2 format) to
support internationalization (i18n). A char can be treated as an integer in the range of [0, 65535] in arithmetic operations. For example,
character '0' is 48 (decimal) or 30H (hexadecimal); character 'A' is 65 (decimal) or 41H (hexadecimal); character 'a' is 97 (decimal) or 61H
(hexadecimal).
Java introduces a new binary type called "boolean", which takes a literal value of either true or false. booleans are used in test in decision and
loop. They are not applicable to arithmetic operations (such as addition and multiplication).
How Integers and Floating-Point Numbers are Represented and Stored in Computer Memory?
Integers are represented in a so called 2's complement scheme as illustrated. The most-significant bit is called Sign Bit (S), where S=0 represents
positive integer and S=1 represents negative integer. The remaining bits represent the magnitude of the integers. For positive integers, the
magnitude is the same as the binary number, e.g., if n=16 (short), 0000000000000010 is +210. Negative integers require 2's complement conversion.
Floating-point numbers are represented in scientific form of Fx2E, where Fraction (F) and Exponent (E) are stored separately. For example, to store
12.7510; first convert to binary of 1100.112; then normalize to 1.100112 x 23; we have F=1.1011 and E=310=112 which are then stored with some
scaling.
For details, read "Data Representation - Integers, Floating-Point Numbers and Characters".
Integer operations are straight-forward. For example, integer addition is carried out as illustrated:
It is obvious that integer operations (such as addition) is much faster than floating-point operations.
Furthermore, integer are precise. All numbers within the range can be represented accurately. For example, a 32-bit int can represent ALL integers
from -2147483648 to +2147483647 with no gap in between. On the other hand, floating-point are NOT precise, but close approximation. This is
because there are infinite floating-point numbers in any interval (e.g., between 0.1 to 0.2). Not ALL numbers can be represented using a finite
precision (32-bit float or 64-bit double).
[Link] 8/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
You need to treat integers and Floating-point numbers as two DISTINCT types in programming!
Use integer if possible (it is faster, precise and uses fewer bits). Use floating-point number only if a fractional part is
required.
In brief, It is important to take note that char '1' is different from int 1, byte 1, short 1, float 1.0, double 1.0, and String "1". They are
represented differently in the computer memory, with different precision and interpretation. They are also processed differently. For examples:
byte 1 is "00000001" (8-bit).
short 1 is "00000000 00000001" (16-bit).
int 1 is "00000000 00000000 00000000 00000001" (32-bit).
long 1 is "00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001" (64-bit).
float 1.0 is "0 01111111 0000000 00000000 00000000" (32-bit).
double 1.0 is "0 01111111111 0000 00000000 00000000 00000000 00000000 00000000 00000000" (64-bit).
char '1' is "00000000 00110001" (16-bit) (Unicode number 49).
String "1" is a complex object (many many bits).
There is a subtle difference between int 0 and double 0.0 as they have different bit-lengths and internal representations.
Furthermore, you MUST know the type of a value before you can interpret a value. For example, this bit-pattern "00000000 00000000 00000000
00000001" cannot be interpreted unless you know its type (or its representation).
/**
* Print the minimum, maximum and bit-length of all primitive types (except boolean)
*/
public class PrimitiveTypesMinMaxBitLen {
public static void main(String[] args) {
/* int (32-bit signed integer) */
[Link]("int(min) = " + Integer.MIN_VALUE);
//int(min) = -2147483648
[Link]("int(max) = " + Integer.MAX_VALUE);
//int(max) = 2147483647
[Link]("int(bit-length) = " + [Link]);
//int(bit-length) = 32
[Link] 9/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
//char(bit-length) = 16
In Java, a char is a single character enclosed by single quotes (e.g., 'A', '0', '$'); while a String is a sequence of characters enclosed by double
quotes (e.g., "Hello").
For example,
It is important to take note that your programs will have data of DIFFERENT types.
Example (Variable Names and Types): Paul has bought a new notebook of "idol" brand, with a processor speed of 2.66GHz, 8 GB of RAM, 500GB
hard disk, with a 15-inch monitor, for $1760.55. He has chosen service plan 'C' among plans 'A', 'B', 'C', and 'D', plus on-site servicing but did not
choose extended warranty. Identify the data types and name the variables.
Exercise (Variable Names and Types): You are asked to develop a software for a college. The system shall maintain information about students.
This includes name, address, phone number, gender, date of birth, height, weight, degree pursued (e.g., [Link]., B.A.), year of study, average GPA,
with/without tuition grant, is/is not a scholar. Each student is assigned a unique 8-digit number as id.
[Link] 10/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
You are required to identify the variables, assign a suitable name to each variable and choose an appropriate type. Write the variable declaration
statements as in the above example.
An int literal may precede with a plus (+) or minus (-) sign, followed by digits. No commas or special symbols (e.g., $, %, or space) is allowed (e.g.,
1,234,567, $123 and 12% are invalid).
You can use a prefix '0' (zero) to denote an integer literal value in octal, and prefix '0x' (or '0X') for a value in hexadecimal, e.g.,
From JDK 7, you can use prefix '0b' or '0B' to specify an integer literal value in binary. You are also permitted to use underscore (_) to break the
digits into groups to improve the readability. But you must start and end the literal with a digit, not underscore. For example,
// JDK 7
int number1 = 0b01010000101000101101000010100010;
int number2 = 0b0101_0000_1010_0010_1101_0000_1010_0010; // break the bits with underscore
int number3 = 2_123_456; // break the decimal digits with underscore
int number4 = _123_456; // error: cannot begin or end with underscore
A long literal outside the int range requires a suffix 'L' or 'l' (avoid lowercase 'l', which could be confused with the number one '1'), e.g.,
123456789012L, -9876543210l. For example,
long sum = 123; // Within the "int" range, no need for suffix 'L'
long bigSum = 1234567890123L; // Outside "int" range, suffix 'L' needed
No suffix is needed for byte and short literals. But you can only use values in the permitted range. For example,
byte smallNumber1 = 123; // This is within the range of byte [-128, 127]
byte smallNumber2 = -1234; // error: this value is out of range
short midSizeNumber1 = -12345; // This is within the range of short [-32768, 32767]
short midSizeNumber2 = 123456; // error: this value is out of range
You are reminded that floating-point numbers are stored in scientific form of Fx2E, where F (Fraction) and E (Exponent) are stored separately.
You can optionally use suffix 'd' or 'D' to denote double literals.
You MUST use a suffix of 'f' or 'F' for float literals, e.g., -1.2345F. For example,
float average = 55.66; // error: RHS is a double. Need suffix 'f' for float.
float average = 55.66F; // float literal needs suffix 'f' or 'F'
float rate = 1.2e-3; // error: RHS is a double. Need suffix 'f' for float.
float rate = 1.2e-3f; // float literal needs suffix 'f' or 'F'
In Java, chars are represented using 16-bit Unicode. Printable characters for English letters (a-z, A-Z), digits (0-9) and symbols (+, -, @, etc.) are
assigned to code numbers 32-126 (20H-7EH), as tabulated below (arranged in decimal and hexadecimal).
Dec 0 1 2 3 4 5 6 7 8 9
[Link] 11/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
4 ( ) * + , - . / 0 1
5 2 3 4 5 6 7 8 9 : ;
6 < = > ? @ A B C D E
7 F G H I J K L M N O
8 P Q R S T U V W X Y
9 Z [ \ ] ^ _ ` a b c
10 d e f g h i j k l m
11 n o p q r s t u v w
12 x y z { | } ~
Hex 0 1 2 3 4 5 6 7 8 9 A B C D E F
3 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
4 @ A B C D E F G H I J K L M N O
5 P Q R S T U V W X Y Z [ \ ] ^ _
6 ` a b c d e f g h i j k l m n o
7 p q r s t u v w x y z { | } ~
In Java, a char can be treated as its underlying integer in the range of [0, 65535] in arithmetic operations. In other words, char and integer are
interchangeable in arithmetic operations. You can treat a char as an int, you can also assign an integer value in the range of [0, 65535] to a char
variable. For example,
Special characters are represented by so-called escape sequence, which begins with a back-slash (\) followed by a pattern, e.g., \t for tab, \n for
newline. The commonly-used escape sequences are:
\r Carriage-return 13 000DH
\uhhhh Unicode number hhhh (in hex), e.g., \u60a8 is 您, \u597d is 好 - hhhhH
For examples,
[Link] 12/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
A String is a sequence of characters. A String literal is composed of zero of more characters surrounded by a pair of double quotes. For
examples,
String directionMsg = "Turn Right";
String greetingMsg = "Hello";
String statusMsg = ""; // An empty string
You need to use an escape sequence for special non-printable characters, such as newline (\n) and tab (\t). You also need to use escape sequence
for double-quote (\") and backslash (\\) due to conflict. For examples,
Single-quote (') inside a String does not require an escape sequence because there is no ambiguity, e.g.,
It is important to take note that \t or \" is ONE single character, NOT TWO!
Exercise: Write a program to print the following animal picture using [Link](). Take note that you need to use escape sequences to
print some characters, e.g., \" for ", \\ for \.
'__'
(oo)
+========\/
/ || %%% ||
* ||-----||
"" ""
End-of-Line (EOL)
Newline (0AH) and Carriage-Return (0DH), represented by the escape sequence \n, and \r respectively, are used as line delimiter (or end-of-line, or
EOL) for text files. Take note that Unix and macOS use \n (0AH) as EOL, while Windows use \r\n (0D0AH).
boolean Literals
There are only two boolean literals, i.e., true and false. For example,
boolean isValid;
isValid = false;
Example on Literals
/**
* Test literals for various primitive types
*/
public class LiteralTest {
public static void main(String[] args) {
String name = "Tan Ah Teck"; // String is double-quoted
char gender = 'm'; // char is single-quoted
boolean isMarried = true; // boolean of either true or false
byte numChildren = 8; // Range of byte is [-127, 128]
short yearOfBirth = 1945; // Range of short is [-32767, 32768]. Beyond byte
int salary = 88000; // Beyond the ranges of byte and short
long netAsset = 8234567890L; // Need suffix 'L' for long. Beyond int
double weight = 88.88; // With fractional part
float gpa = 3.88f; // Need suffix 'f' for float
[Link] 13/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
[Link]("Weight is: " + weight);
//Weight is: 88.88
[Link]("GPA is: " + gpa);
//GPA is: 3.88
}
}
Clearly, you need to initialize the variable, so that the compiler can infer its type.
4. Basic Operations
- Binary x - y Subtraction 1 - 2 ⇒ -1
Unary -x Unary negate 1.1 - 2.2 ⇒ -1.1
* Binary x * y Multiplication 2 * 3 ⇒ 6
3.3 * 1.0 ⇒ 3.3
/ Binary x / y Division 1 / 2 ⇒ 0
1.0 / 2.0 ⇒ 0.5
These operators are typically binary infix operators, i.e., they take two operands with the operator in between the operands (e.g., 11 + 12).
However, '-' and '+' can also be interpreted as unary "negate" and "positive" prefix operator, with the operator in front of the operand. For
examples,
must be written as (1+2*a)/3 + (4*(b+c)*(5-d-e))/f - 6*(7/g+h). You cannot omit the multiplication sign (*) as in Mathematics.
Rules on Precedence
Like Mathematics:
1. Parentheses () have the highest precedence and can be used to change the order of evaluation.
2. Unary '-' (negate) and '+' (positive) have next higher precedence.
3. The multiplication (*), division (/) and modulus (%) have the same precedence. They take precedence over addition (+) and subtraction (-). For
example, 1+2*3-4/5+6%7 is interpreted as 1+(2*3)-(4/5)+(6%7).
4. Within the same precedence level (i.e., addition/subtraction and multiplication/division/modulus), the expression is evaluated from left to right
(called left-associative). For examples, 1+2-3+4 is evaluated as ((1+2)-3)+4, and 1*2%3/4 is ((1*2)%3)/4.
[Link] 14/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
Your program typically contains data of many types, e.g., count and sum are int, average and gpa are double, and message is a String. Hence, it is
important to understand how Java handles types in your programs.
The arithmetic operators (+, -, *, /, %) are only applicable to primitive number types: byte, short, int, long, float, double, and char. They are not
applicable to boolean.
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
5. byte ⊕ double ⇒ int ⊕ double ⇒ double ⊕ double ⇒ double
[Link] 15/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
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 [Link](x, y) to
evaluate x raises to power y; or write your own code.
4.5 Overflow/Underflow
Study the output of the following program:
/**
* Illustrate "int" overflow
*/
public class OverflowTest {
public static void main(String[] args) {
// Range of int is [-2147483648, 2147483647]
int i1 = 2147483647; // maximum int
[Link](i + 1); //-2147483648 (overflow)
[Link](i + 2); //-2147483647 (overflow)
[Link](i + 3); //-2147483646 (overflow)
[Link](i * 2); //-2 (overflow)
[Link](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" @ [Link].
/**
* Test preciseness for int/float/double
*/
public class TestPreciseness {
public static void main(String[] args) {
// doubles are NOT precise
[Link](2.2 + 4.4); //6.6000000000000005
[Link](6.6 - 2.2 - 4.4); //-8.881784197001252E-16 (NOT Zero!)
// Compare two doubles
[Link]((6.6) == (2.2 + 4.4)); //false
[Link] 16/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
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.
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:
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).
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;
[Link] 17/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
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)
[Link]("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?
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"
4.9 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.
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.
[Link] 18/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
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:
var++ Return the old value of var for the other y = x++; oldX = x;
(Post-Increment) operation x = x + 1;
in the same statement, then increment var. y = oldX;
var-- Return the old value of var for the other y = x--; oldX = x;
(Post-Decrement) operation x = x - 1;
in the same statement, then decrement var. 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.
[Link] 19/70
27.09.2023 15:17 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
Examples:
// Return true if x is between 0 and 100 (inclusive)
(x >= 0) && (x <= 100)
// wrong to use 0 <= x <= 100
[Link] 20/70
27.09.2023 15:17 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 [Link](str2) instead. This will be
elaborated later.
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,
"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,
[Link]("The sum is: " + sum); // Value of "sum" converted to String and concatenated
[Link]("The square of " + input + " is " + squareInput);
[Link] 21/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
5. Flow Control
There are three basic flow control constructs - sequential, conditional (or decision), and loop (or iteration), as illustrated below.
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 { }
[Link] 22/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
[Link]("Found new min");
}
// if-then-else
int mark = 50;
if (mark >= 50)
[Link]("PASS"); // Only one statement in the block, can omit { }
else { // More than one statements in the block, need { }
[Link]("FAIL");
[Link]("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
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!
[Link] 23/70
27.09.2023 15:17 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]
[Link]("A");
} else if (mark >= 65) { // [65, 79]
[Link]("B");
} else if (mark >= 50) { // [50, 64]
[Link]("C");
} else { // [0, 49]
[Link]("F");
}
// OR
if (mark < 50) { // [0, 49]
[Link]("F");
} else if (mark < 65) { // [50, 64]
[Link]("C");
} else if (mark < 80) { // [65, 79]
[Link]("B");
} else { // [80, 100]
[Link]("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
[Link]("i and j are zero");
else [Link]("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)
if (j == 0)
[Link]("i and j are zero");
else // associated with if (j == 0) - the nearest if
[Link]("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:
[Link] 24/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
[Link]("i is zero, j is not zero"); // non-ambiguous for inner-if
}
}
switch-case-default
[Link] 25/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
result = num1 * num2; break;
case '/':
result = num1 / num2; break;
default:
[Link]("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,
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.
[Link] 26/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
++number; // update
}
[Link]("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
}
[Link]("factorial is: " + factorial);
// 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);
[Link]("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;
}
[Link]("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.
[Link] 27/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
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.
Example: Below is an example of using while-do with a boolean flag. The boolean flag is initialized to false to ensure that the loop is entered.
// Game loop
boolean gameOver = false;
while (!gameOver) {
[Link] 28/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
// play the game
......
// Update the game state
// Set gameOver to true if appropriate to exit the game loop
if ( ...... ) {
gameOver = true; // exit the loop upon the next iteration test
}
}
Example: Suppose that your program prompts user for a number between 1 to 10, and checks for valid input. A do-while loop with a boolean flag
could be more appropriate as it prompts for input at least once, and repeat again and again if the input is invalid.
The test, however, must be a boolean expression that returns a boolean true or false.
The return statement: You could also use a "return" statement in the main() method to terminate the main() and return control back to the
Java Runtime. For example,
public static void main(String[] args) {
...
if (errorCount > 10) {
[Link]("too many errors");
return; // Terminate and return control to Java Runtime from main()
}
...
}
6. Input/Output
[Link] 29/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
Java SE 5 introduced a new method called printf() for formatted output (which is modeled after C Language's printf()). printf() takes the
following form:
printf(formattingString, arg1, arg2, arg3, ... );
Formatting-string contains both normal texts and the so-called Format Specifiers. Normal texts (including white spaces) will be printed as they are.
Format specifiers, in the form of "%[flags][width]conversionCode", will be substituted by the arguments following the formattingString,
usually in a one-to-one and sequential manner. A format specifier begins with a '%' and ends with the conversionCode, e.g., %d for integer, %f for
floating-point number (float and double), %c for char and %s for String. An optional width can be inserted in between to specify the field-width.
Similarly, an optional flags can be used to control the alignment, padding and others. For examples,
%d, %αd: integer printed in α spaces (α is optional), right-aligned. If α is omitted, the number of spaces is the length of the integer.
%s, %αs: String printed in α spaces (α is optional), right-aligned. If α is omitted, the number of spaces is the length of the string (to fit the
string).
%f, %α.βf, %.βf: Floating point number (float and double) printed in α spaces with β decimal digits (α and β are optional). If α is omitted, the
number of spaces is the length of the floating-point number.
%n: a system-specific new line (Windows uses "\r\n", Unix and macOS "\n").
Examples:
Example Output
// Without specifying field-width Hi,|Hello|123|45.600000|,@xyz
[Link]("Hi,|%s|%d|%f|,@xyz%n", "Hello", 123, 45.6);
// Specifying the field-width and decimal places for double Hi,| Hello| 123| 45.60|,@xyz
[Link]("Hi,|%6s|%6d|%6.2f|,@xyz%n", "Hello", 123, 45.6);
// To print a '%', use %% (as % has special meaning) The rate is: 1.20%.
[Link]("The rate is: %.2f%%.%n", 1.2);
Take note that printf() does not advance the cursor to the next line after printing. You need to explicitly print a newline character (via %n) at the
end of the formatting-string to advance the cursor to the next line, if desires, as shown in the above examples.
There are many more format specifiers in Java. Refer to JDK Documentation for the detailed descriptions (@
[Link] for JDK 10).
(Also take note that printf() take a variable number of arguments (or varargs), which is a new feature introduced in JDK 5 in order to support
printf())
You can read input from keyboard via [Link] (standard input device).
JDK 5 introduced a new class called Scanner in package [Link] to simplify formatted input (and a new method printf() for formatted output
described earlier). You can construct a Scanner to scan input from [Link] (keyboard), and use methods such as nextInt(), nextDouble(),
next() to parse the next int, double and String token (delimited by white space of blank, tab and newline).
[Link] 30/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
[Link]("Enter a string: "); // Show prompting message
str = [Link](); // Use next() to read a String token, up to white space
[Link](); // Scanner not longer needed, close it
You can also use method nextLine() to read in the entire line, including white spaces, but excluding the terminating newline.
/**
* Test Scanner's nextLine()
*/
import [Link]; // Needed to use the Scanner
public class ScannerNextLineTest {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter a string (with space): ");
// Use nextLine() to read entire line including white spaces,
// but excluding the terminating newline.
String str = [Link]();
[Link]();
[Link]("%s%n", str);
}
}
Try not to mix nextLine() and nextInt()|nextDouble()|next() in a program (as you may need to flush the newline from the input buffer).
The Scanner supports many other input formats. Check the JDK documentation page, under module [Link] ⇒ package [Link] ⇒ class
Scanner ⇒ Method (@ [Link] for JDK 10).
6.3 Code Example: Prompt User for Two Integers and Print their Sum
The following program prompts user for two integers and print their sum. For examples,
Enter first integer: 8
Enter second integer: 9
The sum is: 17
// Compute sum
sum = number1 + number2;
// Display result
[Link]("The sum is: " + sum); // Print with newline
}
}
Next $20,000 10
[Link] 31/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
Next $20,000 20
The remaining 30
For example, suppose that the taxable income is $85000, the income tax payable is $20000*0% + $20000*10% + $20000*20% + $25000*30%.
Write a program called IncomeTaxCalculator that reads the taxable income (in int). The program shall calculate the income tax payable (in
double); and print the result rounded to 2 decimal places.
// Declare variables
int taxableIncome;
double taxPayable;
[Link] 32/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
The -1 is known as the sentinel value. (In programming, a sentinel value, also referred to as a flag value, trip value, rogue value, signal value, or
dummy data, is a special value which uses its presence as a condition of termination.)
// Declare variables
int taxableIncome;
double taxPayable;
Notes:
1. The coding pattern for handling input with sentinel (terminating) value is as follows:
[Link] 33/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
import [Link];
/**
* Guess a secret number between 0 and 99.
*/
public class NumberGuess {
public static void main(String[] args) {
// Define variables
final int SECRET_NUMBER; // Secret number to be guessed
int numberIn; // The guessed number entered
int trialNumber = 0; // Number of trials so far
boolean done = false; // boolean flag for loop control
Scanner in = new Scanner([Link]);
Notes:
1. The above program uses a boolean flag to control the loop, in the following coding pattern:
boolean done = false;
while (!done) {
if (......) {
done = true; // exit the loop upon the next iteration
.....
}
...... // done remains false. repeat loop
}
[Link] 34/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
String str = [Link](); // next int
String line = [Link](); // entire line
To open a file via new File(filename), you need to handle the so-called FileNotFoundException, i.e., the file that you are trying to open cannot
be found. Otherwise, you cannot compile your program. There are two ways to handle this exception: throws or try-catch.
/**
* Input from File.
* Technique 1: Declare "throws FileNotFoundException" in the enclosing main() method
*/
import [Link]; // Needed for using Scanner
import [Link]; // Needed for file operation
import [Link]; // Needed for file operation
public class TextFileScannerWithThrows {
public static void main(String[] args)
throws FileNotFoundException { // Declare "throws" here
int num1;
double num2;
String name;
Scanner in = new Scanner(new File("[Link]")); // Scan input from text file
num1 = [Link](); // Read int
num2 = [Link](); // Read double
name = [Link](); // Read String
[Link]("Hi %s, the sum of %d and %.2f is %.2f%n", name, num1, num2, num1+num2);
[Link]();
}
}
To run the above program, create a text file called [Link] containing:
1234
55.66
Paul
/**
* Input from File.
* Technique 2: Use try-catch to handle exception
*/
import [Link]; // Needed for using Scanner
import [Link]; // Needed for file operation
import [Link]; // Needed for file operation
public class TextFileScannerWithCatch {
public static void main(String[] args) {
int num1;
double num2;
String name;
try { // try these statements
Scanner in = new Scanner(new File("[Link]"));
num1 = [Link](); // Read int
num2 = [Link](); // Read double
name = [Link](); // Read String
[Link]("Hi %s, the sum of %d and %.2f is %.2f%n", name, num1, num2, num1+num2);
[Link]();
} catch (FileNotFoundException ex) { // catch and handle the exception here
[Link](); // print the stack trace
}
}
}
/**
* Output to File.
* Technique 1: Declare "throws FileNotFoundException" in the enclosing main() method
*/
import [Link];
import [Link]; // <== note
import [Link]; // <== note
public class TextFileFormatterWithThrows {
public static void main(String[] args)
throws FileNotFoundException { // <== note
// Construct a Formatter to write formatted output to a text file
[Link] 35/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
Formatter out = new Formatter(new File("[Link]"));
// Write to file with format() method (similar to printf())
int num1 = 1234;
double num2 = 55.66;
String name = "Paul";
[Link]("Hi %s,%n", name);
[Link]("The sum of %d and %.2f is %.2f%n", num1, num2, num1 + num2);
[Link](); // Close the file
[Link]("Done"); // Print to console
}
}
Run the above program, and check the outputs in text file "[Link]".
/**
* Output to File.
* Technique 2: Use try-catch to handle exception
*/
import [Link];
import [Link]; // <== note
import [Link]; // <== note
1 /**
2 * Input via a Dialog box
3 */
4 import [Link]; // Needed to use JOptionPane
5 public class JOptionPaneTest {
6 public static void main(String[] args) {
7 String radiusStr;
8 double radius, area;
9 // Read input String from dialog box
10 radiusStr = [Link]("Enter the radius of the circl
11 radius = [Link](radiusStr); // Convert String to double
12 area = radius*radius*[Link];
13 [Link]("The area is " + area);
14 }
15 }
[Link] 36/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
To use the new Console class, you first use [Link]() to retrieve the Console object corresponding to the current system console.
You can then use methods such as readLine() to read a line. You can optionally include a prompting message with format specifiers (e.g., %d, %s) in
the prompting message.
You can use [Link]() for formatted output with format specifiers such as %d, %s. You can also connect the Console to a Scanner for formatted
input, i.e., parsing primitives such as int, double, for example,
Example:
/*
* Testing [Link] class
*/
import [Link];
import [Link];
public class ConsoleTest {
public static void main(String[] args) {
Console con = [Link](); // Retrieve the Console object
// Console class does not work in Eclipse/NetBeans
if (con == null) {
[Link]("Console Object is not available.");
[Link](1);
}
The Console class also provides a secure mean for password entry via method readPassword(). This method disables input echoing and keep the
password in a char[] instead of a String. The char[] containing the password can be and should be overwritten, removing it from memory as
soon as it is no longer needed. (Recall that Strings are immutable and cannot be overwritten. When they are longer needed, they will be garbage-
collected at an unknown instance.)
import [Link];
import [Link];
/**
* Inputting password via Console
*/
public class ConsolePasswordTest {
static String login;
static char[] password;
[Link] 37/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
}
}
It is estimated that over the lifetime of a program, 20 percent of the effort will go into the original creation and testing of the code, and 80 percent
of the effort will go into the subsequent maintenance and enhancement. Writing good programs which follow standard conventions is critical in the
subsequent maintenance and enhancement!!!
// Missing semi-colon
[Link]("Hello")
error: ';' expected
[Link]("Hello")
^
2. Runtime Error: The program can compile, but fail to run successfully. This can also be fixed easily, by checking the runtime error messages. For
examples,
// Divide by 0 Runtime error
int count = 0, sum = 100, average;
average = sum / count;
Exception in thread "main" [Link]: / by zero
3. Logical Error: The program can compile and run, but produces incorrect results (always or sometimes). This is the hardest error to fix as there
is no error messages - you have to rely on checking the output. It is easy to detect if the program always produces wrong output. It is extremely
hard to fix if the program produces the correct result most of the times, but incorrect result sometimes. For example,
// Can compile and run, but give wrong result – sometimes!
if (mark > 50) {
[Link]("PASS");
} else {
[Link]("FAIL");
}
This kind of errors is very serious if it is not caught before production. Writing good programs helps in minimizing and detecting these errors. A
good testing strategy is needed to ascertain the correctness of the program. Software testing is an advanced topics which is beyond our
current scope.
[Link] 38/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
1 import [Link];
2 /**
3 * Prompt user for the size; and print Square pattern
4 */
5 public class PrintSquarePattern {
6 public static void main (String[] args) {
7 // Declare variables
8 final int SIZE; // size of the pattern to be input
9
[Link] 39/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
9
10
// Prompt user for the size and read input as "int"
11
Scanner in = new Scanner([Link]);
12
[Link]("Enter the size: ");
13
SIZE = [Link]();
14
[Link]();
15
16
// Use nested-loop to print a 2D pattern
17
// Outer loop to print ALL the rows
18
for (int row = 1; row <= SIZE; row++) {
19
// Inner loop to print ALL the columns of EACH row
20
for (int col = 1; col <= SIZE; col++) {
21
[Link]("* ");
22
}
23
// Print a newline after all the columns
24
[Link]();
25
}
26
}
27
}
This program contains two nested for-loops. The inner loop is used to print a row of "* ", which is followed by printing a newline. The outer loop
repeats the inner loop to print all the rows.
for (int row = 1; row <= ROW_SIZE; row++) { // outer loop for rows
...... // before each row
for (int col = 1; col <= COL_SIZE; col++) { // inner loop for columns
if (......) {
[Link](......); // without newline
} else {
[Link](......);
}
}
...... // after each row
[Link](); // Print a newline after all the columns
}
You need to print an additional space for even-number rows. You could do so by adding the following statement before the inner loop.
if ((row % 2) == 0) { // print a leading space for even-numbered rows
[Link](" ");
}
[Link] 40/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
1 import [Link];
2 /**
3 * Prompt user for the size and print the multiplication table.
4 */
5 public class PrintTimeTable {
6 public static void main(String[] args) {
7 // Declare variables
8 final int SIZE; // size of table to be input
9
10 // Prompt for size and read input as "int"
11 Scanner in = new Scanner([Link]);
12 [Link]("Enter the size: ");
13 SIZE = [Link]();
14 [Link]();
15
16 // Print header row
17 [Link](" * |");
18 for (int col = 1; col <= SIZE; ++col) {
19 [Link]("%4d", col);
20 }
21 [Link](); // End row with newline
22 // Print separator row
23 [Link]("----");
24 for (int col = 1; col <= SIZE; ++col) {
25 [Link]("%4s", "----");
26 }
27 [Link](); // End row with newline
28
29 // Print body using nested-loops
30 for (int row = 1; row <= SIZE; ++row) { // outer loop
31 [Link]("%2d |", row); // print row header first
32 for (int col = 1; col <= SIZE; ++col) { // inner loop
33 [Link]("%4d", row*col);
34 }
35 [Link](); // print newline after all columns
36 }
37 }
38 }
TRY:
1. Write programs called PrintPattern1x, which prompts user for the size and prints each these patterns.
# * # * # * # * # # # # # # # # # # # # # # # # 1 1
# * # * # * # * # # # # # # # # # # # # # # 2 1 1 2
# * # * # * # * # # # # # # # # # # # # 3 2 1 1 2 3
# * # * # * # * # # # # # # # # # # 4 3 2 1 1 2 3 4
# * # * # * # * # # # # # # # # 5 4 3 2 1 1 2 3 4 5
# * # * # * # * # # # # # # 6 5 4 3 2 1 1 2 3 4 5 6
# * # * # * # * # # # # 7 6 5 4 3 2 1 1 2 3 4 5 6 7
# * # * # * # * # # 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8
(a) (b) (c) (d) (e)
Hints:
The equations for major and opposite diagonals are row = col and row + col = size + 1. Decide on what to print above and below the
diagonal.
2. Write programs called PrintPattern2x, which prompts user for the size and prints each of these patterns.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
(a) (b) (c) (d) (e)
The continue statement aborts the current iteration and continue to the next iteration of the current (innermost) loop.
[Link] 41/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
break and continue are poor structures as they are hard to read and hard to follow. Use them only if absolutely necessary.
Endless loop
for ( ; ; ) { body } is known as an empty for-loop, with empty statement for initialization, test and post-processing. The body of the empty for-
loop will execute continuously (infinite loop). You need to use a break statement to break out the loop.
Similar, while (true) { body } and do { body } while (true) are endless loops.
for (;;) {
...... // Need break inside the loop body
}
while (true) {
...... // Need break inside the loop body
}
do {
...... // Need break inside the loop body
} while (true);
Endless loop is typically a mistake especially for new programmers. You need to break out the loop via a break statement inside the loop body..
Example (break): The following program lists the non-prime numbers between 2 and an upperbound.
/**
* List all non-prime numbers between 2 and an upperbound
*/
public class NonPrimeList {
public static void main(String[] args) {
final int UPPERBOUND = 100;
for (int number = 2; number <= UPPERBOUND; ++number) {
// Not a prime, if there is a factor between 2 and sqrt(number)
int maxFactor = (int)[Link](number);
for (int factor = 2; factor <= maxFactor; ++factor) {
if (number % factor == 0) { // Factor?
[Link](number + " is NOT a prime");
break; // A factor found, no need to search for more factors
}
}
}
}
}
Let's rewrite the above program to list all the primes instead. A boolean flag called isPrime is used to indicate whether the current number is a
prime. It is then used to control the printing.
/**
* List all prime numbers between 2 and an upperbound
*/
public class PrimeListWithBreak {
public static void main(String[] args) {
final int UPPERBOUND = 100;
for (int number = 2; number <= UPPERBOUND; ++number) {
// Not a prime, if there is a factor between 2 and sqrt(number)
int maxFactor = (int)[Link](number);
boolean isPrime = true; // boolean flag to indicate whether number is a prime
for (int factor = 2; factor <= maxFactor; ++factor) {
if (number % factor == 0) { // Factor?
isPrime = false; // number is not a prime
break; // A factor found, no need to search for more factors
}
}
if (isPrime) [Link](number + " is a prime");
}
}
}
Let's rewrite the above program without using break statement. A while loop is used (which is controlled by the boolean flag) instead of for loop
with break.
/**
* List all prime numbers between 2 and an upperbound
*/
public class PrimeList {
public static void main(String[] args) {
final int UPPERBOUND = 100;
for (int number = 2; number <= UPPERBOUND; ++number) {
// Not prime, if there is a factor between 2 and sqrt of number
[Link] 42/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
int maxFactor = (int)[Link](number);
boolean isPrime = true;
int factor = 2;
while (isPrime && factor <= maxFactor) {
if (number % factor == 0) { // Factor of number?
isPrime = false;
}
++factor;
}
if (isPrime) [Link](number + " is a prime");
}
}
}
Example (continue):
/**
* A mystery series created using break and continue
*/
public class MysterySeries {
public static void main(String[] args) {
int number = 1;
while(true) {
++number;
if ((number % 3) == 0) continue;
if (number == 133) break;
if ((number % 2) == 0) {
number += 3;
} else {
number -= 3;
}
[Link](number + " ");
}
}
}
// Can you figure out the output?
// break and continue are hard to read, use it with great care!
Labeled break
In a nested loop, the break statement breaks out the innermost loop and continue into the outer loop. At times, there is a need to break out all the
loops (or multiple loops). This is clumsy to achieve with boolean flag, but can be done easily via the so-called labeled break. You can add a label to
a loop in the form of labelName: loop. For example,
Labeled continue
In a nested loop, similar to labeled break, you can use labeled continue to continue into a specified loop. For example,
[Link] 43/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
for (.....) {
for (......) { // level-3 loop
if (...) continue level1; // continue the next iteration of level-1 loop
if (...) continue level2: // continue the next iteration of level-2 loop
......
}
}
}
Again, labeled break and continue are not structured and hard to read. Use them only if absolutely necessary.
Example (Labeled break): Suppose that you are searching for a particular number in a 2D array.
In arithmetic operations, char (and byte, and short) is first converted to int. In Java, arithmetic operations are only carried out in int, long,
float, or double; NOT in byte, short, and char.
Hence, char ⊕ char ⇒ int ⊕ int ⇒ int, where ⊕ denotes an binary arithmetic operation (such as +, -, *, / and %). You may need to
explicitly cast the resultant int back to char. For examples,
[Link] 44/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
[Link](c1 + c2); // Print int 113
[Link]((char)(c1 + c2)); // Print char 'q'
Similar, char ⊕ int ⇒ int ⊕ int ⇒ int. You may need to explicitly cast the resultant int back to char. For examples,
However, for compound operators (such as +=, -=, *=, /=, %=), the evaluation is carried out in int, but the result is casted back to the LHS
automatically. For examples,
char c4 = '0'; // Code number 48
c4 += 5; // Automatically cast back to char '5'
[Link](c4); // Print char '5'
For increment (++) and decrement (--) of char (and byte, and short), there is no promotion to int. For examples,
That is, suppose c is a char between '0' and '9', (c - '0') is the corresponding int 0 to 9.
The following program illustrates how to convert a hexadecimal character (0-9, A-F or a-f) to its decimal equivalent (0-15), by subtracting the
appropriate base char.
For examples,
[Link] 45/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
[Link]([Link](str)); // return boolean false
[Link]([Link](str)); // return boolean true
// (str == anotherStr) to compare two Strings is WRONG!!!
To check all the available methods for String, open JDK Documentation ⇒ Select "API documentation" ⇒ Click "FRAMES" (top menu) ⇒ From
"Modules" (top-left pane), select "[Link]" ⇒ From "[Link] Packages" (top-left pane), select "[Link]" ⇒ From "Classes" (bottom-left
pane), select "String" ⇒ choose "SUMMARY" "METHOD" (right pane) (@ [Link] for JDK
10).
For examples,
String to int/byte/short/long
You could use the JDK built-in methods [Link](anIntStr) to convert a String containing a valid integer literal (e.g., "1234") into an int
(e.g., 1234). The runtime triggers a NumberFormatException if the input string does not contain a valid integer literal (e.g., "abc"). For example,
Similarly, you could use methods [Link](aByteStr), [Link](aShortStr), [Link](aLongStr) to convert a String
containing a valid byte, short or long literal to the primitive type.
String to double/float
You could use [Link](aDoubleStr) or [Link](aFloatStr) to convert a String (containing a floating-point literal) into a
double or float, e.g.
String to char
You can use [Link](index) to extract individual character from a String, where index begins at 0 and up to [Link]()-1, e.g.,
String to boolean
You can use method [Link](aBooleanStr) to convert string of "true" or "false" to boolean true or false, e.g.,
[Link] 46/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
For examples,
// Using String concatenation operator '+' with an empty String (applicable to ALL primitive types)
String str1 = 123 + ""; // int 123 -> String "123"
String str2 = 12.34 + ""; // double 12.34 -> String "12.34"
String str3 = 'c' + ""; // char 'c' -> String "c"
String str4 = true + ""; // boolean true -> String "true"
[Link]("Hi, %d, %.1f%n", 11, 22.22); // Send the formatted String to console
There is a similar function called [Link]() which returns the formatted string, instead of sending to the console, e.g.,
String str = [Link]("%.1f", 1.234); // Returns a String "1.2" (for further operations)
1 import [Link];
2 /**
3 * Prompt user for a string; and print the input string in reverse order.
4 */
5 public class ReverseString {
6 public static void main(String[] args) {
7 // Declare variables
8 String inStr; // input String
9 int inStrLen; // length of the input String
10
11 // Prompt and read input as "String"
12 Scanner in = new Scanner([Link]);
13 [Link]("Enter a String: ");
14 inStr = [Link]();
15 inStrLen = [Link]();
16 [Link]();
17
18 [Link]("The reverse is: ");
19 // Use a for-loop to extract each char in reverse order
20 for (int inCharIdx = inStrLen - 1; inCharIdx >= 0; --inCharIdx) {
21 [Link]([Link](inCharIdx));
22 }
23 [Link]();
24 }
25 }
[Link] 47/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
1 import [Link];
2 /**
3 * Check if the input string is a valid binary string.
4 */
5 public class ValidateBinString {
6 public static void main(String[] args) {
7 // Declare variables
8 String inStr; // The input string
9 int inStrLen; // The length of the input string
10 char inChar; // Each char of the input string
11 boolean isValid; // "is" or "is not" a valid binary string?
12
13 // Prompt and read input as "String"
14 Scanner in = new Scanner([Link]);
15 [Link]("Enter a binary string: ");
16 inStr = [Link]();
17 inStrLen = [Link]();
18 [Link]();
19
20 isValid = true; // Assume that the input is valid, unless our check fails
21 for (int inCharIdx = 0; inCharIdx < inStrLen; ++inCharIdx) {
22 inChar = [Link](inCharIdx);
23 if (!(inChar == '0' || inChar == '1')) {
24 isValid = false;
25 break; // break the loop upon first error, no need to continue for more errors
26 // If this is not encountered, isValid remains true after the loop.
27 }
28 }
29 [Link]("\"" + inStr + "\" is " + (isValid ? "" : "NOT ") + "a binary string");
30 }
31 }
Version 2
1 import [Link];
2 /**
3 * Check if the input string is a valid binary string.
4 */
5 public class ValidateBinStringV2 {
6 public static void main(String[] args) {
7 // Declare variables
8 String inStr; // The input string
9 int inStrLen; // The length of the input string
10 char inChar; // Each char of the input string
11
12 // Prompt and read input as "String"
13 Scanner in = new Scanner([Link]);
14 [Link]("Enter a binary string: ");
15 inStr = [Link]();
16 inStrLen = [Link]();
17 [Link]();
18
19 for (int inCharIdx = 0; inCharIdx < inStrLen; ++inCharIdx) {
20 inChar = [Link](inCharIdx);
21 if (!(inChar == '0' || inChar == '1')) {
22 [Link]("\"" + inStr + "\" is NOT a binary string");
23 return; // exit the program upon the first error detected
24 }
25 }
26 // for-loop completed. No error detected.
27 [Link]("\"" + inStr + "\" is a binary string");
28 }
29 }
This version, although shorter, are harder to read, and harder to maintain.
[Link] 48/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
1 import [Link];
2 /**
3 * Prompt user for a binary string, and convert into its equivalent decimal number.
4 */
5 public class Bin2Dec {
6 public static void main(String[] args) {
7 // Declare variables
8 String binStr; // The input binary string
9 int binStrLen; // The length of binStr
10 int dec = 0; // The decimal equivalent, to accumulate from 0
11 char binChar; // Each individual char of the binStr
12
13 // Prompt and read input as "String"
14 Scanner in = new Scanner([Link]);
15 [Link]("Enter a binary string: ");
16 binStr = [Link]();
17 binStrLen = [Link]();
18 [Link]();
19
20 // Process char by char from the right (i.e. Least-significant bit)
21 // using exponent as loop index.
22 for (int exp = 0; exp < binStrLen ; ++exp) {
23 binChar = [Link](binStrLen - 1 - exp);
24 // 3 cases: '1' (add to dec), '0' (valid but do nothing), other (error)
25 if (binChar == '1') {
26 dec += (int)[Link](2, exp); // cast the double result back to int
27 } else if (binChar == '0') {
28 } else {
29 [Link]("error: invalid binary string \"" + binStr + "\"");
30 return; // or [Link](1);
31 }
32 }
33
34 // Print result
35 [Link]("The equivalent decimal for \"" + binStr + "\" is " + dec);
36 }
37 }
Notes:
1. The conversion formula is:
binStr = bn-1bn-2....b2b1b0 hi∈{0,1} where b0 is the least-significant bit
2. We use [Link](idx) to extract each individual char from the binStr. The idx begins at zero, and increases from left-to-right. On the
other hand, the exponent number increases from right-to-left, as illustrated in the following example:
binStr : 1 0 1 1 1 0 0 1
charAt(idx) : 0 1 2 3 4 5 6 7 (idx increases from the left)
[Link](2, exp) : 7 6 5 4 3 2 1 0 (exp increases from the right)
[Link]() = 8
idx + exp = [Link]() - 1
3. This code uses exp as the loop index, and computes the idx for charAt() using the relationship idx + exp = [Link]() - 1. You
could also use the idx as the loop index (see next example).
4. We use the built-in function [Link](x, y) to compute the exponent, which takes two doubles and return a double. We need to explicitly
cast the resultant double back to int for dec.
5. There are 3 cases to handle: '1' (add to dec), '0' (valid but do nothing for multiply by 0) and other (error). We can write the nested-if as
follows, but that is harder to read:
if (binChar == '1') {
dec += (int)[Link](2, exp); // cast the double result back to int
} else if (binChar != '0') {
[Link]("error: invalid binary string \"" + binStr + "\"");
return; // or [Link](1);
} // else (binChar == '0') do nothing
6. You can use Scanner's nextInt(int radix) method to read an int in the desired radix. Try reading a binary number (radix of 2) and print its
decimal equivalent. For example,
number = [Link](2); // Input in binary e.g., 10110100
[Link](number); // 180
[Link] 49/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
The following program prompts user for a hexadecimal string and converts into its equivalent decimal number. For example,
1 import [Link];
2 /**
3 * Prompt user for the hexadecimal string, and convert to its equivalent decimal number
4 */
5 public class Hex2Dec {
6 public static void main(String[] args) {
7 // Declare variables
8 String hexStr; // The input hexadecimal String
9 int hexStrLen; // The length of hexStr
10 int dec = 0; // The decimal equivalent, to accumulate from 0
11
12 // Prompt and Read input as "String"
13 Scanner in = new Scanner([Link]);
14 [Link]("Enter a Hexadecimal string: ");
15 hexStr = [Link]();
16 hexStrLen = [Link]();
17 [Link]();
18
19 // Process char by char from the left (most-significant digit)
20 for (int charIdx = 0; charIdx < hexStrLen; ++charIdx) {
21 char hexChar = [Link](charIdx);
22 int expFactor = (int)[Link](16, hexStrLen - 1 - charIdx);
23 // 23 cases: '0'-'9', 'a'-'f', 'A'-'F', other (error)
24 if (hexChar == '0') {
25 // Valid but do nothing
26 } else if (hexChar >= '1' && hexChar <= '9') {
27 dec += (hexChar - '0') * expFactor; // Convert char '0'-'9' to int 0-9
28 } else if (hexChar >= 'a' && hexChar <= 'f') {
29 dec += (hexChar - 'a' + 10) * expFactor; // Convert char 'a'-'f' to int 10-15
30 } else if (hexChar >= 'A' && hexChar <= 'F') {
31 dec += (hexChar - 'A' + 10) * expFactor; // Convert char 'A'-'F' to int 10-15
32 } else {
33 [Link]("error: invalid hex string \"" + hexStr + "\"");
34 return; // or [Link](1);
35 }
36 }
37 [Link]("The equivalent decimal for \"" + hexStr + "\" is " + dec);
38 }
39 }
Notes:
1. The conversion formula is:
hexStr = hn-1hn-2....h2b1h0 hi∈{0,..,9,A,..,F} where h0 is the least-significant digit
2. In this example, we use the charIdx as the loop index, and compute the exponent via the relationship charIdx + exp = [Link]() -
1 (See the illustration in the earlier example).
3. You could write a big switch of 23 cases (0-9, A-F, a-f, and other). But take note how they are reduced to 5 cases.
a. To convert hexChar '1' to '9' to int 1 to 9, we subtract the hexChar by the base '0'.
b. Similarly, to convert hexChar 'a' to 'f' (or 'A' to 'F') to int 10 to 15, we subtract the hexChar by the base 'a' (or 'A') and add 10.
4. You may use [Link]() to convert the input string to lowercase to further reduce the number of cases. But You need to keep the
original String for output in this example (otherwise, you could use [Link]().toLowerCase() directly).
10. Arrays
Suppose that you want to find the average of the marks for a class of 30 students, you certainly do not want to create 30 variables: mark1, mark2, ...,
mark30. Instead, You could use a single variable, called an array, with 30 elements (or items).
An array is an ordered collection of elements of the same type, identified by a pair of square brackets [ ]. To use an array, you need to:
1. Declare the array with a name and a type. Use a plural name for array, e.g., marks, rows, numbers. All elements of the array belong to the same
type.
[Link] 50/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
2. Allocate the array using new operator, or through initialization, e.g.,
When an array is constructed via the new operator, all the elements are initialized to their default value, e.g., 0 for int, 0.0 for double, false for
boolean, and null for objects. [Unlike C/C++, which does NOT initialize the array contents.]
When an array is declared but not allocated, it has a special value called null.
int[] marks = new int[5]; // Declare & allocate a 5-element int array
// Assign values to the elements
marks[0] = 95;
marks[1] = 85;
marks[2] = 77;
marks[3] = 69;
marks[4] = 66;
// Retrieve elements of the array
[Link](marks[0]);
[Link](marks[3] + marks[4]);
In Java, the length of array is kept in an associated variable called length and can be retrieved using "[Link]", e.g.,
int[] factors = new int[5]; // Declare and allocate a 5-element int array
int numFactors = [Link]; // numFactor is 5
Unlike languages like C/C++, Java performs array index-bound check at the
runtime. In other words, for each reference to an array element, the index is
checked against the array's length. If the index is outside the range of [0,
[Link]-1], Java Runtime will signal an exception called
ArrayIndexOutOfBoundException. It is important to note that checking array
index-bound consumes computation power, which inevitably slows down the
processing. However, the benefits gained in terms of good software
engineering out-weight the slow down in speed.
1 /**
2 * Find the mean and standard deviation of numbers kept in an array
3 */
4 public class MeanSDArray {
5 public static void main(String[] args) {
6 // Declare variable
7 int[] marks = {74, 43, 58, 60, 90, 64, 70};
8 int sum = 0;
9 int sumSq = 0;
10 double mean, stdDev;
11
12 // Compute sum and square-sum using loop
13 for (int i = 0; i < [Link]; ++i) {
14 sum += marks[i];
15 sumSq += marks[i] * marks[i];
16 }
17
[Link] 51/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
18 mean = (double)sum / [Link];
19 stdDev = [Link]((double)sumSq / [Link] - mean * mean);
20
21 // Print results
22 [Link]("Mean is: %.2f%n", mean);
23 [Link]("Standard deviation is: %.2f%n", stdDev);
24 }
}
Syntax Example
for (type item : anArray) { int[] numbers = {8, 2, 6, 4, 3};
body; int sum = 0, sumSq = 0;
} for (int number : numbers) { // for each int number in int[] numbers
// type must be the same as the sum += number;
// anArray's type sumSq += number * number;
}
[Link]("The sum is: " + sum);
[Link]("The square sum is: " + sumSq);
This loop shall be read as "for each element in the array...". The loop executes once for each element in the array, with the element's value copied
into the declared variable. The for-each loop is handy to transverse all the elements of an array. It requires fewer lines of code, eliminates the loop
counter and the array index, and is easier to read. However, for array of primitive types (e.g., array of ints), it can read the elements only, and
cannot modify the array's contents. This is because each element's value is copied into the loop's variable, instead of working on its original copy.
In many situations, you merely want to transverse thru the array and read each of the elements. For these cases, enhanced for-loop is preferred
and recommended over other loop constructs.
1 import [Link];
2 /**
3 * Prompt user for the length and all the elements of an array; and print [a1, a2, ..., an]
4 */
5 public class ReadPrintArray {
6 public static void main(String[] args) {
7 // Declare variables
8 final int NUM_ITEMS;
9 int[] items; // Declare array name, to be allocated after numItems is known
10
11 Scanner in = new Scanner([Link]);
12 // Prompt for a non-negative integer for the number of items;
13 // and read the input as "int". No input validation.
14 [Link]("Enter the number of items: ");
15 NUM_ITEMS = [Link]();
16
17 // Allocate the array
18 items = new int[NUM_ITEMS];
19
20 // Prompt and read the items into the "int" array, only if array length > 0
21 if ([Link] > 0) {
22 [Link]("Enter the value of all items (separated by space): ");
23 for (int i = 0; i < [Link]; ++i) {
24 items[i] = [Link]();
25 }
26 }
27 [Link]();
28
29 // Print array contents, need to handle first item and subsequent items differently
30 [Link]("The values are: [");
31 for (int i = 0; i < [Link]; ++i) {
32 if (i == 0) {
33 // Print the first item without a leading commas
34 [Link](items[0]);
35
[Link] 52/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
35 } else {
36 // Print the subsequent items with a leading commas
37 [Link](", " + items[i]);
38 }
39 }
40 [Link]("]");
41 }
42 }
[Link]() (JDK 5)
JDK 5 provides an built-in methods called [Link](anArray), which returns a String in the form [a0, a1, ..., an]. You need to
import [Link]. For examples,
[Link]([Link](a1)); //[6, 1, 3, 4, 5]
[Link]([Link](a2)); //[]
[Link]([Link](a3)); //[0.0]
a3[0] = 2.2;
[Link]([Link](a3)); //[2.2]
}
}
0- 9: **
10- 19:
20- 29:
30- 39:
40- 49:
50- 59: ***
60- 69:
70- 79:
80- 89: *
90-100: **
*
* * *
* * * *
0-9 10-19 20-29 30-39 40-49 50-59 60-69 70-79 80-89 90-100
1 import [Link];
2 import [Link]; // for [Link]()
3 /**
4 * Print the horizontal and vertical histograms of grades.
5 */
6 public class GradesHistograms {
7 public static void main(String[] args) {
8 // Declare variables
9 int numStudents;
10 int[] grades; // Declare array name, to be allocated after numStudents is known
11 int[] bins = new int[10]; // int array of 10 histogram bins for 0-9, 10-19, ..., 90-100
12
[Link] 53/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
13 Scanner in = new Scanner([Link]);
14 // Prompt and read the number of students as "int"
15 [Link]("Enter the number of students: ");
16 numStudents = [Link]();
17
18 // Allocate the array
19 grades = new int[numStudents];
20
21 // Prompt and read the grades into the int array "grades"
22 for (int i = 0; i < [Link]; ++i) {
23 [Link]("Enter the grade for student " + (i + 1) + ": ");
24 grades[i] = [Link]();
25 }
26 [Link]();
27
28 // Print array for debugging
29 [Link]([Link](grades));
30
31 // Populate the histogram bins
32 for (int grade : grades) {
33 if (grade == 100) { // Need to handle 90-100 separately as it has 11 items.
34 ++bins[9];
35 } else {
36 ++bins[grade/10];
37 }
38 }
39 // Print array for debugging
40 [Link]([Link](bins));
41
42 // Print the horizontal histogram
43 // Rows are the histogram bins[0] to bins[9]
44 // Columns are the counts in each bins[i]
45 for (int binIdx = 0; binIdx < [Link]; ++binIdx) {
46 // Print label
47 if (binIdx != 9) { // Need to handle 90-100 separately as it has 11 items
48 [Link]("%2d-%3d: ", binIdx*10, binIdx*10+9);
49 } else {
50 [Link]("%2d-%3d: ", 90, 100);
51 }
52 // Print columns of stars
53 for (int itemNo = 0; itemNo < bins[binIdx]; ++itemNo) { // one star per item
54 [Link]("*");
55 }
56 [Link]();
57 }
58
59 // Find the max value among the bins
60 int binMax = bins[0];
61 for (int binIdx = 1; binIdx < [Link]; ++binIdx) {
62 if (binMax < bins[binIdx]) binMax = bins[binIdx];
63 }
64
65 // Print the Vertical histogram
66 // Columns are the histogram bins[0] to bins[9]
67 // Rows are the levels from binMax down to 1
68 for (int level = binMax; level > 0; --level) {
69 for (int binIdx = 0; binIdx < [Link]; ++binIdx) {
70 if (bins[binIdx] >= level) {
71 [Link](" * ");
72 } else {
73 [Link](" ");
74 }
75 }
76 [Link]();
77 }
78 // Print label
79 for (int binIdx = 0; binIdx < [Link]; ++binIdx) {
80 [Link]("%3d-%-3d", binIdx*10, (binIdx != 9) ? binIdx * 10 + 9 : 100);
81 // Use '-' flag for left-aligned
82 }
83 [Link]();
84 }
85 }
[Link] 54/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
Notes:
1. We use two arrays in this exercise, one for storing the grades of the students (of the length numStudents) and the other to storing the
histogram counts (of length 10).
2. We use a 10-element int arrays called bins, to keep the histogram counts for grades of [0, 9], [10, 19], ..., [90, 100]. Take note that there
are 101 grades between [0, 100], and the last bin has 11 grades (instead of 10 for the rest). The bins's index is grade/10, except grade of 100.
1 import [Link];
2 /**
3 * Prompt user for a hexadecimal string, and print its binary equivalent.
4 */
5 public class Hex2Bin {
6 public static void main(String[] args) {
7 // Define variables
8 String hexStr; // The input hexadecimal String
9 int hexStrLen; // The length of hexStr
10 char hexChar; // Each char in the hexStr
11 String binStr =""; // The equivalent binary String, to accumulate from an empty String
12 // Lookup table for the binary sub-string corresponding to Hex digit '0' (index 0) to 'F' (index 15)
13 final String[] BIN_STRS =
14 {"0000", "0001", "0010", "0011",
15 "0100", "0101", "0110", "0111",
16 "1000", "1001", "1010", "1011",
17 "1100", "1101", "1110", "1111"};
18
19 // Prompt and read input as "String"
20 Scanner in = new Scanner([Link]);
21 [Link]("Enter a Hexadecimal string: ");
22 hexStr = [Link]();
23 hexStrLen = [Link]();
24 [Link]();
25
26 // Process the string from the left (most-significant hex digit)
27 for (int charIdx = 0; charIdx < hexStrLen; ++charIdx) {
28 hexChar = [Link](charIdx);
29 if (hexChar >= '0' && hexChar <= '9') {
30 binStr += BIN_STRS[hexChar - '0']; // index into the BIN_STRS array and concatenate
31 } else if (hexChar >= 'a' && hexChar <= 'f') {
32 binStr += BIN_STRS[hexChar - 'a' + 10];
33 } else if (hexChar >= 'A' && hexChar <= 'F') {
34 binStr += BIN_STRS[hexChar - 'A' + 10];
35 } else {
36 [Link]("error: invalid hex string \"" + hexStr + "\"");
37 return; // or [Link](1);
38 }
39 }
40 [Link]("The equivalent binary for \"" + hexStr + "\" is \"" + binStr + "\"");
41 }
42 }
Notes
1. We keep the binary string corresponding to hex digit '0' to 'F' in an array with indexes of 0-15, used as look-up table.
2. We extract each hexChar, find its array index (0-15), and retrieve the binary string from the array based on the index.
a. To convert hexChar '1' to '9' to int 1 to 9, we subtract the hexChar by the base '0'.
b. Similarly, to convert hexChar 'a' to 'f' (or 'A' to 'F') to int 10 to 15, we subtract the hexChar by the base 'a' (or 'A') and add 10.
1 import [Link];
2 /**
3 * Prompt user for an int, and print its equivalent hexadecimal number.
4
[Link] 55/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
5 */
6 public class Dec2Hex {
7 public static void main(String[] args) {
8 // Declare variables
9 int dec; // The input decimal number in "int"
10 String hexStr = ""; // The equivalent hex String, to accumulate from an empty String
11 int radix = 16; // Hex radix
12 final char[] HEX_CHARS = // Use this array as lookup table for converting 0-15 to 0-9A-F
13 {'0','1','2','3', '4','5','6','7', '8','9','A','B', 'C','D','E','F'};
14
15 // Prompt and read input as "int"
16 Scanner in = new Scanner([Link]);
17 [Link]("Enter a decimal number: ");
18 dec = [Link]();
19 [Link]();
20
21 // Repeated modulus/division and get the hex digits (0-15) in reverse order
22 while (dec > 0) {
23 int hexDigit = dec % radix; // 0-15
24 hexStr = HEX_CHARS[hexDigit] + hexStr; // Append in front of the hex string corresponds to reverse order
25 dec = dec / radix;
26 }
27 [Link]("The equivalent hexadecimal number is " + hexStr);
28 }
}
Notes
1. We use modulus/divide algorithm to get the hex digits (0-15) in reserve order. See "Number System Conversion".
2. We look up the hex digit '0'-'F' from an array using index 0-15.
In the above example, grid is an array of 12 elements. Each of the elements (grid[0] to grid[11]) is an 8-element int array. In other words, grid
is a "12-element array" of "8-element int arrays". Hence, [Link] gives 12 and grid[0].length gives 8.
To be precise, Java does not support multi-dimensional array directly. That is, it does not support syntax like grid[3, 2] like some languages.
Furthermore, it is possible that the arrays in an array-of-arrays have different length.
[Link] 56/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
Take note that the right way to view the "array of arrays" is as shown, instead of
treating it as a 2D table, even if all the arrays have the same length.
For example,
Example: Suppose that we need to evaluate the area of a circle many times, it is better to write a method called getArea(), and re-use it when
needed.
In the above example, a reusable method called getArea() is defined, which receives an argument in double from the caller, performs the
calculation, and return a double result to the caller. In the main(), we invoke getArea() methods thrice, each time with a different parameter.
Take note that there is a transfer of control from the caller to the method called, and from the method back to the caller, as illustrated.
// Examples
// Return circle's area given its radius
public static double getArea(double radius) {
return radius * radius * [Link];
}
[Link] 58/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
}
}
Take note that you need to specify the type of the arguments and the return value in method definition.
Calling Methods
To call a method, simply use methodName(arguments). For examples, to call the above methods:
// Calling getArea()
double area1 = getArea(1.1); // with literal as argument
double r2 = 2.2;
double area2 = getArea(r2); // with variable as argument
double r3 = 3.3;
[Link]("Area is: " + area(r3));
// Calling max()
int result1 = max(5, 8);
int i1 = 7, i2 = 9;
int result2 = max(i1, i2);
[Link]("Max is: " + max(15, 16));
Take note that you need to specify the type in the method definition, but not during invocation.
Another Example:
/** Example of Java Method definition and invocation */
public class EgMinMaxMethod {
// The entry main() method
public static void main(String[] args) {
int a = 6, b = 9, max, min;
max = max(a, b); // invoke method max() with arguments
min = min(a, b); // invoke method min() with arguments
[Link](max + "," + min);
Notice that main() is a method with a return-value type of void. main() is called by the Java runtime, perform the actions defined in the body, and
return nothing back to the Java runtime.
In the above example, the variable (double radius) declared in the signature of getArea(double radius) is known as formal parameter. Its
scope is within the method's body. When the method is invoked by a caller, the caller must supply so-called actual parameters or arguments,
whose value is then used for the actual computation. For example, when the method is invoked via "area1=getArea(radius1)", radius1 is the
actual parameter, with a value of 1.1.
It also provides the main() method to test the isMagic(). For example,
1 import [Link];
2 /**
3 * This program contains a boolean method called isMagic(int number), which tests if the
4 * given number contains the digit 8.
5 */
6 public class MagicNumber {
7 public static void main(String[] args) {
8 // Declare variables
9 int number;
10 Scanner in = new Scanner([Link]);
11
12 // Prompt and read input as "int"
13 [Link]("Enter a positive integer: ");
14 number = [Link]();
15
16 // Call isMagic() to test the input
17 if (isMagic(number)) {
18 [Link](number + " is a magic number");
19 } else {
20 [Link](number + " is not a magic number");
21 }
22 [Link]();
23 }
24
25 /**
26 * Check if the given int contains the digit 8, e.g., 18, 82, 1688.
27 * @param number The given integer
28 * @return true if number contains the digit 8
29 * @Precondition number > 0 (i.e., a positive integer)
30 */
31 public static boolean isMagic(int number) {
32 boolean isMagic = false; // shall change to true if found a digit 8
33
34 // Extract and check each digit
35 while (number > 0) {
36 int digit = number % 10; // Extract the last digit
37 if (digit == 8) {
38 isMagic = true;
39 break; // only need to find one digit 8
40 }
41 number /= 10; // Drop the last digit and repeat
42 }
43 return isMagic;
44 }
45 }
public static void print(int[] array); // Print [a1, a2, ...., an]
public static int min(int[] array); // Return the min of the array
[Link] 60/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
public static int sum(int[] array); // Return the sum of the array
public static double average(int[] array); // Return the average of the array
It also contains the main() method to test all the methods. For example,
Enter the number of items: 5
Enter the value of all items (separated by space): 8 1 3 9 4
The values are: [8, 1, 3, 9, 4]
The min is: 1
The sum is: 25
The average (rounded to 2 decimal places) is: 5.00
1 import [Link];
2 /**
3 * Test various int[] methods.
4 */
5 public class IntArrayMethodsTest {
6 public static void main(String[] args) {
7 // Declare variables
8 final int NUM_ITEMS;
9 int[] items; // Declare array name, to be allocated after numItems is known
10
11 // Prompt for a non-negative integer for the number of items;
12 // and read the input as "int". No input validation.
13 Scanner in = new Scanner([Link]);
14 [Link]("Enter the number of items: ");
15 NUM_ITEMS = [Link]();
16
17 // Allocate the array
18 items = new int[NUM_ITEMS];
19
20 // Prompt and read the items into the "int" array, if array length > 0
21 if ([Link] > 0) {
22 [Link]("Enter the value of all items (separated by space): ");
23 for (int i = 0; i < [Link]; ++i) {
24 items[i] = [Link]();
25 }
26 }
27 [Link]();
28
29 // Test the methods
30 [Link]("The values are: ");
31 print(items);
32 [Link]("The min is: " + min(items));
33 [Link]("The sum is: " + sum(items));
34 [Link]("The average (rounded to 2 decimal places) is: %.2f%n", average(items));
35 }
36
37 /**
38 * Prints the given int array in the form of [x1, x2, ..., xn]
39 * @param array The given int array
40 * @Postcondition Print output as side effect
41 */
42 public static void print(int[] array) {
43 [Link]("[");
44 for (int i = 0; i < [Link]; ++i) {
45 [Link]((i == 0) ? array[i] : ", " + array[i]);
46 }
47 [Link]("]");
48 }
49
50 /**
51 * Get the min of the given int array
52 * @param array The given int array
53 * @return The min value of the given array
54 */
55 public static int min(int[] array) {
56 int min = array[0];
57 for (int i = 1; i < [Link]; ++i) {
58 if (array[i] < min) min = array[i];
59 }
60 return min;
61 }
62
63 /**
64
[Link] 61/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
For example,
Notes:
1. Although there is a variable called number in both the main() and increment() method, there are two distinct copies - one available in main()
and another available in increment() - happen to have the same name. You can change the name of either one, without affecting the
program.
For arrays (and objects - to be described in the later chapter), the array reference is passed into the method and the method can modify the
contents of array's elements. It is known as pass-by-reference. For example,
[Link] 62/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
for (int i = 0; i < [Link]; ++i) ++array[i];
[Link]("Inside method, after operation, array is "
+ [Link](array)); // [10, 6, 7, 2, 5]
}
}
JDK 5 introduces variable arguments (or varargs) and a new syntax "Type...". For example,
Varargs can be used only for the last argument. The three dots (...) indicate that the last argument may be passed as an array or as a sequence of
comma-separated arguments. The compiler automatically packs the varargs into an array. You could then retrieve and process each of these
arguments inside the method's body as an array. It is possible to pass varargs as an array, because Java maintains the length of the array in an
associated variable length.
Notes:
If you define a method that takes a varargs String..., you cannot define an overloaded method that takes a String[].
"varargs" will be matched last among the overloaded methods. The varargsMethod(String, String), which is more specific, is matched
before the varargsMethod(String...).
From JDK 5, you can also declare your main() method as:
public static void main(String... args) { .... } // JDK 5 varargs
Example 1
[Link] 63/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
version 1
7
version 2
7
version 3
7.1
version 3
7.05
Example 2: Arrays
Suppose you need a method to compute the sum of the elements for int[], short[], float[] and double[], you need to write all overloaded
versions - there is no shortcut.
/** Testing Array Method Overloading */
public class SumArrayMethodOverloading {
public static void main(String[] args) {
int[] a1 = {9, 1, 2, 6, 5};
[Link](sum(a1)); // invoke version 1
double[] a2 = {1.1, 2.2, 3.3};
[Link](sum(a2)); // invoke version 2
float[] a3 = {1.1f, 2.2f, 3.3f};
//[Link](sum(a3)); // error - float[] is not casted to double[]
}
Notes:
1. Unlike primitives, where int would be autocasted to double during method invocation, int[] is not casted to double[].
[Link] 64/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
2. To handle all the 7 primitive number type arrays, you need to write 7 overloaded versions to handle each array types!
Suppose that we wish to write a method called isOdd() to check if a given number is odd.
1 /**
2 * Testing boolean method (method that returns a boolean value)
3 */
4 public class BooleanMethodTest {
5 // This method returns a boolean value
6 public static boolean isOdd(int number) {
7 if (number % 2 == 1) {
8 return true;
9 } else {
10 return false;
11 }
12 }
13
14 public static void main(String[] args) {
15 [Link](isOdd(5)); // true
16 [Link](isOdd(6)); // false
17 [Link](isOdd(-5)); // false
18 }
19 }
This seemingly correct code produces false for -5, because -5%2 is -1 instead of 1. You may rewrite the condition:
The above produces the correct answer, but is poor. For boolean method, you can simply return the resultant boolean value of the comparison,
instead of using a conditional statement, as follow:
[Link] // 3.141592653589793
Math.E // 2.718281828459045
To check all the available methods, open JDK API documentation ⇒ select module "[Link]" ⇒ select package "[Link]" ⇒ select class "Math"
⇒ choose method (@ [Link] for JDK 10).
For examples,
int secretNumber = (int)[Link]()*100; // Generate a random int between 0 and 99
int x1 = 1, y1 = 1, x2 = 2, y2 = 2;
double distance = [Link]((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
int dx = x2 - x1;
[Link] 65/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
int dy = y2 - y1;
distance = [Link](dx*dx + dy*dy); // Slightly more efficient
Each argument, i.e., "12", "3456" and "+", is a String. Java runtime packs all the arguments into a String array and passes into the main()
method as args. For this example, args has the following properties:
java Arithmetic 3 2 +
3+2=5
java Arithmetic 3 2 -
3-2=1
java Arithmetic 3 2 /
3/2=1
[Link] 66/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
| Binary x | y Bitwise OR
Example
Compound operator &=, |= and ^= are also available, e.g., x &= y is the same as x = x & y.
2. The bitwise NOT (or bit inversion) operator is represented as '~', which is different from logical NOT (!).
3. The bitwise XOR is represented as '^', which is the same as logical XOR (^).
4. The operators' precedence is in this order: '~', '&', '^', '|', '&&', '||'. For example,
[Link](true | true & false); // true | (true & false) -> true
[Link](true ^ true & false); // true ^ (true & false) -> true
Bitwise operations are powerful and yet extremely efficient. [Example on advanced usage.]
>> Binary x >> count Right-shift and padded with sign bit (signed-extended right-shift)
>>> Binary x >>> count Right-shift and padded with zeros (unsigned-extended right-shift)
Since all the Java's integers (byte, short, int and long) are signed integers, left-shift << and right-shift >> operators perform signed-extended bit shift.
Signed-extended right shift >> pads the most significant bits with the sign bit to maintain its sign (i.e., padded with zeros for positive numbers and
ones for negative numbers). Operator >>> (introduced in Java, not in C/C++) is needed to perform unsigned-extended right shift, which always pads
the most significant bits with zeros. There is no difference between the signed-extended and unsigned-extended left shift, as both operations pad
the least significant bits with zeros.
Example
As seen from the example, it is more efficient to use sign-right-shift to perform division by 2, 4, 8... (power of 2), as integers are stored in binary.
14. Algorithms
Before writing a program to solve a problem, you have to first develop the steps involved, called algorithm, and then translate the algorithm into
programming statements. This is the hardest part in programming, which is also hard to teach because the it involves intuition, knowledge and
experience.
An algorithm is a step-by-step instruction to accomplice a task, which may involve decision and iteration. It is often expressed in English-like
pseudocode, before translating into programming statement of a particular programming language. There is no standard on how to write
pseudocode - simply write something that you, as well as other people, can understand the steps involved, and able to translate into a working
program.
To test whether a number x is a prime number, we could apply the definition by dividing x by 2, 3, 4, ..., up to x-1. If no divisor is found, then x is a
prime number. Since divisors come in pair, there is no need to try all the factors until x-1, but up to √x.
TRY: translate the above pseudocode into a Java program called PrimeTest.
[Link] 68/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
for (int i = 1; i < x; ++i) {
if (x is divisible by i) {
i is a proper divisor;
add i into the sum;
}
}
if (sum == x)
x is a perfect number
else
x is not a perfect number
TRY: translate the above pseudocode into a Java program called PerfectNumberTest.
Assume that a and b are positive integers and a >= b, the Euclidean algorithm is based on these two properties:
1. GCD(a, 0) = a
2. GCD(a, b) = GCD(b, a mod b), where "a mod b" denotes the remainder of a divides by b.
For example,
GCD(15, 5) = GCD(5, 0) = 5
GCD(99,88) = GCD(88,11) = GCD(11,0) = 11
GCD(3456,1233) = GCD(1233,990) = GCD(990,243) = GCD(243,18) = GCD(18,9) = GCD(9,0) = 9
Before explaining the algorithm, suppose we want to exchange (or swap) the values of two variables x and y. Explain why the following code does
not work.
To swap the values of two variables, we need to define a temporary variable as follows:
int x = 55, y=66;
int temp;
// swap the values of x and y
temp = y;
y = x;
x = temp;
Let us look into the Euclidean algorithm, GCD(a, b) = a, if b is 0. Otherwise, we replace a by b; b by (a mod b), and compute GCD(b, a mod b).
Repeat the process until the second term is 0. Try this out on pencil-and-paper to convince yourself that it works.
15. Summary
This chapter covers the Java programming basics:
Comments, Statements and Blocks.
Variables, Literals, Expressions.
The concept of type and Java's eight primitive types: byte, short, int, long, float, double, char, and boolean; and String.
Implicit and explicit type-casting.
Operators: assignment (=), arithmetic operators (+, -, *, /, %), increment/decrement (++, --) relational operators (==, !=, >, >=, <, <=), logical
operators (&&, ||, !, ^) and conditional (? :).
[Link] 69/70
27.09.2023 15:17 Java Basics - Java Programming Tutorial
Three flow control constructs: sequential, condition (if, if-else, switch-case and nested-if) and loops (while, do-while, for and nested
loops).
Input (via Scanner) & Output (print(), println() and printf()) operations.
Arrays and the enhanced for-loop.
Methods and passing parameters into methods.
Gelişmiş bitsel mantıksal işleçler ( &, |, ~, ^) ve bit kaydırma işleçleri ( <<, >>, >>>)
Problemlerin çözümü için algoritma geliştirme.
[Link] 70/70