Java Basics-Páginas-1
Java Basics-Páginas-1
This chapter explains the basic syntaxes of the Java programming language. I shall assume that you have written some simple Java programs. Otherwise, read "Introduction
To Java Programming for First-time Programmers".
The first few sections are a bit boring, as I have to explain the basic concepts with some details.
Basic Syntaxes
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 1/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
Step 1: Write the source code Xxx.java using a programming text editor (such as Sublime Text, Atom, Notepad++, Textpad, gEdit) or an IDE (such as Eclipse or
NetBeans).
Step 2: Compile the source code Xxx.java into Java portable bytecode Xxx.class using the JDK Compiler by issuing command:
javac Xxx.java
Step 3: Run the compiled bytecode Xxx.class with the input to produce the desired output, using the Java Runtime by issuing command:
java Xxx
/**
* Comment to state the purpose of the program
*/
public class Classname { // Choose a meaningful Classname. Save as "Classname.java"
public static void main(String[] args) { // Entry point of the program
// Your programming statements here!!!
}
}
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 2/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
/**
* Find the sums of the running odd numbers and even numbers from a given lowerbound
* to an upperbound. Also compute their absolute difference.
*/
public class OddEvenSum { // Save as "OddEvenSum.java"
public static void main(String[] args) {
// Declare variables
final int LOWERBOUND = 1;
final int UPPERBOUND = 1000; // Define the bounds
int sumOdd = 0; // For accumulating odd numbers, init to 0
int sumEven = 0; // For accumulating even numbers, init to 0
int absDiff; // Absolute difference between the two sums
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.
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;
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 4/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
int product;
number2 = 8;
product = number1 * number2 * number3;
System.out.println("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
System.out.println("PASS");
System.out.println("Well Done!");
System.out.println("Keep it Up!");
}
i = 1;
while (i < 8) { // A while-loop statement
System.out.print(i + " ");
++i;
}
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 5/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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;
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.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 7/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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.
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.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 8/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
An identifier cannot be a reserved keyword or a reserved literal (e.g., class, int, double, if, else, for, true, false, null).
Identifiers are case-sensitive. A rose is NOT a Rose, and is NOT a ROSE.
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).
Variable Declaration
To use a variable in your program, you need to first introduce it by declaring its name and type, in one of the following syntaxes. The act of declaring a variable allocates a
storage of size capable of holding a value of the type.
Syntax Example
// Declare a variable of a specified type int sum;
type identifier; double average;
String statusMsg;
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 9/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
Constant Naming Convention: Use uppercase words, joined with underscore. For example, MIN_VALUE, MAX_SIZE, and INTEREST_RATE_6_MTH.
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.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 10/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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
Assignment (=)
An assignment statement evaluates the RHS (Right-Hand Side) and assigns the resultant value to the variable of the LHS (Left-Hand Side).
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,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 11/130
1/9/25, 3:48 PM 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]
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 12/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 13/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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:
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 14/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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).
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.
Data Representation
Read "Data Representation - Integers, Floating-Point Numbers and Characters" if you wish to understand how the numbers and characters are represented inside the
computer memory.
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).
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 15/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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) */
System.out.println("int(min) = " + Integer.MIN_VALUE);
//int(min) = -2147483648
System.out.println("int(max) = " + Integer.MAX_VALUE);
//int(max) = 2147483647
System.out.println("int(bit-length) = " + Integer.SIZE);
//int(bit-length) = 32
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 16/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.println("short(bit-length) = " + Short.SIZE);
//short(bit-length) = 16
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 17/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 18/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
int harddiskSizeInGB = 500; // or short
int monitorInInch = 15; // or byte
double price = 1760.55;
char servicePlan = 'C';
boolean onSiteService = true;
boolean extendedWarranty = false;
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., B.Sc., 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.
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,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 19/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
// 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'
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 20/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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
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,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 21/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 22/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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,
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 System.out.println(). 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,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 23/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 24/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
}
Clearly, you need to initialize the variable, so that the compiler can infer its type.
Basic Operations
Arithmetic Operators
Java supports the following binary/unary arithmetic 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
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 25/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
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,
Arithmetic Expressions
In programming, the following arithmetic expression:
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.
The arithmetic operators (+, -, *, /, %) are only applicable to primitive number types: byte, short, int, long, float, double, and char. They are not applicable to
boolean.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 26/130