Documente Academic
Documente Profesional
Documente Cultură
ACADEMIC YEAR
2018-19
REFERENCES:
1. Amritendu De, “Spring 4 and Hibernate 4: Agile Java Design and Development”,
McGraw-Hill Education, 2015
2. Herbert Schildt, The Complete Reference – Java 2, Ninth Edition, Tata McGraw Hill,
2014
3. Joyce Farrell, “Java Programming”, Cengage Learning, Seventh Edition, 2014
4. John Dean, Raymond Dean, “Introduction to Programming with JAVA – A Problem
Solving Approach”, Tata Mc Graw Hill, 2014.
5. Mahesh P. Matha, “Core Java A Comprehensive Study”, Prentice Hall of India, 2011
6. R. Nageswara Rao,“Core Java: An Integrated Approach”, DreamTech Press, 2016
JAVA FUNDAMENTALS
1.1 Introduction
James Gosling is a famous Canadian software developer who has been with Sun Microsystems
since 1984 and is considered as father of Java programming language. Gosling did the original
design of Java and implemented its original compiler and virtual machine.
History of Java:
• In 1990, Sun Micro Systems Inc. (US) was conceived a project to develop software for
consumer electronic devices that could be controlled by a remote. This project was called Stealth
Project but later its name was changed to Green Project.
• In January 1991, Project Manager James Gosling and his team members Patrick Naughton,
Mike Sheridan, Chris Wrath, and Ed Frank met to discuss about this project.
• Gosling thought C and C++ would be used to develop the project. But the problem he faced
with them is that they were system dependent languages. The trouble with C and C++ (and most
other languages) is that they are designed to be compiled for a specific target and could not be
used on various processors, which the electronic devices might use.
• James Gosling with his team started developing a new language, which was completely system
independent. This language was initially called OAK. Since this name was registered by some
other company, later it was changed to Java.
• James Gosling and his team members were consuming a lot of coffee while developing this
language. Good quality of coffee was supplied from a place called "Java Island'. Hence they
fixed the name of the language as Java. The symbol for Java language is cup and saucer.
• Sun formally announced Java at Sun World conference in 1995. On January 23rd 1996,
JDK1.0 version was released.
HISTORY:
Java is a lot like C but the major difference between Java and C is that Java is an object-
oriented language and mechanism to define classes and objects.
Java does not include the C unique statement keywords goto, sizeof, and typedef.
Java does not contain the data types struct, union and enum.
Java does not define the type modifiers keywords auto, extern, register, signed and
unsigned.
Java does not support an explicit pointer type.
Java does not have a preprocessor and therefore we cannot use # define, #include, and #
ifdef statements.
Java does not support any mechanism for defining variable arguments to functions.
Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
Java add new operators such as instanceof and >>>.
Java adds labelled break and continue statements.
Java adds many features required for object-oriented programming.
JAVA AND C++:
• Operating systems
• Processors
• System resources
will not force any changes in Java programs
Object Oriented:
• Java is a true object oriented language
• Almost everything in Java is an object
• All programs code and data reside within objects and
classes
• Java comes with an extensive set of classes arranged in
packages
Distributed:
• Java is designed as a distributed language for creating applications on networks
• It has the ability to share both data and programs
• Java applications can open and access remote object as easily as they can do in a local
system
• Enables multiple programmers at multiple locations work together on a single project
• Java is small and simple language. Many features of C and C++ are not part of Java
eg. : Java does not provide
• Pointers
• Preprocessors header file
• goto statements
• Operator overloading
• Multiple inheritance
• Familiarity is another feature of Java
• It is modeled on C and C++ languages
• Java is a simplified version of C++
High Performance:
• Java performance is impressive for an interpreted language
• Due to the use of intermediate byte code
• Java architecture is also designed to reduce overheads during runtime
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
• The incorporation of multithreading enhances the overall execution speed of Java
programs
• Class libraries
• Methods
• Objects
• Java programs supports functions written in other languages such as C and C++
• These functions are known as “native methods”
• This facility enables the programmers to use the efficient available in these languages
• Native methods are dynamically linked at runtime
Java environment includes a large number of development tools and hundreds of classes and
methods.
The development tools are part of the system known as Java Development Kit (JDK) and the
classes and methods are parts of the Java Standard Library (JSL), also known as the Application
Programming Interface (API).
• Language Support Package: A collection of classes and methods required for implementing
basic features of Java.
• Utilities Packages: A collection of classes to provide utility functions such as date and time
functions.
• Input/Out Package: A collection of classes required for input/ output manipulation.
• Networking Package: A collection of classes for communicating with other computers via
Internet.
• AWT Package: The Abstract Window Tools Kit packages contains classes that implements
platform-independent graphical user interface.
• Applet Package: This includes a set of classes that allows us to create Java applets.
• A class library is a collection of classes that we can use when developing programs
• The Java standard class library is pad of any Java development environment
• Its classes are not pad of the Java language perse, but we rely on them heavily
• Various classes we've already used (system, Scanner, string) are pad of the Java standard class
Library (Look them up on Sun website)
• Other class libraries can be obtained through third party vendors
An expression is a construct made up of variables, operators, and method invocations, which are
constructed according to the syntax of the language, that evaluates to a single value. You've
already seen examples of expressions, illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
The data type of the value returned by an expression depends on the elements used in the
expression. The expression cadence = 0 returns an int because the assignment operator returns a
value of the same data type as its left-hand operand; in this case, cadence is an int. As you can
The Java programming language allows you to construct compound expressions from various
smaller expressions as long as the data type required by one part of the expression matches the
data type of the other. Here's an example of a compound expression:
1*2*3
In this particular example, the order in which the expression is evaluated is unimportant because
the result of multiplication is independent of order; the outcome is always the same, no matter in
which order you apply the multiplications. However, this is not true of all expressions. For
example, the following expression gives different results, depending on whether you perform the
addition or the division operation first:
x + y / 100 // ambiguous
You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ).
For example, to make the previous expression unambiguous, you could write the following:
If you don't explicitly indicate the order for the operations to be performed, the order is
determined by the precedence assigned to the operators in use within the expression. Operators
that have a higher precedence get evaluated first. For example, the division operator has a higher
precedence than does the addition operator. Therefore, the following two statements are
equivalent:
x + y / 100
x + (y / 100) // unambiguous, recommended
When writing compound expressions, be explicit and indicate with parentheses which operators
should be evaluated first. This practice makes code easier to read and to maintain.
Statements
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();
In addition to expression statements, there are two other kinds of statements: declaration
statements and control flow statements. A declaration statement declares a variable. You've seen
many examples of declaration statements already:
// declaration statement
double aValue = 8933.234;
Finally, control flow statements regulate the order in which statements get executed.
Blocks: A block is a group of zero or more statements between balanced braces and can be used
anywhere a single statement is allowed. The following example, BlockDemo, illustrates the use
of blocks:
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups −
Arithmetic Operators
Relational Operators
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Arithmetic Operators:
The arithmetic operators are used to construct mathematical expressions as in algebra. Their
operands are of numeric type.
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
public class Example {
public static void main(String[] args) {
int j, k, p, q, r, s, t;
j = 5;
k = 2;
p = j + k;
q = j - k;
r = j * k;
s = j / k;
t = j % k;
System.out.println("p = " + p);
System.out.println("q = " + q);
System.out.println("r = " + r);
System.out.println("s = " + s);
System.out.println("t = " + t);
}
}
Java has six relational operators that compare two numbers and return a boolean value. The
relational operators are < , > , <= , >= , == , and != . True if x is less than y, otherwise false. True
if x is greater than y, otherwise false.A relational operator compares two values and determines
the relationship between them.
Bitwise operators is used to control values of primitive data-types such as long, integer, short and
byte. These operators do changes to the variables by doing some action and manipulation on bits
level. There are four defined bitwise operators in java which are : AND operator, OR operator,
XOR operator and complement operator. The first three operators are binary which means that
they need two operands while the last one is unary operator which means it needs only one
operand. Next will explain the usage of each operator by example.
LOGICAL OPERATOR:
Sometimes, expressions that use logical operators are called “compound expressions” because
the effect of the logical operators is to let you combine two or more condition tests into a single
expression.
Assignment Operator:
The assignment operator (=) is the most commonly used binary operator in Java. It evaluates the
operand on the tight hand side and then assigns the resulting value to a variable on the left hand
side. The right operand can be a variable, constant, function call or expression. The type of right
operand must be type compatible with the left operand. The general form of representing
assignment operator is x=y.
c *= a ;
System.out.println("c *= a = " + c );
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
}
}
Instanceof Operator: The java instanceof operator is used to test whether the object is an
instance of the specified type (class or subclass or interface).The instanceof in java is also known
as type comparison operator because it compares the instance with type. It returns either true or
false. If we apply the instanceof operator with any variable that has null value, it returns false .
Example:
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
In Java, control statements can be divided into the following three categories:
Selection Statements
Iteration Statements
Jump Statements
SELECTION STATEMENTS
Selection statements allow you to control the flow of program execution on the basis of the
outcome of an expression or state of a variable known during runtime.
Selection statements can be divided into the following categories:
The if and if-else statements
The if-else statements
The if-else-if statements
The switch statements
The if statements
The first contained statement (that can be a block) of an if statement only executes when the
specified condition is true. If the condition is false and there is not else keyword then the first
contained statement will be skipped and execution continues with the rest of the program. The
condition is an expression that returns a boolean value.
Example
import java.util.Scanner;
class IfDemo
{
public static void main(String[] args) {
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter Age: ");
age = inputDevice.nextInt();
if(age > 18)
System.out.println("above 18 ");
}
}
In if-else statements, if the specified condition in the if statement is false, then the statement after
the else keyword (that can be a block) will execute.
import java.util.Scanner;
public class IfElseDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 )
System.out.println( "above 18 " );
else
System.out.println( "below 18" );
}
}
if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;
import java.util.Scanner;
public class IfElseIfDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 && age <=35 )
System.out.println( "between 18-35 " );
else if(age >35 && age <=60)
System.out.println("between 36-60");
else
System.out.println( "not matched" );
}
}
Syntax of switch-case:
switch(expression){
case 1 :
action1 statement;
break;
case 2:
action2 statement;
break;
.
.
.
case N:
actionN statement;
break;
default:
default statement;
}
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
Example: import java.util.Scanner;
An expression must be of a type of byte, short, int or char. Each of the values specified in the
case statement must be of a type compatible with the expression. Duplicate case values are not
allowed. The break statement is used inside the switch to terminate a statement sequence. The
break statement is optional in the switch statement.
ITERATION STATEMENTS
Repeating the same code fragment several times until a specified condition is satisfied is called
iteration. Iteration statements execute the same set of instructions until a termination condition is
met.
It continually executes a statement (that is usually be a block) while a condition is true. The
condition must return a boolean value.
while (condition) {
action statements:
}
Where condition: is any boolean expression that returns a true or false value. The loop continues
upto condition returns true value.
Example :
int i = 1;
while(i<=5){
i++;
System.out.println(“value of i is : “+i);
}
do-while loop
The do-while loops execute certain statements till the specified condition is true. This loop
ensures that the loop body is executed atleast once.
Syntax of do-while loop:
do{
action statements;
}while(condition){
action statements;
}
Example :
int j = 8;
do{
j = j+2;
System.out.println(“value of j is : “ +j);
}while(j>=10 && j<=50){
j = j+5;
System.out.println(“value of j is : “ +j);
}
All loops have some common feature: a counter variable that is initialized before the loop
begins. The for loop provides the feature that, initialized the variable before loop begins, a
condition for counter variable and counter upto which loop lasts.
Example :
for(int i=1;i<=10;i++){
System.out.println(“Value of i is “ +i);
}
JUMP STATEMENTS
Jump statements are used to unconditionally transfer the program control to another part of the
program.
Java provides the following jump statements:
break statement
continue statement
return statement
Break Statement :
The break statements are used to,
- Terminate a statement sequence in a switch statement
- Exit a loop
Example :
class BreakExample{
public static void main(String args[]){
for(int count=1;count<=100;count++;{
if(count==10){
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
break;
}
System.out.println(“The value of num is : “ +count);
}
System.out.println(“Outside loop“);
}
}
Continue Statement:
Sometimes the programmer might want to continue a loop, but stop processing the remainder of
the code in its body for a particular iteration. The continue statement can be used for such a
scenario. In w
hile and do-while loops, a continue statement can be used, as shown in below example.
Example :
class ContinueDemo{
public static void main(String args[]){
for(int count = 1; count <= 10; count++){
System.out.println(“Value of count before : “+count);
if(count%2==0){
continue;
}
System.out.println(“Value of count after : “+count);
}
}
}
Return Statement:
The return statement is used to immediately quit the current method and return to the calling
method. It is mandatory to use a return statement for non-void methods to return a value.
Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, OOPS
is a programming approach which provides solution to problems with the help of algorithms
based on real world. It uses real world approach to solve a problem. So object oriented technique
offers better and easy way to write program then procedural programming model such as C,
ALGOL, PASCAL.
Java supports the following fundamental concepts:
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing
In this chapter, we will look into the concepts - Classes and Objects.
Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of
a class.
Class - A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
Fields , methods, constructors, blocks, nested class and interface
Class:In Java everything is encapsulated under classes. Class is the core of Java language. Class
can be defined as a template/ blueprint that describe the behaviors /states of a particular entity. A
class defines new data type. Once defined this new type can be used to create object of that type.
Object is an instance of class. You may also call it as physical existence of a logical template
class. A class is declared using class keyword. A class contain both data and code that operate on
that data. The data or variables defined within a class are called instance variables and the code
that operates on this data is known as methods. Thus, the instance variables and methods are
known as class members. class is also known as a user defined datatype.
A class and an object can be related as follows: Consider an ice tray(like of cube shape) as a
class. Then ice cubes can be considered as the objects which is a blueprint of its class i.e of ice
tray.
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
Rules for Java Class:
Finally, the source file name must match the public class name and it must have a java suffix
Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can find many
objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields
and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-
to-object communication is done via methods.
Classes in Java
Local variables: Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into
classes of the Java Language.
Constructors
When discussing about classes, one of the most important sub topic would be constructors. Every
class has a constructor. If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor.
The Singleton's purpose is to control object creation, limiting the number of objects to only one.
Since there is only one Singleton instance, any instance fields of a Singleton will occur only once
per class, just like static fields. Singletons often control access to resources, such as database
connections or sockets.
For example, if you have a license for only one connection for your database or your JDBC
driver has trouble with multithreading, the Singleton makes sure that only one connection is
made or that only one thread can access the connection at a time.
Implementing Singletons
Example 1
The easiest implementation consists of a private constructor and a field to hold its result, and a
static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using
an initializer. The getInstance( ) method (which must be public) then simply returns this
instance −
Here is the main program file, where we will create a singleton object:
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
// File Name: SingletonDemo.java
public class SingletonDemo {
public static void main(String[] args) { Singleton
tmp = Singleton.getInstance( );
tmp.demoMethod( );
}
}
This will produce the following result −
demoMethod for singleton
Example 2
The ClassicSingleton class maintains a static reference to the lone singleton instance and
returns that reference from the static getInstance() method.
Here, ClassicSingleton class employs a technique known as lazy instantiation to create the
singleton; as a result, the singleton instance is not created until the getInstance() method is
called for the first time. This technique ensures that singleton instances are created only when
needed.
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' keyword is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes
the new object.
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
Following is an example of creating an object:
public class Puppy{
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it will produce the following result:
Passed Name is :tommy
Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path:
Example
This example explains how to access instance variables and methods of a class.
public class Puppy{
int puppyAge;
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}
public int getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
If we compile and run the above program, then it will produce the following result:
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
As the last part of this section, let's now look into the source file declaration rules. These rules
are essential when declaring classes, import statements and package statements in a source file.
There can be only one public class per source file.
The public class name should be the name of the source file as well which should be
appended by .java at the end. For example: the class name is public class
Employee{} then the source file should be as Employee.java.
If the class is defined inside a package, then the package statement should be the first
statement in the source file.
If import statements are present, then they must be written between the package
statement and the class declaration. If there are no package statements, then the import
statement should be the first line in the source file.
Import and package statements will imply to all the classes present in the source file. It
is not possible to declare different import and/or package statements to different classes
in the source file.
Classes have several access levels and there are different types of classes; abstract classes,
final classes, etc. We will be explaining about all these in the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special classes called
Inner classes and Anonymous classes.
1.5 INHERITANCE
In Java, classes can be derived from classes. Basically, if you need to create a new class and
here is already a class that has some of the code you require, then it is possible to derive your
new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing class without having to
rewrite the code in a new class. In this scenario, the existing class is called the superclass and
the derived class is called the subclass.
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
33
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class.
Following is the syntax of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Sample Code
Following is an example demonstrating Java inheritance. In this example, you can observe two
classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction()
of Calculation class.
Copy and paste the following program in a file with name My_Calculation.java
Example
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
javac My_Calculation.java
java My_Calculation
After executing the program, it will produce the following result −
Output
The Superclass reference variable can hold the subclass object, but using that variable you can
access only the members of the superclass, so to access the members of both classes it is
recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below. But using the
superclass reference variable ( cal in this case) you cannot call the method multiplication(),
which belongs to the subclass My_Calculation.
super.variable
super.method();
Sample Code
This section provides you a program that demonstrates the usage of the super keyword.
In the given program, you have two classes namely Sub_class and Super_class, both have a
method named display() with different implementations, and a variable named num with
different values. We are invoking display() method of both classes and printing the value of the
variable num of both classes. Here you can observe that we have used super keyword to
differentiate the members of superclass from subclass.
Copy and paste the program in a file with name Sub_class.java.
Example
class Super_class {
int num = 20;
sub.display();
javac Super_Demo
java Super
On executing the program, you will get the following result −
Output
super(values);
Sample Code
The program given in this section demonstrates how to use the super keyword to invoke the
parametrized constructor of the superclass. This program contains a superclass and a subclass,
where the superclass contains a parameterized constructor which accepts a integer value, and
we used the super keyword to invoke the parameterized constructor of the superclass.
Copy and paste the following program in a file with the name Subclass.java
Example
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String argd[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}
Compile and execute the above code using the following syntax.
javac Subclass
java Subclass
On executing the program, you will get the following result −
Output
With the use of the extends keyword, the subclasses will be able to inherit all the properties of
the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example
class Animal {
}
true
true
true
Since we have a good understanding of the extends keyword, let us look into how
the implements keyword is used to get the IS-A relationship.
Generally, the implements keyword is used with classes to inherit the properties of an interface.
Interfaces can never be extended by a class.
Example
interface Animal{}
class Mammal implements Animal{}
true
true
true
HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain
class HAS-A certain thing. This relationship helps to reduce duplication of code as well as
bugs.
Lets look into an example −
Example
class. So, basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.
Types of Inheritance
There are various types of inheritance as demonstrated below.
A very important fact to remember is that Java does not support multiple inheritance. This
means that a class cannot extend more than one class. Therefore following is illegal −
Example
However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance
1.6 PACKAGES AND INTERFACES
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and namespace management.
The types that are part of the Java platform are members of various packages that bundle classes
by function: fundamental classes are in java.lang, classes for reading and writing (input and
output) are in java.io, and so on.
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.
A package is a grouping of related types providing access protection and name space
management. Note that types refers to classes, interfaces, enumerations, and annotation types.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by name
of the package as the first statement in java source file.
Syntax : package mypack;
public class employee
{
...statement;
}
The above statement create a package called mypack.
Java uses file system directory to store package. For example the .class for any classes you
define to be part of mypack package must be stored in a directory called mypack.
All classes of the package which we wish to access outside the package must be declared
public.
All classes within the package must have the package statement as its first line.
All classes of the package must be compiled before use (So that its error free)
import keyword:
import keyword is used to import built-in and user-defined packages into your java source file so
that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to class that is present in different package
Using fully qualified name(But this is not a good practice.)
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
If you import package.classname then only declared class of this package will be accessible.
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Access Protection:
INTERFACE:
Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements. Unless the
class that implements the interface is abstract, all the methods of the interface need to be defined
in the class.
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface −
Following is an example of an interface −
/* File name : NameOfInterface.java */
import java.lang.*;
// Any number of import statements
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations\
}
An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Methods in an interface are implicitly public.
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive
types and their corresponding object wrapper classes. For example, converting an int to
an Integer, a double to a Double, and so on. If the conversion goes the other way, this is
called unboxing. Here is the simplest example of autoboxing:
Character ch = 'a';
The rest of the examples in this section use generics. If you are not yet familiar with the syntax
of generics, see the Generics (Updated) lesson.
Although you add the int values as primitive types, rather than Integer objects, to li, the code
compiles. Because li is a list of Integer objects, not a list of int values, you may wonder why the
Java compiler does not issue a compile-time error. The compiler does not generate an error
because it creates an Integer object from i and adds the object to li. Thus, the compiler converts
the previous code to the following at runtime:
Converting a primitive value (an int, for example) into an object of the corresponding wrapper
class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive
value is:
Because the remainder (%) and unary plus (+=) operators do not apply to Integer objects, you
may wonder why the Java compiler compiles the method without issuing any errors. The
compiler does not generate an error because it invokes the intValue method to convert
an Integer to an int at runtime:
sum += i.intValue();
return sum;
}
Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is
called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:
import java.util.ArrayList;
import java.util.List;
absolute value of -8 = 8
pi = 3.1416
Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The
following table lists the primitive types and their corresponding wrapper classes, which are used
by the Java compiler for autoboxing and unboxing:
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result,
here a is implicitly declared as an array of type int[]. Below is a code snippet for illustrating the
above concept :
// Java program to demonstrate varargs
class Test1
{
// A method that takes variable number of intger
// arguments.
static void fun(int ...a)
{
System.out.println("Number of arguments: " + a.length);
// Driver code
public static void main(String args[])
{
// Calling the varargs method with different number
// of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}
Run on IDE
Output:
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0
In this case, the first two arguments are matched with the first two parameters and the remaining
arguments belong to c.
// Java program to demonstrate varargs with normal
// arguments
class Test2
{
// Takes string as a argument followed by varargs
static void fun2(String str, int ...a)
{
System.out.println("String: " + str);
System.out.println("Number of arguments is: "+ a.length);
System.out.println();
}
String: GeeksforGeeks
Number of arguments is: 2
100 200
String: CSportal
Number of arguments is: 5
12345
String: forGeeks
Number of arguments is: 0
Important points:
Vararg Methods can also be overloaded but overloading may lead to ambiguity.
Prior to JDK 5, variable length arguments could be handled into two ways : One was using
overloading, other was using array argument.
There can be only one variable argument in a method.
Variable argument (varargs) must be the last argument.
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
Or
The exception handling in java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to know
how exception handling works in Java.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs. Errors are generated to indicate errors generated by the runtime environment.
Example: JVM is out of memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored at
the time of compilation, the programmer should take care of (handle) these exceptions.
Built-in Exceptions:
• Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important
built-in exceptions in Java.
• Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
• ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
• ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
• FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
• IOException
It is thrown when an input-output operation failed or interrupted
• InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
• NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
• NoSuchMethodException
It is thrown when accessing a method which is not found.
• NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
• NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
• RuntimeException
This represents any exception which occurs during runtime.
• StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the
size of the string
Java Exception Handling Keywords : There are 5 keywords used in java exception handling.
try –Java try block is used to enclose the code that might throw an exception. It must be used
within the method. Java try block must be followed by either catch or finally block.
keyword appears at the end of a method's signature. You can throw an exception, either a newly
instantiated one or an exception that you just caught, by using the throw keyword
catch – Java catch block is used to handle the Exception. It must be used after the try block
only.You can use multiple catch block with a single try.
finally – optional statement used after a try-catch block to run a segment of code regardless if a
exception is generated, Java finally block. Java finally block is a block that is used to execute
important code such as closing connection, stream etc. Java finally block is always executed
whether exception is handled or not. Java finally block follows try or catch block
throws - Use of throws keyword in Java. 1. The throws keyword is used in method declaration,
in order to explicitly specify the exceptions that a particular method might throw. When a
method declaration has one or more exceptions defined using throws clause then the method-
call must handle all the defined exceptions
Syntax:
try
{
// Code which might throw an exception
}
catch(Exceptionclass object1)
{
// code to handle an exception
}
catch(Exceptionclass object2)
{
// code to handle an exception
}
finally
{
// ALWAYS executed whether an exception was thrown or not
}
If more than one exception can occur, then we use multiple catch blocks
When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed
After one catch statement executes, the others are bypassed
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java finally block:
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
UNIT II
COLLECTIONS AND ADVANCE FEATURES
PACKAGES
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
The package java.util contains a number of useful classes and interfaces. Although the name of
the package might imply that these are utility classes, they are really more important than that. In
fact, Java depends directly on several of the classes in this package, and many programs will find
these classes indispensable. The classes and interfaces in java.util include:
BitSet
Name : BitSet
Class Name: java.util.BitSet
Superclass: java.lang.Object
Immediate Subclasses: None
Interfaces Implemented: java.lang.Cloneable, java.io.Serializable
Availability: JDK 1.0 or later
Description
The BitSet class implements a set of bits. The set grows in size as needed. Each element of
a BitSet has a boolean value. When a BitSet object is created, all of the bits are set to false by
default. The bits in a BitSet are indexed by nonnegative integers, starting at 0. The size of
a BitSet is the number of bits that it currently contains. The BitSet class provides methods to set,
clear, and retrieve the values of the individual bits in a BitSet. There are also methods to perform
logical AND, OR, and XOR operations.
Class Summary
public final class java.util.BitSet extends java.lang.Object
implements java.lang.Cloneable, java.io.Serializable {
// Constructors
public BitSet();
public BitSet(int nbits);
// Instance Methods
public void and(BitSet set);
public void clear(int bit);
public Object clone();
public boolean equals(Object obj);
public boolean get(int bit);
public int hashCode();
public void or(BitSet set);
public void set(int bit);
public int size();
public String toString();
public void xor(BitSet set);
}
Constructors
BitSet
public BitSet()
Description
This constructor creates a BitSet with a default size of 64 bits. All of the bits in
the BitSet are initially set to false.
public BitSet(int nbits)
Parameters
nbits
The initial number of bits.
Description
This constructor creates a BitSet with a size of nbits. All of the bits in the BitSet are
initially set to false.
Instance Methods
and
public void and(BitSet set)
Parameters
set
The BitSet to AND with this BitSet.
Description
This method computes the logical AND of this BitSet and the specified BitSet and stores
the result in this BitSet. In other words, for each bit in this BitSet, the value is set to
only true if the bit is already true in this BitSet and the corresponding bit in set is true.
If the size of set is greater than the size of this BitSet, the extra bits in set are ignored. If
the size of set is less than the size of this BitSet, the extra bits in this BitSet are set
to false.
clear
public void clear(int bit)
Parameters
bit
The index of the bit to clear.
Description
This method sets the bit at the given index to false. If bit is greater than or equal to the
number of bits in the BitSet, the size of the BitSet is increased so that it
contains bit values. All of the additional bits are set to false.
clone
public Object clone()
Returns
A copy of this BitSet.
Overrides
Object.clone()
Description
This method creates a copy of this BitSet and returns it. In other words, the
returned BitSet has the same size as this BitSet, and it has the same bits set to true.
equals
public boolean equals(Object obj)
Parameters
obj
The object to be compared with this object.
Returns
true if the objects are equal; false if they are not.
Overrides
Object.equals()
Description
This method returns true if obj is an instance of BitSet and it contains the same bit values
as the object this method is associated with. In other words, this method compares each
bit of this BitSet with the corresponding bit of obj. If any bits do not match, the method
returns false. If the size of this BitSet is different than obj, the extra bits in either
this BitSet or in obj must be false for this method to return true.
get
public boolean get(int bit)
Parameters
bit
The index of the bit to retrieve.
Returns
The boolean value of the bit at the given index.
Description
This method returns the value of the given bit. If bit is greater than or equal to the number
of bits in the BitSet, the method returns false.
hashCode
public int hashCode()
Returns
The hashcode for this BitSet.
Overrides
Object.hashCode()
Description
This method returns a hashcode for this object.
or
public void or(BitSet set)
Parameters
set
The BitSet to OR with this BitSet.
Description
This method computes the logical OR of this BitSet and the specified BitSet, and stores
the result in this BitSet. In other words, for each bit in this BitSet, the value is set
to true if the bit is already true in this BitSet or the corresponding bit in set is true.
If the size of set is greater than the size of this BitSet, this BitSet is first increased in size
to accommodate the additional bits. All of the additional bits are initially set to false.
set
public void set(int bit)
Parameters
bit
The index of the bit to set.
Description
This method sets the bit at the given index to true. If bit is greater than or equal to the
number of bits in the BitSet, the size of the BitSet is increased so that it
contains bit values. All of the additional bits except the last one are set to false.
size
public int size()
Returns
The size of this BitSet.
Description
This method returns the size of this BitSet, which is the number of bits currently in the
set.
toString
public String toString()
Returns
A string representation of this BitSet.
Overrides
Object.toString()
Description
This method returns a string representation of this BitSet. The string lists the indexes of
all the bits in the BitSet that are true.
xor
public void xor(BitSet set)
Parameters
set
The BitSet to XOR with this BitSet.
Description
This method computes the logical XOR (exclusive OR) of this BitSet and the
specified BitSet and stores the result in this BitSet. In other words, for each bit in
this BitSet, the value is set to true only if the bit is already true in this BitSet, and the
corresponding bit in set is false, or if the bit is false in this BitSet and the corresponding
bit in set is true.
If the size of set is greater than the size of this BitSet, this BitSet is first increased in size
to accommodate the additional bits. All of the additional bits are initially set to false.
Inherited Methods
Method Inherited From Method Inherited From
finalize() Object getClass() Object
notify() Object notifyAll() Object
wait() Object wait(long) Object
wait(long, int) Object
Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and
manipulate groups of objects. Although these classes were quite useful, they lacked a central,
unifying theme. Thus, the way that you used Vector was different from the way that you used
Properties. The collections framework was designed to meet several goals. The framework had
to be high-performance. The implementations for the fundamental collections dynamicarrays,
linkedlists, trees, andhashtables are highly efficient.
The framework had to allow different types of collections to work in a similar manner and
with a high degree of interoperability.
Extending and/or adapting a collection had to be easy. Towards this end, the entire collections
framework is designed around a set of standard interfaces.
Interfaces: These are abstract data types that represent collections. Interfaces allow collections
to be manipulated independently of the details of their representation. In object oriented
languages, interfaces generally form a hierarchy.
Implementations, i.e., Classes: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface.
In addition to collections, the framework defines several map interfaces and classes. Maps store
key/value pairs. Although maps are not collections in the proper use of the term, but they are
fully integrated with collections.
The Collection Interface : This enables you to work with groups of objects; it is at the top of the
collections hierarchy.
The List Interface: This extends Collection and an instance of List stores an ordered collection
of elements.
The Set: This extends Collection to handle sets, which must contain unique elements
The Map.Entry: This describes an element akey / valuepair in a map. This is an inner class of
Map.
The SortedMap: This extends Map so that the keys are maintained in ascending order.
The Enumeration: This is legacy interface and defines the methods by which you can enumerate
obtainoneatatime the elements in a collection of objects. This legacy interface has been
superceded by Iterator.
4 Hashtable : Hashtable was part of the original java.util and is a concrete implementation of a
Dictionary.
5 Properties : Properties is a subclass of Hashtable. It is used to maintain lists of values in which
the key is a String and the value is also a String.
6 BitSet : A BitSet class creates a special type of array that holds bit values. This array can
increase in size as needed.
The Collection Algorithms:
The collections framework defines several algorithms that can be applied to collections and
maps. These algorithms are defined as static methods within the Collections class.
Several of the methods can throw a ClassCastException, which occurs when an attempt is made
to compare incompatible types, or an UnsupportedOperationException, which occurs when an
attempt is made to modify an unmodifiable collection.
Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. All
are immutable.
Summary:
The Java collections framework gives the programmer access to prepackaged data structures as
well as to algorithms for manipulating them.
A collection is an object that can hold references to other objects. The collection interfaces
declare the operations that can be performed on each type of collection.
The classes and interfaces of the collections framework are in package java.util.
What is a Java Collection Framework?
A Java collection framework provides an architecture to store and manipulate a group of objects.
A Java collection framework includes the following:
Interfaces
Classes
Algorithm
Classes: Classes in Java are the implementation of the collection interface. It basically refers to
the data structures that are used again and again.
Algorithm: Algorithm refers to the methods which are used to perform operations such as
searching and sorting, on objects that implement collection interfaces. Algorithms are
polymorphic in nature as the same method can be used to take many forms or you can say
perform different implementations of the Java collection interface.
The Java collection framework provides the developers to access prepackaged data structures as
well as algorithms to manipulate data. Next, let us move to the Java collections framework
hierarchy and see where these interfaces and classes resides.
Java Collection Framework Hierarchy
As we have learned Java collection framework includes interfaces and classes. Now, let us see
the Java collections framework hierarchy.
In the above image, blue part refers to the different interfaces and the yellow part defines the
class. Now, let us understand these components in detail.
Java Collections : Interface
Iterator interface : Iterator is an interface that iterates the elements. It is used to traverse the list
and modify the elements. Iterator interface has three methods which are mentioned below:
1. public boolean hasNext() – This method returns true if iterator has more elements.
2. public object next() – It returns the element and moves the cursor pointer to the next
element.
3. public void remove() – This method removes the last elements returned by the iterator.
There are three components that extend the collection interface i.e List, Queue and Sets. Let’s
learn about them in detail:
Java collections: List
A List is an ordered Collection of elements which may contain duplicates. It is an interface that
extents the Collection interface. Lists are further classified into the following:
1. ArrayList
2. LinkedList
3. Vectors
Array list: ArrayList is the implementation of List Interface where the elements can be
dynamically added or removed from the list. Also, the size of the list is increased dynamically if
the elements are added more than the initial size.
Syntax:
ArrayList object = new ArrayList ();
Some of the methods in array list are listed below:
Method Description
boolean add(Collection c) Appends the specified element to the end of a list.
Return the index in this list of the last occurrence of the specified
int lastIndexOf(Object o)
element, or -1 if the list does not contain this element.
Object clone() Return a shallow copy of an ArrayList.
Object[] toArray() Returns an array containing all the elements in the list.
Jack
Tyler
Linked List: Linked List is a sequence of links which contains items. Each link contains a
connection to another link.
Syntax: Linkedlist object = new Linkedlist();
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List: In a singly Linked list each node in this list stores the data of the node and a
pointer or reference to the next node in the list. Refer to the below image to get a better
understanding of single Linked list.
Doubly Linked List: In a doubly Linked list, it has two references, one to the next node and
another to previous node. You can refer to the below image to get a better understanding of
doubly linked list.
void add (int index, Object element) Inserts the element at the specified element in the vector.
7 al.add("Rajat");
8 Iterator<String> itr = al.iterator();
9 while(itr.hasNext()){
10 System.out.println(itr.next());
11 }
12 }
13 }
The output of the above program would be:
Rachit
Rahul
Rajat
Vectors : Vectors are similar to arrays, where the elements of the vector object can be accessed
via an index into the vector. Vector implements a dynamic array. Also, the vector is not limited
to a specific size, it can shrink or grow automatically whenever required. It is similar to
ArrayList, but with two differences :
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Syntax:
Vector object = new Vector(size,increment);
Below are some of the methods of the Vector class:
Method Description
boolean add(Object o) Appends the specified element to the end of the list.
void clear() Removes all of the elements from this list.
void add(int index, Object element) Inserts the specified element at the specified position.
Removes the first occurrence of the specified element from
boolean remove(Object o)
this list.
boolean contains(Object element) Returns true if this list contains the specified element.
Now, let us move to the next sub type of the Java Collections interface i.e Queue.
Java collections: Queue
Queue in Java follows a FIFO approach i.e. it orders the elements in First In First Out manner. In
a queue, the first element is removed first and last element is removed in the end. Each basic
method exists in two forms: one throws an exception if the operation fails, the other returns a
special value.
Also, priority queue implements Queue interface. The elements of the priority queue are
ordered according to their natural ordering, or by a Comparator provided at the queue
construction time. The head of this queue is the least element with respect to the specified
ordering.
Below are some of the methods of Java Queue interface:
Method Description
boolean Inserts the specified element into the queue and returns true if it is a
add(object) success.
boolean
Inserts the specified element into this queue.
offer(object)
Retrieves and removes the head of the queue, or returns null if the queue is
Object poll()
empty.
Object element() Retrieves, but does not remove the head of the queue.
Retrieves, but does not remove the head of this queue, or returns null if the
Object peek()
queue is empty.
Let us understand these priority queue with a programmatic example:
1 import java.util.*;
2 class QueueExample {
3 public static void main(String args[]){
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
73
head:Amit
head:Amit
iterating the queue elements:
Amit
Rachit
Rahul
after removing two elements:
Rahul
Next, let us move forward to our next topic in “Java Collections” blog, i.e. Sets.
Java Collections: Sets
A Set refers to a collection that cannot contain duplicate elements. It is mainly used to model the
mathematical set abstraction. Set has its implementation in various classes such as HashSet,
TreeSetand LinkedHashSet.
boolean contains(Object o) Returns true if the set contains the specified element.
Amit
Rachit
jack
Linked Hashset : Java LinkedHashSet class is a Hash table and Linked list implementation of
the set interface. It contains only unique elements like HashSet. Linked HashSet also provides all
optional set operations and maintains insertion order. Let us understand these linked Hashset
with a programmatic example:
1 import java.util.*;
2 class LinkedHashsetExample{
3 public static void main(String args[]){
4 LinkedHashSet<String> al=new LinkedHashSet(); // creating linkedhashset
5 al.add("Mariana"); // adding elements
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
75
6 al.add("Rick");
7 al.add("Sam");
8 Iterator<String> itr=al.iterator();
9 while(itr.hasNext()){
10 System.out.println(itr.next());
11 }
12 }
13 }
14 }
The output of the above code would be:
Mariana
Rick
Sam
TreeSet : TreeSet class implements the Set interface that uses a tree for storage. The objects of
this class are stored in the ascending order. Also, it inherits AbstractSet class and implements
NavigableSet interface. It contains only unique elements like HashSet. In TreeSet class, access
and retrieval time are faster.
Below are some of the methods of Java TreeSet class:
Method Description
boolean addAll(Collection c) Add all the elements in the specified collection to this set.
boolean contains(Object o) Returns true if the set contains the specified element.
boolean isEmpty() Returns true if this set contains no elements.
boolean remove(Object o) Remove the specified element from the set.
void add(Object o) Add the specified element to the set.
void clear() Removes all the elements from the set.
Object clone() Return a shallow copy of this TreeSet instance.
Object first() Return the first element currently in the sorted set.
Object last() Return the last element currently in the sorted set.
int size() Return the number of elements in the set.
John
Rick
Sam
Now you must be wondering what is the difference between all these sets?
HashSet stores elements in random order whereas LinkedHashSet stores elements according to
insertion order and TreeHashSet stores according to natural ordering.
1.4 GENERICS
It would be nice if we could write a single sort method that could sort the elements in an Integer
array, a String array, or an array of any type that supports ordering.
Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods, or with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at
compile time.
Using Java Generic concept, we might write a generic method for sorting an array of objects,
then invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to
sort the array elements.
Generic Methods
You can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles
each method call appropriately. Following are the rules to define Generic Methods −
All generic method declarations have a type parameter section delimited by angle
brackets <and><and> that precedes the method's return type <E>in the next
example<E>in the next example .
Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic
type name.
The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.
A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types like int, double and
char like int, double and char .
Example
Following example illustrates how we can print an array of different type using a single Generic
method −
Output
Array integerArray contains:
12345
There may be times when you'll want to restrict the kinds of types that are allowed to be passed
to a type parameter. For example, a method that operates on numbers might only want to accept
instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends
keyword, followed by its upper bound.
Example
Following example illustrates how extends is used in a general sense to mean either "extends" as
in classes as in Classes or "implements" as in interfaces . This example is Generic method to
return the largest of three Comparable objects −
if(y.compareTo(max) > 0) {
max = y; // y is the largest so far
}
if(z.compareTo(max) > 0) {
max = z; // z is the largest now
}
return max; // returns the largest object
}
Output
Max of 3, 4 and 5 is 5
Generic Classes
A generic class declaration looks like a non-generic class declaration, except that the class name
is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more
type parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.
Example
public T get() {
return t;
}
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
Output
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements on the basis of any data
member, for example rollno, name, age or anything else.
compare() method
public int compare(Object obj1,Object obj2): compares the first object with second object.
Collections class
Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. But we cannot sort the elements of
List. Collections class provides methods for sorting the elements of List type elements also.
public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.
Let's see the example of sorting the elements of List on the basis of age and name. In this
example, we have created 4 java classes:
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
This class defines comparison logic based on the age. If age of first object is greater than the
second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first
object is less than the second object, we are returning negative value, it can be any negative
value and if age of both objects are equal, we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
AgeComparator.java
1. import java.util.*;
2. class AgeComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. if(s1.age==s2.age)
5. return 0;
6. else if(s1.age>s2.age)
7. return 1;
8. else
9. return -1;
10. }
11. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. return s1.name.compareTo(s2.name);
5. }
6. }
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3. class Simple{
4. public static void main(String args[])
5. {
6. ArrayList<Student> al=new ArrayList<Student>();
7. al.add(new Student(101,"Vijay",23));
8. al.add(new Student(106,"Ajay",27));
9. al.add(new Student(105,"Jai",21));
10.
11. System.out.println("Sorting by Name...");
12.
13. Collections.sort(al,new NameComparator());
14. for(Student st: al){
15. System.out.println(st.rollno+" "+st.name+" "+st.age);
16. }
17.
18. System.out.println("sorting by age...");
19.
20. Collections.sort(al,new AgeComparator());
21. for(Student st: al){
22. System.out.println(st.rollno+" "+st.name+" "+st.age);
23. }
24.
25. }
26. }
Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
Java annotations
In the Java computer programming language, an annotation is a form of syntactic metadata that
can be added to Java source code. Classes, methods, variables, parameters and packages may be
annotated. Like Javadoc tags, Java annotations can be read from source files.
Unlike Javadoc tags, Java annotations can also be embedded in and read from class
files generated by the compiler. This allows annotations to be retained by Java VM at run-
time and read via reflection. It is possible to create meta-annotations out of the existing ones in
Java
The Java platform has various ad-hoc annotation mechanisms—for example,
the transient modifier, or the @deprecated javadoc tag. JSR-175 introduced the general-purpose
annotation (also known as metadata) facility to the Java Community Process in 2002; it gained
approval in September 2004.[4] Annotations became available in the language itself beginning
with version 1.5 of the JDK. The apt tool provided a provisional interface for compile-time
annotation processing in JDK version 1.5; JSR-269 formalized this, and it became integrated into
the javac compiler in version 1.6.
Built-in annotations
Java defines a set of annotations that are built into the language. Of the seven standard
annotations, three are part of java.lang, and the remaining four are imported from
java.lang.annotation.
Annotations applied to Java code:
@Override - Checks that the method is an override. Causes a compile error if the method is
not found in one of the parent classes or implemented interfaces.
@Deprecated - Marks the method as obsolete. Causes a compile warning if the method is
used.
@SuppressWarnings - Instructs the compiler to suppress the compile time warnings
specified in the annotation parameters.
Annotations applied to other annotations (also known as "Meta Annotations"):
@SafeVarargs - Suppress warnings for all callers of a method or constructor with a generics
varargs parameter, since Java 7.
@FunctionalInterface - Specifies that the type declaration is intended to be a functional
interface, since Java 8.
@Repeatable - Specifies that the annotation can be applied more than once to the same
declaration, since Java 8.
Example
Built-in annotations[edit]
This example demonstrates the use of the @Override annotation. It instructs the compiler to
check parent classes for matching methods. In this case, an error is generated because
the gettype() method of class Cat doesn't in fact override getType() of class Animal like is
desired. If the @Override annotation was absent, a new method of name gettype() would be
created in class Cat.
@Override
public String gettype() { // Compile-time error due to mistyped name.
return "Cat";
}
}
Custom annotations[edit]
Annotation type declarations are similar to normal interface declarations. An at-sign (@)
precedes the interface keyword. Each method declaration defines an element of the annotation
type. Method declarations must not have any parameters or a throws clause. Return types are
restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.
Methods can have default values.
Annotations themselves may be annotated to indicate where and when they can be used:
this.id = id;
}
The annotations are not method calls and will not, by themselves, do anything. Rather, the class
object is passed to the JPA implementation at run-time, which then extracts the annotations to
generate an object-relational mapping.
A complete example is given below:
package com.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,
ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE,
ElementType.PACKAGE,ElementType.FIELD,ElementType.LOCAL_VARIABLE})
@Inherited
}
package com.validators;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import com.annotation.UnderConstruction;
import com.annotation.Unfinished;
import com.annotation.Unfinished.Priority;
import com.util.Util;
@UnderConstruction(owner="Jon Doe")
public class DateValidator implements Validator {
if (!Util.validateAGivenDate(date))
{
@Unfinished(changedBy = "Steve",
value = "whether to add message to context or not, confirm",
priority = Priority.HIGH
)
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary(errorLabel);
message.setDetail(errorLabel);
throw new ValidatorException(message);
}
}
}
Processing
When Java source code is compiled, annotations can be processed by compiler plug-ins called
annotation processors. Processors can produce informational messages or create additional Java
source files or resources, which in turn may be compiled and processed, and also modify the
annotated code itself. The Java compiler conditionally stores annotation metadata in the class
files, if the annotation has a Retention Policy of CLASS or RUNTIME. Later, the JVM or other
programs can look for the metadata to determine how to interact with the program elements or
change their behavior.
In addition to processing an annotation using an annotation processor, a Java programmer can
write their own code that uses reflections to process the annotation. Java SE 5 supports a new
interface that is defined in the java.lang.reflect package. This package contains the interface
called Annotated Element that is implemented by the Java reflection classes
including Class, Constructor, Field, Method, and Package. The implementations of this interface
are used to represent an annotated element of the program currently running in the Java Virtual
Machine. This interface allows annotations to be read reflectively.
The Annotated Element interface provides access to annotations having RUNTIME retention.
This access is provided by the getAnnotation, getAnnotations, and isAnnotationPresent methods.
Because annotation types are compiled and stored in byte code files just like classes, the
annotations returned by these methods can be queried just like any regular Java object. A
complete example of processing an annotation is provided below:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
Provides services that allow Java programming language agents to instrument programs running
on the JVM. The mechanism for instrumentation is modification of the byte-codes of methods.
ClassFileTransformer
An agent provides an implementation of this interface in order to transform class files.
Instrumentation This class provides services needed to instrument Java programming language
code.
ClassDefinition
This class serves as a parameter block to the Instrumentation. redefine Classes method.
Premain
The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this
attribute is the name of the agent class. The agent class must implement a public static premain
method similar in principle to the main application entry point. After the Java Virtual Machine
(JVM) has initialized, each premain method will be called in the order the agents were specified,
then the real application main method will be called. Each premain method must return in order
for the startup sequence to proceed.
The premain method has one of two possible signatures. The JVM first attempts to invoke the
following method on the agent class:
If the agent class does not implement this method then the JVM will attempt to invoke:
The agent class may also have an agent main method for use when the agent is started after VM
startup. When the agent is started using a command-line option, the agent main method is not
invoked.