2 Data Types in Java

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 51

Paper name : Java Programming

Paper code : BCA 206

Lecture 2 : Data types in Java


Java Is a Strongly Typed Language
• In C/C++ you can assign a floating-point value
to an integer. In Java, you cannot.
• In C there is not necessarily strong type-
checking between a parameter and an
argument. In Java, there is.
The Simple Data Types in Java
• Integers - This group includes byte, short, int, and long,
which are for whole valued signed numbers.
• Floating-point numbers- This group includes float and
double, which represent numbers with fractional precision.
• Characters- This group includes char, which represents
symbols in a character set, like letters and numbers.
• Boolean- This group includes boolean, which is a special
type for representing true/false values.
Imp. --all data types have a strictly defined range. For
example, an int is always 32 bits, regardless of the
particular platform.
Data Types - Integers
No concept of unsigned data type

• long 64 : -263 to 263 – 1.


useful when big, whole numbers are needed.

• int 32 : -2,147,483,648 to 2,147,483,647


most versatile and efficient type

• short 16 : -32,768 to 32,767


it is defined as having its high byte first (called big-endian format). This type is
mostly applicable to 16-bit computers, which are becoming increasingly scarce.

• byte 8 : -128 to 127


byte are especially useful when you’re working with a stream
of data from a network or file. They are also useful when you’re working with
raw binary data
Floating-Point , Character Types
Name Width Approximate Range
double 64 approximately 1.7976931348623157 x 10308,
4.9406564584124654 x 10-324
(15 significant decimal digits)
float 32 approximately 3.40282347 x 1038, 1.40239846 x 10-45
(6-7 significant decimal digits)

Character type
• 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. It is a unification of dozens of character
sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more.
• In Java char is a 16-bit type.
• The range of a char is 0 to 65,536.
• There are no negative chars.
Sample programs
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
// Compute distance light travels in 1000 days, using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
int days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 300000000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " meters.");
}
}
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Booleans
Two possible values, true or false
// Demonstrate boolean values.
class BoolTest {
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("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
Literals
Integer Literals
• Decimal (base ten),octal (base eight) and hexadecimal (base 16).
• Octal values are denoted in Java by a leading zero.
• Normal decimal numbers cannot have a leading zero. Thus, the
seemingly valid value 09 will produce an error from the
compiler.
• A hexadecimal constant is denoted with a leading zero-x, (0xor
0X).
• to specify a long literal, append an upper- or lowercase L to
the literal.e.g. 0x7ffffffffffffffL or 9223372036854775807L
Literals
Floating-Point Literals
• Standard notation : 2.0, 3.14159, and 0.6667
• Scientific notation : 6.022E23, 314159E–05,
and 2e+100.
• Floating-point literals in Java default to double
precision. To specify a float literal, you must
append an F or f to the constant.
Literals
Boolean Literals
• true and false.
• The values of true and false do not convert
into any numerical representation.
• The true literal in Java does not equal 1, nor
does the false literal equal 0.
Literals
Character Literals
A literal character is represented inside a pair of single quotes.
Escape Sequence Description
\ddd Octal character (ddd)
(‘\141’ is letter ‘a’)
\uxxxx Hexadecimal UNICODE character (xxxx)
(‘\u0061’ is the ISO-Latin-1 ‘a’)
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New line (also known as line feed)
\f Form feed
\t Tab
\b Backspace
Literals
String Literals
• by enclosing a sequence of characters
between a pair of double quotes.
• “Hello World”
• “two\nlines”
Variables
• initialize using constants
• Initialize 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);
}
}
Variables
class LifeTime {
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);
}
}
}
Variables
Although blocks can be nested, you cannot declare a variable to
have the same name as one in an outer scope. In this regard,
Java differs from C and C++.
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}
Type Conversion and Casting
Java’s Automatic Conversions
• When one type of data is assigned to another type
of variable, an automatic type 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.
• When these two conditions are met, a widening
conversion takes place. For example, the int type is
always large enough to hold all valid byte values.
Casting Incompatible Types
• Larger data type to smaller : narrowing conversion
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
Type Conversion
• Size Direction of Data Type
– Widening Type Conversion (Casting down)
• Smaller Data Type  Larger Data Type
– Narrowing Type Conversion (Casting up)
• Larger Data Type  Smaller Data Type
• Conversion done in two ways
– Implicit type conversion
• Carried out by compiler automatically
– Explicit type conversion
• Carried out by programmer using casting
Type Conversion

• Widening Type Converstion


– Implicit conversion by compiler automatically

byte
byte ->
-> short,
short, int,
int, long,
long, float,
float, double
double
short
short -> -> int,
int, long,
long, float,
float, double
double
char
char -> -> int,
int, long,
long, float,
float, double
double
int
int ->
-> long,
long, float,
float, double
double
long
long ->-> float,
float, double
double
float
float ->-> double
double
Type Conversion
• Narrowing Type Conversion
– Programmer should describe the conversion
explicitly
byte
byte ->
-> char
char
short
short ->
-> byte,
byte, char
char
char
char ->
-> byte,
byte, short
short
int
int ->
-> byte,
byte, short,
short, char
char
long
long ->-> byte,
byte, short,
short, char,
char, intint
float
float ->
-> byte,
byte, short,
short, char,
char, int,
int, long
long
double
double -> -> byte,
byte, short,
short, char,
char, int,
int, long,
long, float
float
L 3.7
Type Conversion

