Sunteți pe pagina 1din 90

PRIYADARSHINI ENGINEERING COLLEGE – VANIYAMBADI

(Approved by AICTE, New Delhi, Affiliated to Anna University-


Chennai)
Listed in 2(f) & 12(B) Sections of UGC

MC5304-PROGRAMMING WITH JAVA


REGULATION 2017

DEPARTMENT OF COMPUTER APPLICATIONS


III SEMESTER

ACADEMIC YEAR
2018-19

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


SYLLABUS

UNIT I JAVA FUNDAMENTALS 9


Java features – Java Platform – Java Fundamentals – Expressions, Operators, and Control
Structures – Classes, Methods – Inheritance - Packages and Interfaces – Boxing, Unboxing –
Variable-Length Arguments (Varargs), Exception Handling.

UNIT II COLLECTIONS AND ADVANCE FEATURES 9


Utility Packages- Introduction to collection –Hierarchy of Collection framework – Generics,
Array list, LL, HashSet, Treeset, HashMap – Comparators – Java annotations – Premain method.

UNIT III ADVANCED JAVAPROGRAMMING 9


Input Output Packages – Inner Classes – Java Database Connectivity - Introduction JDBC
Drivers - JDBC connectivity with MySQL/Oracle -Prepared Statement & Result Set – JDBC
Stored procedures invocation - Servlets - RMI – Swing Fundamentals - Swing Classes.

UNIT IV OVERVIEW OF DATA RETRIEVAL & ENTERPRISE APPLICATION


DEVELOPMENT 9
Tiered Application development - Java Servers, containers –Web Container – Creating Web
Application using JSP/Servlets – Web Frameworks Introduction to Spring/ Play Framework –
ORM Layer – Introduction to Hibernate.

UNIT V JAVA INTERNALS AND NETWORKING 9


Java jar Files-Introspection – Garbage collection – Architecture and design – GC Cleanup
process, Invoking GC, Generation in GC - Networking Basics Java and the Net – InetAddress –
TCP/IP Client Sockets – URL –URL Connection – TCP/IP Server Sockets – A
Caching Proxy HTTP Server – Datagrams.

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


UNIT - 1

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:

 James Gosling - Sun Microsystems


 Co founder – Vinod Khosla
 Oak - Java, May 20, 1995, Sun World
JDK Evolutions

 JDK 1.0 (January 23, 1996)


 JDK 1.1 (February 19, 1997)
 J2SE 1.2 (December 8, 1998)
 J2SE 1.3 (May 8, 2000)
 J2SE 1.4 (February 6, 2002)
 J2SE 5.0 (September 30, 2004)
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
 Java SE 6 (December 11, 2006)
 Java SE 7 (July 28, 2011)
JAVA AND C:

 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++:

 Java is a true object-oriented language while C++ is basically C with object-oriented


extension.
 Listed below are some major c++ features that were intentionally committed from Java or
significantly modified.
 Java does not support operator overloading.
 Java does not have temple classes as in C++.
 Java does not support multiple inheritence of classes. This is accomplished using a new
feature called "interface".
 Java does not support global variables. Every variable and
method is declared within a class and forms parts of that class.
 Java does not use pointers.
 Java has replaced the destructors function with a finalize()
function.
 There are no header files in Java.
JAVA EDITIONS.
 J2SE(Java 2 Standard Edition) - to develop client-side standalone applications or
applets.

 J2ME(Java 2 Micro Edition ) - to develop applications for mobile devices such as


cell phones.
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
 J2EE(Java 2 Enterprise Edition ) - to develop server-side applications such as
Java servlets and Java ServerPages.

FEATURES OF JAVA APPLICATIONS


Sun Micro Systems officially describes Java with the following features

Compiled and Interpreted:


• Usually a computer language is either compiled or interpreted
• Java combines both these approaches, thus making Java a two stage system
• First Java compiler translates source code into byte code instructions
• Byte codes are not machine instructions
• In the second stage Java interpreter generates machine code.
• That can be directly executed by the machine

Platform Independent and Portable:
• The most significant feature of Java is its portability
• Java programs can be easily moved from one computer system to another ,anywhere and
at anytime
Changes and upgrades in

• 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

Robust and Secure:

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


• Java is a robust language
• It provides many safeguards to ensure reliable code
• It has strict compile time and runtime for data types
• It is designed as a garbage collected language
• Java also provides concept of exception handling which identifies errors and eliminates
• Security becomes an important issue for a language that is used for programming on
internet
• Threat of viruses and abuse of resources
• Java systems not only verify all memory access, but also ensure that no viruses are
communicated with an applet
• The absence of pointers in Java ensures that programs cannot gain access to memory
location without proper initialization

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

Simple, Small and Familiar:

• 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++

Multithreaded and Interactive:


