KEMBAR78
Java Basics-Páginas-1 | PDF | Java (Programming Language) | Computer Programming
0% found this document useful (0 votes)
69 views26 pages

Java Basics-Páginas-1

Uploaded by

Johnson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views26 pages

Java Basics-Páginas-1

Uploaded by

Johnson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

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

Table of Contents (Hide)

Java Programming Tutorial


Java Basics

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".

To be proficient in a programming language, you need to master two things:


1. The syntax of the programming language: Not too difficult to learn a small set of keywords and syntaxes. For examples, JDK 1.8 has 48 keywords; C11 has 44, and
C++11 has 73.
2. The Application Program Interface (API) libraries associated with the language: You don’t want to write everything from scratch yourself. Instead, you can re-use the
available code in the library. Learning library could be difficult as it is really huge, evolving and could take on its own life as another programming language.

The first few sections are a bit boring, as I have to explain the basic concepts with some details.

You may also try the "Exercises on Java Basics".

Basic Syntaxes

Steps in Writing a Java Program


The steps in writing a Java program is illustrated as follows:

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

Java Program Template


You can use the following template to write your Java programs. Choose a meaningful "Classname" that reflects the purpose of your program, and write your programming
statements inside the body of the main() method. Don't worry about the other terms and keywords now. I will explain them in due course. Provide comments in your
program!

/**
* 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

A Sample Program Illustrating Sequential, Decision and Loop Constructs


Below is a simple Java program that demonstrates the three basic programming constructs: sequential, loop, and conditional. Read "Introduction To Java Programming for
First-time Programmers" if you need help in understanding this program.

/**
* 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

// Use a while loop to accumulate the sums from LOWERBOUND to UPPERBOUND


int number = LOWERBOUND; // loop init
while (number <= UPPERBOUND) { // loop test
// number = LOWERBOUND, LOWERBOUND+1, LOWERBOUND+1, ..., UPPERBOUND
// A if-then-else decision
if (number % 2 == 0) { // Even number
sumEven += number; // Same as sumEven = sumEven + number
} else { // Odd number
sumOdd += number; // Same as sumOdd = sumOdd + number
}
++number; // loop update for next number
}
// Another if-then-else Decision
if (sumOdd > sumEven) {
absDiff = sumOdd - sumEven;
} else {
absDiff = sumEven - sumOdd;
}
// OR using one liner conditional expression
//absDiff = (sumOdd > sumEven) ? sumOdd - sumEven : sumEven - sumOdd;

// Print the results


https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 3/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.println("The sum of odd numbers from " + LOWERBOUND + " to " + UPPERBOUND + " is: " + sumOdd);
System.out.println("The sum of even numbers from " + LOWERBOUND + " to " + UPPERBOUND + " is: " + sumEven);
System.out.println("The absolute difference between the two sums is: " + absDiff);
}
}

The expected outputs are:

The sum of odd numbers from 1 to 1000 is: 250000


The sum of even numbers from 1 to 1000 is: 250500
The absolute difference between the two sums is: 500

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).

There are two kinds of comments in Java:


1. Multi-Line Comment: begins with a /* and ends with a */, and can span multiple lines. /** .... */ is a special documentation comment. These comment can be
extracted to produce documentation.
2. End-of-Line (Single-Line) Comment: begins with // and lasts till the end of the current line.

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.

Statements and Blocks


Statement: A programming statement is the smallest independent unit in a program, just like a sentence in the English language. It performs a piece of programming action.
A programming statement must be terminated by a semi-colon (;), just like an English sentence ends with a period. (Why not ends with a period like an English sentence?
This is because period crashes with decimal point - it is challenging for the dumb computer to differentiate between period and decimal point in the early days of computing!)

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!");
}

if (input != -1) { // A if-else statement


System.out.println("Continue");
} else {
System.out.println("Exit");
}

i = 1;
while (i < 8) { // A while-loop statement
System.out.print(i + " ");
++i;
}

public static void main(String[] args) { // A method definition statement


...statements...
}

public class Hello { // A class definition statement


...statements...
}

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

