Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Data Types

Java is a strongly typed programming language implying that all variables must have a
declared data type. There 8 primitive data types in Java. Of the 8, four are integer types;
two are real or floating-point number types; one is the character type char used for code
units in Unicode encoding scheme and one is a boolean type for truth tables.

Data Content Min Value Max Value


Type
byte Integer (8 bits) -128 128
short Integer (16 -32768 32767
bits)
int Integer (32 bit) -2147483648 2147483647
long Integer (64 bit) -9223372036854775808 9223372036854775807
float Real (32 bit) -3.40282347E+38F 3.40282347E+38F
double Real (64 bit) - 1.79769313486231570E308
1.79769313486231570E308
char single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and
a maximum value of '\uffff' (or 65,535 inclusive).
Boolean The Boolean data type has only two possible values: true and false. Use this
data type for simple flags that track true/false conditions. This data type
represents one bit of information, but its "size" isn't something that's precisely
defined.

The most commonly used types for general purpose programming are int and double.

Integers

Integers are positive and negative numbers without fractional parts. Unlike in C/C++ the
ranges of the integer types are independent of the machine on which you will be running
the code.

Note that long integer numbers have a suffix L for example 10 567 890 46L

Integer literals can be expressed by these number systems:

Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number
system you use every day

Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A
through F. The prefix 0x indicates hexadecimal for example 0xDFAC.

Prepared by Zanamwe N @ 2014 1


Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary
literals in Java SE 7 and later). The prefix 0b indicates binary for example 0b10101.

Floating-Point types

Floating-point numbers have fractional parts and here we have double and float as
floating–point types.

Doubles are often called double precision numbers because they have twice the precision
of the float type.

float type numbers have a suffix F or f for example 6.789F. Whereas it is mandatory to
suffix float type numbers with F it is optional to suffix double type numbers with D or d.

The floating point types (float and double) can also be expressed using E or e (for
scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the
default and by convention is omitted).

double d1 = 123.4;

// same value as d1, but in scientific notation

double d2 = 1.234e2;

float f1 = 123.4f;

Using Underscore Characters in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere
between digits in a numerical literal. This feature enables you, for example to separate
groups of digits in numeric literals, which can improve the readability of your code.

For instance, if your code contains numbers with many digits, you can use an underscore
character to separate digits in groups of three, similar to how you would use a
punctuation mark like a comma, or a space, as a separator.

The following example shows other ways you can use the underscore in numeric literals:

Prepared by Zanamwe N @ 2014 2


long creditCardNumber = 1234_5678_9012_3456L;

long socialSecurityNumber = 999_99_9999L;

float pi = 3.14_15F;

long hexBytes = 0xFF_EC_DE_5E;

long hexWords = 0xCAFE_BABE;

long maxLong = 0x7fff_ffff_ffff_ffffL;

byte nybbles = 0b0010_0101;

long bytes = 0b11010010_01101001_10010100_10010010;

You can place underscores only between digits; you cannot place underscores in the
following places:

At the beginning or end of a number

Adjacent to a decimal point in a floating point literal

Prior to an F or L suffix

In positions where a string of digits is expected

The following examples demonstrate valid and invalid underscore placements (which are
highlighted) in numeric literals:

// Invalid: cannot put underscores

// adjacent to a decimal point

float pi1 = 3_.1415F;

// Invalid: cannot put underscores

// adjacent to a decimal point

Prepared by Zanamwe N @ 2014 3


float pi2 = 3._1415F;

// Invalid: cannot put underscores

// prior to an L suffix

long socialSecurityNumber1 = 999_99_9999_L;

// OK (decimal literal)

int x1 = 5_2;

// Invalid: cannot put underscores

// At the end of a literal

int x2 = 52_;

// OK (decimal literal)

int x3 = 5_______2;

// Invalid: cannot put underscores

// in the 0x radix prefix

int x4 = 0_x52;

// Invalid: cannot put underscores

// at the beginning of a number

int x5 = 0x_52;

// OK (hexadecimal literal)

int x6 = 0x5_2;

// Invalid: cannot put underscores

// at the end of a number

Prepared by Zanamwe N @ 2014 4


int x7 = 0x52_;

Character Type

