0% found this document useful (0 votes)
53 views

Module 2

The document discusses Java data types and operators. It introduces basic syntax, expressions, statements, and blocks in Java. It describes the 8 primitive data types in Java - boolean, byte, short, int, long, float, double, and char. For each data type, it provides details on the possible value ranges and default values. It also discusses variable declaration and naming conventions in Java. Sample code is provided to demonstrate expressions, statements, and usage of different data types.

Uploaded by

Ronald Rivera
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)
53 views

Module 2

The document discusses Java data types and operators. It introduces basic syntax, expressions, statements, and blocks in Java. It describes the 8 primitive data types in Java - boolean, byte, short, int, long, float, double, and char. For each data type, it provides details on the possible value ranges and default values. It also discusses variable declaration and naming conventions in Java. Sample code is provided to demonstrate expressions, statements, and usage of different data types.

Uploaded by

Ronald Rivera
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/ 40

IT Elec 2 – Object-Oriented Programming

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:

At the end of the lesson, you are expected to:

 Identify data types and operators and its uses.


 Write simple expressions.
 Create and use variables to hold data.
 Use operators to manipulate variables.
 Use literals to initialize variables.
 Write a simple program to execute data types and operators.

Start your lesson here.

A. Expressions, statements, and compound statements

Java Expressions
A Java expression consists of variables, operators, literals, and methods. For
example,
int age;
age = 30;

Here, age = 30 is an expression that returns an int value. Consider another


example,

Double x = 5.2, y = 8.4, result;


Sum = x + y - 6.4;

Here, x + y - 3.4 is an expression.


IT Elec 2 – Object-Oriented Programming

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;

Here, we have a statement. The complete execution of this statement involves


multiplying integers 9 and 5 and then assigning the result to the variable score.
In the statement above, we have an expression 9 * 5. And in Java, expressions are
part of statements.

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;

In the above example, we have an expression age = 10. Here, by adding a


semicolon (;), we have converted the expression into a statement (age = 10;).
Consider another example,
// expression
++age
// statement
++age;

Similarly, ++age is an expression whereas ++age; is a statement.


IT Elec 2 – Object-Oriented Programming

Declaration Statements
In Java, declaration statements are used for declaring variables. For example,
Double tax = 9.5;

The statement above declares a variable tax which is initialized to 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) {

String band = "EraserHeads";

if (band == " EraserHeads ") { // start of block


System.out.print("Huling ");
System.out.print("El Bimbo");
} // end of block
}
}

Output:
Huling El Bimbo

In the example above, we have a block if {....}.


Here, inside the block we have two statements:
 System.out.print("Huling ");
 System.out.print("El Bimbo");

However, a block may not have any statements. Consider the following
examples,
class Main {
public static void main(String[] args) {

if (20 > 5) { // start of block

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

B. Defining and Initializing Variables


Java Variables
A variable is a memory location (storage area) that holds data. Each variable
should be given a unique name (identifier) to indicate the storage area.

How to declare variables in Java?


Here is an example on how to declare a variable in Java.

int age = 80;

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,

int age = 80;


... .. ...
age = 90;
IT Elec 2 – Object-Oriented Programming

Java is a statically-typed language. It means that all variables must be declared


before they can be used. But we cannot change the data type of a variable in
Java within the same scope.
int speedLimit = 80;
... .. ...
float speedLimit;

Rules for Naming Variables in Java


Java programming language has its own set of rules and conventions for naming
variables. Here's what you need to know:
 Variables in Java are case-sensitive.
 A variable's name is a sequence of Unicode letters and digits. It can begin with
a letter, $ or _. However, it's a convention to begin a variable name with a
letter. Also, variable names cannot use whitespace in Java.

Variable Naming Convention

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

There are 4 types of variables in Java programming language:


 Instance Variables (Non-Static Fields)
 Class Variables (Static Fields)
 Local Variables
 Parameters

C. Fundamental Data Types


Java Primitive Data Types
Java is a statically-typed language. This means that all variables must be declared
before they can be used.
int age;

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.

8 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) {

boolean flag = true;


System.out.println(flag);
}
}

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

int range = -4250000;


System.out.println(range);
}
}

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

long range = -42332200000L;


System.out.println(range);
}
}

Output:
-42332200000
IT Elec 2 – Object-Oriented Programming

The use of L at the end of -42332200000 represents that it is an integral literal of


the long type.

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

double number = -42.3;


System.out.println(number);
}
}

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

float number = -42.3f;


System.out.println(number);
}
}

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

char letter = '\u0051';


System.out.println(letter);
}
}

Output:
Q

You get the output Q because the Unicode value of Q is '\u0051'.


Here is another example:
class CharExample {
public static void main(String[] args) {

char letter1 = '9';


System.out.println(letter1);

char letter2 = 65;


System.out.println(letter2);
}
}

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.

