2 Data Types in Java
2 Data Types in Java
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
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
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