• Multithreaded means handling multiple tasks simultaneously
• Java supports multithreaded programs
• Need not wait for the application to finish one task before beginning another
• Greatly improves the interactive performance of graphical applications

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

Dynamic and Extensible:


• Java is a dynamic language
• Java is capable of dynamically linking new

• 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

1.2 JAVA PLATFORM

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

Java Developing Kit:


 The Java Developing Kit comes with a collection of tools that are used for developing
and running Java programs. They includes:
Table 2.3 list these tools and their descriptions.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


The way these tools are applied to build and run application programs is illustrated in fig .2.1.
 To create a Java program, we need to create a source code file using a text editor.
 The source code is then compiled using the Java compiler Javac and executed using the
Java interpreter Java.
 The Java debugger jdk is used to find errors, if any, in the source code.
 A compiled Java program can be converted into a source code with the help of Java
disassembler Javap.

Application Programming Interface:


Application program interface (API) is a set of routines, protocols, and tools for building
software applications. An API specifies how software components should interact and APIs are
used when programming graphical user interface (GUI) components.

• 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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


Java Standard Library (JSL):

• 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

1.3. JAVA FNDAMENTALS

1.3.1 JAVA EXPRESSIONS

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

int result = 1 + 2; // result is now 3


if (value1 == value2)
System.out.println("value1 == value2");

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


see from the other expressions, an expression can return other types of values as well, such
as boolean or String.

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:

(x + y) / 100 // unambiguous, recommended

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

Statements are roughly equivalent to sentences in natural languages. A statement forms a


complete unit of execution. The following types of expressions can be made into a statement by
terminating the expression with a semicolon (;).

 Assignment expressions
 Any use of ++ or --
 Method invocations
 Object creation expressions

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


Such statements are called expression statements. Here are some examples of expression
statements.

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

1.3.2 JAVA OPERATOR

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


Relational Operators:

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.

public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


Operator Description Example
Checks if the values of two operands are
== (equal to) equal or not, if yes then condition becomes (A == B) is not true.
true.
Checks if the values of two operands are
!= (not equal to) equal or not, if values are not equal then (A != B) is true.
condition becomes true.
Checks if the value of left operand is greater
> (greater than) than the value of right operand, if yes then (A > B) is not true.
condition becomes true.
Checks if the value of left operand is less than
< (less than) the value of right operand, if yes then (A < B) is true.
condition becomes true.
Checks if the value of left operand is greater
>= (greater than or
than or equal to the value of right operand, if (A >= B) is not true.
equal to)
yes then condition becomes true.
Checks if the value of left operand is less than
<= (less than or equal
or equal to the value of right operand, if yes (A <= B) is true.
to)
then condition becomes true.
Bitwise Operators:

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.

public class Test {


public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 15 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}
}

LOGICAL OPERATOR:

A logical operator (sometimes called a “Boolean operator”) in Java programming is an operator


that returns a Boolean result that’s based on the Boolean result of one or two other expressions.

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.

Operator Name Type Description

Returns true if the operand to the


! Not Unary right evaluates to false. Returns false if the operand to the
right is true.

Returns true if both of the operands


& And Binary evaluate to true. Both operands are
evaluated before the And operator is applied.

Returns true if at least one of the


| Or Binary operands evaluates to true. Both operands
are evaluated before the Or operator is applied.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


Returns true if one — and only
one — of the operands evaluates to true. Returns false
^ Xor Binary
if both operands evaluate to true or if
both operands evaluate to false.

Same as &, but if the operand on


Conditional the left returns false, it returns false without evaluating the
&& Binary
And operand on the
right.

Same as |, but if the operand on the


left returns true, it returns true without evaluating the operand
|| Conditional Or Binary
on the
right.

public class Test {


public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


public class Test {

Operator Usage Effect


public static void main(String args[]) {
+= a+=b; a=a+b;
int a = 10;
-= a-=b; a=a-b;
int b = 20;
*= a*=b; a=a*b;
int c = 0;
/= a/=b; a=a/b;
%= a%=b; a=a%b;
c = a + b;
&= a&=b; a=a&b;
System.out.println("c = a + b = " + c );
|= a|=b; a=a|b;
^= a^=b; a=a^b;
c += a ;
<<= a<<=b; a=a<<b;
System.out.println("c += a = " + c );
>>= a>>=b; a=a>>b;
>>>= a>>>=b; a=a>>>b;
c -= a ;
System.out.println("c -= a = " + c );

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


An object of subclass type is also a type of parent class. For example, if Dog extends Animal
then object of Dog can be referred by either Dog or Animal class.
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}

1.3.3 CONTROL STRUCTURE


A control structure is a block of programming that analyzes variables and chooses a direction in
which to go based on given parameters. The term flow control details the direction the program
takes (which way program control "flows")

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

The if-else statements :

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

The if-else-if statements :


This statement following the else keyword can be another if or if-else statement.
That would looks like this:

if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


Whenever the condition is true, the associated statement will be executed and the remaining
conditions will be bypassed. If none of the conditions are true then the else block will execute.

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

The Switch Statements :


The switch statement is a multi-way branch statement. The switch statement of Java is another
selection statement that defines multiple paths of execution of a program. It provides a better
alternative than a large series of if-else-if statements.

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;

public class SwitchDemo


{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
switch ( age )
{
case 18:
System.out.println( "age 18" );
break;
case 19:
System.out.println( "age 19" );
break;
default:
System.out.println( "not matched" );
break;
}
}
}

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.

Java provides the following loop for iteration statements:

