Vous êtes sur la page 1sur 23

Chapter 2 - Data Types

1 Identifiers

Symbolic names such as variables, labels, class names are called identifiers.

In Java, an identifier

• is a sequence of letters, digits and underscore ( _ );


• must start with a letter or underscore ( _ );
• can be of any length;
• cannot be a keyword;
• cannot have spaces.

Note

Java definition of an identifier is much more general than described here. But, we
will keep this definition.

2 Keywords

The following is the list of keywords in Java. Keywords are reserved - you cannot
use these as your identifiers.

abstract boolean break byte case


catch char class const continue
default do double else extends
final finally float for goto
if implements import instanceof int
interface long native new package
private protected public return short
static super switch synchronized this
throw throws transient try void
volatile while
16G Answer0207

Note:

• Two keywords const and goto are not yet implemented.

• true and false are boolean literals (constants). They are not keywords; still
they cannot be used as identifiers.

• Null is a type name, which is a literal, and cannot be used as an identifier.

3 Data Types

All the data a program uses is divided into different categories. These categories
are called data types.

Basic data types in Java are divided into two kinds: primitive type and reference
types. In this chapter we will discuss primitive data types in detail. We will not
discuss reference data types here.
The primitive types are: Integral type, Floating-point type and Boolean type.

Integral type:
A whole number, without a decimal point is called an integer. A variable or an
expression whose value is an integer is said to be of integer type. No commas are
allowed in representing an integer constant. An integer can internally be stored
using one, two, four or eight bytes. Depending on the storage size (1, 2, 4, or 8
bytes), integers are divided into four types: byte, short, int, and long. They
respectively take 1, 2, 4, and 8 bytes in memory.

Character type:
Internally, a character is stored using two bytes. The character can be one
character from the Unicode list. The name for the character type is char. For all
practical purposes, char is considered an integer type. Character constants are
typed using single quotes (' ').
Floating-point type:
A number represented using a decimal point or represented in the scientific
notation is called a floating-point number. A variable or an expression whose
value is a floating-point number is said to be of floating-point type. No commas
are allowed in representing a floating-point constant. A floating-point number is
internally stored using either 4 or 8 bytes. Depending on the storage size (4
bytes or 8 bytes) floating-point is divided into two types: float and double. The
data type float takes 4 bytes and double takes 8 bytes in memory.

Boolean type:
The truth-values true and false are called boolean constants. A variable or an
expression whose value is one of these two is said to be of type boolean.

Note:
Bits and bytes are introduced in Appendix A.

Data type ranges

The following table lists the size and range of values for all the primitive data
types.

Type Name Size in bits Range of values


boolean 1 bit true or false
byte 8 bits -128 to 127
short 16 bits -32768 to 32767
int 32 bits -2147483648 to 2147483647
long 64 bits -9223372036854775808 to
9223372036854775807
char 16 bits Any one character
float 32 bits 10-45 to 1038
double 64 bits 10-324 to 10308
16G Answer0207

Note:

• The reference type will not be discussed now.

• For all practical purposes, the string null is considered a reference literal.

• In many traditional programming languages the sizes of the basic data


types are system dependent. In Java they are fixed, as shown in the
table above.

• A bit stands for a binary digit. There are two binary digits: 0 and 1.
Please see appendix A for a detailed discussion on number systems

4 Constants in different formats

• Octal notation

Leading 0 in an integer constant indicates octal.

Practice Example 4

0123 is interpreted as an octal number (value of octal 0123 is 83).

Practice Exercise 4

Find the value of the number 0562.

• Hexadecimal notation

A leading 0x or 0X in an integer constant indicates hexadecimal.

Practice Example 4A

0xA4 is interpreted as a hexadecimal number (value of 0xA4 is 164).


Practice Exercise 4A

Find the value of the number 0XAB8.

Note:

Octal numbers are discussed in Appendix A.

• Scientific notation

The scientific format for a floating-point number is NeP, where N is any number
(integer or floating-point) and P is an integer (negative, zero or positive).

e or E can be used.

The value of NeP is N * 10P.

Practice Example 4B

4.21e3 is 4210.0

Practice Example 4C

4.21E-2 is 0.0421

Practice Exercise 4B

Find the value of 12.21e2.

Practice Exercise 4C

Find the value of 0.21e-2.


16G Answer0207

