You are on page 1of 36

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.

Java TutorialsHARACTER TYPES


Java Tutorialsharacter type are the alphabets which are written in single quotes. It is
basically a 16-bit unicode character, its minimum value is \u0000(which equals to 0) and
maximum is \nFFFF(which equals to 65,535). Since it is a 16-bit unicode character so it
takes 2 bytes in the memory upon declaration, while in C a character literal takes 1 byte
in the memory. For eg.
char 'H';
is a character.

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'

Boolean Literals : true, false


String Literals : "shashi", "r4r", "12343"

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;

RULES FOR DECLARING VARIABLES :


1. A variable name is decalared with a letter at begining and then can be a sequence of
letters and digits.
2. Symbols like + or @ cannot be used inside a variable name and also there can't be any
space in variable name.
3. All characters in the variable are case sensitive and length is essentially unlimited.
4. You cannot use java keywords as variable names.

ASSIGNMENT AND INITIALIZATION


After you declare a variable you must initialize it explicitly, as uninitialized varibale can
never be used.
int number;
// this is declaration
number=10;
// this is assignment
In java you can declare a variable and assigned it value upon declaration, i.e. intialization
of variable
int number=10; // this is initialization
You cannot declare two varibles of same name in the same scope.

Java TutorialsONSTANTS IN JAVA


In java you use the keyword final declare a constant. For eg.
public class Java TutorialsonstExample
{
public static void main(String args[])
{
final int NUM = 10;
int num1= 20;
int num3=30;
System.out.println("Multiplication is given by" +(NUM*num1*num3));
}
}

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.

public class Java TutorialsonstExample


{
public static final NUM=10;
public static void main(String args[])
{
int num1=20;
int num3=30;
System.out.println("Multiplication is given by"+(NUM*num1*num3));
}
}

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;

INCREMENT AND DECREMENT OPERATORS


One of the most common operations with a numeric variable is to increment or decrement
it value by 1. Java like in C and C++, has both increment and decrement operators:
p++ adds 1 to the current value of the variable p, and p-- subtracts 1 from it. For e.g.
int = 6;
p++;
changes p to 7. Because these operators change the value of a variable, they cannot be
applied to numbers themselves. For example, 7++ is not a legal statement in java.
There are actually two forms of these operators, in above examples we have seen the
postfix form of the operator that is placed after the operand. There is also a prefix form, +
+p. Both change the value of the variable by 1. But there is difference between the two

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

RELATIONAL AND BOOLEAN OPERATORS


Java has the full complement of relational operators. For testing the equality you use a
double equal sign ==. For example, the value of 5 == 6, is false.
We use a != for inequality. For e.g. the value of the following evaluates to true
3 != 7 is true.
Next we have have the < (less than), > (greater than), <= (less than or equal), and
>=(greater than or equal) operators.
Java also uses && for the logical AND operator and || for the logical OR operator. As you
can easily remember from the != operator, the exclamation point ! is the logical negation
operator. The && and || operators are evaluated in short circuit fashion. This means that
when we have an expression like:
p && q
if the truth value of the expression p has been determined to false, the value for the
expression q is not calculated. For example consider the following expression

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

3. | (OR ) Bitwise operator : A bitwise OR operation takes two binary representations of


same length and then performs logical OR operation on bits of the binary numbers. If 1 is
logically OR with 1 or 0 the result is 1 and if 0 is OR with 0 the result is zero. For eg.

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.

Java TutorialsONTROL FLOW IN JAVA


Java supports both conditional statements and loops to determine control flow just like C
and C++. First we deal with the conditional statements and then move on to loops. In end
we discuss the somewhat cumbersome switch statement that we can use when we have to
test for many values of a single expression.
BLOCK SCOPE
A block or compound statement is any number of simple Java statements that are
surrounded by a pair of braces. Blocks define the scope of your variables and can be
nested inside one another. Here is a block that is nested inside the block of the main
method.
public static void main(String[] args)
{
int p;
. . .
{
int q;
. . .
} // q's scope is upto here
}

It is not possible to declare same named variables in two nested blocks.

Java TutorialsONDITIONAL STATEMENTS


The conditional statement in Java has the form if (condition) statement, just like in C
and C++. In Java you will often execute multiple statements when a single condition is
true. For this you use a block statement that takes the form:
{
statement1;
statement2;
. . .
}
For instance,
if (num >= 10)
{
System.out.println("The value of num is :"+num);
}

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;
}

if-else if-else Statement


