0% found this document useful (0 votes)
33 views

2 - Data Types, Variables and Arrays

The document discusses Java data types including integers, floating point numbers, characters, Booleans, and literals. It describes the byte, short, int, long, float, double, char, and boolean primitive data types. It explains integer, floating point, Boolean, character, and string literals. The document also covers variables, variable declarations, and dynamic initialization of variables.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

2 - Data Types, Variables and Arrays

The document discusses Java data types including integers, floating point numbers, characters, Booleans, and literals. It describes the byte, short, int, long, float, double, char, and boolean primitive data types. It explains integer, floating point, Boolean, character, and string literals. The document also covers variables, variable declarations, and dynamic initialization of variables.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 48

Data Types, Variables and

Arrays
The simple Types…..
• Java defines eight simple types of data: byte, short, int,
long, char, float, double & boolean. These can be put in
four groups……..
• Integers : This group includes byte, short, int & long,
which are for whole valued signed numbers.
• Floating-point numbers : Includes float & double, which
represents numbers with fractional precision.
• Characters : Includes char, which represents symbols in a
character set, like letters and numbers.
• Boolean : Includes boolean, which represents true/false.
GRNICA 2
Integer…..
• Java defines four integer types : byte, short, int & long.
• All of these are signed, positive & negative values.
• Java does not support unsigned, positive-only integers.

GRNICA 3
byte….
• The smallest integer type.
• Signed 8–bit type, ranging from -128 to 127.
• Variable of type byte are used when working with a
stream of data from a network or file.

Usage:
byte b, c;

GRNICA 4
short…..
• It is signed 16-bit type & probably the least-used java
type.
• Most applicable to 16-bit computer, ranging from -32,768
to 32,767.

Usage :
short s;
short t;

GRNICA 5
int…
• Most used type ranging from -2,147,483,648 to
2,147,483,647.
• It is the most versatile and efficient type.

• Usage of short or byte instead of int will never guarantee


that memory is saved. Coz type determines the behavior
and not size.

• But memory will be saved in array if byte or short is


used instead of int.

GRNICA 6
long….
• It is a signed 64-bit type and used where int type is not
large enough.
• It ranges from –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.

Usage :
long seconds;
long mm;

GRNICA 7
long type usage….
/* Compute the number of cubic inches in 1 cubic mile.*/
class Inches
{
public static void main(String args[])
{
long ci, im;
im = 5280 * 12;
ci = im * im * im;
System.out.println("There are " + ci +
" cubic inches in cubic mile.");
}
}

GRNICA 8
/*Use the Pythagorean theorem to find the length of the
hypotenuse given the lengths of the two opposing sides.*/

class Hypot
{
public static void main(String args[])
{
double x, y, z;
x = 3;
y = 4;
z = Math.sqrt(x*x + y*y);
System.out.println("Hypotenuse is " +z);
}
}

GRNICA 9
Floating-Point Types….
• Floating-point numbers (real numbers), used for
evaluating expressions that require fractional precision.
• There are two kinds of floating-point types, float and
double, which represent single- and double-precision
numbers, respectively.
• Type float is 32 bits wide and type double is 64 bits
wide.

GRNICA 10
float….
• The type float specifies a single-precision value that uses
32 bits of storage.
• Single precision is faster on some processors and takes
half as much space as double precision.
• Variables of float type are useful when we need a
fractional component, but don’t require a large degree of
precision.
Usage :
float hightemp, dollar;

GRNICA 11
double….
• double having 64-bit width is actually faster than single
precision on some modern processors that have been
optimized for high-speed mathematical calculations.
• Transcendental math functions like sin(), cos(), and sqrt()
return double values.
Usage :
double gallons, liters;

GRNICA 12
/* This program converts gallons to liters. */

class GalToLit
{
public static void main(String args[])
{
double gallons; // holds the number of gallons
double liters; // holds conversion to liters
gallons = 10; // start with 10 gallons
liters = gallons * 3.7854; // convert to liters
System.out.println(gallons + " gallons is " +
liters + " liters.");
}
}

GRNICA 13
Characters…..
• The data type used to store characters.
• In Java, characters are not 8-bit quantities like they are
in most other computer languages. Instead, Java uses
Unicode.
• Unicode defines a character set that can represent all of
the characters found in all human languages.
• Thus, in Java, char is an unsigned 16-bit type having a
range of 0 to 65,536.
Usage :
char ch; GRNICA 14
class CharArithDemo
{
public static void main(String args[])
{
char ch;
ch = 'X';
System.out.println("ch contains " + ch);

ch++;
System.out.println("ch is now " + ch);

ch = 90;
System.out.println("ch is now " + ch);
}
}