5 Using suffixes with constants

The suffixes can be used with constants. The following table shows permitted
suffixes and their meaning:

Suffix Meaning Example


L or l long 1234L
F or f float 4.21f
D or d double 4.21d

Note:

Floating-point constants, by default, are of type double. If you want a floating-


point constant to be treated as float, a suffix f or F must be included.

Integral constants, by default, are of type int.

6 Named constants

You can give a particular value a name. Every time you want to use the value,
you can just use the name. To make the value a constant you declare the field
as final. Once you declare a field final its value immutable, its value cannot be
changed.

Some advantages of using a name for a constant are:

(1) You need not remember the actual constant


(2) When you want to change the constant value, you just need to change one
line when you declare the value to the name.

Two points to be remembered about final fields:

• Initialize final fields at the time of declaration


• Declare final fields as static
Syntax:

Static final dataType name = constantValue;

Example:

Static final int number = 100000;


Static final double speed = 12.384747;

7 Symbolic names for special constants

Some of the constants such as maximum int, minimum int, have symbolic
names associated with them. Java predefines these names. The following table
lists the symbolic names, and their values.

Symbolic name Value


Integer.MIN_VALUE -2147483648
Integer.MAX_VALUE 2147483647
Long.MIN_VALUE 0x800000000000000L
Long.MAX_VALUE 0x7FFFFFFFFFFFFFFFL
Float.MIN_VALUE 1.4e-45f
Float.MAX_VALUE 3.4028235e+38f
Double.MIN_VALUE 5e-324
Double.MAX_VALUE 1.7976931348623157e+308

Note:

The significance of Integer, Long, Float and Double in the table will be made
clear in a later chapter.
16G Answer0207

8 Escape sequences

The following are special characters, which are called escape sequences. The
following table gives the meaning of these special characters.

Please read the table for now. You may have to come back to this later when we
use these notations.

Escape Sequence Meaning


\n Line feed
\t Tab
\b Back space
\f Form feed
\r Carriage return
\\ \
\" "
\' '
\ooo - each o is an Character whose ASCII
octal digit value is ooo
\uxxxx - each x is a Character whose Unicode is
hexadecimal digit xxxx

Note:

• Two of them: \n and \t are very commonly used escape sequences.

• The usual escape sequences \a (bell) and \v (vertical tab) are not available in
Java.

9 The String type

Java provides a built-in String type. As you will see later, String is a predefined
class. A character string enclosed within double quotes (" ") is really an object of
the String type. We will discuss String class, its characteristics in detail later.
For now, we will use String as a data type.

Example:

"John Smith" is of String type.

10 Conversion between numbers and strings

Even though a string, such as "421" looks like a number, we cannot use it as a
number. Internally it will not be represented as a number instead it is a string.
If you want to use a string "which looks like" a number, as a number, first you
need to convert the string into a number.

In the following table string is the String value you are trying to convert.

To convert to data type Use


int Integer.parseInt(string)
byte Byte.parseByte(string)
short Short.parseShort(string)
long Long.parseLong(string)
float Float.parseFloat(string)
double Double.parseDouble(string)

Note:
• You will get an error message, if the string has a non-numeric character.

• Occasionally, we need to convert a number into a string. The method


String.valueOf() does the required conversion.

Example: String.valueOf(421) returns the String "421".


16G Answer0207

11 Declaring variables

Every variable name used in a program must be "declared" before it is used. A


declaration of a variable just makes the variable ready to receive data of the
declared type.

Syntax:

type listOfVariables;

Where the listOfVariables is a list of variables separated by commas.

Example:

int a,b,c;

Three variables, a, b, c are declared as int type. We can now save int data in
the variables a, b, and c.

Example:

float x, y;

Two variables x and y are declared as float type. We can now save float data in
the variables x and y.

Example:

String name;

The name is declared as String type. We can now save String data in the
variable name.
Example:

Several variables of the same type can be declared in one declaration or several
declarations:

float p, q, r;

is equivalent to

float p;
float q;
float r;

12 Initializing variables

A declaration of a variable just makes the variable ready to receive data of the
declared type. You can save data in a variable at the time of declaration.

Syntax:

DataType variable = value;

As a rule, the value on the right side must be the same type as the type of the
variable.

Example:

int number1 = 14;

