Learning Objectives
After completing this session, you will be able to:
Identify Java keywords, Java literals, and primitive data types Java Keywords
Keywords are predefined identifiers reserved by Java for a specific purpose.
You cannot use keywords as names for your variables, classes, methods, and so on.
A list of Java keywords are as follows:
Java Literals
Literals are tokens that do not change. They are constant in value.
The different types of literals in Java are:
Integer Literals
Floating-Point Literals
Boolean Literals
Character Literals
String Literals Java Literals: Integer
Integer literals come in different formats:
decimal (base 10)
hexadecimal (base 16)
octal (base 8)
Special notations in using integer literals in Java programs:
Decimal:
No special notation
Example: 12
Hexadecimal:
Precede by 0x or 0X
Example: 0xC
Octal:
Precede by zero
Example: 014 Java Literals: Floating point
Represents decimals with fractional parts:
Example: 3.1416
Can be expressed in standard or scientific notation:
Example: 583.45 (standard), 5.8345e2 (scientific)
Java Literals: Boolean
Boolean literals have only two values, true or false.
Java Literals: Character
Character Literals represent single Unicode characters.
Unicode character:
A 16-bit character set that replaces the 8-bit ASCII character set
Unicode allows the inclusion of symbols and special characters from other languages Java Literals: Character
To use a character literal, enclose the character in single quote delimiter.
For example: The letter a, is represented as ‘a’.
Special characters such as a newline character, a backslash is used followed by the character code. For example, ‘\n’ for the newline character, ‘\r’ for the carriage return, and ‘\b’ for backspace.
Java Literals: String
String literals represent multiple characters and are enclosed by double quotes.
An example of a string literal is, “Hello World”.
Primitive Data Types
The Java programming language defines eight primitive data types:
boolean (for logical)
float (floating point)
Primitive Data Types: Logical-boolean
A boolean data type represents two states of true and false.
An example is boolean result = true;
The earlier example shown, declares a variable named result as boolean type and assigns it a value of true.
Primitive Data Types: Textual-char
A character data type (char), represents a single Unicode character.
It must have its literal enclosed in single quotes(’ ’).
For example the following code:
‘a’ //The letter a
‘\t’ //A tab
To represent special characters like ' (single quotes) or " (double quotes), use the escape character \. For example the following code:
'\'' //for single quotes '\"' //for double quotes
Important points to remember:
A string represents a data type that contains multiple characters. It is not a primitive data type, rather it is a class.
It has its literal enclosed in double quotes(“”). For example, String message=“Hello world!”;
Primitive Data Types: Integral – byte, short, int, and, long
Integral data types in Java uses three forms of decimal, octal, or hexadecimal.
Examples are:
2 // The decimal value 2
077 // The leading 0 indicates an octal value
0xBACC // The leading 0x indicates a hex value
Integral types has int as default data type.
You can define its long value by appending the letter l or L.
For example: 10L
Integral data type have the following ranges:
Integer Length Name or Type Range
8 bits byte -27 to 27-1
16 bits short -215 to 215-1
32 bits int -231 to 231-1
64 bits long -263 to 263-1
Coding Guidelines: In defining a long value, a lowercase L is not recommended because it is hard to distinguish from the digit 1.
Primitive Data Types: Floating Point-float and double Floating point types has double as default data type.
Floating-point literal includes either a decimal point or one of the following,
E or e //(add exponential value)
F or f //(float)
D or d //(double)
Examples are:
3.14 //A simple floating-point value (a double)
6.02E23 //A large floating-point value
2.718F //A simple float size value
123.4E+306D //A large double value with redundant D Floating-point data types have the following ranges:
Try It Out
Problem Statement:
Write a program that contains the literal values for the following statements:
1. Declare an int named size and assign it the value 32 2. Declare a char named initial and assign it the value ‘j’.
3. Declare double named d and assign it the value 456.709 4. Declare a boolean named isAvailable(no assignment)
5. Assign the value true to the isAvailable that is declared earlier
6. Declare an int named y, and assign it the value that is the sum of whatever x and 456.
Code:
Refer File Name: LiteralValues.java to obtain soft copy of the program code
How It Works:
You can assign a value to a variable in one of the following several ways including:
Type a literal value after the equals sign (x = 12, isGood = true, and so on)
Assign the value of one variable to another (x = y)
Use an expression combining the two (x = y + 43)
For the given problem statement, the literal values are shown in bold italics:
int size = 32;
List out few important points while using identifiers, literals, and keywords in Java.
Solution:
An identifier must begin with a letter, dollar sign($), or underscore (_). Subsequent characters may be letters, $, _ (underscore), or digits.
An identifier cannot have a name of a Java keyword. Embedded keywords are accepted. true, false, and null are literals (not keywords), but they cannot be used as identifiers as well.
const and goto are reserved words, but not used.
All numeric data types are signed. char is the only unsigned integral type.
A number is by default an int literal. A decimal number is by default a double literal.
1E-5d is a valid double literal and E2d is not (since it starts with a letter, compiler thinks that it’s an identifier).
Summary
Integer literals can be decimal, octal (e.g. 013), or hexadecimal (e.g. 0x3d).
Literals for longs end in L or l (lowercase of the alphabet L).
Float literals end in F or f, double literals end in a digit D or d.
The boolean literals are true and false.
Literals for chars are single character inside single quotes: ‘d’.
Test Your Understanding
1. Which one of the following is not a token?
a) keyword b) identifier c) method d) literal
2. Which one of the following is not a valid identifier?
total
a) _count b) sum c) 2root
3. The size of a long integer data type is:
a) 8-bits b) 16-bits c) 32-bits d) 64-bits
Session 15: Language Fundamentals and Operators
Learning Objectives
After completing this session, you will be able to:
Define variables
Declare variables
Initialize variables
Convert data types
Cast data types Variables
A variable is an item of data used to store the state of objects.
A variable has a:
data type: The data type indicates the type of value that the variable can hold.
name: The variable name must follow rules for identifiers.
Declaring and Initializing Variables Declare a variable as follows:
<data type> <name> [=initial value];
Note: Values enclosed in <> are required values, while those values in [] are optional.
Reference Variables Versus Primitive Variables Two types of variables in Java:
Primitive Variables
Reference Variables
Primitive Variables:
Variables with primitive data types such as int or long.
Stores data in the actual memory location of where the variable is present
Reference Variables:
Variables that store the address in the memory location
Points to another memory location where the actual data is present
When you declare a variable of a certain class, you are actually declaring a reference variable to the object with that certain class
Example of a reference variable and primitive variable Suppose you have two variables with data types int and String.
int num = 10; // primitive type
String name = "Hello"; // reference type
Example of memory handling of a reference variable and a primitive variable The following picture is the actual memory of your computer, wherein you have the address of the memory cells, the variable name, and the data they hold.
Type Casting
Type Casting is the mapping type of an object to another.
Casting Primitive Types
Casting between primitive types enables you to convert the value of one data from one type to another primitive type
Commonly occurs between numeric types
There is one primitive data type that you cannot do casting and that is the boolean data type
Types of Casting:
o Implicit Casting o Explicit Casting
Implicit Casting
Suppose you want to store a value of int data type to a variable of data type double.
int numInt = 10;
double numDouble = numInt; //implicit cast
In this example, as the data type (double) of the destination variable holds a larger value than the data type (int) of the value, the data is implicitly casted to the data type double of the destination variable.
Example of implicit casting:
int numInt1 = 1;
int numInt2 = 2;
//result is implicitly cast to type double double numDouble = numInt1/numInt2;
Explicit Casting
When you convert a data that has a large type to a smaller type, you must use an explicit cast.
Explicit casts take the following form:
(Type)value where, Type is the name of the type you are converting to value. It is an expression that results in the value of the source type.
Explicit Casting Examples double valDouble = 10.12;
int valInt = (int)valDouble;
//convert valDouble to int type double x = 10.2;
int y = 2;
int result = (int)(x/y); //typecast result of operation to int
Casting Objects
Instances of classes also can be cast into instances of other classes, with one restriction. The source and destination classes must be related by inheritance. One class must be a subclass of the other.
Casting objects is analogous to converting a primitive value to a larger type. Some objects might not need to be cast explicitly.
Cast, (classname)object where, classname is the name of the destination class and object is a reference to the source object.
Casting Objects Example
The following example casts an instance of the class VicePresident to an instance of the class Employee. VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive washroom privileges.
Employee emp = new Employee();
VicePresident vp = new VicePresident();
// no cast needed for upward use
emp = vp;
// must cast explicitly vp = (VicePresident)emp;
Try It Out
Problem Statement:
Write a program that illustrates the implementation of the automatic initialization of member variables.
Code:
class Initialization {
boolean bo;
byte by;
char c;
short s;
int i;
long l;
float f;
double d;
Object o;
public static void main(String[] args) {
Initialization app = new Initialization();
app.run();
} // continued …
Refer File Name: Initialization.java to obtain soft copy of the program code
How It Works:
The Initialization program illustrates the use of the automatic initialization of member variables. It displays the following output:
boolean: false byte: 0
char:
short: 0 int: 0 long: 0 float: 0.0 double: 0.0 Object: null
Tips and Tricks
List out the key points related to ‘instance’ (or member) variables and ‘local’ variables.
Solution:
Instance (or member) variables:
o Accessible anywhere in the class
o Automatically initialized before invoking any constructor o Static variables are initialized at class load time
o Can have the same name as the class
Local variables:
o Must be initialized explicitly and (Or, the compiler will catch it.) Object references can be initialized to null to make the compiler happy
o The following code will not compile. Specify else part or initialize the local variable explicitly.
public String testMethod(int a) {
String tmp;
if (a > 0) tmp = “Positive”;
return tmp;
}
Can have the same name as a member variable and resolution is based on scope Note: Here is the figure of allowable primitive conversion
byte -> short -> int -> long -> float -> double char
Summary
Automatic conversion from narrow to wider type. For e.g., whenever division is performed between a floating type and an integer type, the integer type is
automatically converted (sometimes called promoted) to a floating type and floating arithmetic is performed.
Arithmetic with boolean is not allowed.
Variables can be initialized when declared
All Java variables can be initialized when they are declared.
Member (or instance) variables are automatically initialized
If the programmer doesn't initialize the variables declared inside the class but outside of a method (often referred to as member variables as opposed to local variables), they are automatically initialized to a default value.
The default value for a boolean member variable is false.
Local variables are not automatically initialized
Unlike instance (or member) variables, if you fail to initialize a local variable, the variable is not automatically initialized.
Must initialize or assign value to all local variables
Thus, the programmer is responsible for either initializing all local variables, or
assigning a value to them before attempting to access their value with code later in the program.
Cannot access value from uninitialized local variable
If you attempt to access and use the value from an uninitialized local variable before you assign a value to it, you will get a compiler error.
Test Your Understanding
1. Which one of the following is not true in the case of Type declaration statement?
a) Any number of variables can be declared in a Type declaration statement.
b) Different types of variables can be declared in a single Type declaration statement.
c) The list of variables in a Type declaration statement should be separated by commas.
d) The Type declaration statement can be used to declare as well as initialize a variable.
Session 16: Language Fundamentals and Operators
Learning Objectives
After completing this session, you will be able to:
Write Java programs by declaring and initializing variables Declaring and Initializing Variables: Sample Program
1 public class VariableSamples {
2 public static void main( String[] args ){
3 //declare a data type with variable name 4 //result and boolean data type
5 boolean result;
6
7 //declare a data type with variable name
8 // option and char data type
9 char option;
10 option = 'C'; //assign 'C' to option 11
12 //declare a data type with variable name 13 //grade, double data type and initialized 14 //to 0.0
15 double grade = 0.0;
16 } 17 }
Declaring and Initializing Variables: Coding Guidelines
It is always good to initialize your variables as you declare them.
Apply descriptive names for your variables.
For example, for a student’s grade, the variable name can be given as “grade” or
“studentGrade” instead of giving any other names.
Declare one variable in each line of code.
For example, the variable declarations:
double exam = 0;
double quiz = 10;
double grade = 0;
is preferred over the declaration double exam=0, quiz=10, grade=0;
Try It Out
Problem Statement:
What will happen if you try to compile the code given in the next slide?
Code:
class Digit {
public void add() { int k;
int s = k + 3;
} }
Refer File Name: Digit.java to obtain soft copy of the program code
How It Works:
The preceding code will not compile. You can declare k without a value, but as soon as you try to use it, the compiler freaks out.
Tips and Tricks
Provide some important tips on conversion of primitives in Java Solution:
The three types of conversion are namely assignment conversion, method call conversion, and arithmetic promotion.
boolean may not be converted to or from any type that is not boolean.
byte and short, cannot be converted to char and char cannot be converted to byte and short.
Arithmetic promotion:
Unary operators:
If the operand is byte, short or char { convert it to int;
}
else {
do nothing; no conversion needed;
}
Binary operators:
If the operand is double {
all double; convert the other operand to double;
}
else if one operand is float {
all double; convert the other operand to double;
}
else if one operand is float {
all double; convert the other operand to double;
} else {
all int; convert all to int;
}
Summary
Local variables (method variables) live on the stack.
Objects and their instance variables live on the heap.
Scope of a variable refers to the lifetime of variable.
There are four basic scopes:
Static variables live basically as long as their class lives.
Instance variables live as long as their object lives.
Local variables live as long as their method is on the stack; however, if their method invokes another method, they are temporarily unavailable.
Block variables (e.g., in a for or an if) live until the block completes.
Test Your Understanding
1. State true or false for the following:
a) Extended assignment operators (for example +=) do an implicit cast. (Useful when applied to byte, short or char as provided in the following example)
byte b = 10;
b += 10;
Session 18: Language Fundamentals and Operators
Learning Objectives
After completing this session, you will be able to:
Identify the different types of operators in Java Operators
Different types of operators are:
arithmetic operators
relational operators
logical operators
conditional operators
binary operator
These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first, in case multiple operators are used in one statement.
Arithmetic Operators
Arithmetic Operators: Sample Program 1 public class ArithmeticDemo {
2 public static void main(String[] args){
3 //a few numbers
4 int i = 37;
5 int j = 42;
6 double x = 27.475;
7 double y = 7.22;
8 System.out.println("Variable values...");
9 System.out.println(" i = " + i);
10 System.out.println(" j = " + j);
11 System.out.println(" x = " + x);
12 System.out.println(" y = " + y);
13 System.out.println("Adding...");
14 System.out.println(" i + j = " + (i + j));
15 System.out.println(" x + y = " + (x + y));
16 //subtracting numbers
17 System.out.println("Subtracting...");
18 System.out.println(" i - j = " + (i – j));
19 System.out.println(" x - y = " + (x – y));
20
21 //multiplying numbers
22 System.out.println("Multiplying...");
23 System.out.println(" i * j = " + (i * j));
24 System.out.println(" x * y = " + (x * y));
25
26 //dividing numbers
27 System.out.println("Dividing...");
28 System.out.println(" i / j = " + (i / j));
29 System.out.println(" x / y = " + (x / y));
30 //computing the remainder resulting from dividing 31 // numbers
32 System.out.println("Computing the remainder...");
33 System.out.println(" i % j = " + (i % j));
34 System.out.println(" x % y = " + (x % y));
35
36 //mixing types
37 System.out.println("Mixing types...");
38 System.out.println(" j + y = " + (j + y));
39 System.out.println(" i * x = " + (i * x));
40 }
Arithmetic Operators: Sample Program Output Variable values... Dividing...
i = 37 i / j = 0
j = 42 x / y = 3.8054
x = 27.475
y = 7.22 Computing the remainder...
i % j = 37
Note: When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is a floating point. The integer is implicitly converted to a floating-point number before the operation takes place.
Increment and Decrement Operators
unary increment operator (++) and unary decrement operator (--) are the two increment and decrement operators.
Increment and decrement operators increase and decrease a value stored in a number variable by 1.
For example
the expression, count=count + 1; //increment the value of count by 1 is equivalent to count++;.
Operator Use Description
++ op++ Increments op by 1; evaluates to the value of op before it was incremented ++ ++op Increments op by 1; evaluates to the value of op before it was incremented -- op-- Decrements op by 1; evaluates to the value of op before it was decremented -- --op Decrements op by 1; evaluates to the value of op after it was decremented
The increment and decrement operators can be placed before or after an operand.
When used before an operand, it causes the variable to be incremented or decremented by 1, and then the new value is used in the expression in which it appears.
For example:
int i = 10;
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14
When the increment and decrement operators are placed after the operand, the old value of the variable will be used in the expression where it appears.
For example:
int i = 10;
int j = 3;
int k = 0;
k = j++ + i; //will result to k = 3+10 = 13
Increment and Decrement Operators: Coding Guidelines
Always keep expressions containing increment and decrement operators simple and easy to explain.
Relational Operators
Relational operators compare two values and determine the relationship between those values.
The output of evaluation is the boolean value of true or false.
Operator Use Description
++ op++ Increments op by 1; evaluates to the value of op before it was incremented ++ ++op Increments op by 1; evaluates to the value of op before it was incremented -- op-- Decrements op by 1; evaluates to the value of op before it was decremented -- --op Decrements op by 1; evaluates to the value of op after it was decremented
Relational Operators: Sample Program 1 public class RelationalDemo{
2 public static void main(String[] args){
3 //a few numbers
4 int i = 37;
5 int j = 42;
6 int k = 42;
7 System.out.println("Variable values...");
8 System.out.println(" i = " +i);
9 System.out.println(" j = " +j);
10 System.out.println(" k = " +k);
11 //greater than
12 System.out.println("Greater than...");
13 System.out.println(" i > j = "+(i>j));//false 14 System.out.println(" j > i = "+(j>i));//true 15 System.out.println(" k > j = "+(k>j));//false
16 //greater than or equal to
17 System.out.println("Greater than or equal to");
18 System.out.println(" i >= j = "+(i>=j));//false 19 System.out.println(" j >= i = "+(j>=i));//true 20 System.out.println(" k >= j = "+(k>=j));//true
21 //less than
22 System.out.println("Less than...");
23 System.out.println(" i < j = "+(i<j));//true 24 System.out.println(" j < i = "+(j<i));//false 25 System.out.println(" k < j = "+(k<j));//false
23 System.out.println(" i < j = "+(i<j));//true 24 System.out.println(" j < i = "+(j<i));//false 25 System.out.println(" k < j = "+(k<j));//false