The char is two bytes long, allowing for 65 536 different characters, compared to the one-
byte ASCII code which allows only 255 different characters. The encoding scheme used
is Unicode. The first 255 characters in Unicode are the same as ASCII. Keyboard
characters may be represented as literal characters in single quotes ‘c’; but in general
Unicode characters are represented as ‘\uhhhh’, with single quotes, \u and four hex digits
with leading zeros. Eg N = ‘\u004E’

Methods are provided for converting between Unicode and other encoding schemes such
as ASCII in Microsoft windows.

The ‘\’ backslash character is used to escape or give the next character a special meaning;
these escape sequences include:

Escape Sequence Name Unicode Value


\r Return \u000d
\n newline \u000a
\t tab \u0009
\\ backslash \u005c
\” double quote \u0022
\’ single quote \u0027

System.out.print(“n \n \\n”);

Outputs

\n

Variables

Variable names may include digits, letters, $, and _ and may not start with a digit. Java is
strongly typed and every variable must be declared before use. Every variable should be
initialized before use and the compiler will try to prevent the use of uninitialized
variables.

int i ; // declaration
i = 10; // assignment
Usually declaration and assignment are combined into a definition:

Prepared by Zanamwe N @ 2014 5


int i = 10 // definition
Multiple declarations are possible in a single statement but deprecated or condemned in
this course:
int i, j, j; //?? Affects readability.

When the declaration is made, memory space is allocated to store the value of i.

i is called a variable. A variable has three properties:

1. A memory location to store the value,


2. The type of data stored in the memory location, and
3. The name used to refer to the memory location.

Variable scope

The scope of variables is from the point of declaration to the end of the block in which
they are declared.

{
int i =1;
System.out.println(i);
}
{
int i = 2;
System.out.println(i);
}
Variables can not be declared in overlapping blocks.

{
int i =1;
System.out.println(i);

{
int i = 2; // error
System.out.println(i);
}
}

Constants

Prepared by Zanamwe N @ 2014 6


Constants are declared with access modifier “final” which protects them from
modification. Constants are conventionally written in uppercase:

public static void main(String [] args)


{
final int SECONDS_PER_WEEK = 7*24*60*60;
// …
}
Constants declared local to a class block are initialised by default

Primitive types

The storage allocated to primitive types is defined in the language specification rather
than being left to the language implementer.

There are six numerical data types: byte, short, int, long, float, and double.

Sample variable declarations:


int ik;
float numberTwo;
long bigInteger;
double BigNumber;

At the time a variable is declared, it also can be initialized. For example, we may
initialize the integer variables count and height to 10 and 34 as

int count = 10;


int height = 34;

Type conversion

Conversions which do not lose information are legal:

int x = 1;

double d = 4.567;

d = x ; // OK

x = d; // Error

Prepared by Zanamwe N @ 2014 7


Otherwise values must be cast to the appropriate type before assignment, eg.

x = (int)d; // OK but x is now 4

Note that (int) truncates floating point values. To round floating point values use the
Math.round() method of the Java Math library, but since this returns a long value you
have to cast the result to integer:

int x = (int)Math.round(d);

Note that when you use explicit casts, you are expected to know what you are doing, for
example, the following cast is legal but not sensible:

char c = ‘\uFFFF’; // 2-byte store 1111111111111111

byte b = (byte)c; // 1 byte store 11111111

System.out.println(b); // prints -1

System.out.print(“n \n \\n”);

Outputs

\n

Assignment Operator
Assigning a value to a variable seems straightforward enough; you simply assign the stuff
on the right side of the = to the variable on the left.

Casting
Involves converting values from one type to another. It can be explicit or implicit. An
implicit cast means you don't have to write code for the cast; the conversion happens
automatically. Typically, an implicit cast happens when you're doing a widening
conversion, i.e., when putting a smaller thing into a bigger container. For example:

int a = 100;
long b = a; // Implicit cast, an int value always fits in a long

The large-value-into-small-container conversion is referred to as narrowing and requires


an explicit cast, where you tell the compiler that you're aware of the danger and accept
full responsibility. For example:
float a = 20.002;

Prepared by Zanamwe N @ 2014 8


int b = (int) a;

Operators

The following table summarizes the arithmetic operators available in Java.

Operation Operator
Addition +
Subtraction -
Multiplication *
Division /
Modulus (for remainder) %

Arithmetic Expression

How does the expression

x+3*y

get evaluated? Answer: x is added to 3*y.