Here the variable number1 is not only declared as an int but a value 14 is saved
in it.
16G Answer0207

Example:

double score1=23.5, score2=20.75, score3=23.1;

Here variables score1, score2 and score3 are declared and initialized at the same
time.

Example:

String city = "New York";

Here the variable city is declared as a String variable and also it is assigned the
string New York.

13 Dual role of the + operator

It is important to understand that a String type value, such as "123", even


though it looks like a number it is not a number. Its data type is String.

The operator + behaves differently depending on its operands.

If both operands are numbers, the operator + gives the sum of the numbers.
On the other hand, if one or both operands are of type String, the operator +
concatenates the two strings. The result is of type String in this case.

Example:

• 2 + 4.2 is 6.2.

• "abc"+"xyz" is "abcxyz".

• "421" + "abc" is “421abc”.


Example:

int x=4, y=7;


int z;
z = x+y;
The value of z is 11.

Example:

int x = 15;
String sam = "New York";
String result;
result = x+sam;
The value of result is "15New York".

Example:

String value1 = "15";


String value2 = "12";
String result;
result = value1+value2;
The value of result is "1512".

Notice that the value of result is not 27. If you really like to add values of value1
and value2 as numbers, first you need to convert the string values into int values
using the function Integer.parseInt() as described earlier.

int sum = Integer.parseInt(value1) + Integer.parseInt(value2);

Now the value of sum is 27.


16G Answer0207

14 General rules on formatting code

As a general rule, spaces do not matter in the code. Of course, there cannot be
spaces within keywords and identifiers. Where you can put one space, you can
put more spaces.

Example:

int x = 4;
You can rewrite the statement as follows:
int x=4;

Terminate every statement by a semicolon. Two statements can be placed on


the same line.

Example:

int x=4;
float y=3.4f;
You can rewrite them as follows:
int x=4; float y=3.4f;

15 Programming Examples

Programming Example 1

This examples assigns values to variables in octal and hexadecimal format and
prints them in the usual decimal format.

//Chapter 2 Programming Example 1


class ProgrammingExample1
{
public static void main(String args[])
{
int a = 0253; // 0253 is an octal number
int b = 0xA4B;// 0xA4B is a hexadecimal number
int c = 0777; // 0777 is an octal number
int d = 0Xabcd;//0Xabcd is a hexadecimal number
System.out.println("Value of a is = "+a);
System.out.println("Value of b is = "+b);
System.out.println("Value of c is = "+c);
System.out.println("Value of d is = "+d);
}
}

Output:

Value of a is = 171
Value of b is = 2635
Value of c is = 511
Value of d is = 43981
16G Answer0207

Programming Example 2
In this example we assign values to variables in scientific notation and print them
in the usual decimal format.

//Chapter 2 Programming Example 2


class ProgrammingExample2
{
public static void main(String args[])
{
float a = 42.10e2f;
double b = 0.000534e3;
float c = 5346e-3f;
double d = 546e0;
System.out.println("Value of a is = "+a);
System.out.println("Value of b is = "+b);
System.out.println("Value of c is = "+c);
System.out.println("Value of d is = "+d);
}
}

Output:

Value of a is = 4210.0
Value of b is = 0.534
Value of c is = 5.346
Value of d is = 546.0
Programming Example 3

The following example prints the largest and the smallest values in several of the
data types. Also notice how tabs ('\t') are used.

//Chapter 2 Programming Example 3


class ProgrammingExample3
{
public static void main(String[] args)
{
System.out.println("Minimum int = \t"+Integer.MIN_VALUE);
System.out.println("Maximum int = \t"+Integer.MAX_VALUE);
System.out.println("Minimum long = \t"+Long.MIN_VALUE);
System.out.println("Maximum long = \t"+Long.MAX_VALUE);
System.out.println("Minimum float = \t"+Float.MIN_VALUE);
System.out.println("Maximum float = \t"+Float.MAX_VALUE);
System.out.println("Minimum double = \t"+Double.MIN_VALUE);
System.out.println("Maximum double = \t"+Double.MAX_VALUE);
}
}

OUTPUT:

Minimum int = -2147483648


Maximum int = 2147483647
Minimum long = -9223372036854775808
Maximum long = 9223372036854775807
Minimum float = 1.4E-45
Maximum float = 3.4028235E38
Minimum double = 4.9E-324
Maximum double = 1.7976931348623157E308
16G Answer0207

