Chapter 2 Part II:
Basics of Java
Java Tokens
1
Introduction
Most statements contain expressions, which describe the actions
carried out on data.
Smallest individual units in a program are known as tokens.
In simplest terms, a java program is a collection of tokens,
comments, and white spaces.
Java has five types of tokens: Reserved Keywords, Identifiers,
Literals, Separators and Operators .
2
1. Keywords
Are essential part of a language definition and can not be used as
names for variables, classes, methods and so on.
Java language has reserved 60 words as keywords.
3
2. Identifiers
Are programmer-designed tokens.
Are used for naming classes, methods, variables, objects,
labels, packages and interfaces in a program.
Java identifiers follow the following rules:
They can have alphabets, digits, and the underscore and
dollar sign characters.
They must not begin with a digit
Uppercase and lowercase letters are distinct.
They can be of any length.
4
POP QUIZ
Which of the following are valid Identifiers?
1) $amount 5) score
2) 6tally 6) first Name
3) my*Name 7) total#
4) salary 8) this
5
3. Literals
Literals in Java are a sequence of characters(digits, letters and
other characters) that represent constant values to be stored in
variables.
Five major types of literals in Java:
I. Integer Literals: refers to a sequence of digits (decimal integer, octal
integer and hexadecimal integer)
II. Floating-point Literals
III. Character Literals
IV. String Literals
V. Boolean Literals
6
4. Separators
Are symbols used to indicate where groups of code are divided
and arranged.
They basically define the shape and functions of our code.
Java separators include:
I. Parenthesis ( ) :- used to enclose parameters, to define
precedence in expressions, surrounding cast types
II. Braces { } :- used to contain the values of automatically
initialized arrays and to define a block of code for classes,
methods and local scopes.
7
Contd.
III. Brackets [ ] :- are used to declare array types and for
dereferencing array values.
IV. Semicolon ; :- used to separate statements.
V. Comma , :- used to separate consecutive identifiers in a
variable declaration, also used to chain statements together
inside a “for” statement.
VI. Period . :- Used to separate package names from sub-
package names and classes; also used to separate a variable
or method from a reference variable.
8
5. Operators
Are symbols that take one or more arguments (operands) and
operates on them to a produce a result.
Are used to in programs to manipulate data and variables.
They usually form a part of mathematical or logical
expressions.
Expressions can be combinations of variables,
primitives and operators that result in a value.
9
Java Operators
There are 8 different groups of operators in Java:
Arithmetic operators
Relational operators
Logical operators
Assignment operator
Increment/Decrement operators
Conditional operators
Bitwise operators
Special operators
10
A. Arithmetic Operators
Java has five basic arithmetic operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo division
They all work the same way as they do in other languages.
We cannot use these operators on boolean type .
Unlike C and C++, modulus operator can be applied to the
floating point data.
Order of operations (or precedence) when evaluating an
expression is the same as you learned in school (BODMAS).
11
B. Relational Operators
Relational operators compare two values
Produces a boolean value (true or false) depending on
the relationship.
Java supports six relational operators:
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
Relational expressions are used in decision statements such
as, if and while to decide the course of action of a running
program.
12
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)
13
C. Logical Operators
Symbol Name
&& Logical AND
|| Logical OR
! Logical NOT
Logical operators can be referred to as boolean operators,
because they are only used to combine expressions that have a
value of true or false.
The logical operators && and || are used when we want to
form compound conditions by combining two or more
relations.
An expression which combines two or more relational
expressions is termed as a logical expression or a
compound relational expression.
14
Examples of Logiacal 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
15
4. Assignment Operator
Are used to assign the value of an expression to a variable.
In addition to the usual assignment operator(=), java has a set
of ‘shorthand’ assignment operators which are used in the
form:
var op = expr ;
Where var is a variable, op is a binary operator
and expr is an expresion.The operator op= is known
as shorthand assignment operator.
The assignment statement: var op= expr; is
equivalent to var=var op(expr);
Examples:
x += y + 5; is equivalent to x = x+(y+5);
y *= 7; is equivalent to y = y * 7;
16
5. 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.
Both ++ and -- are unary operators.
17
The increment/decrement operator has two forms:
The prefix form ++count, --count
first adds/subtracts1 to/from 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
18
6. Conditional Operators
The character pair ?: is a ternary operator available in java.
It is used to construct conditional expression of the form:
exp1 ? exp2: exp3;
where exp1, exp2 and exp3 are expressions.
The operator ?: works as follwos:
exp1 is evaluated first. If it is non-zero (true), then the
expression exp2 is evaluated and becomes the value of the
conditional expression. exp3 is evaluated and becomes the value of
the conditional expression if exp1 is false.
Example:
Given a=10, b=15 the expression
x=(a>b)? a:b; will assign the value of
b to x. i.e. x=b=15;
19
6. Bitwise Operators
One of the unique features of java compared to other high-level
languages is that it allows direct manipulation of individual bits
within a word.
Bitwise operators are used to manipulate data at values of bit level.
They are used for testing the bits, or shifting them to the right or left.
They may not be applied to float or double data types.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
20
7. Special Operators
Java supports some special operators of interest such as instanceof
operator and member selection operator(.).
7.1 instanceof Operator: is an object reference operator and
returns true if the object on the left-hand side is an instance of the class
given on the right-hand side.
Example :
person instanceof student;
is true if the object person belongs to the class student; otherwise it is
false
7.2 Dot Operator: is used to access the instance variables and
methods of class objects.
Example:
person.age; // Reference to the variable age.
person1.salary(); // Reference to the method salary.
21
Type Conversion in Expressions
A. Automatic Type Conversion: If the operands
of an expression are of different types, the ‘lower’ type is
automatically converted to the ‘higher’ type before the
operation proceeds. That is, the result is of the ‘higher’ type.
Example :
int a=110;
float b=23.5;
the expression a+b yields a floating point number 133.5
since the ‘higher’ type here is float.
22
Contd.
B. Casting a value: is used to force type conversion.
The general form of a cast is:
(type-name)expression;
where type-name is one of the standard data types.
Example :
x=(int)7.5; will assign 7 to x
a=(int)21.3/(int)3.5; a will be 7
23
Operator Precedence and Associativity.
Operator Description Associativity Rank
. Member Selection
() Function call
Left to right 1
[] Array elements reference
- Unary Minus
++ Increment
-- Decrement
Right to left 2
! Logical negation
~ One’s complement
(type) Casting
* Multiplication
Left to right 3
/ Division
% Modulus
24
Contd.
Operator Description Associativity Rank
+ Addition
Left to right 4
- Subtraction
<< Left Shift
Left to right 5
>> Right Shift
>>> Right shift with zero fill
< Less than
<= Less than or equal to
> Greater than Left to right 6
>= Greater than or equal to
instanceof Type comparison
== Equality
Left to right 7
!= Inequality
25
Operator Precedence and Associativity.
Operator Description Associativity Rank
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional Operator Left to right 13
= Assignment operator Left to right 14
Op= Shorthand assignment Left to right 15
26
//Demonstration of Java Expressions
public class DemoExpress
{
public static void main(String[] args)
{
System.out.println("===== BEGINNING OF THE PROGRAM =====\
n");
//Declaration and Initialization
int a=10,b=5,c=8,d=2;
float x=6.4f,y=3.0f;
//Order of Evaluation
int answer1=a*b+c/++d;
int answer2=--a*(b+++c)/d++;
//Type Conversion
float answer3=a/c;
float answer4=(float)a/c;
float answer5=a/y;
27
//Modulo Operations
int answer6=a%c;
float answer7=x%y;
//Logical Operations
boolean bool1=a>b && c>d;
boolean bool2=a<b && c>d;
boolean bool3=a<b || c>d;
boolean bool4=!(a-b==c);
System.out.println("Order of Evaluation");
System.out.println("a*b+c/++d + "+answer1);
System.out.println("--a*(b+++c)/d++ = " +answer2);
System.out.println("================");
System.out.println("Type Conversion");
System.out.println(" a/c = "+answer3);
System.out.println("(float)a/c = " + answer4);
System.out.println(" a/y = " + answer5);
28
System.out.println("================");
System.out.println("Modulo Operations");
System.out.println(" a%c = "+answer6);
System.out.println(" x%y = "+answer7);
System.out.println("================");
System.out.println("Logical Operations");
System.out.println(" a>b && c>d = "+bool1);
System.out.println(" a<b && c>d = "+bool2);
System.out.println(" a<b || c>d = "+bool3);
System.out.println(" !(a-b==c) = "+bool4);
System.out.println("================");
System.out.println("Bitwise Operations");
29
//Shift Operators
int l=8, m=-8,n=2;
System.out.println(" n & 2= "+(n&2));
System.out.println(" l | n= "+(l|n));
System.out.println(" m | n= "+(m|n));
System.out.println(" l >> 2= "+(l>>2));
System.out.println(" l >>> 1= "+(l>>>1));
System.out.println(" l << 1= "+(l<<1));
System.out.println(" m >> 2= "+(m>>2));
System.out.println(" m >>> 1= "+(m>>>1));
System.out.println("\n===== END OF THE PROGRAM =====");
30
POP QUIZ
1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3; -12
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;
31
Variables and Primitive Data
Types
32
Variables
A variable is an identifier that denotes a storage location used to
store a data value.
Unlike constants, that remain unchanged during the execution
of a program, a variable may take different values at different
times during the execution of the program.
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.
33
Contd.
Variable names may consist of alphabets, digits, the
underscore (_) and dollar ($) characters, subject to the
following conditions:
1. They should not begin with a digit.
2. Keywords should not be used as a variable name.
3. White spaces are not allowed.
4. Uppercase and lowercase are distinct. i.e. A rose is
not a Rose is not a ROSE.
34
5. Variable names can be of any length.
Data Types
Every variable in Java has a data type.
Data types specify the size and type of values that can be stored.
Java language is rich in the data types.
Java data types are of two type:
Primitive Data Types (also called intrinsic or built-in data
types)
Non-Primitive data Types (also known as Derived or
reference types)
35
Data Types in Java
Primitive Non-Primitive
(Intrinsic) (Derived)
Numeric Non-Numeric Classes Arrays
Interfaces
Integer Floating-Point Character Boolean
Data Types in Java
36
Primitive Data Types
There are eight built-in data types in Java:
• 4 integer types (byte, short, int, long)
• 2 floating point types (float, double)
• Boolean (boolean)
• Character (char)
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.
37
A. 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.
38
B. Floating-Point Types
Integer types can hold only whole numbers and therefore we need
another type known as floating point type to hold numbers
containing fractional parts.
There are two data types that can be used to store decimal values
(real numbers).
39
C. Character Type
Is used to store character constants in memory.
Java provides a character data type called char
The char data type assumes a size of 2 bytes but, basically, it
can hold only a single character.
Note that you need to use singular quotation marks while
initializing a variable whose data type is char.
Example:
char firstLetterOfName = 'e' ;
char myQuestion = '?' ;
40
D. Boolean Type
Boolean is a data type used when we want to test a particular
condition during the execution of the program.
There are only two values that a Boolean can take: true or
false.
Boolean type is denoted by the keyword boolean and uses
only one bit of storage.
All comparison operators return boolean type values.
Boolean values are often used in selection and iteration
statements.
41
Declaration of Variables
After designing suitable variable names, we must declare them to the
compiler. Declaration does three things:
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold
3. The place of declaration (in the program) declares the scope of the variable.
A variable must be declared before it is used in the program.
The general form of declaration of Variables is:
type variable1, variable2,...., variableN;
Example:
int count, x,y; //Declaration
char firstLetterOfName = 'e' ; // Declaration & initialization
42
Assigning Values to Variables
A variable must be given a value after it has been declared
this done by using an assignment statement.
Assignment Statement
A simple method of giving value to a variable is through the
assignment statement as follows:
variableName = value;
Example: x = 123, y = -34;
It is possible to assign a value to a variable at the time of
declaration as: type variableName = value;
43