 The while loop


 The do-while loop
 The for loop

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


The while loop

It continually executes a statement (that is usually be a block) while a condition is true. The
condition must return a boolean value.

Syntax of while loop:

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


for loop

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.

Syntax of for loop:

for(initialization statements; condition; increment/decrement statements){


action statements;
.
.
}
where initialization statements : sets or initialize the value for counter variable.
condition : A boolean expression that returns true or false value. The loop terminates if false
value is returned. Increment/decrement statements : Modifies the counter variable. This
statements are always executed after the action statements, and before the subsequent condition
check.

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.

public class ReturnDemo


{
public static void main( String[] args )
{
ReturnDemo returnDemo = new ReturnDemo();
System.out.println( "No : " + returnDemo.returnCall() );
}
int returnCall()
{
return 5;
}
}
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
1.4 CLASSES,METHODS

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:

 A class can have only public or default(no modifier) access specifier.


 It can be either abstract, final or concrete (normal class).
 It must have the class keyword, and class must be followed by a legal identifier.
 It may optionally extend one parent class. By default, it will extend java.lang.Object.
 It may optionally implement any number of comma-separated interfaces.
 The class's variables and methods are declared within a set of curly braces {}.
 Each .java source file may contain only one public class. A source file may contain any
number of default visible classes.

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

A class is a blueprint from which individual objects are created.


Following is a sample of a class.
public class Dog{
String breed;
int age;
String color;
void barking()
{
}
void hungry()
{}
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
void sleeping()
{}
}
A class can contain any of the following variable types.

 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.

Following is an example of a constructor:

public class Puppy{


public Puppy(){
}
Public Puppy(String name){
// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you would be able to create only one instance of a
class.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


Note: We have two different types of constructors. We are going to discuss constructors in
detail in the subsequent chapters.

How to Use Singleton Class?

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 −

// File Name: Singleton.java


public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){ }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}

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

Following implementation shows a classic Singleton design pattern:


public class ClassicSingleton {
private static ClassicSingleton instance = null;
private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}}

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

Accessing Instance Variables and Methods

Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path:

/* First create an object */


ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

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

Source File Declaration Rules

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.

 A source file can have multiple non-public classes.

 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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


32

A simple class example:


Suppose, Student is a class and student's name, roll number, age will be its property. Lets see
this in Java syntax.
class Student.
{
String name; // field
int rollno;
int age;
Add(); // method
}
When a reference is made to a particular student with its property then it becomes an object,
physical existence of Student class.
Student std=new Student();
After the above statement std is instance/object of Student class. Here the new keyword creates
an actual physical copy of the object and assign it to the std variable. It will have physical
existence and get memory in heap area. The new operator dynamically allocates memory for an
object.

Multi-class applications and main():


A Java application is implemented by one or more classes. Small applications can be
accommodated by a single class, but larger applications often require multiple classes. In that
case one of the classes is designated as the main class and contains the main() entry-point
method. For example, Listing 1 presents an application built using three classes: A, B, and C; C
is the main class.
class A
{
}
class B
{
}
class C
{
public static void main(String[] args)
{
System.out.println("Application C entry point");
}
}

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

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z); }
public static void main(String args[]) {

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


34

int a = 20, b = 10;


My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Compile and execute the above code as shown below.

javac My_Calculation.java
java My_Calculation
After executing the program, it will produce the following result −
Output

The sum of the given numbers:30


The difference between the given numbers:10
The product of the given numbers:200
In the given program, when an object to My_Calculation class is created, a copy of the contents
of the superclass is made within it. That is why, using the object of the subclass you can access
the members of a superclass.

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.

Calculation demo = new My_Calculation();


demo.addition(a, b);
demo.Subtraction(a, b);
Note − A subclass inherits all the members (fields, methods, and nested classes) from its
superclass. Constructors are not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


35

The super keyword


The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.
 It is used to differentiate the members of superclass from the members of subclass, if
they have same names.
 It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the superclass have
the names same as the sub class, to differentiate these variables we use super keyword as shown
below.

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;

// display method of superclass


public void display() {
System.out.println("This is the display method of superclass");
}
}