Java uses this statement for the execution of the multiple alternatives and is quite
common, for example
if (totalmarks >= 400)
{
Grade = "A";
result = "Excellent";
}
else if(totalmarks>=300)
{
Grade = "B";
result = "Good";
}
else if (totalmarks>=200)

{
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;
. . .
}

Using break, continue for breaking the Control Flow


break Statement
In Java we have goto as a reserved keyword, but the designers of java decided not to
include it in the language. In general, goto statements are considered poor style of
programming. But some programmers argue that goto is useful for an occasional jump
out of a loop. The Java designers gave it a nod and added a new statement to support this

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.

Java Tutorialsontinue Statement


Another useful statement that works similarly to the break statement is the continue
statement. Unlike break, the continue statement is only useful when working with loops
and has no relation to the switch branch. The continue statement works like the break
statement in that it jumps out of the current iteration of a loop. The difference with
continue is that program execution is restored to the test condition of the loop while break
jumps completely out of a loop. Use break when you want to jump out and terminate a
loop, and use continue when you want to jump immediately to the next iteration of the
loop.
Java Tutorialslass Java Tutorialsontinued
{
public static void main(String args[])
{
int a=0;
for(int i=0;i<10;i++)
{
if(i>7)
Java Tutorialsontinue;
a=i;
System.out.println("The value of a is:"+a);
}
}
}

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.

BIG NUMBERS IN JAVA


While programming if the precision of the integers and floating point number is not
according to the requirements, then we can use the big numbers defined in java. Actually,
the big numbers are contained in java.math package, BigInteger is used for
manipulating the precision of the integral values while BigDecimal is used for the
floating point numbers. The method valueOf(), defined in the package can turn any
ordinary number to a big number. For example,
BigInteger num = BigInteger.valueOf(300);

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 :

BigInteger add(BigInteger second)


// returns the sum
of current BigInteger with the second
BigInteger multiply(BigInteger second)
// returns the
multiplication of current BigInteger with the second
BigInteger divide(BigInteger second)
// returns the
division of current BigInteger with the second
BigInteger subrtact(BigInteger second)
// returns the
subtraction of current BigInteger with the second
BigInteger mod(BigInteger second)
// return the mod
value of current BigInteger with the second
int Java TutorialsompareTo(BigInteger second)

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)

It converts an integer number to the Big Integer type number.


Similarly we can use BigDecimal class to manipulating the precision of the floating point
numbers. The frequent methods which are defined in the java.math.BigDecimal class
are :
BigDecimal add(BigDecimal second)
// returns the sum
of current BigDecimal with the second
BigDecimal multiply(BigDecimal second)
// returns the
multiplication of current BigDecimal with the second
BigDecimal divide(BigDecimal second, int roundoff mode)//returns the
divison of current BigDecimal with
second one with roundoff digits
BigDecimal subrtact(BigDecimal second)
// returns the
subtraction of current BigDecimal with the second
int Java TutorialsompareTo(BigDecimal second)
//
return an integer after comparing the two BigDecimal type numbers
static BigDecimal valueOf(Long p)
// convert an
simple number to the BigDecimal type number
static BigDecimal valueOf(Long p, int scale)
// converts an simple
to the BigDecimal number x /10^scale

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]);
}
}

Java TutorialsOPYING ARRAYS


