Data Types in Java1
Data Types in Java1
Data Types
Java is statically typed and also a strongly typed language because in Java, each
type of data (such as integer, character, hexadecimal, packed decimal, and so forth)
is predefined as part of the programming language and all constants or variables
defined for a given program must be described with one of the data types.
Java has two categories of data:
Primitive data (e.g., number, character)
Object data (programmer created types)
Variables in Java
A variable is the name given to a memory location. It is the basic unit of storage in
a program.
Types of variables
There are three types of variables in Java:
Local Variables
Instance Variables
Static Variables
Let us now learn about each one of these variables in detail.
1. Local Variables: A variable defined within a block or method or constructor
is called local variable.
These variable are created when the block in entered or the function is
called and destroyed after exiting from the block or when the call returns
from the function.
The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access these variable only within that
block.
Initilisation of Local Variable is Mandatory.
2. Instance Variables: Instance variables are non-static variables and are
declared in a class outside any method, constructor or block.
As instance variables are declared in a class, these variables are created
when an object of the class is created and destroyed when the object is
destroyed.
Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier then the default access specifier will be
used.
Initilisation of Instance Variable is not Mandatory. Its default value is 0
Instance Variable can be accessed only by creating objects.
Relational Operators: The relational operators determine the relationship that one
operand has to the other. The relational operators evaluates the relation between
two operations and returns true if the relation exists else false.
‘==’ operator: checks whether the two given operands are equal or not. If
so, it returns true. Otherwise it returns false. For example, 5==5 will return
true.
‘!=’ operator: checks whether the two given operands are equal or not. If
not, it returns true. Otherwise it returns false. It is the exact boolean
complement of the ‘==’ operator. For example, 5!=5 will return false.
‘>’ operator: checks whether the first operand is greater than the second
operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will
return true.
‘<‘ operator:checks whether the first operand is lesser than the second
operand. If so, it returns true. Otherwise it returns false. For example, 6<5 will
return false.
‘>=’ operator: checks whether the first operand is greater than or equal to
the second operand. If so, it returns true. Otherwise it returns false. For
example,5>=5 will return true.
‘<=’ operator: checks whether the first operand is lesser than or equal to the
second operand. If so, it returns true. Otherwise it returns false. For
example, 5<=5 will also return true
Bitwise Operators:
Java provides several bitwise operators to work with integer types long, int,
short, char , byte. Bitwise operators performs bit by bit operation on binary
representation of integers. These operators acts upon he individual bits of their
operands.
Bitwise operators available in Java are:
& (bitwise and): Bitwise & operator performs binary AND operation
bit by bit on the operands. Different a&b = 0001 which is 1
| (bitwise or): Bitwise | operator performs binary OR operation bit by
bit on the operands. a|b = 1111 which is 15
^ (bitwise XOR): Bitwise ^ operator performs binary XOR operation
bit by bit on the operands. a^b = 1110 which is 14
~ (bitwise compliment):Bitwise ~ operator performs binary NOT
operation bit by bit on the operand. ~b = 1000 which is 8
<< (left shift): This operator shifts the bits of the left operand to left
by number of times specified by right operand. a<<1 = 10010 = 18
>> (right shift): This operator shifts the bits of the left operand to
right by number of times specified by right operand. a>>1 = 0100 = 4
>>> (zero fill right shift): Shift right zero fill operator.The left
operand value is shifted to right by number of digits specified by right
operand and shifted digits will be replaced by zero. a>>>2 = 0010 = 2
2. Assignment Operator: The assignment operator is used to assign value to a
variable. The general form of an assignment operator is:
var = expression
Different ways of using assignment operator:
‘=’: This is the simplest assignment operator. It assigns the value of
left operand to the right operand. For example, a = 3.
‘+=’: This operator first adds the left and right operands and then
assigns the result to the left operand. For example, a += b is equivalent to
a = a + b.
‘-=’: This operator first subtracts the right operand from left operand
and then assign the result to left operand. For example, a -= b is
equivalent to a = a – b.
‘*=’: This operator first multiplies the right operand and left operand
and then assign the result to left operand. For example, a *= b is
equivalent to a = a * b
‘/=’: This operator first divides the left operand by right operand and
then assign the result to left operand. For example, a /= b is equivalent to
a=a/b
‘%=’: This operator calculates modulus using left and right operand
and then assigns the result to the left operand. For example, a %= b is
equivalent to a = a % b
Similarly we can also use operators like , ^= , &= , |=.
3. Logical Operators: Logical operators perform logical operations like
logical AND, logical OR etc. Let us assume that variable a holds the boolean
value true and b holds the boolean value false. Below are some logical
operators we can use:
Logical AND (‘&&’): This operator will return true if both the left
and right operands are true, otherwise it will return false. For example, a
&& b is false.
Logical OR (‘||’): This operator will return true if any one of the left
and right operands are true. It will return false when both left and right
operands are false. For example, a || b is True.
Logical NOT (‘!’): This is a unary operator and can be used with a
single operand. This will return true if the operand is false and return
false if the operand is true. For example, !a is false and !b is true.
Precedence Chart
Below table shows the precedence order of operators from highest to lowest.
Operators in same row have equal precedence.
Decision Making in Java (if, if-else, switch,
break, continue, jump)
Decision Making in programming is similar to decision making in real life. In
programming also we face some situations where we want a certain block of code
to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution
of program based on certain conditions. These are used to cause the flow of
execution to advance and branch based on changes to the state of a program.
Java’s Selection statements:
if
if-else
nested-if
if-else-if
switch-case
jump – break, continue, return
These statements allow you to control the flow of your program’s execution based
upon conditions known only during run time.
if: if statement is the most simple decision making statement. It is used to
decide whether a certain statement or block of statements will be executed or
not i.e if a certain condition is true then a block of statement is executed
otherwise not.
Syntax:
if(condition)
{
// Statement to execute if
// condition is true
}
Here, condition after evaluation will be either true or false. if statement
accepts boolean values – if the value is true then it will execute the block of
statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by
default if statement will consider the immediate one statement to be inside its
block. For example
if( condition)
{
Statement 1;
Statement 2;
if-else: The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we want to do
something else if the condition is false. Here comes the else statement. We can use
the else statement with if statement to execute a block of code when the condition
is false.
Syntax:
if (condition )
{
//Executes this block if condition is true
}
else
{
//Executes this block if condition is false
}
if( condition 1)
if( condition 2)
}}
if-else-if ladder: Here, a user can decide among multiple options.The if
statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
if (condition)
Statement;
else if (condition )
statement;
else
statement;
switch (expression)
Case value1:
Statement1;
break;
case valueN
statementN;
break;
default:
statement default;
}
Loops in Java
Looping in programming languages is a feature which facilitates the execution of a
set of instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide
similar basic functionality, they differ in their syntax and condition checking time.
1. while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can
be thought of as a repeating if statement.
Syntax :
while (Boolean conditions)
{
loop statements
}
While loop starts with the checking of condition. If it evaluated to true, then
the loop body statements are executed otherwise first statement following the
loop is executed. For this reason it is also called Entry control loop
Once the condition is evaluated to true, the statements in the loop body are
executed. Normally the statements contain an update value for the variable
being processed for the next iteration.
When the condition becomes false, the loop terminates which marks the end
of its life cycle.
2. for loop: for loop provides a concise way of writing the loop structure.
Unlike a while loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
Syntax:
for(initialization condition; testing condition; increment/decrement)
{
Statements;
}
3. Return:The return statement is used to explicitly return from a method. That is,
it causes a program control to transfer back to the caller of the method.
Arrays in Java
An array is a group of like-typed variables that are referred to by a common name.
Arrays in Java work differently than they do in C/C++. Following are some
important point about Java arrays.
In Java all arrays are dynamically allocated.(discussed below)
Since arrays are objects in Java, we can find their length using member
length. This is different from C/C++ where we find length using sizeof.
A Java array variable can also be declared like other variables with [] after
the data type.
The variables in the array are ordered and each have an index beginning
from 0.
Java array can be also be used as a static field, a local variable or a method
parameter.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.
Array can contains primitives data types as well as objects of a class depending on
the definition of array. In case of primitives data types, the actual values are stored
in contiguous memory locations. In case of objects of a class, the actual objects are
stored in heap segment.
One-Dimensional Arrays :
The general form of a one-dimensional array declaration is
type var_name[ ];
or
type[ ] var_name ;
An array declaration has two components: the type and the name. type declares the
element type of the array. The element type determines the data type of each
element that comprises the array. Like array of int type, we can also create an array
of other primitive data types like char, float, double..etc or user defined data
type(objects of a class).Thus, the element type for the array determines what type
of data the array will hold. Example : an array of reference to objects of the class
MyClass (a class created by user ) : MyClass myClassArray[];
Note :
The length of this array determines the length of the created array.
There is no need to write the new int [] part in the latest versions of JavaAccessing
Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with 0 and
ends at (total array size)-1. All the elements of array can be accessed using Java for
Loop.
for (int i=0; i<arr.length; i++)
System.out.println(“Element at index ” + I + “ : “ + arr[i]);
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other array. These are also known as Jagged Arrays. A
multidimensional array is created by appending one set of square brackets ([]) per
dimension. Examples:
int[ ] [ ] intArray= new int [10] [20]; //a 2-D array