public class Sub_class extends Super_class {


int num = 10;

// display method of sub class


public void display() {
System.out.println("This is the display method of subclass");
}

public void my_method() {


// Instantiating subclass
Sub_class sub = new Sub_class();
// Invoking the display() method of sub class

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


36

sub.display();

// Invoking the display() method of superclass


super.display();

// printing the value of variable num of subclass


System.out.println("value of the variable named num in sub class:"+ sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+ super.num);
}
public static void main(String args[]) {
Sub_class obj = new Sub_class();
obj.my_method();
}
}
Compile and execute the above code using the following syntax.

javac Super_Demo
java Super
On executing the program, you will get the following result −
Output

This is the display method of subclass


This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the superclass. But if you want to call a parameterized constructor of the
superclass, you need to use the super keyword as shown below.

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


37

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

The value of the variable named age in super class is: 24


IS-A Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.

public class Animal {


}
public class Mammal extends Animal {
}
public class Reptile extends Animal {
}
public class Dog extends Mammal {
}
Now, based on the above example, in Object-Oriented terms, the following are true −

 Animal is the superclass of Mammal class.


 Animal is the superclass of Reptile class.
 Mammal and Reptile are subclasses of Animal class.
 Dog is the subclass of both Mammal and Animal classes.
Now, if we consider the IS-A relationship, we can say −
 Mammal IS-A Animal
 Reptile IS-A Animal
 Dog IS-A Mammal
 Hence: Dog IS-A Animal as well

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


38

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

