3 Data Types and Variables
3 Data Types and Variables
Java
Primitive Types
• Form the basis of all other types of data that you can create
– Integer types
• For whole-valued signed numbers
• byte, short, int and long
– Floating-point types
• Numbers with fractional precision
• float and double
– Characters
• Represents symbols in a character set
• char
– Boolean
• A special type representing true / false
• boolean
Integers
• Does not support unsigned, positive-only
integers
– long – 64 bit
– int – 32 bit (most commonly used)
– short – 16 bit (rarely used)
– byte – 8 bit (smallest, -128 to 127)
Java
Variables
• Basic unit of storage in Java program
– type identifier [= value][, identifier [= value] …] ;
• type: built-in type, class or interface
• identifier: name of variable
• value: to initialize the variable; must be of same or compatible
type
– Examples
• int a, b, c;
• int d=3, e, f=5;
• byte z=22;
• double pi = 3.14159
• char x = ‘X’;
Dynamic Initialization
• Variables can be initialized dynamically, using any valid
expression
Class DynInt {
public static void main (String [] args) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt (a*a + b*b);
System.out.println(“Hypotenuse is” + c);
}
}
Scope and Lifetime of Variables
• Variable can be declared inside any block
{ }
– A block defines a scope : New block New scope
• Scopes can be nested
– Variables of outer scope are visible to inner scope but not vice
versa !
• If a variable is visible in a scope, we can not declare
another variable with same identifier in that scope
• Examples
byte b;
int i = 257;
double d = 323.142;
• Example
byte a=40, b = 50;
int c = a * b;
• a and b promoted to int
• However, following code causes problems
byte b = 50;
b = b * 2; // Error! Cannot assign int to byte!
• since b was promoted to int, b*2 is an ‘int’ now and needs
explicit casting to smaller type ‘byte’
b = (byte) b * 2; // Correct
Rules: Automatic Type Promotion
• Following promotions take place in
expressions