We determine the order of evaluation by following the precedence rules:

 Sub expressions ( )
 unary + -
 multiplicative operators * / %
 additive + -
 assignment =

Concatenation Operator (+)


The plus (+) operator is overloaded meaning that it can be used to add numbers and
also concatenate strings and characters and also numbers. For example

System.out.println('a' + 9); // outputs 109


System.out.println('a' + 'b' + 'c'); // outputs 294
System.out.println('a' + "b" + 'c'); // outputs abc
System.out.println("Good" + " " + 9); // Good 9

In Java operator and assignment may be combined in expressions with only one
variable. For example:

y= y + 6; can be expressed as
y += 6;

Increment and Decrement Operators

Prepared by Zanamwe N @ 2014 9


Java has two operators that will increment or decrement a variable by exactly one. These
operators are composed of either two plus signs (++) or two minus signs (--):

 ++ increment (prefix and postfix)

 decrement (prefix and postfix)

k++ and k—(postfix form)


++k and --k (prefix form)
The postfix form increments the variable after the reference and the prefix form
increments before the reference:
int y = 3;
System.out.println(y); // prints 3
System.out.println(++y); // prints 4
System.out.println(y++); // prints 4
System.out.println(y); // prints 5

For clarity avoid using ++ and –- within expressions.

int m = 7;
int n = 7;
int a = 2*++m; // mow a is 16, m is 8
int b = 2*n++; // now b is 14, n is 8

Be aware that integer division discards the remainder:

5/3 evaluates to 1
If at least one of the numbers is floating point then division includes the remainder:

5.0/3
5/3.0
5.0/3.0
5/ (double)4
All evaluate to 1.75
The usual precedence relations hold; use parentheses to override these if necessary.

Relational and Boolean operators

1. less than (<) and greater than (>)


2. less than or equal (<=) and greater than or equal (>=)

Prepared by Zanamwe N @ 2014 10


3. logical AND operator (&&): if two expressions are combined with the logical
AND operator and if the truth value of the first expression is false then it is
impossible for the overall result to be true and the value of the second expression
is not calculated. This can be used to avoid errors such as division by zero. For
example:
x != 0 && 4/x > x + y // no division by 0. (is a short circuit logical operator)
4. logical OR operator (||): when this operator is used to combine expressions, the
overall result is automatically true if the first expression is true and there will be
no need to evaluate the second expression. (is a short circuit logical operator)
5. Logical negation (!)
6. ternary operator (?:) the expression:

The conditional operator is a ternary operator (it has three operands) and is used to
evaluate boolean expressions, much like an if statement except instead of executing a
block of code if the test is true, a conditional operator will assign a value to a
variable.

In other words, the goal of the conditional operator is to decide which of two values
to assign to a variable. This operator is constructed using a ? (question mark) and a :
(colon). The parentheses are optional. Its structure is:

x = (boolean expression) ? value to assign if true : value to assign


if false

Let's take a look at a conditional operator in code:


class Salary {
public static void main(String [] args) {
int numOfPets = 3;
String status = (numOfPets<4) ? "Pet limit not exceeded"
: "too many pets";
System.out.println("This pet status is: " + status);
}
}

You can read the preceding code as Set numOfPets equal to 3. Next we're going to
assign a String to the status variable. If numOfPets is less than 4, assign "Pet limit not
exceeded" to the status variable; otherwise, assign "too many pets" to the status
variable. A conditional operator starts with a boolean operation, followed by two
possible values for the variable to the left of the assignment (=) operator. The first
value (the one to the left of the colon) is assigned if the conditional (boolean) test is
true, and the second value is assigned if the conditional test is false. You can even
nest
conditional operators into one statement:
class AssignmentOps {
public static void main(String [] args) {

Prepared by Zanamwe N @ 2014 11


int sizeOfYard = 10;
int numOfPets = 3;
String status = (numOfPets<4)?"Pet count OK" :(sizeOfYard > 8)? "Pet
limit on the edge" :"too many pets";
System.out.println("Pet status is " + status);
}
}

Bitwise operators

Bitwise operators are used with integer types and they work directly with the bits that
make up the integers.
Here follows the operators:
1. and (&)
2. or (|)
3. xor (^)
4. not (~)
5. shift left (<<)
6. shift right (>>)