In java if you want to copy all values of one array to another, you have to use the
arraycopy method defined in the java.lang.System class. The general form to call this
method is :
System.arraycopy(copyfromarray, startingindex, copytoarray, fromindex,
numberofelements);
Following example gives you the brief knowledge about how to use arraycopy() method:
Java Tutorialslass Java Tutorialsopyarr
{
public static void main(String args[])
{

String[] arr=new String[]{"shashi", "employee", "r4r", "software",


"engineer"};
String[] arr1=new String[3];
System.arraycopy(arr,0,arr1,0,3);
System.out.println("The contents of new array :");
for(int i=0;i<arr1.length;i++)
System.out.println(arr1[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.

Java TutorialsOMMAND LINE ARGUMENTS IN JAVA


Every Java program has a main method in which a string of array i.e.,String[] args is
passed as a parameter, and thus arguments can specified on the command line.i.e. at the
runtime. Following code snippet describes how to pass command line arguments in java:

Java Tutorialslass Java Tutorialsmdparameters


{
public static void main(String[] args)
{
int num1, num2;
int sum;;
num1 = Integer.parseInt(args[0]);
num2 = Integer.parseInt(args[1]);
sum = num1 + num2;
System.out.println("You have passed command line
arguments :"+args[0]+","+args[1]);
System.out.println("The sum of the numbers is given by :"+sum);
}
}

What are classes and objects in java?


In object-oriented programming languages like Java, a class is a construct that is used as
a template to create objects of that class. This construct describes the state and behaviour
that the objects of the class share. Since in Java we cannot do anything without class, so
when we write a source code in java we are actually creating a class but not object.
Writing a class is called implementing a class and has two main components :the class
declaration and the class body. Class declaration contains name of the class and other
attributes like access modifiers, whereas class body consists of various methods,
variables, and the logic of the code. The body of a class is contained within the
curly{}braces, can be declared as :
access-modifier class ClassName
{
//some variables
// methods
// logic of code
}
Objects in java are the entities in the real world problem, and are the building blocks of
any Java program. Whenever we write a source code, we are writting a class and code for
creating the objects from that class. Thus, when a program is running objects are created
for doing their specific jobs for which they have been created. Thus, we can say that a
class is a template that we write and objects are created from the class. In technical terms
we can say that an object is instantiated from a class and this process is called
instantiation, that's why objects are also called the instances of the class.

What are main components of a class ?


Every class in Java have the following components :
fields: Fields are variables that held data specific to each object. For e.g., a student may
have an ID number, also known as member variables.
methods: Methods perform operations on an object. For e.g., a student may have to see
his/her marks.

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();
}
}

What are different types of classes in java ?


Java possesses five different types of class constructs and it is good to know where to use
each type. The various class types used in java are the following :
1. Top Level Classes : A top level class is the one that is present on the top in the
hierarchy of class design as without it one can not develop software at all. An example of
top level class is given as,
Java Tutorialslass r4r
// top level class
{
public static void main(String args[])
{
// some logic
}
}

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. Non-Static Inner(member) Classes : There is a very little difference between the


static inner classes and non-static inner classes, but in terms of their functionalities both
are very different. In java each instance of the inner class is implicitly associated with an
instance of its enclosing class which allows the inner class to directly access the nonstatic member variables and functions of its enclosing class. A non-static inner class
maintains a reference to its enclosing class, an instance of a non-static inner class can not
be created unless there is an instance of the enclosing class. Instances of the inner class
maintain a reference to their enclosing instance which is assigned automatically upon
object creation. If your member class doesn't require access to the enclosing instance
make it static to save resources. Because a non-static inner class cannot exist without an
enclosing class's instance it is very rare to see non-static inner classes that aren't private
or package protected. Static member classes are frequently declared public. The syntax
and usage of non-static inner classes can be shown via the following code snippet,
Java Tutorialslass NonStaticInnerExample
{
public static void main(String args[])
{
new Addition().sum();
// creating the object of
Addition class and calling sum method on it.
new Addition().new Addition1().sum();
// creating the
object of Addition1 class using the object of
Addition class
int d=new Addition().a;
// storing
value of a in d
int e=new exem().new Addition1().c;
// storing value of
c in e
System.out.println("the value of a in outer class is:"+d);
//printing values of d and e
System.out.println("the value of c in inner class is:"+e);
}
}
Java Tutorialslass Addition
// enclosing or
top level class
{
int a=10;
int b=20;
void sum()
{
System.out.println("the sum of two numbers in enclosing class is:"+
(a+b));
}
Java Tutorialslass Addition1
// Non-Static
member class
{

int Java Tutorials=70;


void sum()
{
System.out.println("The sum of three numbers in inner class
is :"+(a+b+c));
}
}
}

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

defined in local class


circle
by :"+a);
by :"+i);

}
// 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

5. Anonymous Classes : Anonymous classes in the Java programming language are


the classes without names thus, we can say, an anonymous class is essentially a local

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
}
};

// anonymous class ends here

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);
}
}

What are access modifiers in java ?


Access modifiers determines the accessibility scope of the Java elements that are being
modified. If we not explicitly use an access modifier with a Java element, the element
implicitly has the default access modifier. The explicit access modifiers may be used with
a class and its members. They cannot be used with the variables inside a method.
The Java has three explicit access modifiers viz. public, private and protected, and also
has a default modifier, which is used when you do not explicitly specify a modifier.
public modifier : The public modifier makes an element most visible, it can be applied
to various classes and their members (instance variable and methods). The elements
declared public can be accessed from anywhere in the java application. That is why you
declare the main method of any application public so that it may be invoked from any
Java runtime environment. The syntax for declaring and using public modifiers within
java program can be shown as:
Java Tutorialslass ModifierDemo
{
public int i;
public ModifierDemo(int i)
{
this.i=i;
System.out.println("the value of i is :"+i);
}
}
Java Tutorialslass PublicModifier
{
public static void main(String[] args)
{
ModifierDemo obj=new ModifierDemo(10);
}
}

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