White Spaces and Formatting Source Code


White Spaces: Blank, tab and newline are collectively called white spaces.
You need to use a white space to separate two keywords or tokens to avoid ambiguity, e.g.,

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.,

// Same as above with many redundant white spaces. Hard to read.


int sum
=0 ;

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?

public class Hello{public static void main(String[] args){System.out.println("Hello, world!");}}

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

// Use empty line liberally to improve readability


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

// 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.

Variables and Types

Variables - Name, Type and Value


Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.

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.

Identifiers (or Names)


An identifier is needed to name a variable (or any other entity such as a method or a class). Java imposes the following rules on identifiers:
An identifier is a sequence of characters, of any length, comprising uppercase and lowercase letters (a-z, A-Z), digits (0-9), underscore (_), and dollar sign ($).
White space (blank, tab, newline) and other special characters (such as +, -, *, /, @, &, commas, etc.) are not allowed. Take note that blank and dash (-) are not
allowed, i.e., "max value" and "max-value" are not valid names. (This is because blank creates two tokens and dash crashes with minus sign!)
An identifier must begin with a letter (a-z, A-Z) or underscore (_). It cannot begin with a digit (0-9) (because that could confuse with a number). Identifiers begin
with dollar sign ($) are reserved for system-generated entities.

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.

Variable Naming Convention


A variable name is a noun, or a noun phrase made up of several words with no spaces between words. The first word is in lowercase, while the remaining words are initial-
capitalized. For examples, radius, area, fontSize, numStudents, xMax, yMin, xTopLeft, isValidInput, and thisIsAVeryLongVariableName. This
convention is also known as camel-case.

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;

// Declare multiple variables of the SAME type, int number, count;


// separated by commas double sum, difference, product, quotient;
type identifier1, identifier2, ..., identifierN; String helloMsg, gameOverMsg;

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

// Declare a variable and assign an initial value int magicNumber = 99;


type identifier = initialValue; double pi = 3.14169265;
String helloMsg = "hello,";

// Declare multiple variables of the SAME type, int sum = 0, product = 1;


// with initial values double height = 1.2, length = 3.45;
type identifier1 = initValue1, ..., identifierN = initValueN; String greetingMsg = "hi!", quitMsg = "bye!";

Take note that:


A variable is declared with a type. Once the type of a variable is declared, it can only store a value belonging to that particular type. For example, an int variable can
hold only integer (such as 123), and NOT floating-point number (such as -2.17) or text string (such as "Hello").
Each variable can only be declared once because identifier shall be unique.
You can declare a variable anywhere inside the program, as long as it is declared before being used.
The type of a variable cannot be changed inside the program, once it is declared.
A variable declaration statement begins with a type, and works for only that type. In other words, you cannot declare variables of two different types in a single
declaration statement.
Java is a statically-typed language. This means that the type is resolved at compile time and never changes.

Constants (final variables)


Constants are non-modifiable (immutable) variables, declared with keyword final. You can only assign values to final variables ONCE. Their values cannot be changed
during program execution. For examples:

final double PI = 3.14159265; // Declare and initialize the constant

final int SCREEN_X_MAX = 1280;


SCREEN_X_MAX = 800; //compilation error: cannot assign a value to final variable

// You can only assign value to final variables ONCE


final int SCREEN_Y_MIN;
SCREEN_Y_MIN = 0; // First assignment
SCREEN_Y_MIN = 10; //compilation error: variable might already have been assigned

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

// Assume that variables sum and number are "int"


sum + number * number // evaluates to an "int" value

// Assume that variables principal and interestRate are "double"


principal * (1.0 + interestRate) // evaluates 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).

The syntax for assignment statement is:

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

8 = number; // Invalid in Programming, LHS shall be a variable


number + 1 = sum; // Invalid in Programming, LHS shall be a variable

'=' is Assignment, NOT Equality


In Java, the equal symbol '=' is known as the assignment operator. The meaning of '=' in programming is different
from Mathematics. It denotes assignment of the RHS value to the LHS variable, NOT equality of the RHS and LHS. The
RHS shall be a literal value or an expression that evaluates to a value; while the LHS must be a variable.

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.