class Mammal extends Animal {


}
class Reptile extends Animal {
}
public class Dog extends Mammal {

public static void main(String args[]) {


Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This will produce the following result −
Output

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

public interface Animal {


}

public class Mammal implements Animal {


}

public class Dog extends Mammal {


}

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


39

The instanceof Keyword


Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal.
Example

interface Animal{}
class Mammal implements Animal{}

public class Dog extends Mammal {

public static void main(String args[]) {


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This will produce the following result −
Output

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

public class Vehicle{}


public class Speed{}

public class Van extends Vehicle {


private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have
to put the entire code that belongs to speed inside the Van class, which makes it possible to
reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


40

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

public class extends Animal, Mammal{}

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


41

Some of the existing packages in Java are −

 java.lang − bundles the fundamental classes


 java.io − classes for input , output functions are bundled in this package

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.

 A java package is a group of similar types of classes, interfaces and sub-packages.


 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
 Here, we will have the detailed learning of creating and using user-defined packages.

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.

Additional points on package:


 A package is always defined in a separate folder having the same name as a package
name.
 Define all classes in that package folder.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


42

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

How to run packages:

 To Compile: javac -d . Simple.java


 To Run: java mypack.Simple

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.

import the only class you want to use(Using packagename.classname)

If you import package.classname then only declared class of this package will be accessible.

import all the classes from the particular package(Using packagename.*)

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:

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


43

INTERFACE:

An interface is a reference type in Java. It is similar to class. It is a collection of abstract


methods. A class implements an interface, thereby inheriting the abstract methods of the
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.

An interface is similar to a class in the following ways −

 An interface can contain any number of methods.


 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.

However, an interface is different from a class in several ways, including −

 You cannot instantiate an interface.


 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


44

Interfaces have the following properties −

 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.

/* File name : MammalInt.java */


public class MammalInt implements Animal {
public void eat() {
System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
When implementation interfaces, there are several rules −

 A class can implement more than one interface at a time.


 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend another
class.
Extending Interfaces
An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods
of the parent interface.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


45

The following Sports interface is extended by Hockey and Football interfaces.


// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

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

Extending Multiple Interfaces


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as –
public interface Hockey extends Sports, Event

1.7 Autoboxing and Unboxing

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


46

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.

Consider the following code:

List<Integer> li = new ArrayList<>();


for (int i = 1; i < 50; i += 2)
li.add(i);

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:

List<Integer> li = new ArrayList<>();


for (int i = 1; i < 50; i += 2)
li.add(Integer.valueOf(i));

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:

 Passed as a parameter to a method that expects an object of the corresponding wrapper


class.
 Assigned to a variable of the corresponding wrapper class.

Consider the following method:

public static int sumEven(List<Integer> li) {


int sum = 0;
for (Integer i: li)
if (i % 2 == 0)
sum += i;
return sum;
}

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:

public static int sumEven(List<Integer> li) {


int sum = 0;
for (Integer i : li)
if (i.intValue() % 2 == 0)

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


47

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:

 Passed as a parameter to a method that expects a value of the corresponding primitive


type.
 Assigned to a variable of the corresponding primitive type.

The Unboxing example shows how this works:

import java.util.ArrayList;
import java.util.List;

public class Unboxing {

public static void main(String[] args) {


Integer i = new Integer(-8);

// 1. Unboxing through method invocation


int absVal = absoluteValue(i);
System.out.println("absolute value of " + i + " = " + absVal);

List<Double> ld = new ArrayList<>();


ld.add(3.1416); // Π is autoboxed through method invocation.

// 2. Unboxing through assignment


double pi = ld.get(0);
System.out.println("pi = " + pi);
}

public static int absoluteValue(int i) {


return (i < 0) ? -i : i;
}
}

The program prints the following:

absolute value of -8 = 8
pi = 3.1416

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


48

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:

Primitive type Wrapper class

boolean Boolean

byte Byte

char Character

float Float

int Integer

long Long

short Short

double Double

1.8 VARIABLE LENGTH ARGUMENTS


Variable Arguments (Varargs) in Java
In JDK 5, Java has included a feature that simplifies the creation of methods that need to take a
variable number of arguments. This feature is called varargs and it is short-form for variable-
length arguments. A method that takes a variable number of arguments is a varargs method.
Prior to JDK 5, variable-length arguments could be handled two ways. One using overloaded
method(one for each) and another put the arguments into an array, and then pass this array to the
method. Both of them are potentially error-prone and require more code. The varargs feature
offers a simpler, better option.
Syntax of varargs :
A variable-length argument is specified by three periods(…). For Example,

public static void fun(int ... a)


{
// method body
}

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


49

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

// using for each loop to display contents of a


for (int i: a)
System.out.print(i + " ");
System.out.println();
}

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

Explanation of above program :


 The … syntax tells the compiler that varargs has been used and these arguments should be
stored in the array referred to by a.
 The variable a is operated on as an array. In this case, we have defined the data type of a as
int. So it can take only integer values. The number of arguments can be found out using
a.length, the way we find the length of an array in Java.
Note: A method can have variable length parameters with other parameters too, but one should
ensure that there exists only one varargs parameter that should be written last in the parameter
list of the method declaration.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


50

int nums(int a, float b, double … c)

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

// using for each loop to display contents of a


for (int i: a)
System.out.print(i + " ");

System.out.println();
}

public static void main(String args[])


{
// Calling fun2() with different parameter
fun2("GeeksforGeeks", 100, 200);
fun2("CSPortal", 1, 2, 3, 4, 5);
fun2("forGeeks");
}
}
Run on IDE

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


51

Erroneous varargs Examples


 Specifying two varargs in a single method:

 void method(String... gfg, int... q)


 {
 // Compile time error as there are two
 // varargs
 }

 Specifying varargs as the first parameter of method instead of last one:

 void method(int... gfg, String q)


 {
 // Compile time error as vararg appear
 // before normal argument

1.9 EXCEPTION HANDLING

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.

 A user has entered an invalid data.


 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run
out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


52

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.

2) Unchecked Exception: An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions. These include programming bugs, such
as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.
MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC
53

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError


etc.

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.

throw – to generate an exception or to describe an instance of an exception, If a method does not


handle a checked exception, the method must declare it using the throws keyword. The throws

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


54

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
}

//Example Java program to demonstrate ArithmeticException


class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


55

System.out.println ("Can't divide a number by 0");


}
}
}

//Java program to demonstrate NullPointerException


class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}

// Java program to demonstrate StringIndexOutOfBoundsException


class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}

MULTIPLE CATCH BLOCK:

 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

public class TestMultipleCatchBlock{


public static void main(String args[]){

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


56

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

System.out.println("rest of the code...");


}
}

NESTED TRY STATEMENTS:


 A try statement can be inside the block of another try
 Each time a try statement is entered, the context of that exception is pushed on the stack
 If an inner try statement does not have a catch, then the next try statement’s catch