Of the six logical operators listed above, three of them (&, |, and ^) can also be used as
"bitwise" operators. Here are several legal statements that use bitwise operators:
byte b1 = 6 & 8;
byte b2 = 7 | 9;
byte b3 = 5 ^ 4;
System.out.println(b1 + " " + b2 + " " + b3);
System.out.println(b1<< 2); // shifts by 2 bits to the left
System.out.println(b2 >> 1); // shifts by 1 bit to the right

Bitwise operators compare two variables bit by bit, and return a variable whose bits have
been set based on whether the two variables being compared had respective bits that were
either both "on" (&), one or the other "on" (|), or exactly one "on" (^). By the way, when
we run the preceding code, we get
0 15 1
0
7

It has been said that && and || are short-circuit, however; & and | are not. The example
below illustrates the difference.

int z = 5;
if(++z > 5 || ++z > 6) z++;// z = 7 after this code

versus:
int z = 5;
if(++z > 5 | ++z > 6) z++; // z = 8 after this code

Prepared by Zanamwe N @ 2014 12


"Equality" Operators
Java also has two relational operators (sometimes called "equality operators") that
compare two similar "things" and return a boolean that represents what's true about the
two "things" being equal. These operators are:
 == equals (also known as "equal to")
 != not equals (also known as "not equal to")