Primitive Types and String


In Java, there are two broad categories of data types:
1. Primitive types (e.g., int, double),
2. Reference types (e.g., objects and arrays).

We shall describe the primitive types here. We will cover the reference types (classes and objects) in the later chapters on "Object-Oriented Programming".

Built-in Primitive Types

TYPE DESCRIPTION
byte Integer 8-bit signed integer
The range is [-27, 27-1] = [-128, 127]

short 16-bit signed integer


The range is [-215, 215-1] = [-32768, 32767]

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

int 32-bit signed integer


The range is [-231, 231-1] = [-2147483648, 2147483647] (≈9 digits, ±2G)

long 64-bit signed integer


The range is [-263, 263-1] = [-9223372036854775808, 9223372036854775807] (≈19 digits)

float Floating-Point 32-bit single precision floating-point number


Number (≈6-7 significant decimal digits, in the range of ±[1.4x10-45, 3.4028235x1038])
F x 2E
double 64-bit double precision floating-point number
(≈14-15 significant decimal digits, in the range of ±[4.9x10-324, 1.7976931348623157x10308])

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.

Java has eight primitive types, as listed in the above table:


There are four integer types: 8-bit byte, 16-bit short, 32-bit int and 64-bit long. They are signed
integers in 2's complement representation, and can hold a zero, positive and negative integer value of the
various ranges as shown in the table.
There are two floating-point types: 32-bit single-precision float and 64-bit double-precision double.
They are represented in scientific notation of Fx2E where the fraction (F) and exponent (E) are stored
separately (as specified by the IEEE 754 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).

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

Integers vs. Floating-Point Numbers


In computer programming, integers (such as 123, -456) and floating-point numbers (such as 1.23, -4.56, 1.2e3, -4.5e-6) are TOTALLY different.
1. Integers and floating-point numbers are represented and stored differently.
2. Integers and floating-point numbers are operated differently.

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".

How Integers and Floating-Point Numbers are Operated?


Integers and floating-point numbers are operated differently using different hardware circuitry. Integers are processed in CPU (Central Processing Unit), while floating-point
numbers are processed in FPU (Floating-point Co-processor Unit).

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

On the other hand, floating-point addition is complex, 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).

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).

Maximum/Minimum Values of Primitive Number Types


The following program can be used to print the maximum, minimum and bit-length of the primitive types. For example, the maximum, minimum and bit-size of int are kept
in built-in constants INTEGER.MIN_VALUE, INTEGER.MAX_VALUE, INTEGER.SIZE.

/**
* 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

/* byte (8-bit signed integer) */


System.out.println("byte(min) = " + Byte.MIN_VALUE);
//byte(min) = -128
System.out.println("byte(max) = " + Byte.MAX_VALUE);
//byte(max) = 127
System.out.println("byte(bit-length) = " + Byte.SIZE);
//byte(bit-length) = 8

/* short (16-bit signed integer) */


System.out.println("short(min) = " + Short.MIN_VALUE);
//short(min) = -32768
System.out.println("short(max) = " + Short.MAX_VALUE);
//short(max) = 32767

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

/* long (64-bit signed integer) */


System.out.println("long(min) = " + Long.MIN_VALUE);
//long(min) = -9223372036854775808
System.out.println("long(max) = " + Long.MAX_VALUE);
//long(max) = 9223372036854775807
System.out.println("long(bit-length) = " + Long.SIZE);
//long(bit-length) = 64

/* char (16-bit character or 16-bit unsigned integer) */


System.out.println("char(min) = " + (int)Character.MIN_VALUE);
//char(min) = 0
System.out.println("char(max) = " + (int)Character.MAX_VALUE);
//char(max) = 65535
System.out.println("char(bit-length) = " + Character.SIZE);
//char(bit-length) = 16

/* float (32-bit floating-point) */