System.out.println("The value of j is :"+obj.j);


print the value of j =5, as j is declared protected
}
}

//

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.

What are Usage Modifiers in java ?


In java there are some modifiers that are not access modifiers, still they can modify the
way a class or a class member is to be used, we call such modifiers the usage modifiers.
Following are usage modifiers used in java :
1. The final Modifier : The final modifier can be applied to a class, a method or a
variable. In general if the an element declared final, is a variable, it means that the value
of the variable is constant, and cannot be changed. If a class is declared final, it means the
class cannot be inherited, and also the final method cannot be overridden. It can be
declared as,

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

StaticModifier obj1=new StaticModifier();


// static_counter value=2,
counter =1
//Since the modifier of static_counter is static, which is available to
all the instances of the class,
// the change in value of static_counter in any of the instance will be
reflected in other instances.
// while the counter value will remain constant whenever any instance
is created as it is not declared static.
}
}

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,

abstract class Shape


// declaring an abstract class
{
abstract void Area();
// an abstract method with no body
void Printanything()
// a simple method
{
System.out.println("hello!! Shashi Chaudhary @ r4r");
}
}
Java Tutorialslass Rectangle extends Shape
// defined a class
which is inheriting Shape class
{
int length;
int breadth;
Rectangle(int length, int breadth)
{
this.length=length;
this.breadth=breadth;
}
void Area()
// implementing the Area() method
defined in Shape class
{
System.out.println("The area of rectangle is given by :"+
(length*breadth));
// displaying area of rectangle
}
}
Java Tutorialslass Java Tutorialsircle extends Shape
{
int radius;
Java Tutorialsircle(int radius)
{
this.radius=radius;
}
void Area()
// Implementing the Area() method
defined in class Shape
{
System.out.println("The area of circle is given by :"+
(Math.PI*radius*radius));
// displaying area of circle
}
}
Java Tutorialslass AbstractModifierExample
{
public static void main(String args[])
{
// Shape shp = new Shape(); /* will cause compilation error as Shape
is defined abstract
Rectangle objrect = new Rectangle(7,5);
Java Tutorialsircle objcirc = new Java Tutorialsircle(7);
objrect.Area();
objcirc.Area();
objcirc.Printanything();
// accessing the method defined
in class Shape through Circle's instance
objrect.Printanything();
// accessing the method defined in
class Shape through Rectangle's instance
}
}

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"))

System.out.println("The value of volatile variable

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

6. The synchronized Modifier : The synchronized modifier is used in multithreaded


programming to control access to critical sections in the program. The synchronized
keyword used to indicate that a method can be accessed by only one thread at a time. The
synchronized modifier is generally used mainly in threading environment. We will
discuss about it in detail in threading. Its declarative syntax is,
public synchronized void Anymethod()
{
// some logic
}

What is Garbage Collection in java ?


An application running on a system computer uses some memory, which makes memory
management a significant issue for any programming language. As Java is comparatively
high-level language, the memory management in Java is automatic. To make it more
efficient, we need to understand garbage collection, i.e. freeing memory from objects that
are no longer in use.
Garbage collection is the process of automatically freeing objects that are no longer
referenced by the program. This frees a programmer from having to keep track of when
to free allocated memory, thus preventing many potential bugs and problems.

What is a Garbage Collector ?


When we create an object by instantiating a class, the object is put on the heap, that is, it
uses some memory. A Java application creates and uses objects. After an object in
memory has been used and is no longer needed, it is sensible to free memory from that
object.The Garbage Collector in Java initiates the memory management by freeing up 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);
}

System.out.println("Free Memory before call to gc(): " +


rt.freeMemory());
System.runFinalization();
System.gc();
System.out.println(" Free Memory after call to gc(): " +
rt.freeMemory());
}

Java Tutorialslass FinalizeMethod


{
String str;
int id;
FinalizeMethod(int id)
{
this.str = new String("r4r tefsoft solutions");
this.id = id;
}
protected void finalize()
{
System.out.println("FinalizeMethod object " + id + " has been
finalized.");
}
}

You might also like