Java Fundamentals
By
Manjiri Tatke
Objectives
• After completing this , participants will be able to:
• Understand Basic Java Language constructs like:
• Keywords
• Primitive Data Types
• Operators
• Variables
• Literals
• Write Java programs using control structures
• Best Practices
Keywords in Java
Primitive Data Types
• Integral types (byte, short, int, and long)
• Floating point types (float and double)
• Textual type (char)
• Logical type (boolean)
Some New Integral Primitive Types
Type Length Range
–27 to 27 – 1
byte 8 bits (–128 to 127,
or 256 possible values)
short 16 bits –215 to 215 – 1
(–32,768 to 32,767, or 65,535 possible
values)
32 bits –231 to 231 –1
int (–2,147,483,648 to 2,147,483,647, or
4,294,967,296 possible values)
–263 to 263 – 1
long (–9,223,372,036854,775,808 to
64 bits 9,223,372,036854,775,807, or
18,446,744,073,709,551,616 possible
values)
Floating Point Primitive Types
Type Float Length
float 32 bits
double 64 bits
(default type for floating
point literals)
Example:
public float pi = 3.141592F;
Textual Primitive Type
• The only primitive textual data type is char.
• It is used for a single character (16 bits).
• Example:
– public char colorCode = 'U';
Single quotes must be used with char literal values.
Java Language Trivia: Unicode
• Unicode is a standard character encoding system.
• It uses a 16-bit character set.
• It can store all the necessary characters from most languages.
• Programs can be written so they display the correct language for most countries.
Constants
• Variable (can change):
– double salesTax = 6.25;
• Constant (cannot change):
– final int NUMBER_OF_MONTHS = 12;
The final keyword
causes a variable to be
read only.
Variables
• A variable refers to something that can change.
• Variables can be initiated with a value.
• The value can be changed.
• A variable holds a specific type of data.
The
Variable value of
The type of name the
data variable
String firstName = "Mary";
firstName = "Gary";
Variables
• Variables are data placeholders.
• Java is a strongly typed language, therefore every variable must have a declared type.
• The variables can be of two types:
• reference types: A variable of reference type provides a reference to an object.
• primitive types: A variable of primitive type holds a primitive.
• In addition to the data type, a Java variable also has a name or an identifier.
Stack
Primitive Variable
value
Reference Variable Heap
reference
Reference Variable null Instance
Variable Types
• Some of the types of values a variable can hold:
• String (example: "Hello")
• int (examples: -10, 0, 2, 10000)
• double (examples: 2.00, 99.99, -2042.00009)
• boolean (true or false)
• If uninitialized, variables have a default value:
• String: null
• int: 0
• double: 0.0
• boolean: false
Naming a Variable
Guidelines:
• Begin each variable with a lowercase letter. Subsequent words should be
capitalized:
– myVariable
• Names are case-sensitive.
• Names cannot include white space.
• Choose names that are mnemonic and that indicate to the casual observer
the intent of the variable.
– outOfStock (a boolean)
– itemDescription (a String)
Java SE 9: The Underscore Character
Is Not a Legal Name
• If you use the underscore character ("_") as a one-character identifier
in source code, then your code won’t compile in Java SE 9.
• For example:
Uses of Variables
• Holding
String data= used
name within
"Sam" ; a method:
double price = 12.35;
boolean outOfStock = true;
• Assigning
String namethe
= value
name1;of one variable to another:
• Representing
total = quantityvalues within ;a mathematical expression:
* price
• Printing the values to the screen:
System.out.println(name);
Types of Variables
• Variable is basic storage in a Java program
• Three types of variables:
• Instance variables
• Instantiated for every object of the class
• Static variables
• Class Variables
• Not instantiated for every object of the class
• Local variables
• Declared in methods and blocks
Types of Variables
Instance Variable
public class Box {
private double dblWidth;
private double dblHeight; Static Variable
private double dblDepth;
private static int boxid;
public double calcVolume() {
double dblTemp;
Local
dblTemp = dblWidth * dblHeight * dblDepth; Variable
return dblTemp;
}
}
Operators in Java
• Operators can be divided into following groups:
• Arithmetic
• Bitwise
• Relational
• Logical
• instanceof Operator
Arithmetic Operators
Bitwise Operators
• Apply upon int, long, short, char and byte data types:
Relational Operators
• Determine the relationship that one operand has to another.
• Ordering and equality.
Logical Operators
Literals
• Literals represents value to be assigned for variable.
• Java has three types of literals:
• Primitive type literals
• String literals
• null literal
• Primitive literals are further divided into four subtypes:
• Integer
• Floating point
• Character
• Boolean
• For better readability of large sized values, Java 7 allows to include ‘_’ in integer literals.
Examples: Variable Declaration and
Initialization
• Basic Example :
String address = "123 Oak St"; //one variable declared
// and initialized
type identifi value
er
• Other Examples:
String customer; //One variable declared
String name, city //Two variables declared
String country ="USA", state="CO" //Two variables declared
//and
initialized
city=" USA"; //One variable initialized after
//being declared earlier
String Concatenation
• String variables can be combined using the '+' operator.
• stringVariable1 + stringVariable2
• stringVariable1 + "String literal"
• stringVariable1 + "String literal" + stringVariable2
• Example:
String greet1 = "Hello";
String greet2 = "World";
String message = greet1 + " " + greet2 + "!";
String message = greet1 + " " + greet2 + " " + 2014 +"!";
String Concatenation
• You can concatenate String variables outside or inside a method
call:
String greet1 = "Hello";
String greet2 = "World";
String message = greet1 + " " +greet2 + "!";
System.out.println(message);
System.out.println(greet1 + " " + greet2 + "!");
Output:
Hello World!
Hello World!
int and double Values
• int variables hold whole number values between:
– –2,147,483,648
– 2,147,483,647
– Examples: 2, 1343387, 1_343_387
• double variables hold larger values containing decimal portions.
– Use when greater accuracy is needed.
– Examples: 987640059602230.7645 , -1111, 2.1E12
Initializing and Assigning Numeric
Values
• int variables:
Compilation fails!
• int quantity = 10;
• int quantity = 5.5;
• double variables: Run time will
• double price = 25.99; interpret as 75.0.
• double price = 75;
Increment and Decrement Operators (+
+ and --)
The long way:
age = age + 1;
or
count = count – 1;
The short way:
age++;
or
count--;
Operator Precedence
•Here’s an example of the need for rules of precedence.
•Is the answer to the following problem 34 or 9?
int c = 25 - 5 * 4 / 2 - 10 + 4;
Operator Precedence
• Rules of precedence:
1. Operators within a pair of parentheses
2. Increment and decrement operators (++ or --)
3. Multiplication and division operators, evaluated from left to right
4. Addition and subtraction operators, evaluated from left to right
Using Parentheses
• Examples:
int c = (((25 - 5) * 4) / (2 - 10)) + 4;
int c = ((20 * 4) / (2 - 10)) + 4;
int c = (80 / (2 - 10)) + 4;
int c = (80 / -8) + 4;
int c = -10 + 4;
int c = -6;
Promotion
• Automatic promotions:
– If you assign a smaller type to a larger type
byte short int long
– If you assign an integral type to a floating point type
3 3.0
• Examples of automatic promotions:
• long intToLong = 6;
• double intToDouble = 3;
Caution with Promotion
• Equation:
55555 * 66666 = 3703629630
• Example of potential issue:
• 1 int num1 = 55555;
• 2 int num2 = 66666;
• 3 long num3;
• 4 num3 = num1 * num2; //num3 is -591337666
• Example of potential solution:
• 1 int num1 = 55555;
• 2 long num2 = 66666; Changed from int to long
• 3 long num3;
• 4 num3 = num1 * num2; //num3 is 3703629630
Caution with Promotion
• Equation:
7 / 2 = 3.5
• Example of potential issue:
• 1 int num1 = 7;
• 2 int num2 = 2;
• 3 double num3;
• 4 num3 = num1 / num2; //num3 is 3.0
• Example of potential solution:
• 1 int num1 = 7;
Changed from int to double
• 2 double num2 = 2;
• 3 double num3;
• 4 num3 = num1 / num2; //num3 is 3.5
Type Casting
• When to cast:
– If you assign a larger type to a smaller type
byte short int long
– If you assign a floating point type to an integral type
3 3.0
• Examples of casting:
• int longToInt = (int)20L;
• short doubleToShort = (short)3.0;
Caution with Type Casting
Example of potential issue:
1 int myInt;
2 long myLong = 123987654321L;
3 myInt = (int) (myLong); // Number is "chopped“
4 // myInt is -566397263
Safer example of casting:
1 int myInt;
2 long myLong = 99L;
3 myInt = (int) (myLong); // No data loss, only zeroes.
4 // myInt is 99
Caution with Type Casting
• Be aware of the possibility of lost precision.
Example of potential issue:
1 int myInt;
2 double myPercent = 51.9;
3 myInt = (int) (myPercent); // Number is "chopped“
4 // myInt is 51
Using Promotion and Casting
Example of potential issue:
1 int num1 = 53; // 32 bits of memory to hold the value
2 int num2 = 47; // 32 bits of memory to hold the value
3 byte num3; // 8 bits of memory reserved
4 num3 = (num1 + num2); // causes compiler error
Solution using a larger type for num3:
1 byte num1 = 53;
2 byte num2 = 47;
3 int num3;
4 num3 = (num1 + num2); Changed from byte to int
Solution using casting:
1 int num1 = 53; // 32 bits of memory to hold the value
2 int num2 = 47; // 32 bits of memory to hold the value
3 byte num3; // 8 bits of memory reserved
4 num3 = (byte)(num1 + num2); // no data loss
Compiler Assumptions for Integral
and Floating Point Data Types
• Most operations result in an int or long:
• byte, char, and short values are automatically promoted to int prior to an
operation.
• If an expression contains a long, the entire expression is promoted to long.
• If an expression contains a floating point, the entire expression is promoted to
a floating point.
• All literal floating point values are viewed as double.
Automatic Promotion
• Example of potential problem:
short a, b, c;
a = 1 ; a and b are automatically promoted to integers.
b = 2 ;
c = a + b ; //compiler error
• Example of potential solutions:
• Declare c as an int type in the original declaration:
int c;
• Type cast the (a+b) result in the assignment line:
c = (short)(a+b);
Using Floating Points
Example of potential problem: Expressions are automatically
promoted to floating points.
int num1 = 1 + 2 + 3 + 4.0; //compiler error
int num2 = (1 + 2 + 3 + 4) * 1.0; //compiler error
Example of potential solutions:
• Declare num1 and num2 as double types:
double num1 = 1 + 2 + 3 + 4.0; //10.0
double num2 = (1 + 2 + 3 + 4) * 1.0; //10.0
• Type cast num1 and num2 as int types in the assignment line:
int num1 = (int)(1 + 2 + 3 + 4.0); //10
int num2 = (int)((1 + 2 + 3 + 4) * 1.0); //10
Floating Point Data Types and
Assignment
• Example of potential problem:
float float1 = 27.9; //compiler error
• Example of potential solutions:
– The F notifies the compiler that 27.9 is a float value:
float float1 = 27.9F;
– 27.9 is cast to a float type:
float float1 = (float) 27.9;
Control Statements
• Use control flow statements to:
• Conditionally execute statements
• Repeatedly execute a block of statements
• Change the normal, sequential flow of control
• Categorized into two types:
• Selection Statements
• Iteration Statements
Selection Statements
• Allows programs to choose between alternate actions on execution.
• “if” used for conditional branch:
if (condition) statement1;
else statement2;
• “switch” used as an alternative to multiple “if’s”:
switch(expression){ Expression can be
case value1: //statement sequence of String type!
break;
case value2: //statement sequence
break; …
default: //default statement sequence
}
switch case : an example
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<=4; i++)
switch(i) {
case 0:
System.out.println("i is zero."); break;
case 1:
System.out.println("i is one."); break;
case 2:
System.out.println("i is two."); break;
case 3: Output:
System.out.println("i is three."); break; i is zero.
default: i is one.
System.out.println("i is greater than 3."); i is two.
} i is three.
}} i is greater than
3.
Iteration Statements
• Allow a block of statements to execute repeatedly
• While Loop: Enters the loop if the condition is true
while (condition)
{ //body of loop
}
• Do – While Loop: Loop executes at least once even if the condition is false
do
{ //body of the loop
} while (condition)
Iteration Statements
• For Loop:
for( initialization ; condition ; iteration)
{ //body of the loop }
// Demonstrate the for loop.
class SampleFor {
• Example public static void main(String args[]) {
int number;
for(number =5; number >0; n--)
System.out.print(number +”\t”);
}
} Output: 5 4 3 2 1
Summary
• In this lesson you have learnt:
• Keywords
• Primitive Data Types
• Operators and Assignments
• Variables and Literals
• Flow Control: Java’s Control Statements