Programming Example 4

This example illustrates the conversion of strings into numbers.

//Chapter 2 Programming Example 4


class ProgrammingExample4
{
public static void main(String args[])
{
String x = "45";
String y = "12";
int a = Integer.parseInt(x);
int b = Integer.parseInt(y);
System.out.println("Sum of x and y \t"+(x+y));
System.out.println("Sum of a and b \t"+(a+b));
}
}

Output:

Sum of x and y 4512


Sum of a and b 57

Note:
The parentheses around a+b are required. Observe that the following code will not
produce the required result:
System.out.println("Sum of a and b \t"+a+b);
16 Chapter 2 Exercises

Problem 1:
Indicate if the following identifiers are valid or invalid. Explain why invalid
identifiers are so.

(a) abcdef Answer


(b) 4IBM Answer
(c) boolean Answer
(d) _special Answer
(e) first class Answer
(f) item#1 Answer
(g) float Answer

Problem 2

Identify the data type of each of the following:


14 Answer
2.345 Answer
'm' Answer
'\t' Answer
"m" Answer
"Apple" Answer
18L Answer
3.46 Answer
3.46d Answer
3.46f Answer
'\n' Answer
5.0 Answer
5f Answer
5L Answer
16G Answer0207

Problem 3
Write the values of each of the following numbers in the usual decimal format:

2.43e3 Answer
12.003e-2 Answer
0.0034E4 Answer
0234 Answer
0xABC Answer
0Xa2c Answer
0134 Answer
53.4e0 Answer

Problem 4
Write the declaration for each of the following:

(a) Two variables number1 and number2 to Answer


be of type int.
(b) One variable value1 as an int and another Answer
variable value2 as a float.
(c) A variable lastName as a String. Answer
(d) Three variables n1, n2, and n3 as int and Answer
initialize them to 4, 2 and 0 respectively.
(e) Four variable x1, x2, x3 and x4 as double Answer
and initialize them to 1.2, 2.3, 4.1 and 5.4
respectively.
(f) Two variables lastName and firstName as Answer
String and intialize them to Smith and John
respectively.
Problem 5

In each of the following problems, write the value of the variable answer. If
there is something wrong in the code, explain a possible fix for the mistake and
then write the value of the variable answer.

(a)String s1="12", s2="28"; Answer


int answer;
answer = s1+s2;
(b) String s1="12", s2="28"; Answer
String answer;
answer=s1+s2;
(c) int x = 4;float y = 2.8; Answer
float answer = x+y;
(d) String x = "4.21"; Answer
String y = "5.23";float answer;
answer = Float.parseFloat(x)+Float.parseFloat(y);
(e) String x = "234", y = "512"; Answer
int answer = Integer.parseInt(x) +
Integer.parseInt(y);
(f) String x = "234.23", y ="512.12"; Answer
String answer = x+y;
(g)int a = 3; b = 5; Answer
int answer = a+b;
(h) int a = 4.0, b = 5.0; Answer
int answer = a+b;

Problem 6
Write a program to assign 0647, 0x5AB, 0XAAA, 4.32e4, 0.0035e3, 0.345e-2 to
variables and print the values of the variables in the decimal format.

Problem 7
Assign "24.35" and "87.23" to two variables and print their sum (i) as strings and
(ii) as numbers.
16G Answer0207

Answer to Chapter 2 Exercise 6


class Exercise0206
{
public static void main(String args[])
{
int a = 0647;
int b = 0x5AB;
int c = 0XAAA;
double d = 4.32e4;
double e = 0.0035e3;
double f = 0.345e-2;
System.out.println("0647 is "+a);
System.out.println("0x5AB is "+b);
System.out.println("0XAAA is "+c);
System.out.println("4.32e4 is "+d);
System.out.println("0.0035e3 is "+e);
System.out.println("0.345e-2 is "+f);
}
}

Answer to Chapter 2 Exercises 7

class Exercise0207
{
public static void main(String args[])
{
String x = "24.35";
String y = "87.23";
String a = x+y;//adding as strings
double b = Double.parseDouble(x) +Double.parseDouble(y);
System.out.println("x and y added as strings "+a);
System.out.println("x and y added as numbers "+b);
}
}

Vous aimerez peut-être aussi