System.out.println("float(min) = " + Float.MIN_VALUE);
//float(min) = 1.4E-45
System.out.println("float(max) = " + Float.MAX_VALUE);
//float(max) = 3.4028235E38
System.out.println("float(bit-length) = " + Float.SIZE);
//float(bit-length) = 32

/* double (64-bit floating-point) */


System.out.println("double(min) = " + Double.MIN_VALUE);
//double(min) = 4.9E-324
System.out.println("double(max) = " + Double.MAX_VALUE);
//double(max) = 1.7976931348623157E308
System.out.println("double(bit-length) = " + Double.SIZE);
//double(bit-length) = 64

/* No equivalent constants for boolean type */


}
}

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

One More Important Type - String


Beside the 8 primitive types, another important and frequently-used type is String. A String is a sequence of characters (texts) such as "Hello, world". String is
not a primitive type (this will be elaborated later).

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,

String greetingMsg = "hello, world"; // String is enclosed in double-quotes


char gender = 'm'; // char is enclosed in single-quotes
String statusMsg = ""; // an empty String

Choice of Data Types for Variables


As a programmer, YOU need to decide on the type of the variables to be used in your programs. Most of the times, the decision is intuitive. For example, use an integer type
for counting and whole number; a floating-point type for number with fractional part, String for text message, char for a single character, and boolean for binary
outcomes.

It is important to take note that your programs will have data of DIFFERENT types.

Rules of Thumb for Choosing Data Types


For numbers, use an integer type if possible. Use a floating-point type only if the number contains a fractional part. Although floating-point numbers includes integers
(e.g., 1.0, 2.0, 3.0), floating-point numbers are approximation (not precise) and require more resources (computational and storage) for operations.
Although there are 4 integer types: 8-bit byte, 16-bit short, 32-bit int and 64-bit long, we shall use int for integers in general. Use byte, short, and long only if
you have a good reason to choose that particular precision.
Among there are two floating-point types: 32-bit float and 64-bit double, we shall use double in general. Use float only if you wish to conserve storage and do not
need the precision of double.
char, boolean and String have their specific usage.

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.

The possible variable names and types are:

String name = "Paul";


String brand = "idol";
double processorSpeedInGHz = 2.66; // or float
double ramSizeInGB = 8; // or float

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.

Literals for Primitive Types and String


A literal, or literal constant, is a specific constant value, such as 123, -456, 3.1416, -1.2E3, 4.5e-6, 'a', "Hello", that is used in the program source. It can be
assigned directly to a variable; or used as part of an expression. They are called literals because they literally and explicitly identify their values. We call it literal to distinguish
it from a variable.

Integer (int, long, short, byte) literals


A whole number literal, such as 123 and -456, is treated as an int by default. For example,

int number = -123;


int sum = 1234567890; // This value is within the range of int
int bigSum = 8234567890; // error: this value is outside the range of int
int intRate = 6%; // error: no percent sign
int pay = $1234; // error: no dollar sign
int product = 1,234,567; // error: no grouping commas

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.,

int number1 = 1234; // The usual decimal


int number2 = 01234; // Octal 1234, Decimal 2322
int number3 = 0017; // Octal 17, Decimal 15
int number4 = 0x1abc; // Hexadecimal 1ABC, decimal 15274

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

Floating-point (double, float) literals


A literal number with a decimal point, such as 55.66 and -33.44, is treated as a double by default. You can also express them in scientific notation, e.g., 1.2e3, -5.5E-
6, where e or E denotes the exponent in base of 10. You could precede the fractional part or exponent with a plus (+) or minus (-) sign. Exponent values are restricted to
integer. There should be no space or other characters in the number.

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'

Character (char) Literals and Escape Sequences


A printable char literal (such as letters, digits and special symbols) is written by enclosing the character with a pair of single quotes, e.g., 'A', 'z', '0', '9', '$', and
'@'. Special char literals (such as tab, newline) are represented using so-called escape sequences (to be described later).

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

3 SP ! " # $ % & '

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

2 SP ! " # $ % & ' ( ) * + , - . /

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

char letter = 'a'; // Same as 97