handlers are inspected for a match
 If a method call within a try block has try block within it, then then it is still nested try

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[]){

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


57

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


58

UNIT II
COLLECTIONS AND ADVANCE FEATURES

Utility Packages- Introduction to collection –Hierarchy of Collection framework – Generics,


Array list, LL, HashSet, Treeset, HashMap – Comparators – Java annotations – Premain
method.

PACKAGES

 A java package is a group of similar types of classes, interfaces and sub-packages.


 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


59

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

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

2.1 UTILITY PACKAGES

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:

 The Hashtable class for implementing hashtables, or associative arrays.


 The Vector class, which supports variable-length arrays.
 The Enumeration interface for iterating through a collection of elements.
 The StringTokenizer class for parsing strings into distinct tokens separated by delimiter
characters.
 The EventObject class and the EventListener interface, which form the basis of the new
AWT event model in Java 1.1.
 The Locale class in Java 1.1, which represents a particular locale for internationalization
purposes.
 The Calendar and TimeZone classes in Java. These classes interpret the value of
a Date object in the context of a particular calendar system.
 The ResourceBundle class and its
subclasses, ListResourceBundle and PropertyResourceBundle, which represent sets of
localized data in Java 1.1.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


60

Figure shows the class hierarchy for the java.util package.


Figure : The java.util package

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


61

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


62

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


63

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


64

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.

Several standard implementations such as LinkedList, HashSet, and TreeSet, of these


interfaces are provided that you may use as-is and you may also implement your own collection,
if you choose.
A collections framework is a unified architecture for representing and manipulating collections.
All collections frameworks contain the following:

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 Interfaces:


The collections framework defines several interfaces. This section provides an overview of each
interface:

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 SortedSet : This extends Set to handle sorted sets

The Map: This maps unique keys to values.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


65

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.

The Collection Classes:


Java provides a set of standard collection classes that implement Collection interfaces. Some of
the classes provide full implementations that can be used as-is and others are abstract class,
providing skeletal implementations that are used as starting points for creating concrete
collections.
The standard collection classes are summarized in the following table:

1 AbstractCollection: Implements most of the Collection interface.


2 AbstractList:Extends AbstractCollection and implements most of the List interface.
3 AbstractSequentialList: Extends AbstractList for use by a collection that uses sequential
rather than random access of its elements.
4 LinkedList: Implements a linked list by extending AbstractSequentialList.
5 ArrayList: Implements a dynamic array by extending AbstractList.
6 AbstractSet: Extends AbstractCollection and implements most of the Set interface.
7 HashSet: Extends AbstractSet for use with a hash table.
8 LinkedHashSet:Extends HashSet to allow insertion-order iterations.
9 TreeSet : Implements a set stored in a tree. Extends AbstractSet.
10 AbstractMap : Implements most of the Map interface.
11 HashMap : Extends AbstractMap to use a hash table.
12 TreeMap : Extends AbstractMap to use a tree.
13 WeakHashMap: Extends AbstractMap to use a hash table with weak keys.
14 LinkedHashMap : Extends HashMap to allow insertion-order iterations.
15 IdentityHashMap : Extends AbstractMap and uses reference equality when comparing
documents.
The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap
classes provide skeletal implementations of the core collection interfaces, to minimize the effort
required to implement them.
The following legacy classes defined by java.util have been discussed in previous tutorial:
1 Vector : This implements a dynamic array. It is similar to ArrayList, but with some differences.
2 Stack : Stack is a subclass of Vector that implements a standard last-in, first-out stack.
3 Dictionary : Dictionary is an abstract class that represents a key/value storage repository and
operates much like Map.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


66

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.

How to use an Iterator ?


Often, you will want to cycle through the elements in a collection. For example, you might want
to display each element.
The easiest way to do this is to employ an iterator, which is an object that implements either the
Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator
extends Iterator to allow bidirectional traversal of a list and the modification of elements.

How to use a Comparator ?


Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that
defines precisely what sorted order means.
This interface lets us sort a given collection any number of different ways. Also this interface can
be used to sort any instances of any class evenclasseswecannotmodify.

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

Let’s learn about them in detail:


Interfaces: Interface in Java refers to the abstract data types. They allow Java collections to be
manipulated independently from the details of their representation. Also, they form a hierarchy
in object-oriented programming languages.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


67

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:

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


68

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

Let’s go into detail on each one of them:

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.

void add(int index, Object


Inserts the specified element at the specified position.
element)
void clear() Removes all the elements from this list.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


69

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.

Trims the capacity of this ArrayList instance to be the list’s current


void trimToSize()
size.
Let us understand Array list with a programmatic example:
1 import java.util.*;
2 class ArrayListExample{
3 public static void main(String args[]){
4
5 ArrayList al=new ArrayList(); // creating array list
6 al.add("Jack"); // adding elements
7 al.add("Tyler");
8 Iterator itr=al.iterator();
9 while(itr.hasNext()){
10 System.out.println(itr.next());
11 }
12 }
13 }
In the above code, it will return the names that we have added using add() method i.e:

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


 Doubly Linked List

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


70

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.

Some of the methods in the linked list are listed below:


Method Description
It is used to append the specified element to the end of
boolean add( Object o)
the vector.
boolean contains(Object o) Returns true if this list contains the specified element.

void add (int index, Object element) Inserts the element at the specified element in the vector.

void addFirst(Object o) It is used to insert the given element at the beginning.

void addLast(Object o) It is used to append the given element to the end.

int size() It is used to return the number of elements in a list


Removes the first occurrence of the specified element
boolean remove(Object o)
from this list.
Returns the index of the first occurrence of the specified
int indexOf(Object element)
element in this list, or -1.
Returns the index of the last occurrence of the specified
int lastIndexOf(Object element)
element in this list, or -1.
Let us understand linked list with a programmatic example:
1 import java.util.*;
2 public class LinkedlistExample{
3 public static void main(String args[]){
4 LinkedList<String> al=new LinkedList<String>(); // creating linked list
5 al.add("Rachit"); // adding elements
6 al.add("Rahul");

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


71

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


72

Returns the index of the first occurrence of the specified


int indexOfObject (Object element)
element in the list, or -1.
int size() Returns the number of elements in this list.
Return the index of the last occurrence of the specified
int lastIndexOf(Object o) element in the list, or -1 if the list does not contain any
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)

Object remove() Retrieves and removes the head of the queue.

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

4 PriorityQueue<String> queue=new PriorityQueue<String>(); // creating priority queue


5 queue.add("Amit"); // adding elements
6 queue.add("Rachit");
7 queue.add("Rahul");
8 System.out.println("head:"+queue.element());
9 System.out.println("head:"+queue.peek());
10 System.out.println("iterating the queue elements:");
11 Iterator itr=queue.iterator();
12 while(itr.hasNext()){
13 System.out.println(itr.next());
14 }
15 queue.remove();
16 queue.poll();
17 System.out.println("after removing two elements:");
18 Iterator<String> itr2=queue.iterator();
19 while(itr2.hasNext()){
20 System.out.println(itr2.next());
21 }
22 }
23 }
In the above code, the output would be :

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.