GRNICA 15
The Boolean Type…..
• The boolean type represents true/false values.
• Java defines the values true and false using the reserved
words true and false.
• boolean is also the type required by the conditional
expressions that govern the control statements such as if
and for.
Usage :
boolean b;
b = true;
GRNICA 16
class BoolDemo
{
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
if(b)
System.out.println("This is executed.");
b = false;
if(b)
System.out.println(“Will not execute.");
System.out.println("10 > 9 is " + (10 > 9));
}
} GRNICA 17
Literals….
• In Java, literals refer to fixed values that are represented
in their human-readable form.

• For example, the number 100 is a literal. Literals are also


commonly called constants.

• Java literals can be of any of the primitive data types.

• For example, 'a' and ' %' are both character constants.

GRNICA 18
Integer Literals….
• Integer constants are specified as numbers without
fractional components.
• For example, 1, 2, 42…are integer constants. These are
all decimal values, meaning they are describing a base 10
number.
• Octal - use a leading 0, for example: 0127.
• Hex - use a leading 0x, for example: 0xffff.
• Long – to specify a long literal append an l or L to the
literal, for example: 0xffffffffffL.
GRNICA 19
Floating Point Literals…
• Floating Point Literals represent decimal values with a
fractional component.
• Standard notation, for example: 123.456
• Scientific notation, for example: 6.022E23, 314159E-05
and 2e+100.

GRNICA 20
Boolean Literals…
• Boolean Literals can only be true or false.
• The values of true and false do not convert into any
numerical representation.
• Boolean true does not equal 1.
• Boolean false does not equal 0.

GRNICA 21
Character Literals – Escape Sequences….
•Octal character - \ooo
•Unicode character - \uxxxx
•Single quote - \’
•Double quote - \”
•Backslash - \\
•Carriage return - \r
•New Line or Line Feed - \n
•Form feed - \f
•Tab - \t
•Backspace - \b

GRNICA 22
String Literals…..
• Enclose string literals in double quotes–“Hello World!\n”
• Embedded escape sequences are allowed –
“this string will take up\ntwo lines\n”
• Embedded quotes for printing names –
System.out.println(“Error: \”” + filename + “\” is missing”);

GRNICA 23
Variables…..
• The variable is the basic unit of storage in a java
program.
• A variable is defined by the combination of an identifier,
a type, and an optional initializer.
• All variables have a scope, which defines their visibility
and lifetime.

GRNICA 24
Variable declarations….
• int intvar; // simple variable declaration
• int i = 0; // declaration with initialization
• int i = 0, j = 0, k = 23; // multiple declarations and
initializations on one line
• double PI = 3.14159; // double precision floating point
variable declaration with initialization.
• double sqrtOfTwo = Math.sqrt(2); // dynamic
initialization, initialization will be performed when the
program runs.
• char x = ‘x’; // declare and init a character variable.
GRNICA 25
Dynamic Initialization…
• Java allows variables to be initialized dynamically.

class DynInit
{
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);
}
}

GRNICA 26
/* here is a short program that computes the volume of a
cylinder given the radius of its base and its height*/

class DynInit2
{
public static void main(String args[])
{
double radius = 4, height = 5;
// dynamically initialize volume
double volume = 3.1416 * radius * radius * height;
System.out.println("Volume is " + volume);
}
}