char anotherLetter = 98; // Same as the letter 'b'
// You can assign an integer in the range of [0, 65535] to char
System.out.println(letter); // 'a' printed
System.out.println(anotherLetter); // 'b' printed instead of the number, because the type is char
anotherLetter += 2; // 100 or 'd'
System.out.println(anotherLetter); // 'd' printed

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:

Escape Unicode Unicode


Description
Sequence (Decimal) (Hex)
\t Tab 9 0009H

\n Newline (or Line-feed) 10 000AH

\r Carriage-return 13 000DH

\" Double-quote (Needed to be used inside double-quoted String) - -

\' Single-quote (Needed to be used inside single-quoted char, i.e., '\'') - -

\ Back-slash (Needed as back-slash is given a special meaning) - -

\uhhhh Unicode number hhhh (in hex), e.g., \u60a8 is 您, \u597d is 好 - hhhhH

For examples,

char tabChar = '\t'; // tab


char anotherTabChar = 9; // Code number 9 is tab
char newlineChar = '\n'; // newline, code number 10
char backSlashChar = '\\'; // Since back-slash is given a special meaning,
// to write a back-slash, use double back-slash
char singleQuoteChar = '\''; // Need to use escape sequence to resolve conflict
char doubleQuoteChar = '"'; // No conflict. No need for escape sequence
System.out.println("A tab " + tabChar + " before this; end with two newlines!" + newlineChar + newlineChar);

String Literals and Escape Sequences


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,

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

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,

String str1 = "hello\tworld\n"; // tab and newline


String str2 = "a double quoted \"hello\"";
String str3 = "1 back-slash \\, another 2 back-slashes \\\\";
String str1 = "A \"string\" nested \\inside\\ a string" // A "string" nested \inside\ a string
String str2 = "Hello, \u60a8\u597d!" // "Hello, !" 您好
Single-quote (') inside a String does not require an escape sequence because there is no ambiguity, e.g.,

String str3 = "Hi, I'm a string!" // Single quote OK

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,

boolean done = true;


boolean gameOver = false;

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

// println() can be used to print value of any type


System.out.println("Name is: " + name);
//Name is: Tan Ah Teck
System.out.println("Gender is: " + gender);
//Gender is: m
System.out.println("Is married is: " + isMarried);
//Is married is: true
System.out.println("Number of children is: " + numChildren);
//Number of children is: 8
System.out.println("Year of birth is: " + yearOfBirth);
//Year of birth is: 1945
System.out.println("Salary is: " + salary);
//Salary is: 88000
System.out.println("Net Asset is: " + netAsset);
//Net Asset is: 8234567890
System.out.println("Weight is: " + weight);
//Weight is: 88.88
System.out.println("GPA is: " + gpa);
//GPA is: 3.88

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
}
}

var - Local Variable Type Inference (JDK 10)


JDK 10 introduces a new way to declare variables via a new keyword var, for examples,

var v1 = 0; // type inferred to "int"


var v2 = 0.0; // type inferred to "double"
var v3 = 1.0f; // type inferred to "float"
var v4 = '0'; // type inferred to "char"
var v5 = "hello"; // type inferred to "String"
//var v6; //compilation error: cannot use 'var' on variable without initializer

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:

Operator Mode Usage Description Examples


+ Binary x + y Addition 1 + 2 ⇒ 3
Unary +x Unary positive 1.1 + 2.2 ⇒ 3.3

- 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

% Binary x % y Modulus (Remainder) 5 % 2 ⇒ 1


-5 % 2 ⇒ -1
5.5 % 2.2 ⇒ 1.1

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,

int number = -9;


number = -number; // Unary negate

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.

Type Conversion in Arithmetic Operations


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.

Same-Type Operands of int, long, float, double


If BOTH operands are int, long, float or double, the binary arithmetic operations are carried in that type, and evaluate to a value of that type, i.e.,
int ⊕ int ⇒ int, where ⊕ denotes a binary arithmetic operators such as +, -, *, /, %.
long ⊕ long ⇒ long
float ⊕ float ⇒ float

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

You might also like