Data Types in Java
Data Types in Java
Data Types in Java
Java is a strongly typed language so there must be a data type associated with every
variable declared. Mainly there are eight primitive data types which are used in the java.
Out of the eight data types used 4 are integer data types, 2 are float data types, one is
character type and last but not the least is boolean type data type. Now we shall see all
these data types in detail :
INTEGER TYPES
Integer data types are used for integral numbers i.e. the numbers that do not have
fractional parts. For Integer types there are four kind of data types are used in java, each
having different storage capactiy and range and based upon that they can be categorised
as under :
TYPE
byte
short
int
long
STORAGE
RANGE
NEED
(BYTES)
1
-128 to 127
2
-32768 to 32767
-2147,483,648 to
4
2147,483,647
9,223,372,036,854,775,808
8
to
-9,223,372,036,854,775,80
7
In java the ranges of the integer data types does not depend upon the machine on which
you are executing your java code, their ranges are fixed, but unlike, in C++ or C the
values of the integer data types changes if there is a change in the platform. Following
show the way how we can write various integer literals in java :
1. int literals are written in decimal notation as usual like 123 or -23445.
2. long literals are written in decimal notation but postfixed by an L, eg 234556L or
-56467776768L.
NB : Java does not have unsigned types.
FLOATING-POINT TYPES
Floating-point types are the numbers that are having fractional part. Based upon the
storage capacity and range they can be categorised into the following types :
TYPE
STORAGE
NEED (IN
BYTES)
RANGE
float
double
4
8
approx 3.40282237E+38 F
approx
1.79769312486231570E+308
D
Here, double corresponds to the fact that, it has double precision than that of float types,
that's why double are also referred as double precision numbers. For floating-point types,
we mostly use the double types, because of the fact that float has a less precision so it
may be incompatible for certain type of calculations that require more precision.
For writing float literals we just postfixes F after the number as 4343.45455F, and a
number not followed by F, will be simply termed as double by default.
BOOLEAN TYPES
Boolean types are usually used for checking the logical conditions. These data types have
two values true and false and also you cannot use integers instead of boolean values in
java as you use in C or C++.
If you will use if(z=0) statement, in C or C++ it will compile but in java it will not
compile and will give compilation error.
Identifiers represent names which can be assigned to variables, methods, and classes to
uniquely identify them. In java you can be creative in naming identifiers, but there are
some limitations such as, all Java identifiers are case-sensitive and must begin with a
letter, an underscore (_), or a dollar sign ($). Letters include both upper and lowercase
letters, identifier characters can include the numbers from 0 to 9 and finally we cannot
use Java defined keywords as identifiers. For e.g.
_shashi7, $r4remployee, programmer are some valid identifiers.
LITERALS
Literals are the constant values that are used in a program. These can include integers,
floating-point numbers, characters, boolean and string values. Following are the
examples of literals :
Integer Literals : 2, 3, -4, 5
Floating point Literals : 3.45, .0987, 943.45
Character Literals : 'h', 'k','1', '2'
VARIABLES IN JAVA
A variable may be defined as a storage location in memory for storing different data
types. Thus, every variable has a type so we can declare a variable as :
int sum;
double sum;
char name;
The keyword final suggests that you can assign the variable once, after that its value is set
once for all. The constant name should be in capital letters or upper case.
It is more common in java to declare constants that are available to multiple methods of
the class, such constants are called class constants. You can declare a class constant by
declaring them static final. For eg.
The class constant is defined outside the main method, that means it can be accessed by
all the methods of the same class.
OPERATORS IN JAVA
The basic arithmetic operators +, , *, / are used in Java for addition, subtraction,
multiplication and division. The / operator denotes integer division if both arguments are
integers, and floating-point division otherwise. The mod function is denoted by %. For
example, 19 / 2 is 9, 21 % 2 is 1, and 7.0 / 2 is 3.5.Note that integer division by 0 raises
an exception, whereas floating-point division by 0 yields an infinite result.You can use
the arithmetic operators in your variable initializations:
int p = 9
int q = 2 * p;
// The value of q is 18
There is a convenient shortcut for using binary arithmetic operators in an assignment. For
e.g.
p += 4;
is equal to
p = p + 4;
and can only appear when they are used inside expressions. The prefix form does the
addition first, the postfix form evaluates to the old value of the variable.
int p = 3;
int q = 3;
p++;
++q;
int x = 4 * p;
int y = 4 * q;
// x is 12, p is 8
// y is 16, q is 8
KEYWORDS
Keywords are predefined identifiers reserved by Java for a specific purpose and are used
only in a limited, specified manner. Java has a richer set of keywords than C or C++. The
following keywords are reserved for Java:
abstract
boolean
break
byte
byvalue
case
catch
char
class
const
continue
default
double
else
extend
false
final
finally
float
for
goto
if
implements
import
int
interface
long
native
new
null
package
private
protected
public
return
short
super
switch
synchronized
this
threadsafe
throw
transient
true
try
void
while
int p=7;
int q=1;
if((p==6)&&(q==1))
{
p=p+1;
q=q-1;
}
In the above e.g. the first condition p==6 is evaluated to false, so second condition q==1
is never evaluated.
Similarly, if p evaluates to true, then the value of p || q is automatically true, without
evaluating q.
Java also supports the ternary ?: operator that is occasionally useful. The expression
condition ? p : q evaluates to p if the condition is true, else it evaluates to q. For e.g.,
p>q?p:q
the above expression gives the value p if p is greater than q or else it will give q.
BITWISE OPERATORS
While working with any kinds of the integer types, we have the bitwise operators that can
directly work with the bits that make up the integers, i.e. you can use masking
techniques to get at individual bits in a number. Following are the basic bitwise operators
that are commonly used :
1. & (AND) Bitwise operator : A bitwise AND operation takes two binay
representations of same length and then performs the logical AND operation on the bits
of the binary numbers. If 1is logically ANDed with 1 the result is 1, else the result is 0.
For e.g.
00 10
1 0 11
_____________
ANDed 0 0 1 0
2. ~ (NOT) Bitwise operator : A NOT Bitwise operator is a unary operation that perform
logical negation on each bit. i.e it performs a one's complement on the binary
representation of the integers. The digits with 0 becomes 1 and vice-versa. For e.g.
NOT=
0011
11 00
0110
1011
__________
OR =
1 1 11
4. ^ (XOR) Bitwise operator : A bitwise XOR operation takes two binary representation
of same length and then performs logical XOR operation on bits of the binary numbers.
The result is 1 if both the binary digits are different else result is 0. For e.g.
0011
1001
_____________
XOR=1 0 1 0
The order of preceedence for the bitwise operators starting with the highest preceedence
first is given by | > ^ > &.
There are also >> and << operators, which shift a bit pattern to the right or left. These
operators are often convenient when you need to build up bit patterns to do bit masking.
int fourth_from_right = (p & (1 << 3)) >> 3;
There is even a >>> operator that fills the top bits with zero, whereas >> extends the sign
bit into the top bits. There is no <<< operator.
In above example the statements surrounded by the braces will be executed when num is
greater than or equal to 10.
if-else Statement
Java, like C and C++ also has if-else conditional statements which takes the form
if(condition is true)
{
//will execute statements if condition is true otherwise
control passes to else block
statment1;
statement2;
}
else
{
// will execute if condition is false
statement3;
}
{
Grade = "C";
result = "Average";
}
else
{
System.out.println("Failed");
}
LOOP CONTROL
In Java there are control structures that let you repeat statements. Such control structures
are called Loops. Loops can be further categorised as :
1. Indeterminate Loops
2. Determinate Loops
INDETERMINATE LOOPS
Loops in which you do not know how many times a loop should be processed are called
Indeterminate loops. Two types of indeterminate loops are following as under :
Firstly there is the while loop that only executes the body of the loop while a condition is
true. Its general form is:
while (condition)
{
statement1;
statement2;
}
The while loop will never execute if the condition is false. Its structure is quite very
similar to other languages like C and C++.
Secondly there is the do-while loop that executes the body of the loop at least once
irrespective of the condition is true or false. Just like other languages it has the following
form :
do
{
statement1;
statement2;
}while(condition);
DETERMINATE LOOPS
The for loop is a very common construct to support iteration that is controlled by a
counter or similar variable that is updated after every iteration. Like other languages it
has the form :
for(int j=0; j<10; j++)
{
System.out.println(j);
}
The above program prints numbers from 0-9.
In general, the first slot of the for loop contains the counter initialization, second for
testing the condition given and the last one is for updating the counter. Java like C, allows
almost any expression in the various slots of a for loop, but it's an unwritten rule that the
three slots of a for statement should only initialize, test, and update the same counter
variable.
SWITCH STATEMENT
Similar to the if-else branch, the switch statement is specifically designed to conditionally
switch among multiple alternatives. The syntax for the switch statement follows:
switch (input) {
Java Tutorialsase label1:
Statement1;
break;
Java Tutorialsase label2:
Statement2;
break;
default:
DefaultStatement;
}
The switch branch evaluates and compares input to all of the case label and branches the
programs execution to the matching case statement list. If no case label matches input,
the program branches to the DefaultStatement, if one has been defined (DefaultStatement
is optional). In switch a statement list is simply a series, or list, of statements. Unlike the
if-else branch, which directs program flow to a simple or compound statement, the switch
statement directs the flow to list of statements. When the program execution moves into
a case statement list, it continues from there in a sequential manner.
Note that the case labels must be integers. You cannot test strings. For example, the
following is an error:
String input = "anyvalue";
switch (input)
// wrong, show error
{
Java Tutorialsase "p":
//wrong, will show error
. . .
break;
. . .
}
programming style, the labeled break. Let us first look at the unlabeled break statement.
The break statement that you use to exit a switch can also be used to break out of a loop.
For example,
Java Tutorialslass DemoUnlabeledBreak
{
public static void main (String args[])
{
int i = 0;
do
{
System.out.println(demobreak);
i++;
if (i > 50)
break;
}
while (true);
}
}
In above example, an infinite do-while loop is created by setting the loop condition to
true. But here we incorporate the break statement to exit the loop when i is incremented
past 50.
Java also offers a labeled break statement that lets you break out of multiple nested loops.
Occasionally something weird happens inside a deeply nested loop. In that case, you may
want to break completely out of all the nested loops. It is inconvenient to program that
simply by adding extra conditions to the various loop tests.
Java Tutorialslass DemoLabelBreak
{
public static void main (String args[])
{
int i = Integer.parseInt(args[0]);
labelbreak:
while(true)
{
for(i=0;i<51;i++)
{
System.out.println(demobreak);
i++;
if (i > 50)
break labelbreak;
}
}
System.out.println("Undesired value of
}
}
i");
In above program if the value of i is greater than 50 is inputted by user than control will
come out of the loop and will pass to the very next statement after the loop.
The output of the program will print values 0 to 7, after the value of i become greater
than 7 next statement after continue will not be executed and its control will pass to the
header of the loop i.e in case of for loop the control will pass to incrementing slot till the
loop terminates.
In this example we have converted a simple integer 300 to a BigInteger type value and
assigned it to the num. Also note that we cannot use basic operators like +, -, /, * directly
on the big numbers, infact we have to use predefined methods like add(), multiply() in
order to combine the big numbers. For e.g.
BigInteger num = BigInteger.valueOf(300);
BigInteger p = num.add(BigInteger.valueOf(200));
p=num+200= 300+200=500
// it goes as
Some of the methods which are defined in java.math.BigInteger class and used more
commonly are :
It compares the value of the current BigInteger with the second and then returns an
integral value. If current number is greater than second than it will give a positive integer,
if equal it will return 0, else it will return a negative value.
static BigInteger valueOf(Long p)
ARRAYS
An array is a data structure that stores a collection of homogeneous(same type) values.
You can access each individual value of the array through an integer index. For example,
if arr is an array of integers, then arr[i] is the ith integer in the array. You can declare an
array variable by specifying the array type which is the element type followed by [] and
the array variable name. For example we can delare an array variable arr as
int[] arr; //please prefer this one
or
int arr[];
Above statement only declares the variable arr. It doesn't intiailize the arr with an actual
array, for that we have to use new operator to declare an array. For instance,
int[] arr = new int[50];
Above declaration creates an array of integer type which can accomodate 50 integers. In
Java too, like other programming languages, the index of array starts from 0 to (length-1).
In this case array enteries are numbered from 0 to 49. Also Java doesnt allow you to
specify the size of an empty array when declaring the array. You always must explicitly
set the size of the array with the new operator or by assigning a list of items to the array
on creation. If you try to access the element arr[50] (or any other index outside the range
0 ..49), then your program will terminate with an array index out of bounds exception.
As in other languages like C and C++ once you create an array, you cannot change its
size.
ANONYMOUS ARRAYS
Java can directly create an array object and supply initial values at the same time just like
other languagaes. For e.g.
int[] numbers = { 2, 3, 4, 5, 6, 7, 8 };
You do not call new when you declare an array using this approach.You can even
initialize an anonymous array in java like the following one:
new int[] { 11, 12, 13, 14, 15, 16, 17};
Above declaration allocates a new array and fills it with the values inside the braces and
counts the number of initial values then sets the array size accordingly. You can use this
syntax to reinitialize an array without creating a new variable. For example,
numbers = new int[] { 11, 12, 13, 14, 15, 16, 17 };
is a shorthand for
int[] anonymousarr = { 11, 12, 13, 14, 15, 16, 17 };
numbers = anonymousarr;
Once an array is created you can access its elements throught its index values.For
calculating the length of an array we use length() method viz. arrayname.length, gives the
length of the array. Following code snippet shows the very same:
Java Tutorialslass ArrayAccess
{
public static void main(String[] args)
{
int[] numbers={2, 3, 4, 5, 6, 7, 8};
System.out.println("The elements of the array are :");
for(int i=0;i<numbers.length;i++)
{
System.out.println(a[i]);
}
Here, we have use numbers. length to calculate the length of the array and a[i] gives the
elements of the array.
SORTING AN ARRAY
In java if you want to sort an array, you can use sort() method defined in the
java.util.Arrays class. You can use the method both on the primitive type as well as on
the object type arrays. For example,
int [] arr = new int[100];
/* some
logic */
Arrays.sort(arr);
Following program shows how to use sort() method for sorting an array :
import java.util.Arrays;
Java Tutorialslass sort
{
public static void main(String args[])
{
String[] arr=new String[]{"shashi", "employee", "r4r", "software",
"engineer"};
Arrays.sort(arr);
for(int i=0; i<arr.length;i++)
System.out.println(arr[i]);
}
}
SEARCH IN ARRAYS
In java for searching an element in an array we have a predefined method in the
java.util.Arrays class, which searches for the element by using the binary search
technique. Its general syntax is given as :
static int binarySearch(type[] arr, valuetobesearched);
For searching the above method takes a sorted array of any data type and the value to be
searched as parameters. This method will return an integer value, which will be index of
the element if it exists in the array, otherwise, it will give a negative value at which the
element can be stored. Following code snippet will help you understand the concept
better :
import java.util.Arrays;
Java Tutorialslass sort
{
public static void main(String args[])
{
String[] arr=new String[]{"shashi", "employee", "r4r", "software",
"engineer"};
Arrays.sort(arr);
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
int j=Arrays.binarySearch(arr,"r4r");
System.out.println("The element is at"+j);
System.out.println("The element is:"+arr[j]);
}
}
In above program we have stored the value returned by the binarySearch() method in an
integer variable i.e j and then we printed the index of the element and its value.
static fields Static fields are common to any object of the same class, only one static field
exists for one class.
static methods: Static methods are methods that do not affect a specific object.
nested classes:It is useful to contain a class within another one if it cannot be accessed
outside of the class.
Java Tutorialsonstructors: It is a special method that generates a new object and have
same name as of a class.
Example,
Java Tutorialslass ShowClass
{
private static int i=0;
//defined a static field
int j=1;
ShowClass()
{
//default constructor declaration
}
public static void show()
//defined a static method
{
System.out.println("The value of i is :"+i);
//System.out.println("The value of j is :"+j);
//this statement
will cause compilation error, since j is non-static
}
public static void main(String args[])
{
ShowClass sc=new ShowClass();
show();
//we don't have to
create an object to call a static method
sc.show();
}
}
2. Static Inner Classes : Static member classes are the most common type of nested
classes. A nested class is defined inside the body of an enclosing class and should only be
present to assist the enclosing class. There is no boundation to the depth of nesting of
classes but it is quite very rare to see more than one level of such classes. Static member
classes are also know as static inner classes.The syntax of static member classes is shown
in following code snippet,
Java Tutorialslass InnerStaticClassExample
// main class
{
public static void main(String args[])
{
shape.Rectangle obj=new shape.Rectangle(4,7);
// creating
object for inner class Rectangle, using dot notation
obj.area();
//calculating the area of Rectangle
System.out.println("The value of x is: "+t.a);
//printing the variable defined in Rectangle
obj.new Java Tutorialsircle(7).area();
//calculating the area of circle using the object of Rectangle
System.out.println("The value of y is :"+obj.new Java
Tutorialsircle(7).y);
//printing the value of y
}
Java Tutorialslass Shape
//top level class
{
public static class Rectangle
//staticinner class, whose enclosing class is Shape
{
int a=10;
int length;
int breadth;
public Rectangle(int length, int breadth)
//constructor of Rectangle
{
this.length=length;
this.breadth=breadth;
}
public void area()
//this
method calculates the area of rectangle
{
System.out.println("The area of rectangle is :"+length*breadth);
}
public class Java Tutorialsircle
//
simple member class Circle, whose enclosing class is Rectangle which is
static
{
int radius;
int y=27;
public Java Tutorialsircle(int radius)
//
constructor of Circle
{
this.radius=radius;
}
public void area()
{
System.out.println("The area of circle is: "+Math.PI*radius*radius);
}
}
}
}
}
3. Local Classes : A local class is a class that is defined within a block of Java code. A
local class is declared inside a method body while member classes are declared inside a
class. It is only accessible only to the method in which it is declared, which makes local
classes less generally useful than non-static inner classes. While local classes are
probably most frequently defined within methods and constructors, they can also be
defined inside static initializer blocks and instance initializers. Since an object of a local
class must be internally linked to an object of the enclosing class,therefore object of the
local class cannot exist in the absence of an object of the enclosing class, thus a local
class is truly an inner class.
The most important benefit of using local classes has to do with accessing the members
of enclosing classes. Just like with member classes, methods of a local class have direct
access to all the members of the enclosing classes, including private members. Thus, the
use of local classes may eliminate the requirement to connect objects together via
constructor parameters. The methods in a local class can access local variables and
method parameters only if they are declared final. As with local variables, local classes
cannot be declared public, protected, private, or static. Following code will show the
syntax of local classes.
Java Tutorialslass Shape
// top class
{
int i=5;
Java Tutorialslass Rectangle
// member class
{
int a=10;
// taken a variable a
int length;
int breadth;
public Rectangle(int length, int breadth)
// constructor
declaration for Rectangle class
{
this.length=length;
this.breadth=breadth;
}
public void Area()
// defined a method Area(), in
which we defined a local class Circle
{
System.out.println("The area of rectangle is :"+length*breadth);
Java Tutorialslass Java Tutorialsircle
//local class declaration
int radius;
int y=27;
public Java Tutorialsircle(int radius)
local class
{
this.radius=radius;
}
public void Area()
//method Area
{
System.out.println("The area of circle is:
"+Math.PI*radius*radius);
//printing area of
System.out.println("The value of a is given
// printing the value
of a and i defined in Rectangle and shape
System.out.println("The value of i is given
// which shows local classes
have access to members of enclosing class
// constructor of
}
// closing
Area() method
}
// closing
local class Circle
final Java Tutorialsircle obj=new Java Tutorialsircle(7);
//
creating object of Circle class
obj.Area();
// calling Area() method
System.out.println("The class path of enclosing class is given
by :"+getClass().getName());
//printing
the class name for Rectangle class
System.out.println("The class path is given
by :"+obj.getClass().getName());
//printing
the class name for local class Circle
System.out.println("The value of a declared in Rectangle is given
by :"+Rectangle.this.a);
//printing the
value of variable a defined in class
}
}
}
Java Tutorialslass man2
class
{
public static void main(String args[])
{
new Shape().new Rectangle(4,5).Area();
method defined in class Rectangle
}
its object with top class Shape
}
// controlling
//invoking Area()
//by associating
class without a name. The main advantage of using an anonymous class is Encapsulation.
An anonymous class is, in a way, the ultimate in private object oriented encapsulation. It
is defined exactly where it is needed, it can never be used anywhere else, and it is having
a total local scope. Anonymous classes provide a very clear syntax for implementing
event listeners in GUI programming, and are very much useful for implementing method
parameters and returning objects.
One of the key advantages of using anonymous classes is that it relieves the programmer
from defining large numbers of special purpose classes. Such classes are used only once
and are defined right where the action is taking place, and never used again. Also,
anonymous classes have access to all data and methods of their containing classes,
including private members which means that for small highly localized tasks, they
generally need less initialization. The syntax of anonymous classes have one of the two
forms which are shown below :
1. Interface Based : The syntax for declaring interface based anonymous class is given as,
new InterfaceName()
{
// ClassBody
}
An interface based anonymous class has to implement the entire interface on which it is
based upon, to understand it better, take a look at the following code snippet :
Java Tutorialslass AnonymousClassExample
{
public static void main(String args[])
{
Runnable obj = new Runnable()
// anonymous class is
defined here
{
private static final int ARRAY_LIMIT =
50;
private int[] arr = new int[ARRAY_LIMIT];
// instance intialization code
{
for(int i=0; i< arr.length; i++)
arr[i] = i;
}
public void run()
{
int sum = 0;
for(int i=0; i<ARRAY_LIMIT; i++)
sum = sum + arr[i];
System.out.println("The sum of the
array elements is :"+sum); // printing the sum of array
}
};
obj.run();
2. Class Based Anonymous Class : The syntax for class based anonoymous class is,
new ClassName (optional Argument_List)
{
// Class Body
}
A class based anonymous class has access to its base class methods and members and it
can override its members, just like any other subclass. To understand more take a look at
this code snippet,
Java Tutorialslass AnonymousClassExample2
{
ShowMessage anonymous_obj = new ShowMessage("R4R Example")
{
public void display()
{
System.out.println("anonymous override"+"member display ShowMessage
Output :"+msg);
}
};
public AnonymousClassExample2()
{
ShowMessage obj = new ShowMessage("hi!!!!!!");
obj.display();
ShowMessage anonymous_obj2 =new ShowMessage("hi!!!!!!!")
{
public void
display()
{
System.out.println("anonymous override"+"local display ShowMessage
output :"+msg);
}
};
anonymous_obj2.display();
this.anonymous_obj.display();
}
public static void main(String args[])
{
AnonymousClassExample2 example = new AnonymousClassExample2();
}
}
Java Tutorialslass ShowMessage
{
String msg="";
public ShowMessage(String msg)
{
this.msg=msg;
}
public void display()
{
System.out.println("SimpleClass output :"+msg);
}
}
private modifier : The private modifier is used to make a java element least visible. The
private modifier cannot be used for a top-level class, and can be applied only to the
members of a top-level class viz. instance variables, methods. A private member of a
class can only be accessed from the code inside the same class in which this member is
declared. It cannot be accessed from any other class or from a subclass of the class in
which it is declared.The code snippet shows the syntax for using private modifier,
Java Tutorialslass ModifierDemo
{
private int i=10;
public int j=5;
}
Java Tutorialslass PublicModifier
{
public static void main(String[] args)
{
ModifierDemo obj=new ModifierDemo();
System.out.println("The value of i is :"+obj.i);
// cause
a compile error as i's defined private.
System.out.println("The value of j is :"+obj.j);
//
print the value of j =5
}
}
The accessibility of i have been kept private so we can't directly access it merely by
creating the object of the class in which it is defined, so it will cause a compiler error, but
if we comment out this line from prog. then we will get the value of j=5 as output.
protected modifier : The protected modifier makes a class member more visible than
private modifier but less accessible than public modifier. This modifier may be applied
only to class members viz. variables, methods, and inner classesbut not to the class
itself. A class member declared protected is visible to the following elements:
1.The classes in the same package that contains the class that owns the protected member.
2.The subclasses of the class that owns the protected member. These subclasses have
access even if they are not in the same package as the parent class.
The usage of protected modifier can be shown as,
Java Tutorialslass ModifierDemo
{
private int i=10;
protected int j=5;
}
Java Tutorialslass PublicModifier extends ModifierDemo
{
public static void main(String[] args)
{
PublicModifier obj=new PublicModifier();
System.out.println("The value of i is :"+obj.i);
a compile error as i's defined private.
// cause
//
default modifier : In java we cannot specify any modifier for the variables inside a
method, and also we cannot specify the protected modifier for a class. When we do not
specify any access modifier for an element, it is implied that the access is default. It can
be applied to a class, a variable, or a method. A class or a class member declared default
i.e. with no access modifier specified is accessible from anywhere in the same package in
which the accessed class exists. Consider the following code fragment:
package example;
Java Tutorialslass ShowExample
{
private int i=10;
void Show()
{
System.out.println("The value of
}
}
i is :"+i);
Above code contains a method of default modifier show returning void, and it is
contained in a package called example.
package example2;
Java Tutorialslass ReviewExample extends ShowExample
{
Show();
// will cause compiler error
}
The Show() method called in class ReviewExample causes a compiler error, as Show()
method is declared default in ShowExample which is in a totally different package and,
it is obvious that a default method cannot be accessed from a different package other than
in which it is defined.
final int i = 5;
final double d = 2.5;
the above declaration tell us that the values of i and d will remain constant throughout
the course of the program and cannot be changed. For understanding the final modifier in
terms of classes and methods, consider the following code snippet,
Java Tutorialslass ShowFinal
{
private final int i=10;
void Java Tutorialsalculate(int i)
{
System.out.println("The value of i is:"+i);
}
}
Java Tutorialslass FinalExample
{
public static void main(String args[])
{
final ShowFinal obj=new ShowFinal();
//obj.i=7;
//compilation error as value of i is final can't be
changed
obj.Calculate(10);
}
}
2. The static Modifier : The static modifier can be applied to variables, methods, and a
block of code inside a method. The static elements of a class are visible to all the
instances of that class. Thus, if one instance of the class makes a change to a static
element, all the instances will see that change. A static variable belongs to the class, not
to a specific instance of the class, therefore, is initialized when the class is loaded. A
static variable may be referenced by an instance of the class in which it is declared or by
the class name itself. For better understanding, consider the following code snippet,
Java Tutorialslass StaticModifier
{
static int static_counter=0;
int Java Tutorialsounter =0;
public StaticModifier()
{
static_counter++;
System.out.println("The value of static counter is :"+static_counter);
Java Tutorialsounter++;
System.out.println("The value of normal counter is :"+counter);
}
}
Java Tutorialslass StaticModifierExample
{
public static void main(String args[])
{
StaticModifier obj=new StaticModifier();
// static_counter value=1,
counter =1
Just like a static variable, a static method also belongs to the class in which it is defined
and not to a specific instance of the class. Therefore, a static method can only access the
static members of the class. In other words, a method declared static in a class cannot
access the non-static variables and methods of the class. Because a static method does not
belong to a particular instance of the class in which it is defined, it can be called even
before a single instance of the class exists. For example, every Java application has a
method main(), which is the entry point for the application execution. It is executed
without instantiating the class in which it exists. This can be explained by the following
example,
Java Tutorialslass StaticModifierExample2
{
static int a=10;
static int b=20;
static void sum()
{
System.out.println("The value of sum of two numbers is :"+(a+b));
}
public static void main(String args[])
{
sum();
// static method is called before instantiating any
object of StaticModifierExample2
}
}
3. The abstract Modifier : The abstract modifier may be applied to a class or a method,
but not to a variable. A class which is declared abstract cannot be instantiated .i.e. its
object cannot be created because it is not fully implemented. There is a relationship
between an abstract class and an abstract method which is, if a class has one or more
abstract methods, it must be declared abstract. A class may define abstract methods in any
of the following ways:
1. A class may have one or more abstract methods defined in it.
2. A class might have inherited one or more abstract methods from its superclass, and has
not provided implementation for all or some of them.
3. A class declares that it implements an interface, but does not provide implementation
for at least one method in the interface.
In above shown cases, the class must be declared abstract.But, if there is no abstract
method in the class, it could still be declared abstract but in this case the class cannot be
instantiated.
Following code snippet will give a good idea about the abstract modifier,
A abstract class is some what opposite to the final class. A final class cannot be extended
or inherited, whereas an abstract class must be extended, before it can be instantiated. An
abstract class or an abstract method means its not fully implemented .i.e if you want to
use it, you have to implement it.
4. The native Modifier : In java applications, sometimes we will want to use a method
that exists outside the JVM. In this scenario, the native modifier can help, native modifier
can only apply to a method. Just as the abstract keyword, the native keyword indicates
that the implementation of the method exists elsewhere. In case of abstract, the
implementation of a method may exist in a subclass of the class in which the abstract
method is declared.
But in the case of native, the implementation of the method exists in a library outside the
JVM. The native method is usually implemented in a non-Java language such as C or C+
+. Before a native method can be invoked, a library that contains the method must be
loaded and that library is loaded by making the following system call:
System.loadLibrary("libraryName");
To declare a native method, precede the method with the native modifier, but do not
define any body for the method. For example:
public native void Nativemethod() ;
After you declare a native method, you must write the native method and follow a
complex series of steps to link it with your Java code. For example, the following code
fragment presents an example of loading a library named NativeMethodDef which
contains a method named NativeMethod():
Java Tutorialslass NativeModifierExample
{
native void NativeMethod();
static
{
System.loadLibrary("NativeMethodDef");
}
}
Note that the library is loaded in a static code block which suggest that the library is
loaded at the class load time, so it is there when a call to the native method is made. One
can use the native method in the same way as we use a non-native method. For example,
the following two lines of code would invoke the native method,
NativeModifierExample obj = new NativeModifierExample();
obj.NativeMethod();
5. The transient Modifier : In an java based application, while is in running mode, the
objects are put in the random access memory (RAM) of the computer.That determines the
scope and life of the object. However, if an object may be stored in persistent storage
outside the JVM, for later use by the same application or by some another application.
The process of storing an object is called serialization. For an object to be serializable,
the corresponding class must implement the interface Serializable. Thus, the transient
modifier is related to storing an object in persistant storage. Such storage is called the
objects persistent state. A variable declared transient is not stored, and hence does not
become part of the objects persistent state.The transient modifier can be used to prevent
a security-sensitive piece of data from copying to a source where there is no security
mechanism exists.
The transient modifier can only be applied to instance variables. When you are declaring
an instance variable transient, you are telling the Java Virtual Machine not to store this
variable when the object, in which it is declared, is serialized. Thus, when an instance
variable is declared as transient, then its value need not persist when an object is stored.
For example,
Java Tutorialslass TransientModifier
{
transient int num1;
// variable will not persist
int num2;
// variable will persist
}
6. The volatile Modifier : In java the volatile modifier only applies to instance variables
just like the transient modifier. The variables declared volatile are subject to
asynchronous modifications. Thus we can say that, declaring a variable volatile tells the
compiler that this variable might be changed unexpectedly by other parts of the program.
So, the compiler takes some special precautions to keep this variable properly updated,
volatile variables are generally used in multithreaded or multiprocessor environments.
The volatile modifier tells the accessing thread that it should synchronize its private copy
of the variable with the original copy in the memory. Consider the following example for
the better understanding,
Java Tutorialslass VolatileModifier extends Thread
{
private volatile static int someVal;
// declared a volatile
variable
VolatileModifier(String str)
{
super(str);
}
public void run()
// implementing the run method for
threads
{
for (int j=0; j<7; j++)
{
try
{
System.out.println(getName() + "->"+i);
if(getName().equals("r4r thread1"))
{
someVal=7;
}
if(getName().equals("r4r thread2"))
is :"+someVal);
}
Thread.sleep(2000);
Java Tutorialsatch(InterruptedException e)
e.printStackTrace();
}
}
Java Tutorialslass VolatileModifierExample
{
public static void main(String args[])
{
Thread t=new VolatileModifier("r4r thread1");
object
Thread t1=new VolatileModifier("r4r thread2");
t.start();
execution of thread
t1.start();
}
}
// creating a thread
// starting the
memory from objects that are no longer referenced. The importance of this is that you do
not need to code the memory management into your application program, also you have
no control over when the garbage collector runs. While coding in some application we
can do following things in order to help the memory management through the garbage
collector :
1. Firstly, make an object eligible for the garbage collection, as garbage collector will
only free memory from an eligible object.
2. Also make a request for garbage collection by making a system call to the garbage
collector via, System.gc();.
We can also invoke the gc() method by using an instance of the Runtime class that a
running program always has. It is contained in java.lang package, we can get hold of this
instance by calling the static method getRuntime() of the Runtime class. The following
example will show how we can invoke gc() method via Runtime class and some other
runtime tasks,
Java Tutorialslass garc
{
public static void main(String args[])
{
Runtime runtimeobject = Runtime.getRuntime();
// creating an
object of Runtime class
// this statement returns the total memory available in bytes to
jvm
System.out.println("The value of total memory of jvm
is :"+runtimeobject.totalMemory());
// this statement returns the free memory available in bytes to jvm
System.out.println("The value of free memory availabe to jvm
is :"+runtimeobject.freeMemory());
runtimeobject.gc();
// calling gc method on Runtime object
System.out.println("The amount of memory allocated to jvm after
calling gc is :"+runtimeobject.freeMemory());
}
}
It should be noted that a call to the garbage collector gives no guarantee that the memory
will be free. There can be a situation that the JVM in which your program is running did
not even implement the gc() method. The Java language also allows a dummy gc()
method, the basic requirement for garbage collection is that you must make your object
eligible for garbage collection. An object is considered eligible for garbage collection if
there is no reference pointing to it. We can remove the references to an object in two
ways:
1. By setting the object reference variable pointing to the object to null, such as,
GCclass object = new GCclass();
object = null;
2. Secondly by reassign a reference variable of an object to another object i.e. if a
reference variable object is pointing to an object of the GCclass, you can free this object
from this reference by pointing the reference to another object by the following statement
myObject = new GC2class();
Now, the object reference GCobject is pointing to an object of the class GC2class and not
to an object of GCclass, to which it was pointing earlier.
In java if an object has no object references pointing to it, can be deleted by the garbage
collector to regain the memory. On the other hand, if an object has a finalize() method
then it will be executed before regaining the memory in order to give the object a last
chance to clean up itself i.e. to release all the resources that the object was using. The
finalize() method is inherited from the Object class by any class you define. The syntax
of the finalize() method declaration is shown below,
protected void finalize()
Inside this finalize() method you must specify the actions that are needed to be performed
before an object is recycled. The finalize() is only called just prior to garbage collection
to if any resource was left to be released .It is advised that not use finalize() method just
to be on a safer side. The program must release the resources in program itself, since
garbage collectors run is not guaranteed, so finalize() execution will also not be
guaranteed. The Java programming language specifies that the finalize() method will be
called before the object memory is reclaimed, but it does not guarantee exactly when it
will happen. Note that the finalize() method which a class inherited does not do
anything,thus, if you want your object to clean up itself, you have to override the
finalize() method. Also remember that, the finalize() method is never invoked more than
once by a Java virtual machine for any given object. Generally, it is considered a good
programming practice to invoke the finalize() of the superclass, i.e.,
protected void finalize()
{
super.finalize();
// some other logic
}
The following code snippet will guide you how to use finalize() method during the
garbage collection,
Java Tutorialslass UsingFinalize
{
public static void main(String[] args)
{
Runtime rt = Runtime.getRuntime();
System.out.println("Total available
memory:"+rt.totalMemory());
System.out.println("Available Free Memory: " +
rt.freeMemory());
for(int j=0; j<1000; j++ )
{
FinalizeMethod obj = new FinalizeMethod(j);
}