A Literal is the actual representation of a fixed value.


Values like 1.5, 4, true, '\u0050' that appear directly in a program without requiring
computation are literals.
In the above example, flag is a variable. Since it is a boolean type variable, it may
store a value of either false or true. For the compiler to understand it, it requires
computation. However, literals like -5, 'a', true represents fixed value.

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

 Integer literals can be expressed in decimal, hexadecimal and binary number


systems.
 The numbers starting with prefix 0x represents hexadecimal. Similarly, numbers
starting with prefix 0b represents binary.
 // decimal
 int decNumber = 34;// 0x represents hexadecimal
 int hexNumber = 0x2F;// 0b represents binary
int binNumber = 0b10010;

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

double myDouble = 3.4;


float myFloat = 3.4F;

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

Character and String Literals


 They contain Unicode (UTF-16) characters.
 For char literals, single quotations are used. For example, 'a', '\u0111' etc.
IT Elec 2 – Object-Oriented Programming

 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) {

char myChar = 'g';


char newLine = '\n';
String myString = "Java 8";

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.

Example 1: Assignment Operator


class AssignmentOperator {
public static void main(String[] args) {

int number1, number2;

// Assigning 5 to number1
number1 = 5;
System.out.println(number1);

// Assigning value of variable number2 to number1


number2 = number1;
System.out.println(number2);
}
}

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

Example 2: Arithmetic Operator


class ArithmeticOperator {
public static void main(String[] args) {

double number1 = 10.5, number2 = 2.5, result;

// Using addition operator


result = number1 + number2;
System.out.println("number1 + number2 = " + result);

// Using subtraction operator


result = number1 - number2;
System.out.println("number1 - number2 = " + result);

// Using multiplication operator


result = number1 * number2;
System.out.println("number1 * number2 = " + result);

// Using division operator


result = number1 / number2;
System.out.println("number1 / number2 = " + result);

// Using remainder operator


result = number1 % number2;
System.out.println("number1 % number2 = " + result);
}
}

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;

The + operator can also be used to concatenate two or more strings.


IT Elec 2 – Object-Oriented Programming

Example 3: Arithmetic Operator to Add String


class ArithmeticOperator {
public static void main(String[] args) {

String start, middle, end, result;

start = "Talk is cheap. ";


middle = "Show me the code. ";
end = "- Linus Torvalds";

result = start + middle + end;


System.out.println(result);
}
}

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)

- Unary minus (used to invert the sign of an expression)

++ Increment operator (increments value by 1)


-- decrement operator (decrements value by 1)

! Logical complement operator (used to invert the value of a


boolean)

Example 4: Unary Operator


class UnaryOperator {
public static void main(String[] args) {

double number = 5.2, resultNumber;


boolean flag = false;

System.out.println("+number = " + +number);


// number is equal to 5.2
IT Elec 2 – Object-Oriented Programming

System.out.println("-number = " + -number);


// number is equal to 5.2

// ++number is same as number = number + 1


System.out.println("number = " + ++number);
// number is equal to 6.2

// --number is same as number = number - 1


System.out.println("number = " + --number);
// number is equal to 5.2

System.out.println("!flag = " + !flag);


// flag is still false.
}
}

Output:
+number = 5.2
-number = -5.2
number = 6.2
number = 5.2
!flag = true

Increment and Decrement Operator


You can also use ++ and -- operator as both prefix and postfix in Java.
The ++ operator increases value by 1 and -- operator decreases the value by 1.
int myInt = 5;
++myInt // myInt becomes 6
myInt++ // myInt becomes 7
--myInt // myInt becomes 6
myInt-- // myInt becomes 5

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

Example 5: Unary Operator


class UnaryOperator {
public static void main(String[] args) {

double number = 5.2;

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

Here, notice the line,


System.out.println(number++);

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 print the increased value. That is 6.2.


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


The equality and relational operators determine the relationship between the two
operands. It checks if an operand is greater than, less than, equal to, not equal to
and so on. Depending on the relationship, it is evaluated to either true or false.
Operator Description Example
== equal to 5 == 3 is evaluated to false
!= not equal to 5 != 3 is evaluated to true
> greater than 5 > 3 is evaluated to true
< less than 5 < 3 is evaluated to false
>= greater than or equal to 5 >= 5 is evaluated to true
<= less than or equal to 5 <= 5 is evaluated to true

Equality and relational operators are used in decision making and loops. Check
this simple example.

Example 6: Equality and Relational Operators


class RelationalOperator {
public static void main(String[] args) {

int number1 = 5, number2 = 6;

if (number1 > number2) {


System.out.println("number1 is greater than number2.");
}
else {
System.out.println("number2 is greater than number1.");
}
}
}

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,

Example 7: instanceof Operator


Here's an example of instanceof operator.
class instanceofOperator {
public static void main(String[] args) {

String test = "asdf";


boolean result;

result = test instanceof String;


System.out.println("Is test an object of String? " + result);
}
}

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

Example 8: Logical Operators


class LogicalOperator {
public static void main(String[] args) {

int num1 = 1, num2 = 2, num3 = 9;


boolean result;

// At least one expression needs to be true for the result to be true


result = (num1 > num2) || (num3 > num1);

// result will be true because (num1 > num2) is true


System.out.println(result);

// All expression must be true for result to be true


result = (num1 > num2) && (num3 > num1);

// result will be false because (num3 > num1) is false


System.out.println(result);
}
}

Output:
true
false

Note: Logical operators are used in decision making and looping.

Ternary Operator
The conditional operator or ternary operator ?: is shorthand for the if-then-else
statement. The syntax is:
variable = Expression ? expression1 : expression2

Here's how it works.


 If the Expression is true, expression1 is assigned to the variable.
 If the Expression is false, expression2 is assigned to the variable.
IT Elec 2 – Object-Oriented Programming

Example 9: Ternary Operator


class ConditionalOperator {
public static void main(String[] args) {

int februaryDays = 29;


String result;

result = (februaryDays == 28) ? "Not a leap year" : "Leap


year";
System.out.println(result);
}
}

Output:
Leap year

Here, we have used the ternary operator to check if the year is a leap year or not.

Bitwise and Bit Shift Operators


To perform bitwise and bit shift operators in Java, these operators are used.
Operator Description
~ Bitwise Complement
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
These operators are not commonly used.

More Assignment Operators


We have only discussed one assignment operator = at the beginning of the article.
Except for this operator, there are quite a few assignment operators that help us
to write cleaner code.
Operator Example Equivalent to
+= a += 5 a=a+5

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

&= 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.

Java Operator Precedence


Operator precedence defines the order in which the operators of an expression
are evaluated.

Now, take a look at the statement below:


int myInt = 12 - 5 * 2;

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.

Operator Precedence Table


The table below lists the precedence of operators in Java; higher it appears in the
table, the higher its precedence.

Java Operator Precedence


Operators Precedence
postfix increment and decrement ++ --
prefix increment and decrement, and unary ++ -- + - ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
IT Elec 2 – Object-Oriented Programming

equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %=
&= ^= |= <<= >>= >>>=

Example: Operator Precedence


class Precedence {
public static void main(String[] args) {

int a = 10, b = 5, c = 1, result;


result = a-++c-++b;

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.

Associativity of Operators in Java


If an expression has two operators with similar precedence, the expression is
evaluated according to its associativity (either left to right, or right to left). Let's
take an example.
a = b = c;
IT Elec 2 – Object-Oriented Programming

Here, the value of c is assigned to variable b. Then the value of b is assigned of


variable a. It is because the associativity of = operator is from right to left.
The table below shows the associativity of operators along with their associativity.

Java Operator Precedence and Associativity


Operators Precedence Associativity
postfix increment and ++ -- left to right
decrement
prefix increment and ++ -- + - ~ ! right to left
decrement, and unary
multiplicative */% left to right
additive +- left to right
shift << >> >>> left to right
relational < > <= >= instanceof left to right
equality == != left to right
bitwise AND & left to right
bitwise exclusive OR ^ left to right
bitwise inclusive OR | left to right
logical AND && left to right
logical OR || left to right
ternary ? : right to left
assignment = += -= *= /= %= left to right
&= ^= |= <<= >>= >>>=

You don't need to memorize everything. The precedence and associativity of


operators makes sense itself. You can use parenthesis if you think it makes your
code easier to understand.
IT Elec 2 – Object-Oriented Programming

Declaring and Using a Variable


In this section, you write an application to work with a variable and a constant.

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.

Figure 2.1 Output of the DataDemo Application

8. Execute the application from the command line by typing java DataDemo. The
command window output is shown in Figure 2.1.

Trying to Use an Uninitialized Variable


In this section, you see what happens when a variable is uninitialized.

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.

Figure 2.2 Error message generated when a variable is not initialized


3. Modify the aWholeNumber declaration so that the variable is again initialized to 315.
Compile the class, and execute it again.
IT Elec 2 – Object-Oriented Programming

Adding a Named Constant to a Program


In this section, you add a named constant to the DataDemo program.

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

Figure 2.3 Output of DataDemo program after recent Changes

3. Save the program, and then compile and execute it. The output appears in Figure 2.3.

Working with Integers


In this section, you work more with integer values.
1. Open a new file in your text editor, and create a shell for an IntegerDemo class as
follows:
public class IntegerDemo
{
}
2. Between the curly braces, indent a few spaces and write the shell for a main()method
as follows:
public static void main(String[] args)
{
}
IT Elec 2 – Object-Oriented Programming

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.

Figure 2.4 Output of the IntegerDemo program

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.

9. At the Java Web site (www.oracle.com/technetwork/java/index.html), examine the list


of println() methods in the PrintStream class. Although you can find versions that
accept String, int, and long arguments, you cannot find ones that accept byte or
short values. Yet, the println() statements in the latest version of the program work
correctly. The reason has to do with type conversion.

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

Accepting User Input


In the next steps you create a program that accepts user input.

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.

Figure 2.9 Typical execution of the IntegerDemoInteractive program

Adding String Input


Next, you add String input to the IntegerDemoInteractive program.

1. Change the class name of the IntegerDemoInteractive program to


IntegerDemoInteractiveWithName, and immediately save the file as
IntegerDemoInteractiveWithName.java.

2. Add a new variable with the other variable declarations as follows:


String name;
3. After the last input statement (that gets the value for aLong), add three statements that
prompt the user for a name, accept the name, and use the name as follows:
System.out.print("Please enter your name >> ");
name = input.nextLine();
System.out.println("Thank you, " + name);
4. Save the file, and compile and execute it. Figure 2.10 shows a typical execution. You
can enter the numbers, but when the prompt for the name appears, you are not given the
opportunity to respond. Instead, the string "Thank you, ", including the ending comma
and space, is output immediately, and the program ends. This output is incorrect because
the input statement that should retrieve the name from the keyboard instead retrieves the
Enter key that was still in the keyboard buffer after the last numeric entry.
IT Elec 2 – Object-Oriented Programming

Figure 2.10 Typical execution of incomplete IntegerDemoInteractiveWithName


application that does not accept a name

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.

Figure 2.11 Typical successful execution of IntegerDemoInteractiveWithName


application
IT Elec 2 – Object-Oriented Programming

Using Arithmetic Operators


In these steps, you create a program that uses arithmetic operators.

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

secondNumber + " is " + difference);


System.out.println("The average of " + firstNumber +
" and " + secondNumber + " is " + average);
8. Save the file as ArithmeticDemo.java, and then compile and execute it. Enter values
of your choice. Figure 2.12 shows a typical execution. Notice that because integer division
was used to compute the average, the answer is an integer.

Figure 2.12 Typical execution of ArithmeticDemo application

9. Execute the program multiple times using various integer values, and confirm that the
results are accurate.

Performing Floating-Point Arithmetic


Next, you will modify the ArithmeticDemo application to work with floating-point values
instead of integers.

1. Within the ArithmeticDemo application, change the class name to


ArithmeticDemo2, and immediately save the file as ArithmeticDemo2.java. Change
all the variables’ data types to double. Change the two prompts to request double
values, and change the two calls to the nextInt() method to nextDouble(). Save,
compile, and execute the program again. Figure 2.13 shows a typical execution. Notice
that the average calculation now includes decimal places.

Figure 2.13 Typical execution of the ArithmeticDemo2 application


IT Elec 2 – Object-Oriented Programming

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.

Figure 2.14 Another typical execution of the ArithmeticDemo2 application

Recommended Learning Materials and Resources


To supplement the lesson in this module, you may visit the following links:
 https://www.w3schools.com/java/java_operators.asp
 https://www.programiz.com/java-programming/expressions-statements-
blocks
 https://www.youtube.com/watch?v=8CX4Tdttbqk

Flexible Teaching Learning Modality (FTLM) adapted


In this lesson, the online and remote FTLM is adapted using the university’s
Learning Management System called SeDi. For the online modality, the Virtual
Classroom of SeDi shall be used for the purpose of delivering a lecture and allowing
a synchronous discussion with the students. For the remote modality, SeDI shall be
used to upload the module and to allow asynchronous discussion with the
students. This will also be used as platform for the submission of the requirements.
IT Elec 2 – Object-Oriented Programming

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

B. Variables and Expressions


1. What is the numeric value of each of the following expressions as evaluated by
Java?
a. 4 + 6 * 2 d. 19 % (2 + 3)
b. 10 / 5 + 8 e. 3 + 4 * 20 / 3
c. 12 / 4 + 16 / 2

2. What is the value of each of the following Boolean expressions?


a. b. 8 <= (2 + 6) d. 8 != (2 + 5)
b. 3 >= 3 e. 3 + 2 * 6 == 15
c. 3 * 3 == 2 * 4

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

Farrell, Joyce. 2016. JAVA Programming, 8th Edition.


Gaddis, Tony. 2016. Starting Out with JAVA: From Control Structures through
Objects, 6th edition.

Prepared by:

FELIPE B. AMMUGAUAN, JR.


ISU ANGADANAN

You might also like