Chapter 2
Basics in Java Programming
AU HHC Information Technology. Dept. By Megersa.O
1 1/17/2021
What is a Variable?
Variables are places where information can be
stored while a program is running.
Their values can be changed at any point over the
course of a program
2 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Creating Variables
To create a variable, declare its name and the type of
information that it will store.
The type is listed first, followed by the name.
Example: a variable that stores an integer representing
the highest score on an exam could be declared as
follows:
int highScore ;
type name
3 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Creating Variables (continued)
Now you have the variable (highScore), you will
want to assign a value to it.
Example: the highest score in the class exam is
98.
highScore = 98;
Examples of other types of variables:
String studentName;
boolean gameOver;
4 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Naming Variables
The name that you choose for a variable is called an
identifier. In Java, an identifier can be of any length,
but must start with:
a letter (a – z),
a dollar sign ($),
or, an underscore ( _ ).
The rest of the identifier can include any character
except those used as operators in Java such as + , - , * .
In addition, there are certain keywords reserved (e.g.,
"class") in the Java language which can never be used
as identifiers.
5 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Naming (Continued)
Java is a case-sensitive language – the
capitalization of letters in identifiers matters.
A rose is not a Rose is not a ROSE
It is good practice to select variable names that
give a good indication of the sort of data they hold
For example, if you want to record the size of a hat,
hatSize is a good choice for a name whereas qqq
would be a bad choice
6 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
When naming a variable, the following
convention is commonly used:
The first letter of a variable name is lowercase
Each successive word in the variable name begins
with a capital letter
All other letters are lowercase
Here are some examples:
pageCount
loadFile
anyString
threeWordVariable
7 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
QUIZ
Which of the following are valid variable names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
8 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Statements
A statement is a command that causes something to
happen.
All statements in Java are separated by semicolons ;
Example:
System.out.println(“Hello,
World”);
You have already used statements to create a variable
and assign it a value.
9 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Variables and Statements
One way is to declare a variable and then assign a
value to it with two statements:
int e; // declaring a variable
e = 5; // assigning a value to a variable
Another way is to write a single initialization
statement:
int e = 5; // declaring AND assigning
10 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Java is a Strongly-Typed Language
All variables must be declared with a data type before
they are used.
Each variable's declared type does not change over
the course of the program.
Certain operations are only allowed with certain data
types.
If you try to perform an operation on an illegal data
type (like multiplying Strings), the compiler will
report an error.
11 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Primitive Data Types
There are eight built-in (primitive) data types in the Java
language
4 integer types (byte, short, int, long)
2 floating point types (float, double)
Boolean (boolean)
Character (char)
**see Appendix II: Summary of Primitive Data Types for a
complete table of sizes and formats**
12 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Integer Data Types
There are four data types that can be used to store
integers.
The one you choose to use depends on the size of the
number that we want to store.
Data Type Value Range
byte -128 to +127
short -32768 to +32767
int -2147483648 to +2147483647
long -9223372036854775808 to +9223372036854775807
In this course, we will always use int when dealing
with integers.
13 AU HHC Information Technology. 1/17/2021
Dept. By Megersa.O
Here are some examples of when you would want to
use integer types:
- byte smallValue;
smallValue = -55;
- int pageCount = 1250;
- long bigValue = 1823337144562L;
Note: By adding an L to the end of the value in the last
example, the program is “forced” to consider the value to be
of a type long even if it was small enough to be an int
14 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Floating Point Data Types
There are two data types that can be used to
store decimal values (real numbers).
The one you choose to use depends on the size
of the number that we want to store.
Data Type Value Range
float 1.4×10-45 to 3.4×1038
double 4.9×10-324 to 1.7×10308
In this course, we will always use double
when dealing with decimal values.
15 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Here are some examples of when you would want to
use floating point types:
double g = 7.7e100 ;
double tinyNumber = 5.82e-203;
float costOfBook = 49.99F;
Note: In the last example we added an F to the end of
the value. Without the F, it would have automatically
been considered a double instead.
16 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Boolean Data Type
Boolean is a data type that can be used in
situations where there are two options, either
true or false.
Example:
boolean monsterHungry = true;
boolean fileOpen = false;
17 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Character Data Types
Character is a data type that can be used to store a
single characters such as a letter, number,
punctuation mark, or other symbol.
Example:
char firstLetterOfName = 'e' ;
char myQuestion = '?' ;
Note that you need to use singular quotation
marks when assigning char data types.
18 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Introduction to Strings
Strings consist of a series of characters inside
double quotation marks.
Examples statements assign String variables:
String coAuthor = "John Smith";
String password = "swordfish786";
Strings are not one of the primitive data types,
although they are very commonly used.
Strings are constant; their values cannot be
changed after they are created.
19 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
QUIZ
What data types would you use to store the following
types of information?:
1)Population of Ethiopia int
2)Approximation of π double
3)Open/closed status of a file boolean
4)Your name String
5)First letter of your name char
6)$237.66 double
20 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Appendix I: Reserved Words
The following keywords are reserved in the Java language.
They can never be used as identifiers:
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void violate while
AU HHC Information Technology. Dept. By
21 Megersa.O 1/17/2021
Appendix II: Primitive Data Types
The following tables show all of the primitive data types
along with their sizes and formats:
Integers
Data Type Description
byte Variables of this kind can have a value from:
-128 to +127 and occupy 8 bits in memory
short Variables of this kind can have a value from:
-32768 to +32767 and occupy 16 bits in memory
int Variables of this kind can have a value from:
-2147483648 to +2147483647 and occupy 32 bits in
memory
long Variables of this kind can have a value from:
-9223372036854775808 to +9223372036854775807 and
occupy 64 bits in memory
22 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Appendix II: Primitive Data Types (cont)
Real Numbers
Data Type Description
float Variables of this kind can have a value from:
1.4e(-45) to 3.4e(+38)
double Variables of this kind can have a value from:
4.9e(-324) to 1.7e(+308)
Other Primitive Data Types
char Variables of this kind can have a value from:
A single character
boolean Variables of this kind can have a value from:
True or False
23 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Operators: What are Operators?
• Operators are special symbols used for
– mathematical functions
– assignment statements
– logical comparisons
• Examples:
3 + 5 // uses + operator
14 + 5 – 4 * (5 – 3) // uses +, -, *
operators
• Expressions can be combinations of variables,
primitives and operators that result in a value.
24 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
The Operator Groups
There are 5 different groups of operators:
1. Arithmetic operators
2. Assignment operator
3. Increment/Decrement operators
4. Relational operators
5. Conditional operators
25 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Arithmetic Operators
Java has 6 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo (remainder)
^ exponent (to the power of)
Order of operations (or precedence) when evaluating an
expression is the same as you learned in school
(PEMDAS).
26 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Order of Operations
Example: 10 + 15 / 5;
The result is different depending on whether the
addition or division is performed first
(10 + 15) / 5 = 5
10 + (15 / 5) = 13
Without parentheses, Java will choose the second
case
Note: you should be explicit and use parentheses to
avoid confusion
27 AU HHC Information Technology. Dept. By Megersa.O
1/17/2021
Integer Division
In the previous example, we were lucky that
(10 + 15) / 5 gives an exact integer
answer (5).
But what if we divide 63 by 35?
Depending on the data types of the variables that
store the numbers, we will get different results.
28 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Integer Division Example
int i = 63;
int j = 35;
System.out.println(i / j);
Output: 1
double x = 63;
double y = 35;
System.out.println(x / y);
Ouput: 1.8
The result of integer division is just the integer
part of the quotient!
29 AU HHC Information Technology. Dept. By Megersa.O
1/17/2021
Assignment Operator
The basic assignment operator (=) assigns the value of
var to expr
var = expr ;
Java allows you to combine arithmetic and assignment
operators into a single operator.
Examples:
x = x + 5; is equivalent to x += 5;
y = y * 7; is equivalent to y *= 7;
30 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Increment/Decrement Operators
count = count + 1;
can be written as:
++count; or count++;
++ is called the increment operator.
count = count - 1;
can be written as:
--count; or count--;
-- is called the decrement operator.
31 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
The increment/decrement operator has two forms:
The prefix form ++count, --count
first adds 1 to the variable and then continues to any other operator in the
expression
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6
The postfix form count++, count--
first evaluates the expression and then adds 1 to the variable
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
32 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Relational (Comparison) Operators
• Relational operators compare two values
• Produces a boolean value (true or false)
depending on the relationship
operation is true when . . .
a > b a is greater than b
a >= b a is greater than or equal to b
a == b a is equal to b
a != b a is not equal to b
a <= b a is less than or equal to b
a < b a is less than b
1/17/2021 AU HHC Information Technology. Dept. By 33
Megersa.O
Examples of Relational Operations
int x = 3;
int y = 5;
boolean result;
1) result = (x > y);
now result is assigned the value false because
3 is not greater than 5
2) result = (15 == x*y);
now result is assigned the value true because the product of
3 and 5 equals 15
3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
34 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Conditional Operators
Symbol Name
&& AND
|| OR
! NOT
Conditional operators can be referred to as boolean
operators, because they are only used to combine
expressions that have a value of true or false.
1/17/2021 AU HHC Information Technology. Dept. By 35
Megersa.O
Truth Table for Conditional Operators
x y x && y x || y !x
True True True True False
True False False True False
False True False True True
False False False False True
1/17/2021
AU HHC Information Technology. Dept. By Megersa.O
36
Examples of Conditional Operators
boolean x = true;
boolean y = false;
boolean result;
1. Let result = (x && y);
now result is assigned the value false
(see truth table!)
2. Let result = ((x || y) && x);
(x || y) evaluates to true
(true && x) evaluates to true
now result is assigned the value true
37 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Using && and ||
Examples:
(a && (b++ > 3))
(x || y)
Java will evaluate these expressions from left to
right and so will evaluate
a before (b++ > 3)
x before y
Java performs short-circuit evaluation:
it evaluates && and || expressions from left to
right and once it finds the result, it stops.
38 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Short-Circuit Evaluations
(a && (b++ > 3))
What happens if a is false?
Java will not evaluate the right-hand expression (b++ >
3) if the left-hand operator a is false, since the result is
already determined in this case to be false. This means b
will not be incremented!
(x || y)
What happens if x is true?
Similarly, Java will not evaluate the right-hand operator y
if the left-hand operator x is true, since the result is
already determined in this case to be true.
39 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
Appendix : operator precedence
40 AU HHC Information Technology. Dept. 1/17/2021
By Megersa.O
QUIZ
1) What is the value of number? -12
int number = 5 * 3 – 3 / 6 – 9 * 3;
2) What is the value of result?
int x = 8; false
int y = 2;
boolean result = (15 == x * y);
3) What is the value of result?
boolean x = 7;
true
boolean result = (x < 8) && (x > 4);
4) What is the value of numCars?
int numBlueCars = 5;
int numGreenCars = 10; 27
int numCars = numGreenCars++ + numBlueCars + +
+numGreeenCars;
41 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021
References
Summary of Java operators
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/opsummar
y.html
Order of Operations (PEMDAS)
1. Parentheses
2. Exponents
3. Multiplication and Division from left to right
4. Addition and Subtraction from left to right
42 AU HHC Information Technology. Dept. By Megersa.O 1/17/2021