• byte and short are always promoted to int


• if one operand is long, the whole expression is
promoted to long
• if one operand is float, the entire expression is
promoted to float
• if any operand is double, the result is double
Type Casting

• General form: (targetType) value


• Examples:
• 1) integer value will be reduced module bytes
range:
int i;
byte b = (byte) i;
• 2) floating-point value will be truncated to integer
value:
float f;
int i = (int) f;
Automatic Type Promotion in Expressions
Java automatically promotes each byte or short operand to int
when evaluating an expression.
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
subexpression a * b is performed using integers—not bytes. Thus,
2,000, the result of the intermediate expression, 50 * 40, is legal
even though a and b are both specified as type byte.
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
• Solution:- use an explicit cast, such as b = (byte)(b * 2);
Type Promotion Rules
First, all byte and short values are promoted to
int.
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 double, the result is
double.
Type Promotion Rules
class Promote {
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);
}
}
Primitive Casting Outer ring is most
inclusive data type.
Double Inner ring is least
inclusive.
float
In expressions
long
variables and
int sub expressions
of less inclusive
short, data types are
char automatically cast
From MORE to LESS to more inclusive.
byte
If trying to place
expression that is
more inclusive into
variable that is less
inclusive, explicit cast
must be performed.
29
Casting Incompatible Types
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);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Casting Incompatible Types
• Conversion of int to byte.
• i and b 257 1

• Conversion of double to int.


• d and i 323.142 323

• Conversion of double to byte.


• d and b 323.142 67
Arrays in Java
• type var-name[ ];
• int month_days[];
• no array actually exists. the value of month_days is
set to null, which represents an array with no value
• array-var = new type[size]; // for memory allocation
• month_days = new int[12];
• elements in the array allocated by new will
automatically be initialized to zero
Arrays in Java
• arrays hold elements of the same type
– primitive data types or classes
– space for array must be dynamically allocated with
new operator. (Size is any integer expression. Due
to dynamic allocation does not have to be
constant.)
• all arrays must be dynamically allocated
• elements start with an index of zero, last index is
(length – 1)
Array Initialization
• Arrays may be initialized with an initializer list:
int[] intList = {2, 3, 5, 7, 11, 13};
double[] dList = {12.12, 0.12, 45.3};
String[] sList = {"Olivia", "Kelly", "Isabelle"};
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.");
}
}
Multidimensional Arrays
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();
}
}
Multidimensional Arrays
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];
• when you allocate dimensions manually, you
do not need to allocate the same number of
elements for each dimension
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
initialize multidimensional arrays
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 }
};
Array
int threeD[][][] = new int[3][4][5];

int al[] = new int[3]; or int[] a2 = new int[3];

char twod1[][] = new char[3][4];


or
char[][] twod2 = new char[3][4];
Operators
• Basic Assignment: =
• Arithmetic Operators: +, -, *, /, %(remainder)
– integer, floating point, and mixed arithmetic and
expressions
• Assignment Operators: +=, -=, *=, /=, %=
• increment and decrement operators: ++, --
– prefix and postfix.
int x = 3;
x++;
Bitwise Operators
• can be applied to the integer types, long,int, short, char, and byte.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
The Left Shift
• Zero is brought in on the right. If you shift a 1 bit into the high-order position (bit
31 or 63), the value will become negative.

class ByteShift {
public static void main(String args[]) {
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
The output generated by this program is shown here:
Original value of a: 64
i and b: 256 0
The Right Shift
int a = 32;
a = a >> 2; // a now contains 8
int a = 35;
a = a >> 2; // a still contains 8
When you are shifting right, the top (leftmost) bits exposed by
the right shift are filled in with the previous contents of the
top bit. This is called sign extension and serves to preserve
the sign of negative numbers when you shift them right.
For example,
–8>> 1 is –4, which, in binary, is
11111000 = –8
>>1
11111100 = –4
Expressions
• Expressions are evaluated based on the
precedence of operators
• Java will automatically convert numerical primitive
data types but results are sometimes surprising
– take care when mixing integer and floating point
numbers in expressions
• The meaning of an operator is determined by its
operands
/
is it integer division or floating point division?
Unsigned Right Shift
• to shift a zero into the high-order bit no matter
what its initial value was.
int a = -1;
a = a >>> 24;
• 11111111 11111111 11111111 11111111 –1 in
binary as an int
• >>>24
• 00000000 00000000 00000000 11111111 255
in binary as an int
Relational Operators
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Relational Operators
int done;
// ...
If(done) ... // Valid in C/C++
if(done) ... // but not in Java.
In Java, these statements must be written like this:
if(done == 0)) ... // This is Java-style.
if(done != 0) ...
Boolean Logical Operators
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
Short-Circuit Logical Operators

• secondary versions of the Boolean AND and


OR operators
• if (denom != 0 && (num / denom) > 10)
• there is no risk of causing a run-time exception
when denom is zero
Assignment Operator
• int x, y, z;
• x = y = z = 100; // set x, y, and z to 100
Operator Precedence
Highest
() [] .
++ –– ~ !
* / %
+ –
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest

You might also like