Module 2
Module 2
Chapter 2
Basic Syntax, Data Types and Operators
In this lesson, introduces the Basic Syntax as well as the use of Data Types and
Operators in java programming. It discusses brief introductions to expressions, data
types, variables and mathematical operators. Sample code fragments will be
presented to demonstrate how some expressions and statements behaves.
Problem sets (Try Me!) will be given at the end of the lesson to give you time to
practice before taking the assessment tasks. Assessment tasks will be submitted on
or before the scheduled date as specified in the Course Guide.
Learning Outcomes:
Java Expressions
A Java expression consists of variables, operators, literals, and methods. For
example,
int age;
age = 30;
if (x == y)
System.out.println("x is larger than y");
Here, x == y is an expression that returns a boolean value. Also, "x is larger than
y" is considered to be a string expression.
Java Statements
Each statement in Java is a whole unit of execution. For example,
int x = 9*5;
Expression statements
We can convert an expression into a statement by terminating the expression
with a semicolon (;). These are known as expression statements. For example,
// expression
age = 10
// statement
age = 10;
Declaration Statements
In Java, declaration statements are used for declaring variables. For example,
Double tax = 9.5;
Java Blocks
A block is a group of statements (compound statements) that is enclosed in curly
braces { }. For example,
class Main {
public static void main(String[] args) {
Output:
Huling El Bimbo
However, a block may not have any statements. Consider the following
examples,
class Main {
public static void main(String[] args) {
} // end of block
}
}
IT Elec 2 – Object-Oriented Programming
This is a valid Java program. Here, we have a block if {...}. However, there is no any
statement inside this block.
class AssignmentOperator {
public static void main(String[] args) { // start of block
} // end of block
}
Here, we have block public static void main() {...}. However, similar to the above
example, this block does not have any statement.
Here, age is a variable of int data type and is assigned a value of 80. It means that
the age variable can store integer values. In the example, a value was assigned
to the variable during declaration. But it's not required. We can declare variables
without assigning the value, and later we can store the value as we wish. For
example,
int age;
age = 80;
The value of a variable can be changed in the program, hence the name
'variable'. For example,
When choose a name that makes sense creating variables. For example,
grade. age, temperature makes more sense than variable names such as g, a,
and t.
For one-word variable names, use all lowercase letters. For example, it's better
to use age rather than AGE, or aGE.
IT Elec 2 – Object-Oriented Programming
For variable names having more than one word, use all lowercase letters for
the first word and capitalize the first letter of each succeeding word. For
example, ageLimit.
Here, age is a variable, and the data type of the variable is int. The int data type
determines that the age variable can only contain integers.
In short, a variable's data type determines the values a variable can store. There
are 8 data types predefined in Java programming language, known as primitive
data types.
boolean
A boolean data type has two possible values, either true or false.
Default value: false.
They are usually used for true/false conditions. For example,
class BooleanExample {
public static void main(String[] args) {
Output:
True
IT Elec 2 – Object-Oriented Programming
byte
A byte data type can have values ranging from -128 to 127 (8-bit signed two's
complement integer).
It is used instead of int or other integer data types to save memory area if it's
certain that the value of a variable will be within [-128, 127].
Default value: 0
Example:
class ByteExample {
public static void main(String[] args) {
byte range;
range = 124;
System.out.println(range);
}
}
Output:
124
short
A short data type can have values ranging from -32768 to 32767 (16-bit signed
two's complement integer).
It's used instead of other integer data types to save memory if it's certain that
the value of the variable will be within [-32768, 32767].
Default value: 0
Example:
class ShortExample {
public static void main(String[] args) {
short temperature;
temperature = -200;
System.out.println(temperature);
}
}
Output:
-200
IT Elec 2 – Object-Oriented Programming
int
An int data type can have values from -231 to 231-1 (32-bit signed two's
complement integer).
If you are using Java 8 or later, you can use unsigned 32-bit integer with a
minimum value of 0 and a maximum value of 2 32-1.
Default value: 0
Example:
class IntExample {
public static void main(String[] args) {
Output:
-4250000
long
A long data type can have values from -263 to 263-1 (64-bit signed two's
complement integer).
If you are using Java 8 or later, you can use unsigned 64-bit integer with a
minimum value of 0 and a maximum value of 2 64-1.
Default value: 0
Example:
class LongExample {
public static void main(String[] args) {
Output:
-42332200000
IT Elec 2 – Object-Oriented Programming
double
A double data type is a double-precision 64-bit floating-point.
It should not be used for exact values such as currency.
Default value: 0.0 (0.0d)
Example:
class DoubleExample {
public static void main(String[] args) {
Output:
-42.3
float
A float data type is a single-precision 32-bit floating-point.
It should not be used for exact values such as currency.
Default value: 0.0 (0.0f)
Example:
class FloatExample {
public static void main(String[] args) {
Output:
-42.3
IT Elec 2 – Object-Oriented Programming
We have used -42.3f instead of -42.3 in the above program because -42.3 is
a double literal. You need to use f or F to tell the compiler to treat -
42.3 as float rather than double.
char
It's a 16-bit Unicode character.
The minimum value of the char data type is '\u0000' (0). The maximum value
of the char data type is '\uffff'.
Default value: '\u0000'
Example:
class CharExample {
public static void main(String[] args) {
Output:
Q
Output:
9
A
IT Elec 2 – Object-Oriented Programming
When we print letter1, we will get 9 because letter1 is assigned character '9'.
When we print letter2, we get A because the ASCII value of 'A' is 65. A Java
compiler treats a character as an integral type.
String
Java provides support for character strings via java.lang.String class. Here's how
you can create a String object in Java:
myString = "Programming is awesome";
Java literals
To understand literals, let's take an example to assign value to a variable.
boolean flag = false;
Here,
boolean - is a data type.
flag - is variable
false - is literal.
Integer Literals
Integer literals are used to initialize variables of integer data types byte, short,
int and long.
If an integer literal ends with l or L, it's of type long. Tip: it is better to use L instead
of l.
// Error! literal 42332200000 of type int is out of range
int Variable1 = 42332200000;// 42332200000L is of type long, and it's not
out of range
long Variable2 = 42332200000L;
IT Elec 2 – Object-Oriented Programming
Floating-point Literals
Floating-point literals are used to initialize variables of data type float and double.
If a floating-point literal ends with f or F, it's of type float. Otherwise, it's of type
double. A double type can optionally end with D or d. However, it's not necessary.
They can also be expressed in scientific notation using E or e.
class DoubleExample {
public static void main(String[] args) {
// 3.445*10^2
double myDoubleScientific = 3.445e2;
System.out.println(myDouble);
System.out.println(myFloat);
System.out.println(myDoubleScientific);
}
}
Output:
3.4
3.4
344.5
For String literals, double quotation is used. For example, "programming", "Java
8"
Java also supports a few special escape sequences. For example,
\b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage
return), \" (double quote),
\' (single quote), and \\ (backslash).
class DoubleExample {
public static void main(String[] args) {
System.out.println(myChar);
System.out.println(newLine);
System.out.println(myString);
}
}
Output:
g
Java 8
D. Mathematical Operators
Java Operators
In this Lesson, you'll learn about different types of operators in Java, their syntax
and how to use them with the help of examples.
Operators are special symbols or characters which carry out operations with
operands such as variables and values. For example, + is an operator that is used
for addition.
In the previous lesson, you have learned about Java Variables. You have learned
to declare variables and assign values to variables. Now, you will learn to use
operators to manipulate variables.
IT Elec 2 – Object-Oriented Programming
Assignment Operator
Assignment operators are used in to assign values to variables. For example,
int age;
age = 20;
The assignment operator assigns the value from its right to the variable on its left.
Here, 20 is assigned to the variable age using = operator.
There are other assignment operators too.
// Assigning 5 to number1
number1 = 5;
System.out.println(number1);
Output:
5
5
Arithmetic Operators
Arithmetic operators are used to carry out mathematical operations like addition,
subtraction, multiplication, etc.
Operator Meaning
+ Addition (also used for string concatenation)
- Subtraction Operator
* Multiplication Operator
/ Division Operator
% Remainder Operator
IT Elec 2 – Object-Oriented Programming
Output:
number1 + number2 = 13.0
number1 - number2 = 8.0
number1 * number2 = 26.25
number1 / number2 = 4.2
number1 % number2 = 0.5
In the above example, all operands used are variables. However, it's not necessary
at all. Operands used in arithmetic operators can be literals as well. For example,
result = number1 + 5.2;
result = 2.3 + 4.5;
number2 = number1 -2.9;
Output:
Talk is cheap. Show me the code. - Linus Torvalds
Unary Operators
The unary operator performs operations on only one operand.
Operator Meaning
+ Unary plus (not necessary, since numbers are already positive)
Output:
+number = 5.2
-number = -5.2
number = 6.2
number = 5.2
!flag = true
Simple enough until now. However, there is a crucial difference while using
increment and decrement operators as prefix and postfix. Consider this example,
IT Elec 2 – Object-Oriented Programming
System.out.println(number++);
System.out.println(number);
System.out.println(++number);
System.out.println(number);
}
}
Output:
5.2
6.2
7.2
7.2
When this statement is executed, the original value is evaluated first. Then
the number is increased. This is the reason you are getting 5.2 as an output.
Now, when the line,
System.out.println(number);
will increase the number by 1 first and then the statement is executed. Hence the
output is 7.2.
Similar is the case for decrement -- operator.
IT Elec 2 – Object-Oriented Programming
Equality and relational operators are used in decision making and loops. Check
this simple example.
Output:
number2 is greater than number1.
Here, we have used > operator to check if number1 is greater than number2 or
not. Since number2 is greater than number1, the expression number1 > number2 is
evaluated to false.
Hence, the block of code inside else is executed and the block of code inside if is
skipped.
IT Elec 2 – Object-Oriented Programming
Remember that the equality and relational operators compare two operands and
is evaluated to either true or false.
instanceof Operator
The instanceof is a type comparison operator which compares an object to a
specified type. For example,
Output:
Is test an object of String? true
Here, since the variable test is of String type. Hence, the instanceof operator
returns true.
Logical Operators
The logical operators && (conditional AND) and || (conditional OR) operate on
boolean expressions. Here's how they work.
Operator Description Example
|| conditional-OR: true if either of the false || true is evaluated
boolean expression is true to true
&& conditional-AND: true if all boolean false && true is evaluated
expressions are true to false
IT Elec 2 – Object-Oriented Programming
Output:
true
false
Ternary Operator
The conditional operator or ternary operator ?: is shorthand for the if-then-else
statement. The syntax is:
variable = Expression ? expression1 : expression2
Output:
Leap year
Here, we have used the ternary operator to check if the year is a leap year or not.
-= a -= 5 a=a-5
*= a *= 5 a=a*5
IT Elec 2 – Object-Oriented Programming
/= a /= 5 a=a/5
%= a %= 5 a=a%5
^= a ^= 5 a=a^5
|= a |= 5 a=a|5
Now you know about Java operators, it's time to know about the order in which
operators in an expression are evaluated when two operators share a common
operand.
What will be the value of myInt? Will it be (12 - 5)*2, that is, 16? Or it will be 12 - (5
* 2), that is, 5?
When two operators share a common operand, 5 in this case, the operator with
the highest precedence is operated first.
In Java, the precedence of * is higher than that of -. Hence, the multiplication is
performed before subtraction, and the value of myInt will be 4.
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %=
&= ^= |= <<= >>= >>>=
System.out.println(result);
}
}
Output:
2
The operator precedence of prefix ++ is higher than that of - subtraction operator. Hence,
result = a-++c-++b;
is equivalent to
result = a-(++c)-(++b);
When dealing with multiple operators and operands in a single expression, you
can use parentheses like in the above example for clarity. Any expression inside
parentheses is evaluated first.
1. Open a new document in your text editor. Create a class header and an opening and
closing curly brace for a new class named DataDemo by typing the following:
public class DataDemo
{
}
2. Between the curly braces, indent a few spaces and type the following main()method
header and its curly braces:
public static void main(String[] args)
{
}
3. Between the main()method’s curly braces, type the following variable declaration:
int aWholeNumber = 315;
4. Type the following output statements. The first uses the print() method to display a
string that includes a space before the closing quotation mark and leaves the insertion
point for the next output on the same line. The second statement uses println() to
display the value of aWholeNumber and then advance to a new line.
System.out.print("The number is ");
System.out.println(aWholeNumber);
5. Save the file as DataDemo.java.
6. Up to this point in the book, every print() and println() statement you have seen
has used a String as an argument. When you added the last two statements to the
DataDemo class, you wrote a println() statement that uses an int as an argument.
As a matter of fact, there are many different versions of print() and println() that
use different data types.
IT Elec 2 – Object-Oriented Programming
7. Compile the file from the command line by typing javac DataDemo.java. If necessary,
correct any errors, save the file, and then compile again.
8. Execute the application from the command line by typing java DataDemo. The
command window output is shown in Figure 2.1.
1. In the DataDemo class, remove the assignment operator and the initialization value of
the aWholeNumber variable so the declaration becomes:
int aWholeNumber;
2. Save the class and recompile it. An error message appears as shown in Figure 2.2.
Notice that the declaration statement does not generate an error because you can declare
a variable without initializing it. However, the println() statement generates the error
message because in Java, you cannot display an uninitialized variable.
1. After the declaration of the aWholeNumber variable in the DataDemo class, insert a
new line in your program and type the following constant declaration:
final int STATES_IN_US = 50;
2. Following the last println() statement in the existing program, add a new statement
to display a concatenated string and numeric constant. The println() method call uses
the version that accepts a String argument.
System.out.println("The number of states is " +
STATES_IN_US);
3. Save the program, and then compile and execute it. The output appears in Figure 2.3.
3. Within the main() method, create four declarations, one each for the four integer data
types.
int anInt = 12;
byte aByte = 12;
short aShort = 12;
long aLong = 12;
4. Next, add four output statements that describe and display each of the values. The
spaces are included at the ends of the string literals so that the values will be aligned
vertically when they are displayed.
System.out.println("The int is " + anInt);
System.out.println("The byte is " + aByte);
System.out.println("The short is " + aShort);
System.out.println("The long is " + aLong);
5. Save the file as IntegerDemo.java. Then compile and execute it. Figure 2.4 shows the
output. All the values are legal sizes for each data type, so the program compiles and
executes without error.
6. Change each assigned value in the application from 12 to 1234, and then save and
recompile the program. Figure 2.5 shows the error message generated because 1234 is
too large to be placed in a byte variable. The message “possible lossy conversion from
int to byte” means that if the large number had been inserted into the small space, the
accuracy of the number would have been compromised. A lossy conversion is one in
which some data is lost. The opposite of a lossy conversion is a lossless conversion—
one in which no data is lost. (The error message differs in other development environments
and in some earlier versions of Java.)
IT Elec 2 – Object-Oriented Programming
Figure 2.5 Error message generated when a value that is too large is assigned to a byte
variable
7. Change the value of aByte back to 12. Change the value of aShort to 123456. Save
and recompile the program. Figure 2-11 shows the result. The error message “possible
lossy conversion” is the same as when the byte value was invalid, but the error indicates
that the problem is now with the short variable.
Figure 2.6 Error message generated when a value that is too large is assigned to a short
variable
8. Change the value of the short variable to 12345, and then save and compile the
program. Now, the program compiles without error. Execute the program, and confirm that
it runs as expected.
10. Replace the value of aLong with 1234567890987654321. Save the program and
compile it. Figure 2.7 shows the error message that indicates that the integer number is
too large. The message does not say that the value is too big for a long type variable.
IT Elec 2 – Object-Oriented Programming
Instead, it means that the literal constant was evaluated and found to be too large to be a
default int before any attempt was made to store it in the long variable.
Figure 2.7 Error message generated when a value that is too large is assigned to a long
variable
11. Remedy the problem by adding an L to the end of the long numeric value. Now, the
constant is the correct data type that can be assigned to the long variable. Save, compile,
and execute the program; it executes successfully.
12. Watch out for errors that occur when data values are acceptable for a data type when
used alone, but together might produce arithmetic results that are out of range. To
demonstrate, add the following declaration at the end of the current list of variable
declarations in the IntegerDemo program:
int anotherInt = anInt * 10000000;
13. At the end of the current list of output statements, add another output statement so
that you can see the result of the arithmetic:
System.out.println("Another int is " + anotherInt);
Save, compile, and execute the program. The output appears in Figure 2.8. Although 1234
and 10000000 are both acceptable int values, their product is out of range for an int,
and the resulting int does not appear to have been calculated correctly. Because the
arithmetic result was too large, some information about the value has been lost, including
the result’s sign. If you see such unreasonable results in your programs, you need to
consider using different data types for your values.
IT Elec 2 – Object-Oriented Programming
Figure 2.8 Output of the modified IntegerDemo program with an out-of-range integer
1. Open the IntegerDemo.java file you created in a “You Do It” section earlier in this
chapter. Change the class name to IntegerDemoInteractive, and save the file as
IntegerDemoInteractive.java.
2. As the first line in the file, insert an import statement that will allow you to use the
Scanner class:
import java.util.Scanner;
3. Remove the assignment operator and the assigned values from each of the four numeric
variable declarations.
4. Following the numeric variable declarations, insert a Scanner object declaration:
Scanner input = new Scanner(System.in);
5. Following the variable declarations, insert a prompt for the integer value, and an input
statement that accepts the value, as follows:
System.out.print("Please enter an integer >> ");
anInt = input.nextInt();
6. Then add similar statements for the other three variables:
System.out.print("Please enter a byte integer >> ");
aByte = input.nextByte();
System.out.print("Please enter a short integer >> ");
aShort = input.nextShort();
System.out.print("Please enter a long integer >> ");
aLong = input.nextLong();
IT Elec 2 – Object-Oriented Programming
7. Save the file, and then compile and execute it. Figure 2.9 shows a typical execution.
Execute the program a few more times, using different values each time and confirming
that the correct values have been accepted from the keyboard.
5. To fix the problem, insert an extra call to the nextLine() method just before the
statement that accepts the name. This call will consume the Enter key. You do not need
an assignment operator with this statement, because there is no need to store the Enter
key character.
input.nextLine();
6. Save, compile, and execute the program. Figure 2.11 shows a typical successful
execution.
1. Open a new file in your text editor, and type the import statement needed for
interactive input with the Scanner class:
import java.util.Scanner;
2. Type the class header and its curly braces for a class named ArithmeticDemo. Within
the class’s curly braces, enter the main() method header and its braces.
public class ArithmeticDemo
{
public static void main(String[] args)
{
}
}
3. Within the main() method, declare five int variables that will be used to hold two
input values and their sum, difference, and average:
int firstNumber;
int secondNumber;
int sum;
int difference;
int average;
4. Also declare a Scanner object so that keyboard input can be accepted.
Scanner input = new Scanner(System.in);
5. Prompt the user for and accept two integers:
System.out.print("Please enter an integer >> ");
firstNumber = input.nextInt();
System.out.print("Please enter another integer >> ");
secondNumber = input.nextInt();
6. Add statements to perform the necessary arithmetic operations:
sum = firstNumber + secondNumber;
difference = firstNumber - secondNumber;
average = sum / 2;
7. Display the three calculated values:
System.out.println(firstNumber + " + " +
secondNumber + " is " + sum);
System.out.println(firstNumber + " - " +
IT Elec 2 – Object-Oriented Programming
9. Execute the program multiple times using various integer values, and confirm that the
results are accurate.
2. Rerun the program, experimenting with various input values. Some of your output might
appear with imprecisions similar to those shown in Figure 2.14. If you are not satisfied with
the slight imprecisions created when using floating-point arithmetic, you can round or
change the display of the values, as discussed in Appendix C.
Assessment Task
A. Multiple Choice
1. Which of the following is not a primitive data type in Java?
a. boolean c. int
b. byte d. sector
2. Which of the following elements is not required in a variable declaration?
a. a type c. an assigned value
b. an identifier d. a semicolon
3. The assignment operator in Java is _______.
a. = c. :=
b. == d. ::
4. Assuming you have declared shoeSize to be a variable of type int, which of the
following is a valid assignment statement in Java?
a. shoeSize = 9; c. shoeSize = '9';
b. shoeSize = 9.5; d. shoeSize = "nine";
5. Which of the following data types can store a value in the least amount of
memory?
a. short c. int
b. long d. byte
6. A boolean variable can hold _______.
a. any character c. any decimal number
b. any whole number d. the value true or false
7. The value 137.68 can be held by a variable of type _______.
a. int d. Two of the preceding
b. float answers are correct.
c. double
8. The “equal to” relational operator is _______.
a. = c. !=
b. == d. !!
9. In Java, what is the value of 3 + 7 * 4 + 2?
a. 21 c. 42
b. 33 d. 48
10. Which assignment is correct in Java?
a. double money = 12; c. double money = 12.0d;
b. double money = 12.0; d. All of the above are correct.
IT Elec 2 – Object-Oriented Programming
3. Choose the best data type for each of the following so that any reasonable
value is accommodated but no memory storage is wasted. Give an example of a
typical value that would be held by the variable.
a. the number of siblings you have d. one player’s score in a Scrabble
b. your final grade in this class game
c. the population of Earth e. the price of an automobile
C. Programming Exercise
1. a. Write a class that declares a variable named inches, which holds a length in
inches, and assign a value. Display the value in feet and inches; for example, 86
inches becomes 7 feet and 2 inches. Be sure to use a named constant where
appropriate. Save the class as InchesToFeet.java.
1.b. Write an interactive version of the InchesToFeet class that accepts the inches
2. Write a class that declares variables to hold your three initials. Display the three
initials with a period following each one, as in S.M.B. Save the class as Initials.java.
IT Elec 2 – Object-Oriented Programming
References
Prepared by: