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

2_Data Types, Variables and Arrays

The document provides an overview of data types, variables, and arrays in Java, detailing the eight simple data types including integers, floating-point numbers, characters, and boolean types. It explains the usage and characteristics of each type, variable declaration, initialization, scope, lifetime, and type conversion. Additionally, it covers arrays, including their declaration and examples of one-dimensional arrays.

Uploaded by

sindhus121985
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

2_Data Types, Variables and Arrays

The document provides an overview of data types, variables, and arrays in Java, detailing the eight simple data types including integers, floating-point numbers, characters, and boolean types. It explains the usage and characteristics of each type, variable declaration, initialization, scope, lifetime, and type conversion. Additionally, it covers arrays, including their declaration and examples of one-dimensional arrays.

Uploaded by

sindhus121985
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 56

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.
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.

3
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;

4
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;

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.

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;

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.");
}
}

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);
}
}

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.

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;

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;

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.");
}
}

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;
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);
}
}

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;
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.

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.

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.

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.

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

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”);

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.

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.
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);
}
}

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);
}
}

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. 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.

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);
}
}
}

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.

32
Java’s Automatic conversion…..
• Automatic casting will occur if 2 conditions are met.
• The two types are compatible
• 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.

33
3
4
Casting Incompatible Types…
• Although the automatic type conversions are helpful, they
will not fulfill all needs.
• It cannot assign an 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.
35
3
6
…..
Syntax:
(target-type) value;

int a;
byte b;
b = (byte) a;

37
// Demonstrate casts.
class Conversion {
public static void main(String[] args) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i); Conversion of int to byte.
i and b 257 1
System.out.println("\nConversion of double to byte.");
Conversion of double to int.
b = (byte) d; d and i 323.142 323
Conversion of double to byte.
System.out.println("d and b " + d + " " + b); d and b 323.142 67
38
}
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 ;

39
The Type Promotion Rules
• 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.

40
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.

41
One-Dimensional Arrays….
• A one-dimensional array is a list of related variables.
• Syntax to declare a one-dimensional array:
type array-var[];
array-var = new type[size];
new is a special
Ex : int a[]; operator that
a = new int[10]; allocates memory.

type array-name[ ] = new type[size];


Ex: int a[] = new int[10];
42
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");
}
}
43
Example program2…..
class Arraytrials
{
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]);
}
}

44
…..
• 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.

45
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.”);
}
}

46
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 );
}
}

47
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];

48
….
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]

49
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++) 01234
56789
System.out.print(twoD[i][j] + " ") ;
10 11 12 13 14
System.out.println( ); 15 16 17 18 19
}
}
} GRNICA 50
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];

51
Introducing Type Inference with Local Variables
• two important aspects of variables.
• First, all variables in Java must be declared prior to their use
• Second, a variable can be initialized with a value when it is
declared.
• when a variable is initialized, Initialization type same as declared type
• In older JDK, such inference was not supported, and all variables
required an explicitly declared type, whether they were initialized or
not.
• Beginning with JDK 10, it is now possible to let the compiler infer the
type of a local variable based on the type of its initializer, thus avoiding
the need to explicitly specify the type 52
• Thus, in principle, it would not be necessary to specify an explicit type
for an initialized variable because it could be inferred by the type of its
initializer.
• Local variable type inference offer a number of advantages.
• it can streamline code by eliminating the need to redundantly
specify a variable’s type when it can be inferred from its initializer.
• It can simplify declarations in cases in which the type name is quite
lengthy, such as can be the case with some class names.
• It can also be helpful when a type is difficult to discern or cannot be
denoted.
• Local variable type inference has become a common part of
contemporary programming environment 53
• To support local variable type inference, the context-sensitive
keyword var was added.
• To use local variable type inference, the variable must be declared
with var as the type name and it must include an initializer

double avg = 10.0; type inference var avg = 10.0;

54
class VarDemo {
public static void main(String[] args) {
var avg = 10.0;
System.out.println("Value of avg: " + avg);
int var = 1;
System.out.println("Value of var: " + var);
var k = -var;
System.out.println("Value of k: " + k);
}
}

var myArray = new int[10]; // This is valid.

var[] myArray = new int[10]; // Wrong


var myArray[] = new int[10]; // Wrong

In both cases, the use of the brackets is wrong because the type is
55
inferred from the type of the initializer.
Some var Restrictions:
•Only one variable can be declared at a time;
• a variable cannot use null as an initializer;
•the variable being declared cannot be used by the initializer
expression.
• var myArray = new int[10]; // This is valid.
• var myArray = { 1, 2, 3 }; // Wrong
•var cannot be used as the name of a class.
• It also cannot be used as the name of other reference types,
including an interface, enumeration, or annotation, or as the name of a
generic type parameter

You might also like