You are on page 1of 28

Java: Data Types, Variables, Arrays

CS F213: Object Oriented Programming

Dipanjan Chakraborty
Department of CS&IS

1
Strongly Typed Language

Every variable and expression has a type

Every type is strictly defined

All assignments are checked for type-
compatibility

No automatic coercing/conversion of conflicting
types

2
Primitive Data Types

Integers: byte, short, int, long

Floating-poing numbers: float, double

Characters: char

Boolean: boolean

3
Primitive Data Types

Represent single values

Not implemented as objects for efficiency reasons

These form the basis of all complex data that you would
create

Have strictly defined range and mathematical behaviour to
enable portability, unlike C/C++
– e.g. int is always 32 bits

4
Integers

byte: 8 bits

short: 16 bits

int:32 bits

long: 64 bits

5
Floating-Point

double: 64 bits

float: 32 bits

6
Character

char: 16 bits, compatible with 16 bit UNICODE

“old tricks” with int and char in other
languages still valid
char ch1 = 88, ch2 = ‘Y’;
System.out.println(ch1 + " " + ch2); // X Y
ch++;
System.out.println(ch1 + " " + ch2); // Y Y

7
Boolean

Data type that holds either of two values: true
or false

Result of all relational operators like >, <, ==,
etc.
boolean b = (10 > 9);
System.out.println(“b is: “ + b); // b is: true

8
Literals

Literals are constants which can be assigned to variables

Integer literals:
– 42: int
– 0xA798: hexadecimal integer
– 0732: octal integer
– 09: invalid since 9 is not a valid octal digit
– 0b1010: binary number
– 9223372036854775807L: largest allowed long integer

9
Literals

Floating-point literals:
– 3.14159: floating-point
– 6.022E23: 6.022*(10^23)
– By default uses double precision (64 bits).
Append with ‘f’ for 32 bit precision

10
Literals

Character Literals
– ‘a’
– ‘\n’
– ‘\141’ : octal representation for ‘a’
– ‘\u0061’ : hexadecimal representation for ‘a’
– ‘\u092c’: hexadecimal representation for ‘ब’

11
Literals

String Literals
– “Hello”
– “Hello\nWorld”

Strings are not arrays of characters in Java.
Rather, they are implemented as objects.

12
Initialising a Variable
int a = 3, b = 5; // declaration and initialisation

double a = 3.0, b = 5.0;


double hypotenuse = Math.sqrt(a * a + b* b); // dynamic initialisation

13
Scope of Variables

C-like languages: global scope and local scope

Java does not have a global scope since it is strictly Object Oriented and no
code can exist outside a class

Java scopes are defined by block boundaries using curly braces {}
– These might define class boundaries, method boundaries or block
boundaries

Variables must be declared before they can be used

Variables will be reinitialised everytime a block is reentered

Can’t declare a variable to have the same names as one in an outer scope

14
Scope of Variables
class Scope {
public static void main(String[] args) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// int x; // invalid since x is valid in this scope
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
//x is still known here
System.out.println(“x is “ + x);
}
} 15
Type Conversions and Casting

Automatic conversions:
– The two types are compatible.
– The destination type is larger than the source type.
– e.g. int can hold a byte, no explicit cast is required
– Integer and floating-point types are compatible with each other

But no automatic conversion can happen between char or boolean
and numeric types: must use a cast

16
Type Conversions and Casting
int a; byte b;
b = (byte) a;

If the integer’s value is larger than the range of a byte,
it will be reduced modulo (the remainder of an
integer division by the) byte’s range
– e.g. 257 will convert to 1

If floating point is cast to an integer, truncation will
occur float b=2.3f;
int a = b;
– e.g. 1.23 will be truncated to 1
17
Automatic Type Promotions
byte a = 40, b = 50, c = 100;
int d = a * b / c;

For expressions: bytes, shorts and chars are
converted to int automatically

Can cause confusing errors:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
b = (byte)(b * 2);
18
Automatic Type Promotions

Rules:
– All byte, short, char are promoted to int
– If one operand is a long, the expression is
promoted to long
– If one operand is a float, then promoted to float
– If an operand is double, the result is a double

19
Arrays

Group of like-typed variables (or objects)
referred by a common name

Specific element accessed by an index (starting
at 0)

Can be of one or more dimensions

20
1D Arrays

Type[] var_name;
– e.g. int[] month_days;

To allocate memory, the new keyword is used
– month_days = new int[12];

Initialized to 0 for numeric types, false for boolean type,
null for reference types (array of objects, will be
discussed later)

21
1D Arrays

If an array is initialised when declared, then th
new keyword is not required
– int[] month_days = { 31, 28, 31, 30, 31,
30, 31, 31, 30, 31, 30, 31 };

Array index references are strictly checked.
Out of bound references cause Exceptions

22
2D Arrays

2D and multi-dimensional arrays are
implemented as an array of arrays
– e.g. int[][] twoD= new int[4][5];

These are valid:
int[ ][ ] twoD = new int[4][ ]; Int[ ][ ] twoD = new int[4][];
twoD[0] = new int[5]; twoD[0] = new int[1];
twoD[1] = new int[5]; twoD[1] = new int[2];
twoD[2] = new int[5]; twoD[2] = new int[3];
twoD[3] = new int[5]; twoD[3] = new int[4];
23
2D Arrays

Initialising 2D array (may use expressions in
the initialisation

double[ ][ ] m = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};

24
Alternate ways

These are equivalent:
– int al[] = new int[3];
int[] a2 = new int[3];
– char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];

25
Type Inference with Local Variables

Starting with JDK 10, the type of a variable can be
inferred by the compiler:
– double avg = 10.0;
– var avg = 10.0; // avg is of type double

The usage is context sensitive:
– int var = 1; // var is the identifier for a variable
var k = -var; // k is -1

26
Type Inference with Local Variables

There needs to be an initialisation for the inference
– var avg; // incorrect

Can be used for arrays:
– var myArray = new int[10]; // valid
– var[] myArray = new int[10]; // invalid
– var myArray[] = new int[10]; // invalid
– var myArray = { 1, 2, 3 }; // invalid

27
Type Inference with Local Variables

Restrictions:
– Can’t be used in instance variables, parameters or return types
– Only one variable declaration at a time
– Can’t be insitialised to null

The keyword var can’t be the name of a class, interface,
enumeration, annotation

Can’t be used in an Exception type in the catch statement, in lambda
expressions or method references

28

You might also like