Let’s go into detail on each one of them:


HashSet: Java HashSet class creates a collection that use a hash table for storage. Hashset only
contain unique elements and it inherits the AbstractSet class and implements Set interface. Also,

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


74

it uses a mechanism hashing to store the elements.


Below are some of the methods of Java HashSet class:
Method Description
boolean add(Object o) Adds the specified element to this set if it is not already present.

boolean contains(Object o) Returns true if the set contains the specified element.

void clear() Removes all the elements from the set.


boolean isEmpty() Returns true if the set contains no elements.

boolean remove(Object o) Remove the specified element from the set.

Returns a shallow copy of the HashSet instance: the elements


Object clone()
themselves are not cloned.

Iterator iterator() Returns an iterator over the elements in this set.


int size() Return the number of elements in the set.
Let us understand these Hashset with a programmatic example:
1 import java.util.*;
2 class HashsetExample{
3 public static void main(String args[]){
4
5 HashSet<String> al=new HashSet(); // creating hashSet
6 al.add("Rachit"); // adding elements
7 al.add("Amit");
8 al.add("jack");
9 Iterator<String> itr=al.iterator();
10 while(itr.hasNext()){
11 System.out.println(itr.next());
12 }
13 }
14 }
The output of the above code would be:

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.

Let us understand these TreeSet with a programmatic example:


1 import java.util.*;
2 class TreeSetExample{
3 public static void main(String args[]){
4 TreeSet<String> al=new TreeSet<String>(); // creating treeSet
5 al.add("John"); // adding elements
6 al.add("Sam");
7 al.add("Rick");
8 Iterator<String> itr=al.iterator();
9 while(itr.hasNext()){
10 System.out.println(itr.next());
11 }
12 }
13 }

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


76

The output of the above program would be:

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 −

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


77

public class GenericMethodTest {


// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}

public static void main(String args[]) {


// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");


printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");


printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");


printArray(charArray); // pass a Character array
}
}

This will produce the following result −

Output
Array integerArray contains:
12345

Array doubleArray contains:


1.1 2.2 3.3 4.4

Array characterArray contains:


HELLO

Bounded Type Parameters

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


78

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 −

public class MaximumTest {


// determines the largest of three Comparable objects

public static <T extends Comparable<T>> T maximum(T x, T y, T z) {


T max = x; // assume x is initially the largest

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
}

public static void main(String args[]) {


System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",


6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));

System.out.printf("Max of %s, %s and %s is %s\n","pear",


"apple", "orange", maximum("pear", "apple", "orange"));
}
}

This will produce the following result −

Output

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


79

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

Following example illustrates how we can define a generic class −

public class Box<T> {


private T t;

public void add(T t) {


this.t = t;
}

public T get() {
return t;
}

public static void main(String[] args) {


Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();

integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());


System.out.printf("String Value :%s\n", stringBox.get());
}
}

This will produce the following result −

Output

Integer Value :10


String Value :Hello World

Java Comparator interface

Java Comparator interface is used to order the objects of user-defined class.

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


80

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.

Method of Collections class for sorting List elements

public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.

Java Comparator Example (Non-generic Old Style)

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


81

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

Java Comparator Example (Generic)


Student.java
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
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;

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


82

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


83

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

 @Retention - Specifies how the marked annotation is stored—Whether in code only,