Each individual comparison can involve two numbers (including char), two boolean
values, or two object reference variables. You can't compare incompatible types,
however. What would it mean to ask if a boolean is equal to a char? Or if a Button is
equal to a String array? (Exactly, nonsense, which is why you can't do it.)
There are four different types of things that can be tested:
 numbers
 characters
 boolean primitives
 Object reference variables
So what does == look at? The value in the variable—in other words, the bit pattern.

Equality for Primitives


Most programmers are familiar with comparing primitive values. The following code
shows some equality tests on primitive variables:
class ComparePrimitives
{
public static void main(String[] args)
{
System.out.println("char 'a' == 'a'? " + ('a' == 'a'));
System.out.println("char 'a' == 'b'? " + ('a' == 'b'));
System.out.println("5 != 6? " + (5 != 6));
System.out.println("5.0 == 5L? " + (5.0 == 5L));
System.out.println("true == false? " + (true == false));
}
}
This program produces the following output:
char 'a' == 'a'? true
char 'a' == 'b'? false
5 != 6? true
5.0 == 5L? true
true == false? false

As we can see, usually if a floating-point number is compared with an integer and the
values are the same, the == operator returns true as expected.

Equality for Reference Variables


Two reference variables can refer to the same object, as the following code snippet
demonstrates:
JButton a = new JButton("Exit");

Prepared by Zanamwe N @ 2014 13


JButton b = a;
After running this code, both variable a and variable b will refer to the same object (a
JButton with the label Exit). Reference variables can be tested to see if they refer to
the same object by using the == operator. Remember, the == operator is looking at the
bits in the variable, so for reference variables this means that if the bits in both reference
variables are identical then both refer to the same object.

Compound Assignment Operators


There are actually 11 or so compound assignment operators, but only the four most
commonly used (+=, -=, *=, and /=), are discussed. The compound assignment operators
let lazy typists shave a few keystrokes off their workload. Here are example assignments,
first without using a compound operator,

y = y - 6;
x = x + 2 * 5;
Now, with compound operators:
y -= 6;
x += 2 * 5;
The last two assignments give the same result as the first two.

Mathematical functions and constants

The Math class contains many useful functions such as:


1. Math.sqrt(x) // this method returns the square root of x
2. Math.pow(x,n) //returns x to the power n.
3. Math.sin(x)
4. Math.cos(x)
5. Math.log(x)
6. Math.ln(x)
7. Math.exp(x)
8. Math.PI
9. Math.tan(x)

These are all static methods of the Math class. Methods which do not apply to objects
must be declared static. Numbers are not objects so the methods of the Math class which
apply to them are static. All methods must belong to a class. The name of the class the
methods belong to must be given so that the compiler can locate them.

abs

It strips off the sign of a number and returns it simply as a number. Thus the following
will simply print out 99. If the number is not negative you just get back the same number.

Prepared by Zanamwe N @ 2014 14


System.out.println(Math.abs(-99));

ceil

This method returns the next whole number up that is an integer. Thus if you pass

ceil(1.1)

it will return a value of 2.0

If you change that to

ceil(-1.1)

the result will be -1.0;

floor

Returns the largest (closest to positive infinity) double value that is not greater than the
argument and is equal to a mathematical integer.

If that is not entirely clear, here is a short program and its output

public class MyMat{


public static void main(String[] argv){
System.out.println(Math.floor(-99.1));
System.out.println(Math.floor(-99));
System.out.println(Math.floor(99));
System.out.println(Math.floor(-.01));
System.out.println(Math.floor(0.1));
}
}

And the output is

-100.0
-99.0
99.0
-1.0
0.0

max and min

Take note of the following two methods as they take two parameters. You may get
questions with faulty examples that pass them only one parameter. As you might expect
these methods is the equivalent of

Prepared by Zanamwe N @ 2014 15


"which is the largest THIS parameter or THIS parameter"

The following code illustrates how these methods work

public class MaxMin{


public static void main(String argv[]){
System.out.println(Math.max(-1,-10));
System.out.println(Math.max(1,2));
System.out.println(Math.min(1,1));
System.out.println(Math.min(-1,-10));
System.out.println(Math.min(1,2));
}
}

Here is the output

-1
2
1
-10
1

random

Returns a random number between 0.0 and 1.0.

Unlike some random number system Java does not appear to offer the ability to pass a
seed number to increase the randomness. This method can be used to produce a random
number between 0 and 100 as follows.

One of the important aspects of this method is that the value returned is between 0.0 and
1.0. Thus a typical sequence of output might be

0.9151633320773057
0.25135231957619386
0.10070205341831895

Often a program will want to produce a random number between say 0 and 10 or 0 and
100. The following code combines math code to produce a random number between 0
and 100.

System.out.println(Math.round(Math.random()*100));

round

Rounds to the nearest integer. So, if the value is more than half way towards the higher
integer, the value is rounded up to the next integer. If the number is less than this the next
lowest integer is returned. So for example if the input to round is x then :

Prepared by Zanamwe N @ 2014 16


2.0 <=x < 2.5. then Math.round(x)==2.0
2.5 <=x < 3.0 the Math.round(x)==3.0

Here are some samples with output

System.out.println(Math.round(1.01));
System.out.println(Math.round(-2.1));
System.out.println(Math.round(20));
1
-2
20

sin cos tan

These trig methods take a parameter of type double and do just about what trig functions
do in every other language you have used.

sqrt

returns a double value that is the square root of the parameter.

Overflow

Attempts to assign beyond the range of primitive types such as


int i = 1000000000000000000;
double s = 1.45E400;
are detected as errors at compile time. But subsequent overflow is not detected at
compile time or runtime.
int big = 2147483647; // use Integer.MAX_VALUE
System.out.println(big); // 2147483647 (0111…1111)
big = big + 1;
System.out.println(big); // -2147483648 (1111…1111)
big = big + 1;
System.out.println(big); // -2147483647 (?)

For effectively unlimited range use BigInteger and BigDecimal in the java.Math
class.

Precision

With floating point storage, precision is also an important consideration. Float values
provide approximately 7 significant digits and double values provide approximately 15
significant digits. Arithmetic can lead to loss of precision:

Prepared by Zanamwe N @ 2014 17


double originalPrice = 3E14;
System.out.println(originalPrice); // 3E14
double discountedPrice = originalPrice – 0.05;
System.out.println(discountedPrice); // 2.9999999999999994E14
double discount = originalPrice – discountedPrice; // 0.0625

If we assign values of 3E13 and below this error is not apparent.


If we assign the value 3E15 and above then the errors increase dramatically and the
discount printed is zero

Round off errors

Calculations with floating point numbers also suffer from round off errors. With
manual calculator and decimal representation, for example, 1/3 with two-decimal
place precision is 0.33, so 1/3*3 is 0.99 not 1.00. With computers and binary
representation round off also occurs:
double f = 4.35;
int n = (int)(100*f); // should be 435
System.out.println(n); // prints 434!

In the binary system there is no exact representation for 4.35, just as there is no exact
representation for 1/3 in the binary system and the binary representation of 4.35 is
slightly less than 4.35 so 100 times that value is slightly less than 435, and the (int)
cast truncates the value and discards the fractional part. Rather use rounding than
truncation. The Math.round() method returns a long value which can be safely cast
into int;
int n = (int)Math.round(100*f);
System.out.println(n); // prints 435

Prepared by Zanamwe N @ 2014 18

You might also like