Data Types, Variables and
Arrays
Dr. Anuja.R.Nair
Assistant Professor, CSE
1
Agenda
Data types
Primitive data types
Reference data types
Scope and lifetime of variables
Type conversion
Arrays
2
Data Types in Java
Java is a strongly typed language
Every variable, expression has a type and every
type is strictly defined.
Type compatibility is checked.
Impossible to typecast incompatible types.
Data types may be:
Primitive data types
Reference data types
3 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Primitive Data Types in Java
Integer Data Types
byte (1 byte)
All numeric data types are signed
short (2 bytes)
int (4 bytes)
The size of data types remain same
long (8 bytes)
on all platforms
Floating Data Types
float (4 bytes)
double (8 bytes)
Character Data Types
char (2 bytes)
Logical/Boolean Data Types
boolean (1 bit) (true/false)
4 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Integer
All of these are signed, positive and negative
values.
Java does not support unsigned, positive-only
integers.
Because of Java’s portability requirement, all
data types have a strictly defined range for
example: int is always 32 bits.
5
Floating-Point
Also known as real numbers.
Used for evaluating expressions that require
fractional precision.
There are two kinds of floating-point types
float and double
6
Characters
In C/C++, char is 8 bits wide.
Java uses Unicode to represent characters.
Unicode defines a fully international character
set that can represent all of the characters
found in all human languages.
Java char is a 16-bit type.
No negative char.
The range is 0 to
65536.
7
Characters and Integers
8
Booleans
Two possible values:
true or false
This is the type returned by all relational
operators.
Used by conditional expressions.
9
Variables
A named storage location in the computer’s memory that
stores a value of a particular type for use by program.
Declaration:
type identifier [=value] [, identifier=[value] … ];
Example of variable declaration:
10 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Variables (Contd…)
Using primitive data types is similar to other languages
int count;
int max=100;
Variables can be declared anywhere in the program
for (int count=0; count < max; count++) {
int z = count * 10;
}
BEST PRACTICE
Declare a variable in program only when required
Do not declare variables upfront like in C
In Java, if a local variable is used without initializing it, the
compiler will show an error
11 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Give this a Try…
What will be the output of the following code
snippet when you try to compile and run it?
class Sample
{
public static void main (String args[])
{
int count;
System.out.println(count);
}
}
12 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Reference Data Types
Hold the reference of dynamically created objects which are
in the heap
Can hold three kinds of values:
Class type: Points to an object / class instance
Interface type: Points to an object, which is implementing the
corresponding interface
Array type: Points to an array instance or “null”
Difference between Primitive & Reference data types:
Primitive data types hold values themselves
Reference data types hold reference to objects, i.e. they are not
objects, but reference to objects
Size of primitive data type is fixed, whereas for reference data
types, size depends on the number of member variables and their
types.
13 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Reference Data Types (Contd…)
Objects & Arrays are accessed using reference variables in Java
A reference variable is similar to a pointer (stores memory address
of an object)
Java does not support the explicit use of addresses like other
languages
int primitive = 5;
Java does not allow pointer manipulation or pointer arithmetic
String reference = “Hello” ;
Memory Representation:
A variable of reference type contains a reference to (an address
of) an object or 5
an array as shown
primitive in fig.
reference Hello
14 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Stack contains primitive values that are specific to a
method and references to objects that are in a heap
New objects are always created in heap space and the
references to this objects are stored in stack memory.
Garbage collector cannot access stack whereas can
access heap memory
15
Difference between pointers and
references
Printing a pointer will print the address
stored in it whereas Printing a reference
will NOT print the address of the object
referred by it.
A reference is automatically de-referenced
to give the data referred by it and no
special operator is required for this.
16
Reference Data Types (Contd…)
A reference type cannot be cast to primitive type
But Primitive to Reference type you can convert by using Wrapper
classes.
A reference type can be assigned ‘null’ to show that it is not referring
to any object
Arrays, classes, and interfaces are reference types. The value of a
reference type variable, in contrast to that of a primitive type, is a
reference to (an address of) the value or set of values represented by
the variable.
A reference is called a pointer, or a memory address in other
languages. The Java programming language does not support the
explicit use of addresses like other languages do; you need to use the
variable's name instead.
All user defined objects , built in objects like arrays are Reference
types.
Reference variables always take space on Heap while primitive
variables are stored in stack.
17 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Stack vs. Heap
Parameter Stack Memory Heap Space
Stack is used in parts, one at
The entire application uses
Application a time during execution of a
Heap space during runtime
thread
Stack has size limits
Size depending upon OS and is There is no size limit on Heap
usually smaller then Heap
Stores only primitive variables
All the newly created objects
Storage and references to objects that
are stored here
are created in Heap Space
It is accessed using Last-in This memory is accessed via
Order First-out (LIFO) memory complex memory
allocation system management techniques.
Stack memory only exists as
Heap space exists as long as
Life long as the current method is
the application runs
running
Comparatively much faster to
Slower to allocate when
Efficiency allocate when compared to
compared to stack
heap
Heap space is allocated when
This Memory is automatically
new objects are created and
Allocation/ allocated and deallocated
deallocated by Garbage
Deallocation
18 when a method is called and
Collector when they are no
returned respectively
Scope and Lifetime Variables
A block defines the scope of a variable
Java defines two types of scope; Class scope and
method scope
Class scope has unique properties and attributes that
do not apply to method scope
Variables declared inside a scope are not visible (that
is, accessible) to code that is defined outside that
scope
Variables are created when their scope is entered,
and destroyed when their scope is left
Scopes can be nested
Java does not permit using the same name
again if a variable is declared in outer scope
19
Scope of variables
20
Scope of variables
21
Scope of Variables
Instance Variables (also called Member Variables)
Declared inside a class
Outside any method or constructor
Belong to the object
Stored in heap area with the object to which they
belong to
Lifetime depends on the lifetime of object
Local Variables (also called Stack Variables)
Declared inside a method
Method parameters are also local variables
Stored in the program stack along with method calls
and live until the call ends
22 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Lifetime of variables
The lifetime of a variable refers to how long
the variable exists before it is destroyed.
Destroying variables refers to deallocating the
memory that was allotted to the variables
when declaring it.
23
Member & Automatic variables
Java supports variables of two different lifetimes:
• A member variable is the one which is created when an
instance or an object is created, and is accessible from any
method in the class.
• An automatic variable is similar to the local variable. It is alive
as long as the control is within the function. The programmer
must initialize a local variable before it is used.
Member Variables
• Defined in a class, outside methods or constructors.
• They are alive as long as the object exists.
Automatic Variables or Local Variables
• These are declared within methods or blocks
• They are alive as long as the control is within the function.
• Variables passed as parameters also fall in this category
24
Scope of Variables (Contd…)
If we don’t initialize instance variables explicitly, they are
awarded predictable default initial values, based only on the
type of the variable Type Default Value
boolean false
byte (byte) 0
short (short) 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
object reference null
Local variables are not initialized implicitly
25 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Scope of Variables (Contd…)
class Student{ rollNo and name are
instance variables to
int rollNo; be stored in the heap
String name;
public void display (int z){
int x=z+10;
}
}
z and x are local
variables to be
stored in the stack
26 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Scope of Variables (Contd…)
27 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Type Casting and Promotion
Automatic type conversion (widening conversion)
will take place if the following two conditions are
met:
The two types are compatible.
The destination type is larger than the source type.
No automatic conversions from the numeric types to
char or Boolean
Explicit type casting (narrowing conversion)
When a floating-point value is assigned to an integer
type, the fractional component is lost. (truncation)
If the size of the whole number component is too large to
fit into the target integer type, then that value will be
reduced modulo the target type’s range.
(target-type) value
28
Typecasting Primitive Data Types
Automatic type changing is known as Implicit Conversion
Widening conversion
A variable of smaller capacity can be assigned to another
variable of bigger capacity
int i = 10;
double d;
d = i;
Whenever a larger type is converted to a smaller type, we
have to explicitly specify the type cast operator
Type cast operator
double d = 10;
int i;
i = (int) d;
Narrowing conversion
This prevents accidental loss of data
29 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Type casting and conversion
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
float f = 128.78f;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b); // 257 1
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i); // 323.142 323
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b); // 323.142 67
System.out.println("\nConversion of float to byte.");
b = (byte) f;
System.out.println(“f and b " + f + " " + b); // 128.78 -128
}
}
30
Automatic type promotion
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
Java automatically promotes each byte,
short, or char operand to int when
evaluating an expression.
byte b = 50;
b = b * 2; // Error! Cannot assign
an int to a byte!
byte b = 50;
b = (byte)(b * 2);
31
Automatic type promotion
First, all byte, short, and char values are promoted
to int, as just described. Then, if one operand is a
long, the whole expression is promoted to long. If
one operand is a float, the entire expression is
promoted to float. If any of the operands is
class double,
Promote {the result is double.
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result); }
}
32
Type Conversion
byte short int long (implicitly)
byte short int long (explicitly)
float double (implicit)
float double (explicit)
int float, double (explicit)
long float, double (explicit)
char byte, short, int, long, float, double (explicit)
boolean (cannot be casted)
33
Arrays in Java
A data structure which defines an ordered collection of a fixed
number of homogeneous data elements
Size is fixed and cannot increase to accommodate more elements
Arrays in Java are objects and can be of primitive data types or
reference variable type
All elements in the array must be of the same data type
An array holding 5 int elements
22 33 66 100 72
An array holding 4 rabbit objects
Reference to Rabit Object
34 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Arrays in Java (Contd…)
Reference variables are used in Java to store the references
of objects created by the int
operator
x[]; new
int [] x;
Any one of the following syntax can be used to create a
reference to an int array
//Declare a reference to an int array
int [] x;
//Create a new int array and make x refer to it
x = new int[5];
The reference x can be used for referring to any int array
35 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Arrays in Java (Contd…)
The following statement also creates a new int
array and assigns its reference to x
int [] x = new int[5];
In simple terms, references can be seen as
names of an array.
An array can be initialized while it is created
as follows:
int [] x = {1, 2, 3, 4};
char [] c = {‘a’, ‘b’, ‘c’};
36 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Arrays
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
37
Arrays
// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
38
Length of an Array
Unlike C, Java checks the boundary of an array
while accessing an element in it
Programmer not allowed to exceed its boundary
And so, setting a for loop as follows is very
common:
for(int i = 0; i < x.length; ++i){
x[i] = 5;
}
This works for
any size array
use the .length attribute of an array to control the for loop
39 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Multidimensional Arrays
A Multi-dimensional array is an array of arrays
To declare a multidimensional array, specify
each additional index using another set of
square brackets
int [][] x;
//x is a reference to an array of int arrays
x = new int[3][4];
//Create 3 new int arrays, each having 4 elements
//x[0] refers to the first int array, x[1] to the
second and so on
//x[0][0] is the first element of the first array
//x.length will be 3
//x[0].length, x[1].length and x[2].length will be 4
40 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Multidimensional Arrays
To allocate memory for a multidimensional
array, need to only specify the memory for the
first (leftmost) dimension.
Allocate the remaining dimensions separately.
int twoD[ ][ ] = new int[4][ ];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
41 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Alternative Array Definition Syntax
type[ ] var-name;
int al[ ] = new int[3];
int[ ] a2 = new int[3];
char twod1[ ][ ] = new char[3][4];
char[ ][ ] twod2 = new char[3][4];
int[ ] nums, nums2, nums3; // create three arrays
int nums[ ], nums2[ ], nums3[ ]; // create three
arrays
42 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
Command Line Arguments
Information that follows program’s name on the command
line when it is executed
This data is passed to the application in the form of String
arguments
class Echo {
public static void main (String args[]) {
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
Try this: Invoke the Echo application as follows
C:\> java Echo Drink Hot Java
Drink
Hot
Java
43 CONFIDENTIAL© Copyright 2008 Tech Mahindra Limited
THANK YOU!!
ANY QUESTIONS??
44