GRNICA 27
Scope of variables…..
• Java allows variables to be declared within any block.
• A code block within { } braces defines a scope. The
scope determines what parts of your program can see
variables declared in a scope.
• The scope of a variable also defines its lifetime.
• Variables declared inside a scope are not accessible by
code declared outside that scope.
• Objects and variables declared in a nested scope are not
accessible outside the scope, however objects and
variables declared in an outside scope are accessible in the
inner scope. GRNICA 28
Scope Example……
class Scope
{
public static void main(String args[])
{
int x = 10; // known to all code within main
if(x == 10)
{ // start new scope
int y = 20; // y known only in this block
System.out.println("x=“ + x + “y=“ + y); // x, y known
x = y * 2;
}
// y = 100; // Error! y not known here
System.out.println(“x=" + x); // x is still known here
}
} GRNICA 29
Variable Lifetime……
• Variables are created when their scope is entered and
destroyed when their scope is exited.
• Variables declared in a method will not maintain their
value from one method call to the next.
• If a variable declaration includes an initializer, then that
variable will be reinitialized each time the block in
which
it is declared is entered.

GRNICA 30
// Demonstrate lifetime of a variable.
class VarInitDemo
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}

GRNICA 31
Type Conversion and Casting….
• Type casting allows you to assign variable of one type to
variable of another type.
• Automatic conversion is performed by java when the
types are compatible.
• Not all types are compatible, and thus, not all type
conversions are implicitly allowed.

GRNICA 32
Java’s Automatic conversion…..
• Automatic casting will occur when the two types are
compatible AND the destination type is larger than the
source type.
• This is called a widening conversion.
• Automatic conversions occur when storing a literals
integer constants into a byte, short or long.

GRNICA 33
Casting Incompatible Types…
• Although the automatic type conversions are helpful, they
will not fulfill all needs.
• It cannot assign and int value to a byte automatically
because a byte is smaller than an int.
• This kind of conversion is sometimes called a narrowing
conversion, since you are explicitly making the value
narrower so that it will fit into the target type.
• To create a conversion between two incompatible types,
we must use a cast, which is simply an explicit type
conversion.
GRNICA 34
…..
int a;
byte b;
b = (byte) a;

GRNICA 35
Automatic type promotion in expressions…
• Type promotion will occur when mixing variables of
different types in expressions.
• Java promotes each byte or short operand to int when
evaluating expressions.
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c ;

GRNICA 36
…..
• If any operand is a long all operands are promoted to
long.
• If one operand is a float the entire expression is
promoted to a float.
• If one operand is a double the entire expression is
promoted to a double.

GRNICA 37
Arrays…..
• An array is a group of like - typed variable that are
referred to by a common name.
• Arrays of any type can be created and may have one or
more dimensions.
• A specific element in an array is accessed by its index.
• The principal advantage of an array is that it organizes
data in such a way that it can be easily manipulated.

GRNICA 38
One-Dimensional Arrays….
• A one-dimensional array is a list of related variables.
• Syntax to declare a one-dimensional array:
type var-name[]; / type[] var-name;
array-var[] = new type[size]; new is a special
operator that
Ex : int a[];
allocates memory.
a = new int[10];
type array-name[ ] = new type[size];
Ex: int a[] = new int[10];
GRNICA 39
Example program1…
class Array{
public static void main(String args[]) {
int 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");
}
}
GRNICA 40
Example program2…..
class trials
{
public static void main(String args[])
{
int sample[] = new int[10];
int i;
for(i = 0; i < 10; i = i+1)
sample[i] = i;
for(i = 0; i < 10; i = i+1)
System.out.println(“This is sample[" + i + "]:” +sample[i]);
}
}

GRNICA 41
…..
• Arrays can be initialized when they are declared.
• The process is much the same as that used to initialize the
simple types.
• An array initializer is a list of comma – separated
expressions surrounded by curly braces.
• The commas separate the values of the array elements.
• The array will automatically be created large enough to
hold the number of elements you specify in the array
initializer.
GRNICA 42
Example program1…..
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.”);
}
}
GRNICA 43
Example program2……

class Average
{
public static void main(String args[])
{
double nums[ ] = { 10.1, 11.2, 12.3, 23.4, 22.4};
double result = 0;
int i;
for(i = 0; i < 5; i++)
result = result +nums[i];
System.out.println(" Average is “ + result/5 );
}
}
GRNICA 44
Multi-dimensional Arrays….
• In Java multidimensional arrays are actually arrays of
array.
• These look and act like regular multidimensional arrays,
but there are a couple of subtle differences.
• To declare a multidimensional array variable, specify
each additional index using another set of square
brackets.
int twoD[][];
twoD = new int[4][5];

GRNICA 45
….
int twoD[][] = new int[4][5];
• This allocates an array with 4 rows and 5 columns.
• Internally this matrix is implemented as an array of
arrays of int.

[0][0] [0][1] [0][2] [0][3] [0][4]

int twoD[][] = new int[4][5]; [1][0] [1][1] [1][2] [1][3] [1][4]


[2][0] [2][1] [2][2] [2][3] [2][4]
[3][0] [3][1] [3][2] [3][2] [3][3]
GRNICA 46
Example program…
class TwoDArray
{
public static void main(String args[])
{
int twoD [ ] [ ] = new int [ 4] [ 5] ;
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i] [j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ") ;
System.out.println( );
}
}
} GRNICA 47
Arrays of Three or More Dimensions…
• Java allows arrays with more than two dimensions.
• Here is the general form of a multidimensional array
declaration:

type name[ ][ ]...[ ] = new type[size1][size2]...[sizeN];

int multidim[][][] = new int[4][10][3];

GRNICA 48

You might also like