compiled into the class, or available at runtime through reflection.
 @Documented - Marks another annotation for inclusion in the documentation.
 @Target - Marks another annotation to restrict what kind of Java elements the annotation
may be applied to.
 @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by
default annotations are not inherited to subclasses).
Since Java 7, three additional annotations have been added to the language.

 @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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


84

 @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.

public class Animal {


public void speak() {
}

public String getType() {


return "Generic animal";
}
}

public class Cat extends Animal {


@Override
public void speak() { // This is a good override.
System.out.println("Meow.");
}

@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.

// @Twizzle is an annotation to method toggle().


@Twizzle
public void toggle() {
}

// Declares the annotation Twizzle.


public @interface Twizzle {
}

Annotations may include an optional list of key-value pairs:

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


85

// Same as: @Edible(value = true)


@Edible(true)
Item item = new Carrot();

public @interface Edible {


boolean value() default false;
}

@Author(first = "Oompah", last = "Loompah")


Book book = new Book();

public @interface Author {


String first();
String last();
}

Annotations themselves may be annotated to indicate where and when they can be used:

@Retention(RetentionPolicy.RUNTIME) // Make this annotation accessible at runtime via


reflection.
@Target({ElementType.METHOD}) // This annotation can only be applied to class
methods.
public @interface Tweezable {
}

The compiler reserves a set of special annotations


(including @Deprecated, @Override and @SuppressWarnings) for syntactic purposes.
Annotations are often used by frameworks as a way of conveniently applying behaviours to user-
defined classes and methods that must otherwise be declared in an external source (such as an
XML configuration file) or programmatically (with API calls). The following, for example, is an
annotated JPA data class:

@Entity // Declares this an entity bean


@Table(name = "people") // Maps the bean to SQL table "people"
public class Person implements Serializable {
@Id // Map this to the primary key column.
@GeneratedValue(strategy = GenerationType.AUTO) // Database will generate new primary
keys, not us.
private Integer id;

@Column(length = 32) // Truncate column values to 32 characters.


private String name;

public Integer getId() {


return id;
}

public void setId(Integer id) {

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


86

this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

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

public @interface Unfinished {


public enum Priority { LOW, MEDIUM, HIGH }
String value();
String[] changedBy() default "";
String[] lastChangedBy() default "";
Priority priority() default Priority.MEDIUM;
String createdBy() default "James Gosling";
String lastChanged() default "2011-07-08";
}
package com.annotation;

public @interface UnderConstruction {


String owner() default "Patrick Naughton";
String value() default "Object is Under Construction.";
String createdBy() default "Mike Sheridan";
String lastChanged() default "2011-07-08";

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


87

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

public void validate(FacesContext context, UIComponent component, Object value)


throws ValidatorException
{
String date = (String) value;
String errorLabel = "Please enter a valid date.";
if (!component.getAttributes().isEmpty())
{
errorLabel = (String) component.getAttributes().get("errordisplayval");
}

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

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


88

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;

// This is the annotation to be processed


// Default for Target is all Java Elements
// Change retention policy to RUNTIME (default is CLASS)
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeHeader {
// Default value specified for developer attribute
String developer() default "Unknown";
String lastModified();
String [] teamMembers();
int meaningOfLife();
}
// This is the annotation being applied to a class
@TypeHeader(developer = "Bob Bee",
lastModified = "2013-02-12",
teamMembers = { "Ann", "Dan", "Fran" },
meaningOfLife = 42)

public class SetCustomAnnotation {


// Class contents go here
}
// This is the example code that processes the annotation
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;

public class UseCustomAnnotation {


public static void main(String [] args) {
Class<SetCustomAnnotation> classObject = SetCustomAnnotation.class;
readAnnotation(classObject);
}

static void readAnnotation(AnnotatedElement element) {


try {

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


89

System.out.println("Annotation element values: \n");


if (element.isAnnotationPresent(TypeHeader.class)) {
// getAnnotation returns Annotation type
Annotation singleAnnotation =
element.getAnnotation(TypeHeader.class);
TypeHeader header = (TypeHeader) singleAnnotation;

System.out.println("Developer: " + header.developer());


System.out.println("Last Modified: " + header.lastModified());

// teamMembers returned as String []


System.out.print("Team members: ");
for (String member : header.teamMembers())
System.out.print(member + ", ");
System.out.print("\n");

System.out.println("Meaning of Life: "+ header.meaningOfLife());


}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}

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:

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC


90

public static void premain(String agentArgs, Instrumentation inst);

If the agent class does not implement this method then the JVM will attempt to invoke:

public static void premain(String agentArgs);

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.

MC5304-Programming with Java Mrs.M.Deepanayaki,ASP/MCA/PEC

S-ar putea să vă placă și