MC5304 Programming With Java PDF
MC5304 Programming With Java PDF
PART A
UNIT I
Object oriented
dynamic
distributed
portable
multithreaded language.
Class Interface
Methods in a class Methods in an
are declared and are interface are
implemented declared and are not
implemented (i.e)
the methods do not
have abody
Variable in a class Variable in an
can be of any type interface are of type
final
We can’t have more We can have any
than one base number of interface
interface
11. What are the special features in Java that is not in C++?
Distributed: Java programs can access data across a network.
Compiled and interpreted: Java code we write is compiled to bytecode and interpreted
when we executed the program.
Robust: Java programs are less prone to error.
Multithreaded: it allows multiple parts of a program to run simultaneously.
Dynamic: maintaining different versions of an application is very easy in Java.
12. Explain the syntax of jump statement in java.
Break - when you use the break statement in the switch, it terminate the statement
sequence in a switch.
Continue - Sometime you want to continue running the loop, but stop processing the
remainder of the code in its body for this particular iteration the continue statement
performs such an action.
Return -the return statement is used to explicitly return from a method.
13. Write the syntax of iteration statement.
(i) While
While(condition)
{
//body of loop
}
(ii) do..while
do
{
//body of loop
}
while(condition);
(iii)for:
for(initialization;condition;iteration)
{
//body }
14. Discuss about binary operators in java
+ - Addition
- - Subtraction
* - Multiplication
/ - Division
% - Modulus
15. Define Ternary operator?
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the ?, general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true,
then expression2 is evaluated; otherwise, expression3 is evaluated.
16. What is the difference between >>= and >>>= operators?
>>= Shift right assignment-Right shift AND assignment operator for ex: C >>= 2 is same as C =
C >> 2 &>>>= Shift right zero fill assignment-Zero fill right shift assignment (x = x >>> y)
17. What is Garbage Collection?
Objects are dynamically allocated by using the new operator, we wonder how such objects are
destroyed and their memory released for later reallocation. Java handles deallocation
automatically. This is called garbage collection. Garbage collection only occurs sporadically
during the execution of our program. It will not occur simply because one or more objects exist
that are no longer used.
18. Give an example for dynamic initialization of a variable?
public class MainClass {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
class Series
{
public staticvoid main(Stringargs[])
{
inta,d,n=1,t,b;
while(b!=n-1)
{
t=(a+(n-1)*d);
n++;
System.out.print(t+" ");}}}
UNIT II
1. Describe the Collections type hierarchy. What are the main interfaces, and what are the
differences between them?
The Iterable interface represents any collection that can be iterated using the for-each loop.
The Collection interface inherits from Iterable and adds generic methods for checking if an
element is in a collection, adding and removing elements from the collection, determining its size
etc.
The List, Set, and Queue interfaces inherit from the Collection interface.
List is an ordered collection, and its elements can be accessed by their index in the list.
Set is an unordered collection with distinct elements, similar to the mathematical notion of a set.
Queue is a collection with additional methods for adding, removing and examining elements,
useful for holding elements prior to processing.
Map interface is also a part of the collection framework, yet it does not extend Collection. This is
by design, to stress the difference between collections and mappings which are hard to gather
under a common abstraction. The Mapinterface represents a key-value data structure with unique
keys and no more than one value for each key.
2. Describe various implementations of the Map interface and their use case differences.
One of the most often used implementations of the Map interface is the HashMap. It is a typical
hash map data structure that allows accessing elements in constant time, or O(1), but does not
preserve order and is not thread-safe.
To preserve insertion order of elements, you can use the LinkedHashMap class which extends
the HashMap and additionally ties the elements into a linked list, with foreseeable overhead.
The TreeMap class stores its elements in a red-black tree structure, which allows accessing
elements in logarithmic time, or O(log(n)). It is slower than the HashMapfor most cases, but it
allows keeping the elements in order according to some Comparator.
The ConcurrentHashMap is a thread-safe implementation of a hash map. It provides full
concurrency of retrievals (as the get operation does not entail locking) and high expected
concurrency of updates.
The Hashtable class has been in Java since version 1.0. It is not deprecated but is mostly
considered obsolete. It is a thread-safe hash map, but unlike ConcurrentHashMap, all its methods
are simply synchronized, which means that all operations on this map block, even retrieval of
independent values.
3. Explain the difference between LinkedList and ArrayList.
ArrayList is an implementation of the List interface that is based on an array. ArrayList internally
handles resizing of this array when the elements are added or removed. You can access its
elements in constant time by their index in the array. However, inserting or removing an element
infers shifting all consequent elements which may be slow if the array is huge and the inserted or
removed element is close to the beginning of the list.
LinkedList is a doubly-linked list: single elements are put into Node objects that have references
to previous and next Node. This implementation may appear more efficient than ArrayList if you
have lots of insertions or deletions in different parts of the list, especially if the list is large.
4. What is the difference between HashSet and TreeSet?
Both HashSet and TreeSet classes implement the Set interface and represent sets of distinct
elements. Additionally, TreeSet implements the NavigableSetinterface. This interface defines
methods that take advantage of the ordering of elements.
HashSet is internally based on a HashMap, and TreeSet is backed by a TreeMapinstance, which
defines their properties: HashSet does not keep elements in any particular order. Iteration over the
elements in a HashSet produces them in a shuffled order. TreeSet, on the other hand, produces
elements in order according to some predefined Comparator.
5. How is HashMap implemented in Java? How does its implementation
use hashCode and equals methods of objects? What is the time complexity of putting and
getting an element from such structure?
The HashMap class represents a typical hash map data structure with certain design choices.
The HashMap is backed by a resizable array that has a size of power-of-two. When the element is
added to a HashMap, first its hashCode is calculated (an intvalue). Then a certain number of
lower bits of this value are used as an array index. This index directly points to the cell of the
array (called a bucket) where this key-value pair should be placed. Accessing an element by its
index in an array is a very fast O(1) operation, which is the main feature of a hash map structure.
A hashCode is not unique, however, and even for different hashCodes, we may receive the same
array position. This is called a collision. There is more than one way of resolving collisions in the
hash map data structures. In Java’s HashMap, each bucket actually refers not to a single object,
but to a red-black tree of all objects that landed in this bucket (prior to Java 8, this was a linked
list).
6. What is the purpose of the initial capacity and load factor parameters of a HashMap?
What are their default values?
The initialCapacity argument of the HashMap constructor affects the size of the internal data
structure of the HashMap, but reasoning about the actual size of a map is a bit tricky.
The HashMap‘s internal data structure is an array with the power-of-two size. So
the initialCapacity argument value is increased to the next power-of-two (for instance, if you set
it to 10, the actual size of the internal array will be 16).
The initialCapacity is 16 by default, and the loadFactor is 0.75 by default, so you could put 12
elements in a HashMap that was instantiated with the default constructor, and it would not resize.
The same goes for the HashSet, which is backed by a HashMap instance internally.
7. Describe special collections for enums. What are the benefits of their implementation
compared to regular collections?
EnumSet and EnumMap are special implementations of Set and Map interfaces correspondingly.
You should always use these implementations when you’re dealing with enums because they are
very efficient.An EnumSet is just a bit vector with “ones” in the positions corresponding to
ordinal values of enums present in the set. To check if an enum value is in the set, the
implementation simply has to check if the corresponding bit in the vector is a “one”, which is a
very easy operation. Similarly, an EnumMap is an array accessed with enum’s ordinal value as an
index. In the case of EnumMap, there is no need to calculate hash codes or resolve collisions.
8. What is the difference between fail-fast and fail-safe iterators?
Fail-fast iterators (those returned by HashMap, ArrayList, and other non-thread-safe collections)
iterate over the collection’s internal data structure, and they
throw ConcurrentModificationException as soon as they detect a concurrent modification.
Fail-safe iterators (returned by thread-safe collections such
as ConcurrentHashMap, CopyOnWriteArrayList) create a copy of the structure they iterate upon.
They guarantee safety from concurrent modifications. Their drawbacks include excessive
memory consumption and iteration over possibly out-of-date data in case the collection was
modified.
9. How can you use Comparable and Comparatorinterfaces to sort collections?
The Comparable interface is an interface for objects that can be compared according to some
order. Its single method is compareTo, which operates on two values: the object itself and the
argument object of the same type. For instance, Integer, Long, and other numeric types
implement this interface. String also implements this interface, and its compareTo method
compares strings in lexicographical order.
The Comparable interface usually is implemented using natural ordering of the elements. For
instance, all Integer numbers are ordered from lesser to greater values. But sometimes you may
want to implement another kind of ordering, for instance, to sort the numbers in descending order.
The Comparator interface can help here.
As the Comparator interface is a functional interface, you may replace it with a lambda
expression, as in the following example. It shows ordering a list using a natural ordering
(Integer‘s Comparable interface) and using a custom iterator (Comparator<Integer> interface).
10. What is Difference between Hashtable and HashMap in Java?
This Java collection interview question is I guess most popular one. Most of Java programmer
who has at least 2 years of experience has seen this question on core Java or J2EE interview.
Well, there is much difference between them but most important is thread-safety, HashMap is not
thread-safe while Hashtable is a thread-safe collection. See Hashtable vs HashMap in Java for
A poor hashCode function will result in frequent collisions in HashMap, which eventually
increases the time for adding an object into said HashMap.From Java 8 onwards, though,
collisions will not impact performance as much as in earlier versions because, after a threshold,
the linked list will be replaced by the binary tree, which will give you O(log N) performance in
the worst case, as compared to O(N) of a linked list.
UNIT III
Swing is a set of classes that provides more powerful and flexible components than are possible
with the AWT. Unlike AWT components, Swing components are not implemented by platform-
specific code. Instead, they are written entirely in Java and, therefore, are platform-independent.
The term lightweight is used to describe such elements.
25. Explain swing classes?
Class Description
AbstractButton Abstract superclass for Swing buttons.
ButtonGroup Encapsulates a mutually exclusive set of buttons.
ImageIcon Encapsulates an icon.
JApplet The Swing version of Applet.
JButton The Swing push button class.
JCheckBox The Swing check box class.
JComboBox Encapsulates a combo box (an combination of a drop-down list and text field).
JLabel. The Swing version of a label
JRadioButton The Swing version of a radio button.
JScrollPane Encapsulates a scrollable window.
JTabbedPane Encapsulates a tabbed window.
JTable Encapsulates a table-based control.
JTextField The Swing version of a text field.
JTree Encapsulates a tree-based control.
26. Specify the difference between “Get” and “Post” methods in Java servlets. (DEC 2014)
GET and POST basically allow information to be sent back to the webserver from a browser (or
other HTTP client for that matter).
Imagine that you have a form on a HTML page and clicking the "submit" button sends the data in
the form back to the server, as "name=value" pairs.
Choosing GET as the "method" will append all of the data to the URL and it will show up in the
URL bar of your browser. The amount of information you can send back using a GET is
restricted as URLs can only be 1024 characters.
Web module
MVC module
17. What are the benefits of Spring Framework?
Lightweight container
Spring can effectively organize your middle tier objects
Initialization of properties is easy. No need to read from a property file
Application code is much easier to unit test
Objects are created lazily, singleton-configuration
Spring’s configuration management services can be used in any architectural layer
18. What is Play Framework?
Play Framework makes it easy to build scalable, fast and real-time web applications with Java
and Scala. In other words Play Framework is a core offering of the Type safe Reactive Paltform.
It is a web app framework, written in Scala and Java that provides iterative and Reactive
application development very simple. The Play is a clean alternative to the legacy Enterprise Java
stacks.
19. What do you mean by the Java Collection Framework?
Collections are utilized in various programming languages and basic release contained some
classes for collections such as Vector, Stack, Hashtable, and Array. But the more scope and uses
Java 1.2 came up with collections Framework the collections interfaces, implementations and
different type algorithms.
20. What are the advantages of Collections Framework?
Some of the advantages of collections framework are:
The reduce development effort by using core collection classes rather than defining
collection classes.
The code quality is improved with the use of completely tested collections framework
classes.
Reduce some effort for code maintenance by utilizing collection classes with the JDK.
Collection framework also provides reusability and Interoperability.
UNIT V
Introspection is the automatic process of analyzing a bean's design patterns to reveal the
bean's properties, events, and methods. This process controls the publishing and discovery of
bean operations and properties.
5. What are the different advantages in Java Introspection?
Introspection is an automatic process in which the bean's design patterns are analyzed to
extract the bean's properties, events, and methods. Introspection has some great advantages
as under:
Portability.
Re-usability.
6. What are the Different classes in Java Introspection?
BeanDescriptor, BeanInfo, FeatureDescriptor, EventSetDescriptor
MethodDescriptor, PropertyDescriptor, IndexedPropertyDescriptor
Introspector ,SimpleBeanInfo
7. What is meant by garbage collection?
Java garbage collection is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short. When Java programs run on the JVM, objects are created on the heap,
which is a portion of memory dedicated to the program.
8. What are the advantages of Java Garbage Collection?
The biggest benefit of Java garbage collection is that it automatically handles deletion of
unused objects or objects that are out of reach to free up vital memory
resources. Programmers working in languages without garbage collection (like C and C++)
must implement manual memory management in their code.
9.Define Java virtual Machine.
JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the
one that actually calls the main method present in a java code. JVM is a part of JRE(Java
Run Environment).
10.What is meant by Java Virtual machine?
A virtual machine (VM) is a software implementation of a machine (i.e. a computer) that
executes programs like a physical machine. Originally, Java was designed to run based on a
virtual machine separated from a physical machine for implementing WORA (Write Once
Run Anywhere), although this goal has been mostly forgotten
11.What are the main features of Java Virtual Machine?
Stack-based virtual machine, Symbolic reference, Garbage collection, Guarantees platform
independence by clearly defining the primitive data type, Network byte order
12. What is meant by Java Byte Code?
To implement WORA, the JVM uses Java bytecode, a middle-language between Java (user
language) and the machine language. This Java bytecode is the smallest unit that deploys the
Java code.
13. What are sockets?
A socket is an endpoint for communication. Socket is an abstraction for an endpoint of
communication that can be manipulated with a file descriptor. Scope of a socket is the
communication domain in which it exists. A socket address is the combination of an IP
address and a port which is mapped to the application program process.
14.How do you create a socket?
Socket is created using the socket( ) system call. The syntax is as follows
sockfd = socket(int family, int type, int protocol).
sockfd refers to file descriptor for created socket and family represents address family
It can be AF_INET (IPV4) AF_INET6 (IPV6). Here type represents the socket type.
15.What is the use of recv() function?
This function is used to receive data from remote peer. The syntax is
PART B
UNIT I
Packages are containers for classes that are used to keep the class name space separately.
A unique name is to be used for each class to avoid name collisions.
Defining a package:
To create a package, include a package command as the first statement in java source
file.
The package statement defines a name space in which classes are stored.
Syntax: package Mypackage; Here Mypackage is the name of the package.
We can have a hierarchy of packages.
Syntax:package pkg1[.pkg2][.pkg3];
Inside pack1 folder:
package pack1;
public class student
{
String name;
String course;
int tot, avg;
public void initialise(String s1,String c)
{
name=s1;
course=c;
}
public void calc(int m1,int m2,int m3)
{
tot=m1+m2+m3;
avg=tot/3;
}
public void display()
{
System.out.println("\nStudent name : " +name);
System.out.println("\nCourse : " +course);
System.out.println("\nTotal : " +tot);
System.out.println("\nAverage : " +avg);
}
}
MainClass(outside pack1)
import java.io.*;
import pack1.*;
class packeg extends student
{
public static void main(String args[])throws IOException
{
int i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s,s1,s2;
St. Joseph’s College of Engineering - 20 -
MC5304/ Programming With JAVA MCA 2018-2019
int m1,m2,m3;
int no;
System.out.println("\nEnter the number of students :");
s=br.readLine();
no=Integer.parseInt(s);
for(i=1;i<=no;i++)
{
System.out.println("\nEnter Name:");
s1=br.readLine();
System.out.println("\nEnter Course :");
s2=br.readLine();
packeg p=new packeg();
p.initialise(s1,s2);
System.out.println("\nEnter the marks :");
m1=Integer.parseInt(br.readLine());
m2=Integer.parseInt(br.readLine());
m3=Integer.parseInt(br.readLine());
p.calc(m1,m2,m3);
p.display();
}
}
}
Defining Interfaces:
It is basically a kind of class. Like classes, interfaces contain methods and variables.
But the interface defines only abstract methods and final fields.
Syntax: interface interfacename {
variable declaration;
method declaration; }
Extending interfaces:
Like classes, interfaces can also be extended.
The new sub interface will inherit all the members of the super interface.
This is done by extends keyword.
Implementing interfaces:
Interfaces are used as “super classes” whose properties are inherited by classes.
class class-name implements interface-name
{ Body of class-name }
The class class-name implements the interface interface-name.
interface area //Interface defined
{
final static float pi=3.14;
float compute(float x,float y);
}
Class rectangle implements area
{
public float compute(float x,float y)
{
return(x*y);
St. Joseph’s College of Engineering - 21 -
MC5304/ Programming With JAVA MCA 2018-2019
}
}
Class circle implements area
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}
class test
{
public static void main(String args[])
{
rectangle r=new rectangle();
circle c=new circle();
area a; //Interface object
a=r;
System.out.println(“Area of rect:”+a.compute(10,20));
a=c;
System.out.println(“Area of circle:”+a.compute(10,0));
}
}
i) Exception Handling
A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error.
That method may choose to handle the exception itself, or pass it on.
Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code. Manually generated exceptions are typically used to report
some error condition to the caller of a method.
Five keywords
try, catch, throw, throws and finally.
General form of an exception-handling block
Types of Exception: (i) Built – in Exception (ii) User defined exception
class Exc2 {
public static void main(String args[ ]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) {// catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
St. Joseph’s College of Engineering - 22 -
MC5304/ Programming With JAVA MCA 2018-2019
}
}
A java variable can be declared using the keyword final. Then the final variable can be
assigned only once.
A variable that is declared as final and not initialized is called a blank final variable. A
blank final variable forces the constructors to initialise it.
Java classes declared as final cannot be extended. Restricting inheritance!
Methods declared as final cannot be overridden. In methods private is equal to final, but in
variables it is not.
final parameters – values of the parameters cannot be changed after initialization. Do a
small java exercise to find out the implications of final parameters in method overriding.
class FinallyDemo {
6. Write Java program to Check whether the given matrix is upper triangular or not.
import java.io.*;
class uppertri
{
void upper( )
{
int count;
int d[][] = { { 1, 2, 6 }, { 3, 8, 5 }, { 5, 6, 7 } };
System.out.println();
}
for(i = 0; i <= d.length; i++)
{
for(j = 0; j <= d.length; j++)
{
if(i <= j)
{
if(d[i][j] == 0)
count++;
}
}
}
if(count == 3)
else
System.out.println ("\nThe Matrix is not upper triangular\n");
}
}
public static void main(String args[])
{
classtri c = new classtri( );
c.upper( );
(ii) Name and explain the uses of various bit–wise operators in Java.
8. (i) Explain the operators in Java for arithmetic and logical shift operations. Show using
a Java program how multiplication by 2 can be implemented using a logical shift
operation (DEC 2015)
Operators
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.
With higher precedence are evaluated before operators with relatively lower precedence.
Operators on the same line have equal precedence. When operators of equal precedence
appear in the same expression, a rule must govern which is evaluated first.
Control Statements
The statements inside your source files are generally executed from top to bottom, in the order
that they appear. Control flow statements, however, break up the flow of execution by
employing decision making, looping, and branching, enabling your program to conditionally
execute particular blocks of code. This section describes the decision-making statements (if-
then, if-then-else, switch), the looping statements (for, while, do-while), and the branching
statements (break, continue, return) supported by the Java programming language.
void applyBrakes() {
// the "if" clause: bicycle must be moving if
(isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
}
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the
end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause
contains only one statement:
void applyBrakes() {
// same as above, but without braces if
(isMoving)
currentSpeed--;
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the
code more brittle. If a second statement is later added to the "then" clause, a common mistake
would be forgetting to add the newly required braces. The compiler cannot catch this sort of
error; you'll just get the wrong results.
The if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates
to false. You could use an if-then-else statement in the applyBrakes method to take some action
if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply
print an error message stating that the bicycle has already stopped.
void applyBrakes() { if
(isMoving) {
currentSpeed--; }
else {
St. Joseph’s College of Engineering - 28 -
MC5304/ Programming With JAVA MCA 2018-2019
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A
for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the
compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated.
Unlike if-then and if-then-else statements, the switch statement can have a number of possible
execution paths. A switch works with the byte, short, char, and int primitive data types. It also
works with enumerated types (discussed in Enum Types), the String class, and a few special
St. Joseph’s College of Engineering - 29 -
MC5304/ Programming With JAVA MCA 2018-2019
classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in
Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose value
represents a month. The code displays the name of the month, based on the value of month,
using the switch statement.
while (expression) {
statement(s)
The while statement evaluates expression, which must return a boolean value. If the expression
evaluates to true, the while statement executes the statement(s) in the while block. Thewhile
statement continues testing the expression and executing its block until the expression evaluates
to false. Using
the while statement to print the values from 1 through 10 can be
accomplished as in the following WhileDemo program:
class WhileDemo {
public static void main(String[] args){ int count
= 1;
while (count < 11) { System.out.println("Count is: " +
count); count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as
follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are always
executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count); count++;
} while (count < 11);
}
St. Joseph’s College of Engineering - 31 -
MC5304/ Programming With JAVA MCA 2018-2019
}
The for statement provides a compact way to iterate over a range of values. Programmers often
refer to it as the "for loop" because of the way in which it repeatedly loops until a particular
condition is satisfied. The general form of the for statement can be expressed as follows:
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){ for(int
i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
(ii) Demonstrate the if-else ladder using a sample Java code (DEC 2015)
The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false. You could use an if-then-else statement in the applyBrakes method to take
some action if the brakes are applied when the bicycle is not in motion. In this case, the
action is to simply print an error message stating that the bicycle has already stopped.
void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A
for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the
compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated.
Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
Integers
Floating-point numbers
Characters
10. Write a Java program for constructor overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
11. Create a package called "LIBRARY", which contains one class "BOOK" to
maintain all the book information. In another program, import the package and create
two classes "STAFF" and "STUDENT" from the super class "BOOK". In the main( )
method, create array of objects for the classes book and call the method in book class to
read the details of the available books and display the menu as 1. staff 2. student. If the
selected choice is 1, call the read method in staff class to read the details of the staff and
the books they want to take (Check whether the given book ids are available in the book
list). If the selected choice is 2, call the read method in student dais to read details of the
student and the books they want to take (Check whether the given book ids are
available in the book list). Before issuing each book, check that the book is available is
in. the library or not. After reading the values, use the corresponding display methods
to display the details of the staff or student with the books they have taken (DEC2014)
}
import java.util.*;
{
books.put(keyIn, bookIn); // add key and book pair into map
return true;
}
}
// return the book with the given isbn or null if no such book
public Book getBook (String isbnIn)
{
return books.get(isbnIn);
}
12. Explain in detail about Java classes and Java packages(DEC 2015)
/*
* First Java program, which says "Hello, world!"
*/
public class Hello { // Save as "Hello.java"
public static void main(String[] args) {
System.out.println("Hello, world!"); // print message
}
}
Packages are containers for classes that are used to keep the class name space
separately.
A unique name is to be used for each class to avoid name collisions.
Defining a package:
To create a package, include a package command as the first statement in java source
file.
The package statement defines a name space in which classes are stored.
Syntax: package Mypackage; Here Mypackage is the name of the package.
We can have a hierarchy of packages.
Syntax:package pkg1[.pkg2][.pkg3];
Inside pack1 folder:
package pack1;
public class student
{
String name;
String course;
int tot, avg;
public void initialise(String s1,String c)
{
name=s1;
course=c;
}
public void calc(int m1,int m2,int m3)
{
tot=m1+m2+m3;
avg=tot/3;
}
public void display()
{
System.out.println("\nStudent name : " +name);
System.out.println("\nCourse : " +course);
System.out.println("\nTotal : " +tot);
System.out.println("\nAverage : " +avg);
}
}
MainClass(outside pack1)
import java.io.*;
import pack1.*;
class packeg extends student
{
public static void main(String args[])throws IOException
{
int i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s,s1,s2;
int m1,m2,m3;
int no;
System.out.println("\nEnter the number of students :");
s=br.readLine();
no=Integer.parseInt(s);
for(i=1;i<=no;i++)
{
System.out.println("\nEnter Name:");
s1=br.readLine();
System.out.println("\nEnter Course :");
s2=br.readLine();
packeg p=new packeg();
p.initialise(s1,s2);
System.out.println("\nEnter the marks :");
m1=Integer.parseInt(br.readLine());
m2=Integer.parseInt(br.readLine());
m3=Integer.parseInt(br.readLine());
p.calc(m1,m2,m3);
p.display();
}
}
13. Discuss about the expressions, operators and various control structures in Java.
(DEC 2015)
Operators
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.
with higher precedence are evaluated before operators with relatively lower
precedence. Operators on the same line have equal precedence. When operators of
equal precedence appear in the same expression, a rule must govern which is evaluated
first.
Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -
expr ~ !
multiplicative */%
additive +-
Control Statements
The statements inside your source files are generally executed from top to bottom, in the
order that they appear. Control flow statements, however, break up the flow of execution by
employing decision making, looping, and branching, enabling your program to
conditionally execute particular blocks of code. This section describes the decision-making
statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and
the branching statements (break, continue, return) supported by the Java programming
language.
The if-then statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates to true. For
example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the
bicycle is already in motion. One possible implementation of the applyBrakes method could
be as follows:
void applyBrakes() {
// the "if" clause: bicycle must be moving if
(isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
}
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the
end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause
contains only one statement:
void applyBrakes() {
// same as above, but without braces if
(isMoving)
currentSpeed--;
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the
code more brittle. If a second statement is later added to the "then" clause, a common
mistake would be forgetting to add the newly required braces. The compiler cannot catch
this sort of error; you'll just get the wrong results.
The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates
to false. You could use an if-then-else statement in the applyBrakes method to take some
action if the brakes are applied when the bicycle is not in motion. In this case, the action is to
simply print an error message stating that the bicycle has already stopped.
void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A
for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the
compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated.
Unlike if-then and if-then-else statements, the switch statement can have a number of
possible execution paths. A switch works with the byte, short, char, and int primitive data
types. It also works with enumerated types (discussed in Enum Types), the String class,
and a few special classes that wrap certain primitive types: Character, Byte, Short, and
Integer (discussed in Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose value
represents a month. The code displays the name of the month, based on the value of month,
using the switch statement.
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while block.
Thewhile statement continues testing the expression and executing its block until the
expression evaluates to false. Using
class WhileDemo {
public static void main(String[] args){ int
count = 1;
while (count < 11) { System.out.println("Count is: "
+ count); count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed
as follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
The for statement provides a compact way to iterate over a range of values. Programmers
often refer to it as the "for loop" because of the way in which it repeatedly loops until a
particular condition is satisfied. The general form of the for statement can be expressed as
follows:
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop
begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){ for(int
i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
14. i) Explain Any Two Control Structure Supported By Java with Suitable Example
(DEC 2016)
A programming language uses control statements to cause the flow of execution to advance
and branch based on changes to the state of a program. Java’s program control statements can
be put into the following categories:
Selection
iteration
jump
Selection statements
Selection statements allows program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.
Iteration statements
Iteration statements enable program execution to repeat one or more statements (that is,
iteration statements form loops).
Jump statements
Jump statements allows program to execute in a nonlinear fashion. All of Java’s
control statements are examined here.
Selection Statements
1. if Statement
The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if statement:
if (condition)
{ statement1; }
else { statement2; }
Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block). The condition is any expression that returns a boolean value. The
else clause is optional. The if statement works like this:
If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is
executed.
Solution:
Example
class Man { public static void main(String args[]){
int age= 49;
if(age>=35) System.out.println("Old");
else System.out.println("Young");
}}
Output: Old
2. Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the else
and that is not already associated with an else.
3. The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the
if-else-if ladder. It looks like this:
if (condition1)
statement1;
else if (condition2)
statement2; ……………………….. ………………………..
else statement3;
The if statements are executed from the top to down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final else statement will be
executed.
Example
class Result { public static void main(String args[])
{
int mark= 76;
if(mark>=60) System.out.println("1st Division");
else if(mark>=50 && mark<60) System.out.println("2nd Division");
else System.out.println("3rd Division"); } }
Output: 1st Division
Switch Statements
The switch statement is Java’s multi way branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As
such, it often provides a better alternative than a large series of if-else-if statements. Here is
the general form of a switch statement:
switch (expression)
{
case value1: // statement sequence break
; case value2: // statement sequence break;
... case valueN:
// statement sequence break; default: // default statement sequence
}
Solution:
class SampleSwitch
{
public static void main(String args[])
{
14. ii) Declare An Interface Called Sports With Appropritate Methods. Design And
Implements Football And Volleyball Interface Which Extends Sports Interface. Write
Java Classes Which Implements Football And Volleyball Interface.(DEC 2016)
Interface sports{
Float Sport_wt=10.0f;
}
Interface football
{
Void putplayer();}
Interface volleyball(){
Void putplayer1();
}
Class main1{
Int f_player,v_player;
Void getplayer( int p1){
F_player=p1;
}
Void getplayer2(int p2){
V_player=p2
}}
Class main2 extends main1 im plements sports,football,volletball{
Public void putplayer(){
Getplayer();
System.out.println(“team football player is:”+f_player);
}
Public void putplayer(){
Getplayer2();
System.out.println(“team football player is:”+v_player);
}}
Class main3{
Public static void main(String args[]){
Main2 a=new main2();
a.geplayer1(4);
a.getplayer2(10);
a.putplayer1();
a.putplayer();}}
Error occurred in a program can be of two types: syntax error or logical error. An
exception is an abnormal condition that arises in a code sequence at run time. In other words,
an exception is a run-time error.
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. Exception Handling is a mechanism by which exception
occurred in a program is handled.
Java exception handling is managed via five keywords:
Try
Catch
Thro
throws
finally.
Keyword and their meaning
catch block If an exception occurs within the try block, it is throws an exception to
the catch block which handle it in some rational manner.
throw To manually throw an exception, use the keyword throw.
throwsA throws clause lists the types of exceptions that a method might throw
finallyAny code that absolutely must be executed before a method returns is put in a
finally block.
Execution Flow of the try, catch and finally block
The general form of an exception-handling block is:
try { // block of code to monitor for errors }
catch (ExceptionType1 exOb)
{ // exception handler for ExceptionType1 }
catch (ExceptionType2 exOb)
{ // exception handler for ExceptionType2 } ……….. ………..
finally
{ // block of code to be executed before try block ends }
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable
is at the top of the exception class hierarchy.
The Throwable class has two subclasses Error and Exception. Error and Exception classes
are used for handling errors in java.
Object
Throwable
Exception
AWT Error
Error
SQL Exceptionn
Thread
Class not Found
Runtime Exception
Number Format
Using try and catch
The following program includes a try block and a catch clause which processes the
ArithmeticException generated by the division-by-zero error.
Example:
class Ex {
public static void main(String args[])
{
int x, y; try { x = 0; y= 1/ x;
System.out.println("This will not be printed."); }}
catch (ArithmeticException e)
{
System.out.println("Division by zero."); }
System.out.println("After catch statement."); }
UNIT II
Java Annotations
Java annotation is used to provide the extra or supplement information about the program.
Annotations in Java are utilized to give supplement data about a program.
1. class Base
2. {
3. public void display()
4. {
5. System.out.println("Base display()");
6. }
7. }
8. class Derived extends Base
9. {
10. @Override
11. public void display(int x)
12. {
13. System.out.println("Derived display(int )");
14. }
15. public static void main(String args[])
16. {
17. Derived obj = new Derived();
18. obj.display();
19. }
20. }
Java Annotations
i. @Deprecated Annotation
@ Deprecated Java Annotation used to indicate that a declaration has become old
and has been replaced by a newer one, thus it is a marker annotation
The Javadoc @deprecated tag ought to utilize when a component has been
deployed.
A @deprecated tag is for documentation and @Deprecated annotation is for
runtime reflection.
A @deprecated tag has a higher need than @Deprecated annotation when both
areas one utilized.
1. class Base
2. {
3. public void Display()
4. {
5. System.out.println("Base display()");
6. }
7. public static void main(String args[])
8. {
9. Base t1 = new Derived();
10. t1.Display();
11. }
12. }
13. class Derived extends Base
14. {
15. @Override
16. public void Display()
17. {
18. System.out.println("Derived display()");
19. }
20. }
Output –
Derived displays
1. class DeprecatedTest
2. {
3. @Deprecated
4. public void Display()
5. {
6. System.out.println("Deprecatedtest display()");
7. }
8. }
9. public class SuppressWarningTest
10. {
11. @SuppressWarnings({"checked", "deprecation"})
12. public static void main(String args[])
13. {
14. DeprecatedTest d1 = new DeprecatedTest();
15. d1.Display();
16. }
17. }
Output-
Deprecatedtest display()
v. @Target Annotations
It is intended to utilize just as an explanation for another annotation. @Target takes one
argument, which must be consistent with the ElementType count. This annotation determines
the kind of assertions to which Java annotation can connect. The constants are appeared
beneath alongside the sort of affirmation to which they relate.
CONSTRUCTOR Constructor
FIELD Field
METHOD Method
PACKAGE Package
PARAMETER Parameter
SOURCE: Annotations will be held at the source level and disregarded by the
compiler.
CLASS: Annotations will be held at order time and overlooked by the JVM.
RUNTIME: These will be held at runtime.
AnnotationName is an identifier.
Parameter ought not relate to strategy assertions and tosses provision ought not
utilize with technique revelation.
Parameters won’t have an invalid esteem yet can have a default esteem.
default esteem is discretionary.
Return kind of strategy ought either crude, enum, string, class name or exhibit of
crude, enum, string or class name write.
1. import java.lang.annotation.Documented;
2. import java.lang.annotation.Retention;
3. import java.lang.annotation.RetentionPolicy;
4. @Documented
5. @Retention(RetentionPolicy.RUNTIME)
6. @ interface TestAnnotation
7. {
8. String Developer() default "Rahul";
9. String Expirydate();
10. }
11. public class Test
12. {
13. @TestAnnotation(Developer="data", Expirydate="01-10-2020")
14. void fun1()
15. {
16. System.out.println("Test method 1");
17. }
18.
19. @TestAnnotation(Developer="fair", Expirydate="01-10-2020")
20. void fun2()
21. {
22. System.out.println("Test method 2");
23. }
24.
25. public static void main(String args[])
26. {
27. System.out.println("Hello");
28. }
29. }
Output –
Hello
1) List —> It handles sequential list of objects. ArrayList, Vector and LinkedList classes
implement this interface.
2) Queue —> It handles special list of objects in which elements are removed only from the
head. LinkedList and PriorityQueue classes implement this interface.
3) Set —> It handles list of objects which must contain unique element. This interface is
implemented by HashSetand LinkedHashSet classes and extended by SortedSet interface
which in turn, is implemented by TreeSet.
4) Map —> This is the one interface in Collection Framework which is not inherited from
Collection interface. It handles group of objects as Key/Value pairs. It is implemented
by HashMap and HashTable classes and extended by SortedMap interface which in turn is
implemented by TreeMap.
Three of above interfaces (List, Queue and Set) inherit from Collection interface. Although,
Map is included in collection framework it does not inherit from Collection interface.
3. What is the need of collection framework? Give an example. Write down the advantages.
Since all the data operations(sorting/adding/deleting) are possible with Arrays and moreover
array is suitable for memory consumption and performance is also better compared with
Collections.
Arrays are not resizable.
Java Collections Framework provides lots of different useful data types, such as
linked lists (allows insertion anywhere in constant time), resizeable array lists
(like Vector but cooler), red-black trees, hash-based maps (like Hashtable but
cooler).
Java Collections Framework provides abstractions, so you can refer to a list as
a List, whether backed by an array list or a linked list; and you can refer to a
map/dictionary as a Map, whether backed by a red-black tree or a hashtable.
In other words, Java Collections Framework allows you to use the right data structure,
because one size does not fit all.
Yes, it is possible to get the same functionality as List and Set with an array, however there is
a lot of work involved. The whole point of a library is that users do not have to "roll their
own" implementations of common things.
Once you have a single implementation that everyone uses it is easier to justify spending
resources optimizing it as well. That means when the standard collections are sped up or have
their memory footprint reduced that all applications using them get the improvements for
free.
A single interface for each thing also simplifies every developers learning curve - there are
not umpteen different ways of doing the same thing.
If you wanted to have an array that grows over time you would probably not put the growth
code all over your classes, but would instead write a single utility method to do that. Same for
deletion and insertion etc...
Also, arrays are not well suited to insertion/deletion, especially when you expect that the
.length member is supposed to reflect the actual number of contents, so you would spend a
huge amount of time growing and shrinking the array. Arrays are also not well suited for Sets
as you would have to iterate over the entire array each time you wanted to do an insertion to
check for duplicates. That would kill any perceived efficiency.
4. Write in detail about Array list. Write the code to create generic ArrayList.
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.
As shown in above diagram, Java ArrayList class extends AbstractList class which
implements List interface. The List interface extends Collection and Iterable interfaces in
hierarchical order.
Constructor Description
ArrayList(int It is used to build an array list that has the specified initial
capacity) capacity.
Method Description
void add(int index, Object It is used to insert the specified element at the specified
element) position index in a list.
void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of
the specified element, or -1 if the list does not contain this
element.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, It is used to insert all of the elements in the specified collection
Collection c) into this list, starting at the specified position.
int indexOf(Object o) It is used to return the index in this list of the first occurrence
of the specified element, or -1 if the List does not contain this
element.
5. Write down the methods included in Linked list.Write a Java code for linked list
implementation.
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.
As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
In case of doubly linked list, we can add or remove elements from both side.
Constructor Description
1. import java.util.*;
2. public class TestCollection7{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
Method Description
void add(int index, Object It is used to insert the specified element at the specified position index in a
element) list.
void addFirst(Object o) It is used to insert the given element at the beginning of a list.
void addLast(Object o) It is used to append the given element to the end of a list.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean contains(Object o) It is used to return true if the list contains a specified element.
boolean remove(Object o) It is used to remove the first occurence of the specified element in a list.
int indexOf(Object o) It is used to return the index in a list of the first occurrence of the specified
element, or -1 if the list does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the specified
element, or -1 if the list does not contain any element.
13. System.out.println(itr.next());
14. }
15. }
16. }
Test it Now
Output:Ravi
Vijay
Ravi
Ajay
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new LinkedList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
29. }
30. }
31. }
Output:
obj.add("hello");
This statement would add a string hello in the arraylist at last position.
2) add(int index, Object o): It adds the object o to the array list at the given index.
obj.add(2, "bye");
It will add the string bye to the 2nd index (3rd position as the array list starts with index 0) of
array list.
obj.remove("Chaitanya");
This statement will remove the string “Chaitanya” from the ArrayList.
obj.remove(3);
It would remove the element of index 3 (4th element of the list – List starts with o).
5) set(int index, Object o): Used for updating an element. It replaces the element present at
the specified index with the object o.
obj.set(2, "Tom");
It would replace the 3rd element (index =2 is 3rd element) with the value Tom.
6) int indexOf(Object o): Gives the index of the object o. If the element is not found in the
list then this method returns the value -1.
7) Object get(int index): It returns the object of list which is present at the specified index.
8) int size(): It gives the size of the ArrayList – Number of elements of the list.
obj.contains("Steve");
It would return true if the string “Steve” is present in the list else we would get false.
10) clear(): It is used for removing all the elements of the array list in one go. The below
code will remove all the elements of ArrayList whose object is obj.
obj.clear();
6. Write down the impotant methods included in Hash set.Write a Java program to
demonstrate working of HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a collection that
uses a hash table for storage.
A hash table stores information by using a mechanism called hashing. In hashing, the
informational content of a key is used to determine a unique value, called its hash code.
The hash code is then used as the index at which the data associated with the key is stored.
The transformation of the key into its hash code is performed automatically.
1 HashSet( )
2 HashSet(Collection c)
This constructor initializes the hash set by using the elements of the collection c.
3 HashSet(int capacity)
This constructor initializes the capacity of the hash set to the given integer value
capacity. The capacity grows automatically as elements are added to the HashSet.
This constructor initializes both the capacity and the fill ratio (also called load
capacity) of the hash set from its arguments.
Here the fill ratio must be between 0.0 and 1.0, and it determines how full the
hash set can be before it is resized upward. Specifically, when the number of
elements is greater than the capacity of the hash set multiplied by its fill ratio, the
hash set is expanded.
Apart from the methods inherited from its parent classes, HashSet defines following
methods –
1 boolean add(Object o)
2 void clear()
3 Object clone()
Returns a shallow copy of this HashSet instance: the elements themselves are not
cloned.
4 boolean contains(Object o)
5 boolean isEmpty()
6 Iterator iterator()
7 boolean remove(Object o)
8 int size()
Example
The following program illustrates several of the methods supported by HashSet −
Live Demo
import java.util.*;
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
Output
[A, B, C, D, E, F]
7. What are the four constructors available in Tree set? Write down the methods included in
constructors.
Constructors:
Following are the four constructors in TreeSet class.
1. TreeSet t = new TreeSet();
This will create empty TreeSet object in which elements will get stored in default
natural sorting order.
2. TreeSet t = new TreeSet(Comparator comp);
This constructor is used when you externally wants to specify sorting order of elements
getting stored.
Synchronized TreeSet:
Implementation of TreeSet class is not synchronized. If there is need of synchronized version
of TreeSet, it can be done externally using Collections.synchronizedSet() method.
TreeSet ts = new TreeSet();
Set syncSet = Collections.synchronziedSet(ts);
class TreeSetDemo
{
public static void main (String[] args)
{
TreeSet ts1= new TreeSet();
ts1.add("A");
ts1.add("B");
ts1.add("C");
[A, B, C]
Null Insertion:
If we insert null in a TreeSet, it throws NullPointerException because while inserting null it
will get compared to existing elements and null can not be compared to any value.
// Java program to demonstrate null insertion
// in TreeSet
import java.util.*;
class TreeSetDemo
{
public static void main (String[] args)
{
TreeSet ts2= new TreeSet();
ts2.add("A");
ts2.add("B");
ts2.add("C");
ts2.add(null); // Throws NullPointerException
}
}
Output :
Note: For empty tree-set, when you try to insert null as first value, you will get NPE from
JDK 7.From 1.7 onwards null is not at all accepted by TreeSet. However upto JDK 6, null
will be accepted as first value, but any if we insert any more value in TreeSet, it will also
throw NullPointerException.
Hence it was considered as bug and thus removed in JDK 7.
Methods:
TreeSet implements SortedSet so it has availability of all methods in Collection, Set and
SortedSet interfaces. Following are the methods in Treeset interface.
1. void add(Object o): This method will add specified element according to some
sorting order in TreeSet. Duplicate entires will not get added.
2. boolean addAll(Collection c): This method will add all elements of specified
Collection to the set. Elements in Collection should be homogeneous otherwise
ClassCastException will be thrown.Duplicate Entries of Collection will not be added to
TreeSet.
// Java program to demonstrate TreeSet creation from
// ArrayList
import java.util.*;
class TreeSetDemo
{
public static void main (String[] args)
{
ArrayList al = new ArrayList();
al.add("GeeksforGeeks");
al.add("GeeksQuiz");
al.add("Practice");
al.add("Compiler");
al.add("Compiler"); //will not be added
// [Compiler,GeeksQuiz,GeeksforGeeks,Practice]
System.out.println(ts4);
}
}
Output :
Object first() : This method will return first element in TreeSet if TreeSet is not null
else it will throw NoSuchElementException.
Object last(): This method will return last element in TreeSet if TreeSet is not null else
it will throw NoSuchElementException.
SortedSet headSet(Object toElement): This method will return elements of TreeSet
which are less than the specified element.
SortedSet tailSet(Object fromElement): This method will return elements of TreeSet
which are greater than or equal to the specified element.
SortedSet subSet(Object fromElement, Object toElement): This method will return
elements ranging from fromElement to toElement. fromElement is inclusive and
toElement is exclusive.
// Java program to demonstrate TreeSet creation from
// ArrayList
import java.util.*;
class TreeSetDemo
{
public static void main (String[] args)
{
ts5.add("GeeksforGeeks");
ts5.add("Compiler");
ts5.add("practice");
System.out.println(ts5.first()); // Compiler
System.out.println(ts5.last()); //Practice
// Prints nothing
System.out.println(ts5);
}
}
Output :
Compiler
practice
[Compiler, GeeksforGeeks]
[GeeksforGeeks, practice]
[Compiler, GeeksforGeeks]
[]
8. What are the two methods in which the comparator interface can be used?Explain with
program.
Comparator Interface
In Java, Comparator interface is used to order(sort) the objects in the collection in your own
way. It gives you the ability to decide how elements will be sorted and stored within
collection and map.
Comparator Interface defines compare() method. This method has two parameters. This
method compares the two objects passed in the parameter. It returns 0 if two objects are
equal. It returns a positive value if object1 is greater than object2. Otherwise a negative value
is returned. The method can throw a ClassCastException if the type of object are not
compatible for comparison.
Rules for using Comparator interface:
1. If you want to sort the elements of a collection, you need to implement Comparator
interface.
2. If you do not specify the type of the object in your Comparator interface, then, by
default, it assumes that you are going to sort the objects of type Object. Thus, when
you override the compare() method ,you will need to specify the type of the
parameter as Object only.
3. If you want to sort the user-defined type elements, then while implementing the
Comparator interface, you need to specify the user-defined type generically. If you
do not specify the user-defined type while implementing the interface,then by
default, it assumes Object type and you will not be able to compare the user-
defined type elements in the collection
For Example:
If you want to sort the elements according to roll number, defined inside the class Student,
then while implementing the Comparator interface, you need to mention it generically as
follows:
class MyComparator implements Comparator<Student>{}
If you write only,
class MyComparator implements Comparator {}
Then it assumes, by default, data type of the compare() method's parameter to be Object, and
hence you will not be able to compare the Student type(user-defined type) objects.
Example
Student class
class Student
int roll;
String name;
Student(int r,String n)
{
roll = r;
name = n;
}
public String toString()
{
return roll+" "+name;
}
MyComparator class
This class defines the comparison logic for Student class based on their roll. Student object
will be sorted in ascending order of their roll.
class MyComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
if(s1.roll == s2.roll) return 0;
else if(s1.roll > s2.roll) return 1;
else return -1;
}
}
public class Test
{
Note:
If any other collection, like ArrayList,was used, then we need to call sort method of
Collections class and pass the name of the collection and this object as a parameter.
For example, If the above program used ArrayList collection, the public class test
would be as follows:
As the name indicates premain methods are the methods which can be executed before main
method. Java Instrumentation will give a demonstration of how powerful Java is. Most
importantly, this power can be realized by a developer for innovative means. For example
using Java instrumentation, we can access a class that is loaded by the Java classloader from
the JVM and modify its bytecode by inserting our custom code, all these done at runtime.
Don´t worry about security, these are governed by the same security context applicable for
Java classes and respective classloaders.
let us learn to instrument Java byte code using Java instrumentation. Mostly profilers,
application monitoring agents, event loggers use Java instrumentation. This will serve as
introductory level tutorial and once it is done, you can write a basic Java agent and do
instrumentation on the Java byte code.
Note:
---------------------
Package java.lang.instrument 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.
A Java Agent is given the option of modifying the array of bytes representing the class before
the class loader finishes the class loading process. Here is a specification of class loading. In
a nutshell, the bytes are given to the Java Agent after the class loader has retrieved them but
before Linking. Your Java Agent can create a new byte array in a valid class file format and
return it or, if it is not performing a transformation, return null.
package in.anyforum;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
How do you get all of this to work? Here´s what you´ll need to do:
-------------------------------------------------------------------------------------------------------------
1. Create an Implementation of ClassFileTransformer
2. Create a class with a premain method (could be in the first class, but but that would
violate The Single Responsibility Principle).
3. Create jar file
4. Star the VM with a command line parameter.
class with a method called premain that instantiates the class and registers it. Here is a
complete example:
package in.anyforum;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
Generics
Generics was first introduced in Java5. Now it is one of the most profound feature of java
programming language. Generic programming enables the programmer to create
classes,interfaces and methods in which type of data is specified as a parameter. It provides a
facility to write an algorithm independent of any specific type of data. Generics also provide
type safety. Type safety means ensuring that an operation is being performed on the right
type of data before executing that operation.
Using Generics, it has become possible to create a single class ,interface or method that
automatically works with all types of data(Integer, String, Float etc). It has expanded the
ability to reuse the code safely and easily.
Before Generics was introduced, generalized classes,interfaces or methods were created using
references of type Object because Object is the super class of all classes in Java, but this way
of programming did not ensure type safety.
Syntax for creating an object of a generic type
Class_name <data type> reference_name = new Class_name<data type> ();
OR
Class_name <data type> reference_name = new Class_name<>();
This is also known as Diamond Notation of creating an object of Generic type.
class Test
{
public static void main (String[] args)
{
Gen < Integer> iob = new Gen<>(100); //instance of Integer type Gen Class.
int x = iob.getOb();
System.out.println(x);
Gen < String> sob = new Gen<>("Hello"); //instance of String type Gen Class.
String str = sob.getOb();
System.out.println(str);
}
}
100
Hello
In the above program, we first passed an Integer type parameter to the Generic class. Then,
we passed a String type parameter to the same Generic class. Hence, we reused the same
class for two different data types. Thus, Generics helps in code reusability with ease.
public T2 getValue()
{
return value;
}
class Test
{
public static void main (String[] args)
{
Gen < String,Integer> obj = new Gen<>("StudyTonight",1);
String s = obj.getName();
System.out.println(s);
Integer i = obj.getValue();
System.out.println(i);
}
}
Note: Since there are two parameters in Generic class - T1 and T2, therefore, while creating
an instance of this Generic class, we need to mention two data types that needs to be passed
as parameter to this class.
Generic Methods
You can also create generic methods that can be called with different types of arguments.
Based on the type of arguments passed to generic method, the compiler handles each method.
The syntax for a generic method includes a type-parameter inside angle brackets, and should
appear before the method's return type.
<type-parameter> return_type method_name (parameters) {...}
java lang.Integer = 88
java lang.String = This is string
Generic Constructors
It is possible to create a generic constructor even if the class is not generic.
class Test
{
public static void main(String[] args)
{
Gen g = new Gen(100);
Gen g1 = new Gen(121.5f);
g.show();
g1.show();
}
}
100.0
121.5
Generic Interface
Like classes and methods, you can also create generic interfaces.
interface MyInterface< T >
{ .. }
UNIT III
2. What is a servlet? Explain briefly the Servlet life cycle and Servlet HTTP package.
A servlet is a Java programming language class used to extend the capabilities of a server.
Although servlets can respond to any types of requests, they are commonly used to extend the
applications hosted by web servers
Life cycle of a servlet:
init( ) - invoked when the servlet is first loaded into memory
service( ) - called for each HTTP request (for processing)
destroy( ) - unloads the servlet from its memory
Interface: HttpServletRequest, HttpServletResponse, HttpSession,
HttpSessionBindingListener
Class: Cookie, HttpServlet, HttpSessionEvent, HttpSessionBindingEvent
Steps:
Load the driver
Define the connection URL
Establish the connection
Create a Statement object
Execute a query using the Statement
Process the result
Close the connection
import java.sql.*;
public class jdbcodbc
{
AddServerIntf.java
import java.rmi.*;
public interface AddServerIntf extends Remote
{
double add(double d1,double d2)throws RemoteException;
double sub(double d1,double d2)throws RemoteException;
}
AddServerImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf
{
public AddServerImpl()throws RemoteException
{
}
public double add(double d1,double d2)throws RemoteException
{
return d1+d2;
}
public double sub(double d1,double d2)throws RemoteException
{
return d1-d2;
}
}
AddServer.java
import java.net.*;
import java.rmi.*;
public class AddServer
{
public static void main(String args[])
{
try
{
AddServerImpl addserverimpl=new AddServerImpl();
Naming.rebind("AddServer",addserverimpl);
}
catch(Exception e)
{
System.out.println("\nException:" +e);
}
}
}
AddClient.java
import java.rmi.*;
public class AddClient
{
public static void main(String args[])
{
try
{
String addserverurl="rmi://" +args[0]+ "/AddServer";
AddServerIntf addserverintf=(AddServerIntf)Naming.lookup(addserverurl);
System.out.println("\nthe first number is : " +args[1]);
double d1=Double.valueOf(args[1]).doubleValue();
System.out.println("\nthe second number is : " +args[2]);
double d2=Double.valueOf(args[2]).doubleValue();
System.out.println("\nSum is : " +addserverintf.add(d1,d2));
System.out.println("\nSubtraction : " +addserverintf.sub(d1,d2));
}
catch(Exception e)
{
System.out.println("\nException : " +e);
}
}
}
5. Design an application for Student Result Checking using Servlet and JDBC.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class JdbcStudent extends HttpServlet
{
Connection dbConn2;
public void init(ServletConfig config)throws ServletException
{
super.init(config);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbConn2=DriverManager.getConnection("jdbc:odbc:wind");
}
catch(ClassNotFoundException e)
{
System.out.println("JDBC-ODBC bridge not found");
return;
}
catch(SQLException e)
{
System.out.println("SQL exception thrown in init");
return;
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
ServletException,IOException
{
try
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Statement stat=dbConn2.createStatement();
ResultSet students=stat.executeQuery(
"SELECT studentid,studentname,grade,email FROM " +
" Student");
out.println("<HTML>");
out.println("<HEAD><TITLE> Student List </TITLE></HEAD>");
out.println("<BODY>");
out.println("<H2> Student List </H2>");
out.println("<TABLE BORDER=1>");
out.println("<TR><TH>Student ID</TH>");
out.println("<TH> Student Name </TH>");
out.println("<TH> Grade </TH>");
out.println("<TH> Email </TH></TR>");
while(students.next())
{
out.println("<TR><TD>" +
students.getString("studentid") + "</TD><TD>" +
students.getString("studentname") + "</TD><TD>" +
students.getString("grade") + "</TD><TD>" +
students.getString("email") + "</TD><TR>");
}
out.println("</TABLE>");
out.println("</BODY></HTML>");
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public String getServletInfo()
{
return "Sample JDBC Servlet";
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
//Initializing Components
privateJTextField inputs[];
privateJButton add, reset;
privateJLabel labels[];
private final String fldLabel[] = {"First Name: ","Last Name: ","Age: ","
Address:","Country:","State:","City:","Phoneno:","Email ID:"};
privateJPanel p1;
Connection con;
Statement st;
String url;
//Constructing Components
inputs = new JTextField[9];
labels = new JLabel[9];
add = new JButton("Add");
JOptionPane.showMessageDialog(null,"Successfully Connected to
Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
}
catch (HeadlessException | ClassNotFoundException | SQLException e)
{
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error
Connection", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
//Constructing JLabel and JTextField using "for loop" in their desired order
for(int count=0; count<inputs.length&& count<labels.length; count++)
{
labels[count] = new JLabel(fldLabel[count]);
inputs[count] = new JTextField(20);
if(inputs[i].getText().equals(""))
pass=false;
}
if(pass ==false)
JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error
Input", JOptionPane.ERROR_MESSAGE);
else
try {
inputs[5].setText(null);
inputs[6].setText(null);
inputs[7].setText(null);
inputs[8].setText(null);
}
}
);
//Adding JButton "add" and "reset" to JPanel 1 after the JLabel and JTextField
p1.add(add);
p1.add(reset);
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP request.
HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound from a
session.
Class Description
Cookie Allows state information to be stored on a client
machine.
HttpServlet Provides methods to handle HTTP requests and
responses.
HttpSessionEvent Encapsulates a session-changed event.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a
session value, or that a session attribute changed.
- The server calls the destroy( ) method to relinquish any resources such as file
handles that are allocated for the servlet
GenericServlet - Implements the Servlet and ServletConfig interfaces.
ServletInputStream - Provides an input stream for reading requests from a client.
ServletOutputStream - Provides an output stream for writing responses to a client.
ServletException - Indicates a servlet error occurred
GenericServlet
The GenericServlet class provides implementations of the basic life cycle methods for
a servlet
GenericServlet implements the Servlet and ServletConfig interfaces.
a method log() is available to append a string to the server log file.
Methods:
void log(String s)
void log(String s, Throwable e) s is the string to be appended to the log, and e is an
exception that occurred.
The ServletInputStream Class
The ServletInputStream class extends InputStream.
It is implemented by the server and provides an input stream that a servlet developer
can use to read the data from a client request.
Method :
int readLine(byte[ ] buffer, int offset, int size) throws IOException
read bytes from the stream.
buffer is the array into which size bytes are placed starting at offset.
The ServletOutputStream Class
The ServletOutputStream class extends OutputStream.
It is implemented by the server and provides an output stream that a servlet developer
can use to write data to a client response.
It also defines the print( ) and println( ) methods, which output data to the stream.
The ServletException Class
ServletException, which indicates that a servlet problem has occurred.
The second is UnavailableException, which extends ServletException. It indicates
that a servlet is unavailable.
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing
must be subclasses of JApplet. JApplet is rich with functionality that is not found in Applet.
For example, JApplet supports various “panes,” such as the content pane, the glass pane, and
the root pane. When adding a component to an instance of JApplet, do not invoke the add( )
method of the applet. Instead, call add( ) for the content pane of the JApplet object. The
content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form
is shown here:
void add(comp)
Here, comp is the component to be added to the content pane.
Icon: In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an
image. Two of its constructors are shown here:
ImageIcon(String filename)
ImageIcon(URL url)
The first form uses the image in the file named filename. The second form uses the image in
the resource identified by url.
Labels: Swing labels are instances of the JLabel class, which extends JComponent. It can
display text and/or an icon. Some of its constructors are shown here:
JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)
Here, s and i are the text and icon used for the label. The align argument is either LEFT,
RIGHT, CENTER, LEADING, or TRAILING. These constants are defined in the
SwingConstants interface, along with several others used by the Swing classes. The icon and
text associated with the label can be read and written by the following methods:
Icon getIcon( )
String getText( )
void setIcon(Icon i)
void setText(String s)
Here, i and s are the icon and text, respectively
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
// Add text field to the content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}
11. The idea of random mono alphabetic cipher is to use random letters for 'encrypting
the input text. Suppose the keyword is FEATHER. Then first remove duplicate letters,
yielding FEATHR, and append the other letters of the alphabet in reverse order. Now
encrypt the letters as follows: ABCDEFGHIJKLMNOPQRSTUVWXYZ
EATHRZYXWVUSQPONMLKJIGDCB
(DEC2014)
Write a Java program that encrypts and decrypts a file using this cipher.
private static char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'};
{
int f = find(alphabet, letter);
if(((f + shift) < 26) && ((f + shift) >= 0))
{
letter = alphabet[f + shift];
}
else if ((f + shift) >= 26)
{
letter = alphabet[f + shift - 26];
}
e = e + String.valueOf(letter);
}
else
{
e = e + " ";
}
}
return e;
}
public static int find(char[] c, char c2)
{
int w = 0;
for(int i = 0; i < c.length; i++)
{
if(c[i] == (c2))
w = i;
}
return w;
}
12.Create a table (ORACLE) namely "ernp" with the fields eid., ename, hra, da, pf and
lie (ii) Insert 10 records into the table (iii) Alter the table by adding one more field
namely netpay (iv) Compute the netpay of each employee and display it on the screen
and also store it in the table. (DEC2014)
package payslips;
import java.util.*;
import payslips.Employee;
import payslips.Payslip;
static String postcodes[] = { "EH6 7UT", "EH1 1BA", "G15 5GG", "EH5 2PR",
"EH4 4ST" };
list.add(e);
// statements and prompts within the console for the user to follow
System.out.println("Welcome to your Payroll System");
System.out.println();
System.out.println("Please enter your choice below from the following options");
System.out.println();
System.out.println("View all current weekly employees = 1 ");
System.out.println("View all current monthly employees = 2 ");
// allows user to enter number of choice and this reflects which statement is ran in
userChoice method
tempvar = sc.nextInt();
// method to determine what statement runs according to which choice user makes
public static void userChoice()
{
Employee tempEmployee = new Employee();
boolean foundEmployee = false;
}
else if (tempvar == 2)
{
Monthly.printMonthly();
}
else if (tempvar == 3)
{
printEmployeelist();
System.out.println("");
System.out.println("Above are a list of all employees.");
System.out.println("Please enter the payroll number of the employee you wish to
delete from the system");
temppayrollNo = sc.nextInt();
// while loop to search on payroll number, deletes the employee if correct, error
message if not
if (list.isEmpty() == false)
{
int a = 0;
while (a < list.size())
{
tempEmployee = list.get(a);
if (tempEmployee.payrollNo == temppayrollNo)
{
foundEmployee = true;
break;
}
a++;
}
if (foundEmployee == true)
{
System.out.println("You have deleted : "+ tempEmployee.getName());
System.out.println();
list.remove(tempEmployee);
printEmployeelist();
}
else
{
System.out.println("The payroll number you have entered is incorrect");
}
}
}
else if (tempvar == 4) // allows the user to add an employee to the employee list,
entering details using scanner
{
// initialises variables for entering title
String tempstring1;
int stringlength;
int whitespace;
String tempstring2;
String tempstring3;
// initialises variables for entering title
String tempstring4;
int stringlength2;
int whitespace2;
String tempstring5;
String tempstring6;
String tempstring7;
// block of code that repeats same process as above to get street name
System.out.println("Please enter the address of the employee: ");
tempstring4 = sd.nextLine();
stringlength2 = tempstring4.length();
if (tempstring4.contains(" ")) {
whitespace2 = tempstring4.indexOf(" ");
tempstring5 = tempstring4.substring((0), (whitespace2));
tempstring6 = tempstring4.substring((whitespace2) + 1,(stringlength2));
tempEmployee.setStreet(tempstring5 + " " + tempstring6);
}
else
{
tempEmployee.setStreet(tempstring4);
}
{
tempEmployee.setPostcode(tempstring7);
}
else
{
tempEmployee.setPostcode("You have not entered a valid UK postcode");
}
else if (tempvar == 5)
{
Payslip.Payslips(); //runs payslip method from payslip class
}
{
System.out.println("You have exited the system");
System.exit(0);
}
else // if any other choice entered they will be met with this message
{
System.out.println("You have entered the wrong choice");
}
}
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API
and entirely written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
14. Write a Java Program to display the Details of a given Employee Using JDBC
(DEC 2016)
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.*;
import java.io.*;
import java.net.*;
} catch (Exception e) {
System.out.println("Where is your MySQL JDBC Driver?");
System.out.println("Connection Failed! Check output console");
}
System.out.println("MySQL JDBC Driver Registered!");
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
try
{
int ch=' ';
System.out.println("\n1.Select Employee\n2.Add Employee\n3Update Emp\n4.Delete
Employee\n5.Exit\n");
while(ch<='5')
{
System.out.println("\nEnter your choice\n");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());
switch (ch)
{
case 1: ResultSet rs = st.executeQuery("select * from emp");
System.out.println("EMPLOYEE TABLE DETAILS");
System.out.println("Emp No \t Emp Name\n");
while(rs.next())
{
String s1= rs.getString("empno");
String s2=rs.getString("empname");
System.out.println(s1+"\t"+s2+"\n");
}
break;
//int empno=Integer.parseInt(br.readLine());
String empno=br.readLine();
System.out.println("\nEnter the empname\n");
String empname=br.readLine();
String strsql="INSERT INTO emp(empno,empname) VALUES
('"+empno+"','"+empname+"')";
st.executeUpdate(strsql);
System.out.println(strsql);
System.out.println("\nThe above data is Inserted.\n");
break;
//int empno=Integer.parseInt(br.readLine());
String no=br.readLine();
System.out.println("\nEnter the new empname\n");
String name=br.readLine();
String strql="update emp set empname='"+name+"' where empno='"+no+"'";
st.executeUpdate(strql);
System.out.println(strql);
System.out.println("\nThe above data is updated.\n");
break;
//int empno=Integer.parseInt(br.readLine());
no=br.readLine();
//String sql="delete from emp where empno='3'";
String sql="delete from emp where empno='"+ no +"'";
st.executeUpdate(sql);
System.out.println(sql);
System.out.println("\nThe above data is deleted.\n") ;
break;
case 5:
System.exit(0);
break;
default: System.out.println("choice");
break;
}}
connection.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage()); }
}
}
15. Explain various methods of Httpservlet Class which are used to handle Http
Request. (DEC 2016)
Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site.
A subclass of HttpServlet must override at least one method, usually one of these:
There's almost no reason to override the service method. service handles standard HTTP
requests by dispatching them to the handler methods for each HTTP request type
(the doXXX methods listed above).
Likewise, there's almost no reason to override the doOptions and doTrace methods.
Servlets typically run on multithreaded servers, so be aware that a servlet must handle
concurrent requests and be careful to synchronize access to shared resources. Shared
resources include in-memory data such as instance or class variables and external objects
such as files, database connections, and network connections.
doGet
When overriding this method, read the request data, write the response headers, get
the response's writer or output stream object, and finally, write the response data. It's
best to include content type and encoding. When using a PrintWriter object to return
the response, set the content type before accessing the PrintWriter object.
The servlet container must write the headers before committing the response, because
in HTTP the headers must be sent before the response body.
When using HTTP 1.1 chunked encoding (which means that the response has a
Transfer-Encoding header), do not set the Content-Length header.
The GET method should be safe, that is, without any side effects for which users are
held responsible. For example, most form queries have no side effects. If a client
request is intended to change stored data, the request should use some other HTTP
method.
The GET method should also be idempotent, meaning that it can be safely repeated.
Sometimes making a method safe also makes it idempotent. For example, repeating
queries is both safe and idempotent, but buying a product online or modifying data is
neither safe nor idempotent.
Parameters:
req - an HttpServletRequest object that contains the request the client has made of the
servlet
resp - an HttpServletResponse object that contains the response the servlet sends to
the client
Throws:
java.io.IOException - if an input or output error is detected when the servlet handles
the GET request
ServletException - if the request for the GET could not be handled
See Also:
ServletResponse.setContentType(java.lang.String)
getLastModified
Servlets that support HTTP GET requests and can quickly determine their last
modification time should override this method. This makes browser and proxy caches
work more effectively, reducing the load on server and network resources.
Parameters:
req - the HttpServletRequest object that is sent to the servlet
Returns:
a long integer specifying the time the HttpServletRequest object was last modified, in
milliseconds since midnight, January 1, 1970 GMT, or -1 if the time is not known
doHead
Receives an HTTP HEAD request from the protected service method and handles the
request. The client sends a HEAD request when it wants to see only the headers of a
response, such as Content-Type or Content-Length. The HTTP HEAD method counts
the output bytes in the response to set the Content-Length header accurately.
If you override this method, you can avoid computing the response body and just set
the response headers directly to improve performance. Make sure that
the doHead method you write is both safe and idempotent (that is, protects itself from
being called multiple times for one HTTP HEAD request).
If the HTTP HEAD request is incorrectly formatted, doHead returns an HTTP "Bad
Request" message.
Parameters:
req - the request object that is passed to the servlet
resp - the response object that the servlet uses to return the headers to the client.
Throws:
java.io.IOException - if an input or output error occurs
doPost
When overriding this method, read the request data, write the response headers, get
the response's writer or output stream object, and finally, write the response data. It's
best to include content type and encoding. When using a PrintWriter object to return
the response, set the content type before accessing the PrintWriter object.
The servlet container must write the headers before committing the response, because
in HTTP the headers must be sent before the response body.
When using HTTP 1.1 chunked encoding (which means that the response has a
Transfer-Encoding header), do not set the Content-Length header.
This method does not need to be either safe or idempotent. Operations requested
through POST can have side effects for which the user can be held accountable, for
example, updating stored data or buying items online.
If the HTTP POST request is incorrectly formatted, doPost returns an HTTP "Bad
Request" message.
Parameters:
req - an HttpServletRequest object that contains the request the client has made of the
servlet
resp - an HttpServletResponse object that contains the response the servlet sends to
the client
Throws:
java.io.IOException - if an input or output error is detected when the servlet handles
the request
ServletException - if the request for the POST could not be handled
doPut
When overriding this method, leave intact any content headers sent with the request
(including Content-Length, Content-Type, Content-Transfer-Encoding, Content-
Encoding, Content-Base, Content-Language, Content-Location, Content-MD5, and
Content-Range). If your method cannot handle a content header, it must issue an error
message (HTTP 501 - Not Implemented) and discard the request. For more
information on HTTP 1.1, see RFC 2616 .
If the HTTP PUT request is incorrectly formatted, doPut returns an HTTP "Bad
Request" message.
Parameters:
req - the HttpServletRequest object that contains the request the client made of the
servlet
resp - the HttpServletResponse object that contains the response the servlet returns to
the client
Throws:
java.io.IOException - if an input or output error occurs while the servlet is handling
the PUT request
ServletException - if the request for the PUT cannot be handled
doDelete
This method does not need to be either safe or idempotent. Operations requested
through DELETE can have side effects for which users can be held accountable.
When using this method, it may be useful to save a copy of the affected URL in
temporary storage.
Parameters:
req - the HttpServletRequest object that contains the request the client made of the
servlet
resp - the HttpServletResponse object that contains the response the servlet returns to
the client
Throws:
java.io.IOException - if an input or output error occurs while the servlet is handling
the DELETE request
ServletException - if the request for the DELETE cannot be handled
doOptions
There's no need to override this method unless the servlet implements new HTTP
methods, beyond those implemented by HTTP 1.1.
Parameters:
req - the HttpServletRequest object that contains the request the client made of the
servlet
resp - the HttpServletResponse object that contains the response the servlet returns to
the client
Throws:
java.io.IOException - if an input or output error occurs while the servlet is handling
the OPTIONS request
ServletException - if the request for the OPTIONS cannot be handled
doTrace
Parameters:
req - the HttpServletRequest object that contains the request the client made of the
servlet
resp - the HttpServletResponse object that contains the response the servlet returns to
the client
Throws:
java.io.IOException - if an input or output error occurs while the servlet is handling
the TRACE request
ServletException - if the request for the TRACE cannot be handled
Service
Service
A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder
has a title. When a user selects a folder, its contents become visible. Only one of the folders
may be selected at a time. Tabbed panes are commonly used for setting configuration options.
Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent. We
will use its default constructor. Tabs are defined via the following method:
void addTab(String str, Component comp)
Here, str is the title for the tab, and comp is the component that should be added to the tab.
Typically, a JPanel or a subclass of it is added.
The general procedure to use a tabbed pane in an applet is outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the title of
the tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the applet.
Demonstration of Tabbed Panes.
Solution: import javax.swing.*; /* <applet code="JTabbedPaneDemo" width=400
height=100></applet> */
public class JTabbedPaneDemo extends JApplet
{
public void init()
{
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
getContentPane().add(jtp);
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton("New York"); add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2); JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla"); jcb.addItem("Chocolate");
jcb.addItem("Strawberry"); add(jcb);
}
}
UNIT IV
1. What is hibernate? Explain about the architecture of the hibernate with neat diagram
with features
Hibernate Architecture
The Hibernate architecture includes many objects persistent object, session factory,
transaction factory, connection factory, session, transaction etc.
There are 4 layers in hibernate architecture java application layer, hibernate framework layer,
backhand api layer and database layer.Let's see the diagram of hibernate architecture:
This is the high level architecture of Hibernate with mapping file and configuration file.
Hibernate framework uses many objects session factory, session, transaction etc. alongwith
existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction API)
and JNDI (Java Naming Directory Interface).
For creating the first hibernate application, we must know the elements of Hibernate
architecture. They are as follows:
SessionFactory
Session
The session object provides an interface between the application and data stored in the
database. It is a short-lived object and wraps the JDBC connection. It is factory of
Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The
org.hibernate.Session interface provides methods to insert, update and delete the object. It
also provides factory methods for Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
ConnectionProvider
TransactionFactory
The Java EE platform is designed to help developers create large-scale, multi-tiered, scalable,
reliable, and secure network applications. A shorthand name for such applications is
“enterprise applications,” so called because these applications are designed to solve the
problems encountered by large enterprises. Enterprise applications are not only useful for
large corporations, agencies, and governments, however. The benefits of an enterprise
application are helpful, even essential, for individual developers and small organizations in an
increasingly networked world.
The features that make enterprise applications powerful, like security and reliability, often
make these applications complex. The Java EE platform is designed to reduce the complexity
of enterprise application development by providing a development model, API, and runtime
environment that allows developers to concentrate on functionality.
Tiered Applications
In a multi-tiered application, the functionality of the application is separated into isolated
functional areas, called tiers. Typically, multi-tiered applications have a client tier, a middle
tier, and a data tier (often called the enterprise information systems tier). The client tier
consists of a client program that makes requests to the middle tier. The middle tier's business
functions handle client requests and process application data, storing it in a permanent
datastore in the data tier.
applications. Clients can be a web browser, a standalone application, or other servers, and
they run on a different machine from the Java EE server.
Step 1: Compile the OMG IDL File for the Server Application
The basic structure of the client and server portions of the application that runs in the
WebLogic Enterprise domain are determined by statements in the application's OMG IDL
file. When you compile your application's OMG IDL file, the m3idltojava compiler
generates many files, some of which are shown in the following diagram:
As the server application programmer, your task is to write the methods that implement
the operations for each interface you have defined in your application's OMG IDL file.
The Java object implementation file contains:
Method declarations for each operation specified in the OMG IDL file
Your application's business logic
Constructors for each interface implementation (implementing these is optional)
Optionally,
the com.beasys.Tobj_Servant.activate_object and com.beasys.Tobj_Servant.deactivat
e_object methods
Within the activate_object and deactivate_object methods, you write code that
performs any particular steps related to activating or deactivating an object. This
includes reading and writing the object's durable state from and to disk, respectively.
1. Create a copy of the interface.java file, which was created when you compiled your
OMG IDL file with the m3idltojava command, and name it interfaceImpl.java. For
example, using the Bankapp sample file names, you would copy Teller.java to a new
file named TellerImpl.java.
2. Open the new interfaceImpl.java file. For example, in the previously
unedited TellerImpl.java file, we changed:
3. For each method in TellerImpl.java, we added the public keyword. For example, we
changed:
In Java, you use a Server object to initialize and release the server application. You
implement this Server object by creating a new class that derives from
the com.beasys.Tobj.Server class and overrides the initialize and release methods. In the
server application code, you can also write a public default constructor.
For example:
import com.beasys.Tobj.*;
/**
* Provides code to initialize and stop the server invocation.
* BankAppServerImpl is specified in the BankApp.xml input file
* as the name of the Server object.
*/
public class BankAppServerImpl
extends com.beasys.Tobj.Server {
public boolean initialize(string[] args)
throws com.beasys.TobjS.InitializeFailed;
public boolean release()
throws com.beasys.TobjS.ReleaseFailed;
}
In the XML-coded Server Description File, which you process with
the buildjavaserver command, you identify the name of the Server object.
The create_servant method, used in the C++ environment of WebLogic Enterprise, is not
used in the Java environment. In Java, objects are created dynamically, without prior
knowledge of the classes being used. In the Java environment of WebLogic Enterprise, a
servant factory is used to retrieve an implementation class, given the interface repository
ID. This information is stored in a server descriptor file created by
the buildjavaserver command for each implementation class. When a method request is
received, and no servant is available for the interface, the servant factory looks up the
interface and creates an object of the appropriate implementation class.
This collection of the object's implementation and data compose the run-time, active
instance of the CORBA object.
When your Java server application starts, the TP Framework creates the Server object
specified in the XML file. Then, the TP Framework invokes the initialize method. If the
method returns true, the server application starts. If the method throws the
com.beasys.TobjS.InitializeFailed exception, or returns false, the server application does
not start.
When the server application shuts down, the TP Framework invokes the release method on
the Server object.
Any command-line options specified in the CLOPT parameter for your specific server
application in the SERVERS section of the WebLogic Enterprise
domain's UBBCONFIG file are passed to the public boolean initialize(string[] args)
operation as args. For more information about passing arguments to the server application,
see the Administration Guide. For examples of passing arguments to the server
application, see the Guide to the Java Sample Applications.
Within the initialize method, you can include code that does the following, if applicable:
deploying the WebLogic Enterprise Bankapp sample application, see the Guide to the Java
Sample Applications.
To deploy the server application:
1. Place the server application JAR file in the directory listed in APPDIR. On NT
systems, this directory must be on a local drive (not a networked drive). On Solaris,
the directory can be local or remote.
2. If your Java server application uses an XA-compliant resource manager such as
Oracle, you must build an XA-specific version of the JavaServer by using
the buildXAJS command at a system prompt. Provide as input to the command the
resource manager that is associated with the server. In your
application's UBBCONFIG file, you also must use the JavaServerXA element in
place ofJavaServer to associate the XA resource manager with a specified server
group. See the Commands, System Process, and MIB Reference for details about
the buildXAJS command.
3. Create the application's configuration file, also known as the UBBCONFIG file, in a
text editor. Include the parameters to start JavaServer or JavaServerXA.
Every container has a LayoutManager that determines how different components are
positioned within the container.
Container Types
The deployment process installs Java EE application components in the Java EE containers as
illustrated in the following figure.
The Play framework is a clean option to bloated Enterprise Java stacks. It concentrates on
designers’ profit and targets tranquil architectures. Play framework is an immaculate friendly
for nimble programming improvement. The Play framework’s objective is to provide web
applications improvement while staying with Java.
The Java stage is scandalous for its low benefit, primarily because of rehashed and repetitive
order bundle send cycles. That is the reason we re-examined the advancement cycle to make
creating with play an effective methodology.
For example, tying a URI example to a Java call is only one line:
There are three standard bundles in the application directory, one for each one layer of the
MVC structural example. You container obviously include your own particular bundles like
for instance an utils packages.
This directory is part into three standard sub-registries: for pictures, CSS templates and
Javascript records. You ought to attempt to arrange your static holdings like this to keep all
play applications predictable.
Web servers are good for static contents HTML pages but they don’t know how to generate
dynamic content or how to save data into databases, so we need another tool that we can use
to generate dynamic content. There are several programming languages for dynamic content
like PHP, Python, Ruby on Rails, Java Servlets and JSPs.
Java Servlet and JSPs are server side technologies to extend the capability of web servers by
providing support for dynamic response and data persistence.
We will use “Eclipse IDE for Java EE Developers” for creating our first servlet application.
Since servlet is a server side technology, we will need a web container that supports Servlet
technology, so we will use Apache Tomcat server. For ease of development, we can add
configure Tomcat with Eclipse, it helps in easy deployment and running applications.
Go to Eclipse Preference and select Server Runtime Environments and select the version of
your tomcat server, mine is Tomcat 7.
Provide the apache tomcat directory location and JRE information to add the runtime
environment.
Now go to the Servers view and create a new server like below image pointing to the above
added runtime environment.
Now we are ready with our setup to create first servlet and run it on tomcat server.
Select File > New > Dynamic Web Project and use below image to provide runtime as the
server we added in last step and module version as 3.0 to create our servlet using Servlet 3.0
specs.
You can directly click Finish button to create the project or you can click on Next buttons to
check for other options.
Now select File > New > Servlet and use below image to create our first servlet. Again we
can click finish or we can check other options through next button.
When we click on Finish button, it generates our Servlet skeleton code, so we don’t need to
type in all the different methods and imports in servlet and saves us time.
Now we will add some HTML with dynamic data code in doGet() method that will be
invoked for HTTP GET request. Our first servlet looks like below.
package com.journaldev.first;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FirstServlet
*/
@WebServlet(description = "My First Servlet", urlPatterns = { "/FirstServlet" ,
"/FirstServlet.do"}, initParams =
{@WebInitParam(name="id",value="1"),@WebInitParam(name="name",value="pankaj")})
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String HTML_START="<html><body>";
public static final String HTML_END="</body></html>";
/**
* @see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
Date date = new Date();
out.println(HTML_START + "<h2>Hi
There!</h2><br/><h3>Date="+date +"</h3>"+HTML_END);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
Before Servlet 3, we need to provide the url pattern information in web application
deployment descriptor but servlet 3.0 uses java annotations that is easy to understand and
chances of errors are less.
Now chose Run > Run on Server option from servlet editor window
After clicking finish, browser will open in Eclipse and we get following HTML page.
You can refresh it to check that Date is dynamic and keeps on changing, you can open it
outside of Eclipse also in any other browser.
So servlet is used to generate HTML and send it in response, if you will look into the doGet()
implementation, we are actually creating an HTML document as writing it in response
PrintWriter object and we are adding dynamic information where we need it.
It’s good for start but if the response is huge with lot of dynamic data, it’s error prone and
hard to read and maintain. This is the primary reason for introduction of JSPs.
JSP is also server side technology and it’s like HTML with additional features to add
dynamic content where we need it.
JSPs are good for presentation because it’s easy to write because it’s like HTML. Here is our
first JSP program that does the same thing like above servlet.
7. Explain how the Web frameworks are used in JAVA application development.
Java Frameworks are nothing but large bodies of predefined Java code which you can apply
to your own code to solve your problem in a specific domain. You can use a framework by
calling its methods, inheritance, by providing “callbacks”, listeners, or other implementations
of the Observer pattern.
Late in 1990’s the applications were widely developed using JEE standards. The premise of
J2EE was multi-platform/ multi-vendor, if you can code according to the J2EE standards you
can deploy your application on any J2EE application server irrespective of platform. Running
your code on any application server provides you with many benefits like – transaction
management, messaging, mailing, directory interface etc. But as nothing comes easy in this
world, working with J2EE also had some difficulties.
Very Complex: Enterprise Java Bean was developed for reducing the complexity in
J2EE applications. But it didn’t succeed in its aim in implementation. Reason
behind it is that, while writing a component it is required to write a set of XML
files, home interfaces, remote/ local interfaces, etc.
‘look-up’ problem: Whenever a component depended upon another component, it
had to look up for the components it depended upon by itself. This component
‘look-up’ happens only by name, so the name of the dependency was hard-coded in
the component.
Heavy weight: As all features like clustering, remote controlling, etc., were
supported, you have to configure them, regardless of the fact that you need them or
not. This will make your applications bloated.
Advantages of using Java Frameworks
Efficiency: Tasks that generally take you hours and hundreds of lines of code to
compose, can now be done in minutes with pre-built functions. Development
becomes a lot easier, so if it’s much easier, it’s much quicker, and subsequently
more effective.
Security: An extensively used framework will generally have large security
applications. The big benefit is the neighborhood behind that framework, where
users usually end up being long-lasting testers. If you find a vulnerability or a
security hole, you can go to the framework’s web site and let them know so that it
can be fixed.
Expense: Most popular structures are complimentary and so it helps the developer
to code faster. If the coding is done faster the expense for the final client will
certainly be smaller in every aspect, be it time or effort. Moreover the maintenance
cost is also low.
Support: As any other distributed tool, a framework generally includes documents,
a support group or large-community online forums where you can acquire quick
responses.
8. Describe about the role of spring frameworks in enterprise application development with
an example.
Spring is the most popular application development framework for enterprise Java. Millions
of developers around the world use Spring Framework to create high performing, easily
testable, and reusable code.
Spring framework is an open source Java platform. It was initially written by Rod Johnson
and was first released under the Apache 2.0 license in June 2003.
Spring is lightweight when it comes to size and transparency. The basic version of Spring
framework is around 2MB.
The core features of the Spring Framework can be used in developing any Java application,
but there are extensions for building web applications on top of the Java EE platform. Spring
framework targets to make J2EE development easier to use and promotes good
programming practices by enabling a POJO-based programming model.
Spring is organized in a modular fashion. Even though the number of packages and
classes are substantial, you have to worry only about the ones you need and ignore
the rest.
Spring does not reinvent the wheel, instead it truly makes use of some of the existing
technologies like several ORM frameworks, logging frameworks, JEE, Quartz and
JDK timers, and other view technologies.
Spring provides a consistent transaction management interface that can scale down to
a local transaction (using a single database, for example) and scale up to global
transactions (using JTA, for example).
What is dependency injection exactly? Let's look at these two words separately. Here
the dependency part translates into an association between two classes. For example,
class A is dependent of class B. Now, let's look at the second part, injection. All this
means is, class B will get injected into class A by the IoC.
Dependency injection can happen in the way of passing parameters to the constructor
or by post-construction using setter methods. As Dependency Injection is the heart of
Spring Framework, we will explain this concept in a separate chapter with relevant
example.
The key unit of modularity in OOP is the class, whereas in AOP the unit of
modularity is the aspect. DI helps you decouple your application objects from each
other, while AOP helps you decouple cross-cutting concerns from the objects that
they affect.
Spring could potentially be a one-stop shop for all your enterprise applications. However,
Spring is modular, allowing you to pick and choose which modules are applicable to you,
without having to bring in the rest. The following section provides details about all the
modules available in Spring Framework.
The Spring Framework provides about 20 modules which can be used based on an
application requirement.
Core Container
The Core Container consists of the Core, Beans, Context, and Expression Language modules
the details of which are as follows −
The Core module provides the fundamental parts of the framework, including the IoC
and Dependency Injection features.
The Context module builds on the solid base provided by the Core and Beans
modules and it is a medium to access any objects defined and configured. The
ApplicationContext interface is the focal point of the Context module.
The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.
Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction
modules whose detail is as follows −
The JDBC module provides a JDBC-abstraction layer that removes the need for
tedious JDBC related coding.
The ORM module provides integration layers for popular object-relational mapping
APIs, including JPA, JDO, Hibernate, and iBatis.
The OXM module provides an abstraction layer that supports Object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
The Java Messaging Service JMS module contains features for producing and
consuming messages.
Web
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules the
details of which are as follows −
The Web module provides basic web-oriented integration features such as multipart
file-upload functionality and the initialization of the IoC container using servlet
listeners and a web-oriented application context.
If you are running Windows and have installed the JDK in C:\jdk1.6.0_15, you would have
to put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15
Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer,
select Properties → Advanced → Environment Variables. Then, you will have to update the
PATH value and click the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and you use
the C shell, you will have to put the following into your .cshrc file.
Eclipse can be started by executing the following commands on Windows machine, or you
can simply double-click on eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.)
machine −
$/usr/local/eclipse/eclipse
Make a choice whether you want to install Spring on Windows or Unix, and then
proceed to the next step to download .zip file for Windows and .tz file for Unix.
Object-relational mapping, in the purest sense, is a programming technique that supports the
conversion of incompatible types in object-oriented programming languages, specifically
between a data store and programming objects. You can use an ORM framework to persist
model objects to a relational database and retrieve them, and the ORM framework will take
care of converting the data between the two otherwise incompatible states. Most ORM tools
rely heavily on metadata about both the database and objects, so that the objects need to
know nothing about the database and the database doesn’t need to know anything about how
the data is structured in the application. ORM provides a clean separation of concerns in a
well-designed data application, and the database and application can each work with data in
its native form.
TIP: Nicknames and acronyms used for “object-relational mapping” include ORM, OR/M,
and O/R mapping. Although ORM seems to be the term most commonly used in the .NET
world, you’ll often see the others in books and articles. We’ll stick with ORM, mostly
because it is the easiest to type!
The key feature of ORM is the mapping it uses to bind an object to its data in the database.
Mapping expresses how an object and its properties and behaviors are related to one or more
tables and their fields in the database. An ORM uses this mapping information to manage the
process of converting data between its database and object forms, and generating the SQL for
a relational database to insert, update, and delete data in response to changes the application
makes to data objects.
ORM performs the rather amazing task of managing the application’s interactions with the
database. Once you’ve used an ORM’s tools to create mappings and objects for use in an
application, those objects completely manage the application’s data access needs. You won’t
have to write any other low-level data access code. Strictly speaking, you could still write
low-level data access code to supplement the ORM data objects, but this adds a significant
layer of complexity to an application that we’ve rarely found necessary when using a robust
ORM tool. It is better to stick to one or the other and keep the application simpler and more
maintainable.
One potential downside to using an ORM is performance. It is very likely that the data access
code generated by the ORM is more complex than you’d typically write for an application.
This is because most ORMs are designed to handle a wide variety of data-use scenarios, far
more than any single application is ever likely to use. Complex code generally means slower
performance, but a well-designed ORM is likely to generate well-tuned code that minimizes
the performance impact. Besides, in all but the most data-intensive applications the time
spent interacting with the database is a relatively small portion of the time the user spends
using the application. Nevertheless, we’ve never found a case where the small performance
hit wasn’t worth the other benefits of using an ORM. You should certainly test it for your
data and applications to make sure that the performance is acceptable.
ORMs are being hyped for being the solution to Data Access problems. Personally, after
having used them in an Enterprise Project, they are far from being the solution for Enterprise
Application Development. Maybe they work in small projects. Here are the problems we
have experienced with them specifically nHibernate:
1. Configuration: ORM technologies require configuration files to map table schemas into
object structures. In large enterprise systems the configuration grows very quickly and
becomes extremely difficult to create and manage. Maintaining the configuration also
gets tedious and unmaintainable as business requirements and models constantly change
and evolve in an agile environment.
2. Custom Queries: The ability to map custom queries that do not fit into any defined
object is either not supported or not recommended by the framework providers.
Developers are forced to find work-arounds by writing adhoc objects and queries, or
writing custom code to get the data they need. They may have to use Stored
Procedures on a regular basis for anything more complex than a simple Select.
3. Proprietery binding: These frameworks require the use of proprietary libraries and
proprietary object query languages that are not standardized in the computer science
industry. These proprietary libraries and query languages bind the application to the
specific implementation of the provider with little or no flexibility to change if required
and no interoperability to collaborate with each other.
4. Object Query Languages: New query languages called Object Query Languages are
provided to perform queries on the object model. They automatically generate SQL
queries against the databse and the user is abstracted from the process. To Object
Oriented developers this may seem like a benefit since they feel the problem of writing
SQL is solved. The problem in practicality is that these query languages cannot support
some of the intermediate to advanced SQL constructs required by most real world
applications. They also prevent developers from tweaking the SQL queries if necessary.
5. Performance: The ORM layers use reflection and introspection to instantiate and
populate the objects with data from the database. These are costly operations in terms of
processing and add to the performance degradation of the mapping operations. The
Object Queries that are translated to produce unoptimized queries without the option of
tuning them causing significant performance losses and overloading of the database
management systems. Performance tuning the SQL is almost impossible since the
frameworks provide little flexiblity over controlling the SQL that gets autogenerated.
6. Tight coupling: This approach creates a tight dependancy between model objects and
database schemas. Developers don't want a one-to-one correlation between database
fields and class fields. Changing the database schema has rippling affects in the object
model and mapping configuration and vice versa.
7. Caches: This approach also requires the use of object caches and contexts that are
necessary to maintian and track the state of the object and reduce database roundtrips for
the cached data. These caches if not maintained and synchrnonized in a multi-tiered
implementation can have significant ramifications in terms of data-accuracy and
concurrency. Often third party caches or external caches have to be plugged in to solve
this problem, adding extensive burden to the data-access layer.
Web Container is an java application that controls servlet. Servlet do not have a main()
method, So they require a container to load them. Container is a place where servlet gets
deployed.
When a client sends a request to web server that contain a servlet, server sends that request to
container rather than to servlet directly. Container then finds out the requested servlet and
pass the Http Request and response to servlet and loads the servlet methods i.e. doGet() or do
Post().
Diagrams to show the request made by the client to the server and response received by the
client.
A web container like apache tomcat or jetty just implements the JSP and Servlet specification
of Java EE. However there are more specifications within Java EE, mainly the EJB
specification. A servlet container implements only the JSP and Servlet specification, and
doesn’t implement EJB specification. Hence we cannot deploy and execute EJB applications
in a servlet container like Apache Tomcat or Jetty. Instead you need a full application server.
An application server contains an EJB container as well as servlet container and implements
all the required specifications of Java EE. Examples of application servers are Glassfish
Application Server, which is a Java EE reference implementation from Oracle, Websphere
Application Server by IBM, JBoss Application Server by Red Hat inc etc.
A Web application runs within a Web container of a Web server. The Web container provides
the runtime environment through components that provide naming context and life cycle
management. Some Web servers may also provide additional services such as security and
concurrency control. A Web server may work with an EJB server to provide some of those
services. A Web server, however, does not need to be located on the same machine as an EJB
server.
Web applications are composed of web components and other data such as HTML pages.
Web components can be servlets, JSP pages created with the JavaServer Pages™ technology,
web filters, and web event listeners. These components typically execute in a web server and
may respond to HTTP requests from web clients. Servlets, JSP pages, and filters may be used
to generate HTML pages that are an application’s user interface. They may also be used to
generate XML or other format data that is consumed by other application components.
UNIT V
1. What is Java beans? Enumerate its advantages. What are the steps involved to
create a Java Bean?
The properties, events, and methods of a Bean that are exposed to an application
builder tool can be controlled.
A Bean may be designed to operate correctly in different locales, which makes it
useful in global markets.
Steps for creating of a new bean:
(i) Start--new project. A new project dialog window appear.
(ii) In the new project dialog window select general in categories and java
application in project box.
(iii) Then click Next button and specify the project name and project path too.
(iv) Then click Finish button.
JAR Files:
The JAR Utility
A utility is used to generate a JAR file. Its syntax is shown here:
jar options files
Creating a JAR File
The following command creates a JAR file named Xyz.jar that contains all of the .class and
.gif files in the current directory:
jar cf Xyz.jar *.class *.gif
If a manifest file such as Yxz.mf is available, it can be used with the following command:
jar cfm Xyz.jar Yxz.mf *.class *.gif
Tabulating the Contents of a JAR File
The following command lists the contents of Xyz.jar:
jar tf Xyz.jar
Extracting Files from a JAR File
The following command extracts the contents of Xyz.jar and places those files in the
current directory:
jar xf Xyz.jar
Updating an Existing JAR File
The following command adds the file file1.class to Xyz.jar:
jar -uf Xyz.jar file1.class
Recursing Directories
The following command adds all files below directoryX to Xyz.jar:
jar -uf Xyz.jar -C directoryX *
A property is a subset of a Bean’s state. The values assigned to the properties determine the
behavior and appearance of that component. There are three types of properties: simple,
Boolean, and indexed.
Simple Properties: A simple property has a single value. It can be identified by the
following design patterns, where N is the name of the property and T is its type.
public T getN( );
public void setN(T arg);
A read/write property has both of these methods to access its values. A read-only property
has only a get method. A write-only property has only a set method.
Example for Simple Properties:
Design patterns were used to determine the information that was provided to a Bean user.
This section describes how a developer can use the BeanInfo interface to explicitly control
this process.
This interface defines several methods, including these:
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( )
MethodDescriptor[ ] getMethodDescriptors( )
They return arrays of objects that provide information about the properties, events, and
methods of a Bean. By implementing these methods, a developer can designate exactly what
is presented to a user.
SimpleBeanInfo is a class that provides default implementations of the BeanInfo interface,
including the three methods just shown. You may extend this class and override one or more
of them. The following listing shows how this is done for the Colors Bean that was
developed earlier. ColorsBeanInfo is a subclass of SimpleBeanInfo. It overrides
getPropertyDescriptors( ) in order to designate which properties are presented to a Bean
user. This method creates a PropertyDescriptor object for the rectangular property. The
PropertyDescriptor constructor that is used is shown here:
PropertyDescriptor(String property, Class beanCls)
throws IntrospectionException
Here, the first argument is the name of the property, and the second argument is the class of
the Bean.
// A Bean information class.
package sunw.demo.colors;
import java.beans.*;
public class ColorsBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor rectangular = new
PropertyDescriptor("rectangular", Colors.class);
PropertyDescriptor pd[] = {rectangular};
return pd;
}
catch(Exception e) {
}
return null;
}
}
You must compile this file from the BDK\demo directory or set CLASSPATH so that it
includes c:\bdk\demo. If you don’t, the compiler won’t find the Colors.class file properly.
After this file is successfully compiled, the colors.mft file can be updated, as shown here:
Name: sunw/demo/colors/ColorsBeanInfo.class
Name: sunw/demo/colors/Colors.class
Java-Bean: True
Use the JAR tool to create a new colors.jar file. Restart the BDK and create an instance of
the Colors Bean in the BeanBox. The introspection facilities are designed to look for a
BeanInfo class. If it exists, its behavior explicitly determines the information that is
presented to a Bean user. Otherwise, design patterns are used to infer this information.
Interface Description
This interface is designed to work in collusion with
AppletInitializer
java.beans.Beans.instantiate.
A bean implementor who wishes to provide explicit information
about their bean may provide a BeanInfo class that implements
BeanInfo
this BeanInfo interface and provides explicit information about
the methods, properties, events, etc, of their bean.
A customizer class provides a complete custom GUI for
Customizer
customizing a target Java Bean.
This interface is intended to be implemented by, or delegated
from, instances of java.beans.beancontext.BeanContext, in order
DesignMode to propagate to its nested hierarchy of
java.beans.beancontext.BeanContextChild instances, the current
"designTime" property.
ExceptionListener An ExceptionListener is notified of internal exceptions.
A "PropertyChange" event gets fired whenever a bean changes a
PropertyChangeListener
"bound" property.
A PropertyEditor class provides support for GUIs that want to
PropertyEditor
allow users to edit a property value of a given type.
A VetoableChange event gets fired whenever a bean changes a
VetoableChangeListener
"constrained" property.
Under some circumstances a bean may be run on servers where a
Visibility
GUI is not availabl
Class Description
A BeanDescriptor provides global information about a "bean",
BeanDescriptor
including its Java class, its displayName, etc.
Beans This class provides some general purpose beans control methods.
DefaultPersistence The DefaultPersistenceDelegate is a concrete
Delegate implementation of the abstract PersistenceDelegate class
Whether you are making a phone call, sending mail, or establishing a connection across the
Internet, addresses are fundamental. The InetAddress class is used to encapsulate both the
numerical IP address we discussed earlier and the domain name for that address. You interact
with this class by using the name of an IP host, which is more convenient and understandable
than its IP address. The InetAddress class hides the number inside. As of Java 2, version 1.4,
InetAddress can handle both IPv4 and IPv6 addresses.
The InetAddress class has no visible constructors. To create an InetAddress object, you
have to use one of the available factory methods. Factory methods are merely a convention
whereby static methods in a class return an instance of that class. This is done in lieu of
overloading a constructor with various parameter lists when having unique method names
makes the results much clearer. Three commonly used InetAddress factory methods are
shown here.
static InetAddress getLocalHost( )
throws UnknownHostException
static InetAddress getByName(String hostName)
throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName)
throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that represents the local
host. The getByName( ) method returns an InetAddress for a host name passed to it. If these
methods are unable to resolve the host name, they throw an UnknownHostException.
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("osborne.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to- point,
stream-based connections between hosts on the Internet. A socket can be used to connect
Java’s I/O system to other programs that may reside either on the local machine or on any
other machine on the Internet.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients.
The ServerSocket class is designed to be a “listener,” which waits for clients to connect
before doing anything. The Socket class is designed to connect to server sockets and initiate
protocol exchanges.
The creation of a Socket object implicitly establishes a connection between the client and
server. There are no methods or constructors that explicitly expose the details of establishing
that connection. Here are two constructors used to create client sockets:
Socket(String hostName, int port) Creates a socket connecting the local host to the named
host and port; can throw an UnknownHostException or an IOException.
Socket(InetAddress ipAddress, int port) Creates a socket using a preexisting InetAddress
object and a port; can throw an IOException.
A socket can be examined at any time for the address and port information associated with it,
by use of the following methods:
InetAddress getInetAddress( ) Returns the InetAddress associated with the Socket object.
int getPort( ) Returns the remote port to which this Socket object is connected.
int getLocalPort( ) Returns the local port to which this Socket object is connected.
Once the Socket object has been created, it can also be examined to gain access to the input
and output streams associated with it. Each of these methods can throw an IOException if
the sockets have been invalidated by a loss of connection on the Net.
InputStream getInputStream( ) Returns the InputStream associated with the invoking socket.
Java has a different socket class that must be used for creating server applications. The
ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on published ports. Since the Web is driving most of the activity
on the Internet, this section develops an operational web (http) server.
ServerSockets are quite different from normal Sockets. When you create a ServerSocket, it
will register itself with the system as having an interest in client connections. The
constructors for ServerSocket reflect the port number that you wish to accept connections on
and, optionally, how long you want the queue for said port to be. The queue length tells the
system how many client connections it can leave pending before it should simply refuse
connections. The default is 50. The constructors might throw an IOException under adverse
conditions.
Here are the constructors:
ServerSocket(int port) - Creates server socket on the specified port with a queue length of 50.
ServerSocket(int port, int maxQueue) - Creates a server socket on the specified port with a
maximum queue length of maxQueue.
ServerSocket(int port, int maxQueue, InetAddress localAddress) - Creates a server socket on
the specified port with a maximum queue length of maxQueue. On a multihomed host,
localAddress specifies the IP address to which this socket binds.
Datagrams are bundles of information passed between machines. They are somewhat like a
hard throw from a well-trained but blindfolded catcher to the third baseman. Once the
datagram has been released to its intended target, there is no assurance that it will arrive or
even that someone will be there to catch it. Likewise, when the datagram is received, there is
no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to
receive a response. Java implements datagrams on top of the UDP protocol by using two
classes:
The DatagramPacket object is the data container, while the DatagramSocket is the
mechanism used to send or receive the DatagramPackets.
DatagramPacket: DatagramPacket defines several constructors. Four are described here.
The first constructor specifies a buffer that will receive data, and the size of a packet. It is
used for receiving data over a DatagramSocket. The second form allows you to specify an
offset into the buffer at which data will be stored. The third form specifies a target address
and port, which are used by a DatagramSocket to determine where the data in the packet
will be sent. The fourth form transmits packets beginning at the specified offset into the data.
Think of the first two forms as building an “in box,” and the second two forms as stuffing and
addressing an envelope. Here are the four constructors:
DatagramPacket(byte data[ ], int size)
DatagramPacket(byte data[ ], int offset, int size)
DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
There are several methods for accessing the internal state of a DatagramPacket. They give
complete access to the destination address and port number of a packet, as well as the raw
data and its length. Here are some of the most commonly used:
InetAddress getAddress( ) Returns the destination InetAddress, typically used for sending.
int getPort( ) Returns the port number.
byte[ ] getData( ) Returns the byte array of data contained in the datagram. Mostly used to
retrieve data from the datagram after it has been received.
int getLength( ) Returns the length of the valid data contained in the byte array that would be
returned from the getData( ) method. This typically does not equal the length of the whole
byte array.
import java.net.*;
class WriteServer {
public static int serverPort = 998;public static int clientPort = 999;
public static int buffer_size = 1024; public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception {
int pos=0;
while (true) {
int c = System.in.read();
switch (c) {
case -1:
System.out.println("Server Quits.");return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer,pos,
InetAddress.getLocalHost(),clientPort));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}}}
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
}}
public static void main(String args[]) throws Exception {
if(args.length == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
} else {
ds = new DatagramSocket(clientPort);
TheClient();}}}
T
11.Write a client application that executes an infinite loop to perform the following :
Prompts the user for a number (ii) Sends it to :the server (iii) Receives a number sent by
the server (iv) Displays the received number Also write a server that executes an infinite
loop to read a number from a client, compute the square value and send the result to
the client. (DEC2014)
}
}} }
PROGRAM for FTPCLIENT
import java.io.*;
import java.net.*;
class Client
{
public static void main(String args[]) throws IOException
{
Socket s = new Socket("localhost", 8010);
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter p = new PrintWriter(s.getOutputStream(), true);
DataInputStream in = new DataInputStream(System.in);
boolean bo=true;
while(bo)
{
System.out.println("Enter the choice\n 1. Getting the file content\n 2.Sending the file
content\n 3.Exit");
int i=Integer.parseInt(in.readLine());
p.println(i);
String st;
switch(i)
{
case 1:
{
{
bo=false; break;
}
}
}
}
}
The Bean Builder can also be used for building custom UI applications which are to be
integrated and invoked from the Web NMS client. This is easily achievable by making your
applications implement either the NmsPanel Interface or the NmsFrame Interface which form
the building blocks of the Web NMS client. For more details on building NmsPanels and
NmsFrames using Bean Builder, please refer Bean Builder documentation.
Having built the application, our next responsibility is packaging the same so to be invoked
from the Web NMS client. This process is made easy in Bean Builder by using
the NAR mechanism . (NAR stands for Nms ARchive). The NAR proprietary archiving
mechanism used for packaging Web NMS applications. It is as same as a Java ARchive with
some additional Web NMS-specific information. A separate wizard named as the "Package
Wizard" (provide link to package wizard document in Bean Builder) will help you in
generating a NAR file for your application. This tool can be invoked from the following
menu item in Bean Builder : "Project -> Package For WebNMS -> Device Specific/Not
Device Specific".
After packaging your application using the package wizard, a NAR file is generated for your
application. This NAR file can be integrated into the Web NMS client using a tool named
"Deployment Wizard" which can be invoked from the "<Web NMS
Home>/bin/developertools" directory. The way in which your application has to be invoked
from the client (i.e., whether it has to be invoked as a Frame on a menu action or from the
Tree) can be configured using this tool based your application build type (whether an
NmsPanel or an NmsFrame). For more details on installing a NAR file using the Deployment
Wizard. You can refer the document: Deployment tool-->Installing a Client NAR.
Implementation Example
Some of the applications/tools bundled in Web NMS client has been built using Bean Builder
and packaged using the NAR mechanism. The bean builder projects as a whole (Screens,
Source files, etc.) are also bundled with the product and can be accessed from under
the <Web NMS Home>/projects directory. The tools such as "Runtime Administration" and
"Security Administration" which can be accessed from the "Tools" menu of the Java client
and "Batch Configuration" displayed as a node in the client tree are some project examples
built using the Bean Builder tool. One among these builder project is taken as an example and
explained for your reference in the following chapter: "Run-Time Administration: A Bean
Builder Project for Web NMS".
13. Write about Java Bean builder tool with neat example and bean developer Kit
(DEC 2015)
6. Focus on the stop button, choose "Edit" from menu ⇒ "Events" ⇒ "mouse" ⇒
"mouseClicked" and place it onto the "Juggler". In the "EventTargetDialog", select
method "stopJuggling" as the event handler.
7. Click on the buttons, and observe the result.
1. package elect;
2. import java.awt.*;
3. import java.io.Serializable;
4.
5. public class LightBulb extends Canvas implements Serializable {
6.
7. public LightBulb() { // constructor
8. setSize(50,50);
9. setBackground(Color.GRAY);
10. }
11.
12. // Properties
13. private static final Color COLOR_OFF = Color.BLACK;
14. private Color color = Color.ORANGE; // property with a default value
15. public Color getColor() { return color; } // getter
16. public void setColor(Color color) { this.color = color; } // setter
17.
18. boolean on = false; // property with a default value
19. public boolean isOn() { return on; } // getter for boolean
20. public void setOn(boolean on) { this.on = on; } // setter
21.
22. // Override the paint() method to draw the LightBulb
23. public void paint(Graphics g) {
24. if (on) g.setColor(color);
25. else g.setColor(COLOR_OFF);
26. g.fillOval(10, 10, 30, 30);
27. }
28.
29. public void switchOn() { // switch on the Light
30. on = true;
31. repaint();
32. }
33.
34. public void switchOff() { // switch off the Light
35. on = false;
36. repaint();
37. }
38.
39. public void toggle() { // If on turns off; else turns on
40. on = !on;
41. repaint();
42. }
43. }
14. Discuss about Classes and Interface used by Java Bean (DEC 2016)
The Java Beans API: The Java Beans functionality is provided by a set of classes and
interfaces in the java.beans package. Set of classes and interfaces in the java.beans package
Package java.beans Contains classes related to developing beans -- components based on the
JavaBeansTM architecture
BeanDescriptor: A BeanDescriptor provides global information about a "bean", including its
Java class, its displayName, etc Beans This class provides some general purpose beans
control methods.
DefaultPersistenceDelegate: The DefaultPersistenceDelegate is a concrete implementation
of the abstract PersistenceDelegate class and is the delegate used by default for classes about
which no information is available.
Encoder: An Encoder is a class which can be used to create files or streams that encode the
state of a collection of JavaBeans in terms of their public APIs.
EventHandler :The EventHandler class provides support for dynamically generating event
listeners whose methods execute a simple statement involving an incoming event object and a
target object. EventSetDescriptor: An EventSetDescriptor describes a group of events that a
given Java bean fires. Expression An Expression object represents a primitive expression in
which a single method is applied to a target and a set of arguments to return a result - as in
"a.getFoo()". AppletInitializer This interface is designed to work in collusion with
java.beans.Beans.instantiate.
BeanInfo A bean implementor who wishes to provide explicit information about their bean
may provide a BeanInfo class that implements this BeanInfo interface and provides explicit
information about the methods, properties, events, etc, of their bean.
Customizer A customizer class provides a complete custom GUI for customizing a target
Java Bean DesignMode This interface is intended to be implemented by, or delegated from,
instances of java.beans.beancontext.BeanContext, in order to propagate to its nested
hierarchy of java.beans.beancontext.BeanContextChild instances, the current "designTime"
property. ExceptionListener: An ExceptionListener is notified of internal exceptions.
PropertyChangeListener: A "PropertyChange" event gets fired whenever a bean changes a
"bound" property.
PropertyEditor A PropertyEditor class provides support for GUIs that want to allow users to
edit a property value of a given type.
VetoableChangeListener: A VetoableChange event gets fired whenever a bean changes a
"constrained" property Visibility Under some circumstances a bean
The BeanInfoInterface : By default an Introspector uses the Reflection API to determine the
features of a JavaBean.However, a JavaBean can provide its own BeanInfo which will be
used instead by the Introspector to determine the discussed information. This allows a
developer hiding specific properties, events and methods from a builder tool or from any
other tool which uses the Introspector class. Moreover it allows supplying further details
about events/properties/methods as you are in charge of creating the descriptor objects.
Hence you can, for example, call the setShortDescription() method to set a descriptive
description.
A BeanInfo class has to be derived from the SimpleBeanInfo class and its name has to start
with the name of the associated JavaBean. At this point it has to be underlined that the name
of the BeanInfo class is the only relation between a JavaBean and its BeanInfo class. The
BeanInfo interface provides the methods that enable you to specify and retrieve the
information about a JavaBean.
ad.getHostName();
ad.getHostAddress();
Handles Internet addresses both as host names and as IP addresses. Static Method
getByName returns the IP address of a specified host name as an InetAddress object.
Methods for address/name conversion:
public static InetAddress getByName(String host) throws UnknownHostException
public static InetAddress[] getAllByName(String host) throws UnknownHostException
public static InetAddress getLocalHost() throws UnknownHostException
public boolean isMulticastAddress()
public String getHostName()
public byte[] getAddress()
public String getHostAddress()
public int hashCode()
public boolean equals(Object obj)
public String toString()
The UDP classes : 2 classes:
java.net.DatagramSocket class: is a connection to a port that does the sending and
receiving. A DatagramSocket can send to multiple, different addresses.The address to which
data goes is stored in the packet, not in the socket.
public DatagramSocket() throws SocketException public DatagramSocket(int port) throws
SocketException
public DatagramSocket(int port, InetAddress laddr) throws SocketException
java.net.DatagramPacket class : is a wrapper for an array of bytes from which data will be
sent or into which data will be received. It also contains the address and port to which the
packet will be sent.
public DatagramPacket(byte[] data, int length) public DatagramPacket(byte[] data, int length,
InetAddress host, int port)
SERVER:
1. Create a DatagramSocket object DatagramSocket dgramSocket = new
DatagramSocket(1234);
2. Create a buffer for incoming datagrams byte[] buffer = new byte[256];
3. Create a DatagramPacket object for the incoming datagram DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
4. Accept an incoming datagram dgramSocket.receive(inPacket)
5. Accept the sender’s address and port from the packet InetAddress clientAddress =
inPacket.getAddress(); int clientPort = inPacket.getPort();
6. Retrieve the data from the buffer string message = new String(inPacket.getData(), 0,
inPacket.getLength());
7. Create the respons e datagram DatagramPacket outPacket = new DatagramPacket(
response.getBytes(), response.length(), clientAddress, clientPort);
8. Send the response datagram dgramSocket.send(outPacket)
9. Close the DatagramSocket: dgram.close();
CLIENT:
1. Create a DatagramSocket object DatagramSocket dgramSocket = new DatagramSocket;
2. Create the outgoing datagram DatagramPacket outPacket = new DatagramPacket(
message.getBytes(), message.length(), host, port);
3. Send the datagram message dgramSocket.send(outPacket)
4. Create a buffer for incoming datagrams byte[] buffer = new byte[256];
execute locally. Bean that provides real-time price information from a stock or commodities
exchange.
JavaBeans Basic rules: A JavaBean should: be public implement the Serializable
interface have a no-arg constructor be derived from javax.swing.JComponent or
java.awt.Component if it is visual The classes and interfaces defined in the java.beans
package enable you to create JavaBeans.
The Java Bean components can exist in one of the following three phases of development
Construction phase
Build phase
Execution phase
It supports the standard component architecture features of Properties Events
Methods Persistence.
In addition Java Beans provides support for Introspection (Allows Automatic
Analysis of a java beans) Customization (To make it easy to configure a java beans
component)
Elements of a JavaBean:
Properties Similar to instance variables. A bean property is a named attribute of a bean that
can affect its behavior or appearance. Examples of bean properties include color, label, font,
font size, and display size.
Methods: Same as normal Java methods. Every property should have accessor (get) and
mutator (set) method. All Public methods can be identified by the introspection mechanism.
There is no specific naming standard for these methods
Events Similar to Swing/AWT event handling.
The Java Bean Component Specification: Customization: Is the ability of JavaBean to
allow its properties to be changed in build and execution phase. Persistence:-Is the ability of
JavaBean to save its state to disk or storage device and restore the saved state when the
JavaBean is reloaded Communication:- Is the ability of JavaBean to notify change in its
properties to other JavaBeans or the container. Introspection:-Is the ability of a JavaBean to
allow an external application to query the properties, methods, and events supported by it.
Beans Development Kit Is a development environment to create, configure, and test
JavaBeans. The features of BDK environment are:
Provides a GUI to create, configure, and test JavaBeans.
Enables you to modify JavaBean properties and link multiple JavaBeans in an application
using BDK.
Provides a set of sample JavaBeans.
Enables you to associate pre-defined events with sample JavaBeans. Identifying BDK
Components
• Execute the run.bat file of BDK to start the BDK development environment.
The components of BDK development environment are:
1. ToolBox
2. BeanBox(Is a workspace for creating the layout of JavaBean application. )
3. Properties (Displays all the exposed properties of a JavaBean. You can modify JavaBean
properties in the properties window. The following figure shows the Properties window)
4. Method Tracer(Displays the debugging messages and method calls for a JavaBean
application.)
Steps to Develop a User-Defined JavaBean:
1. Create a directory for the new bean
2. Create the java bean source file(s)
3. Compile the source file(s)
16. Explain TCP/IP Client and the Various Classes and Methods Supported By Java
for TCP/IP Client Sockets (DEC 2016)
A socket can be used to connect Java’s I/O system to other programs that may reside either
on the local machine or on any other machine on the Internet. There are two kinds of TCP
sockets in Java. One is for servers, and the other is for clients. The ServerSocket class is
designed to be a “listener,” which waits for clients to connect before doing anything. The
Socket class is designed to connect to server sockets and initiate protocol exchanges.
TCP/IP Client Sockets Here are two constructors used to create client sockets: Socket(String
hostName, int port) Creates a socket connecting the localhost to the named host and port; can
throw an UnknownHostException oran IOException. Socket(InetAddress ipAddress, int port)
Creates a socket using a preexisting InetAddress object and a port; can throw an
IOException.
A socket can be examined at any time for the address and port information associated with it,
by use of the following methods: InetAddress getInetAddress( ) Returns the InetAddress
associated with the Socket object. int getPort( ) Returns the remote port to which this Socket
object is connected. int getLocalPort( ) Returns the local port to which this Socket object is
connected
Once the Socket object has been created, it can also be examined to gain access to the input
and output streams associated with it.
InputStream getInputStream( )
Returns the InputStream associated with the invoking socket.
OutputStream getOutputStream( )
Returns the OutputStream associated with the invoking socket.
The very simple example that follows opens a connection to a whois port on the
InterNIC server, sends the command -line argument down the socket, and then prints the data
that is returned. InterNIC will try to lsookup the argument as a registered Internet domain
name, then send back the IP address and contact information for that site.
import java.net.*;
import java.io.*;
class Whois
{
public static void main(String args[]) throws Exception
{
int c; Socket s = new Socket("internic.net", 43);
InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream();
Stringstr=(args.length==0? "osborne.com":args[0])+"n";
byte buf[] = str.getBytes(); out.write(buf);
while ((c = in.read()) != -1) System.out.print((char) c); s.close();
}
}
URL ( Uniform Resource Locator)
The URL (Uniform Resource Locator) provides a reasonably intelligible form to
uniquely identify or address information on the Internet. URLs are ubiquitous; every browser
uses them to identify information on the Web. In fact, the Web is really just that same old
Internet with all of its resources addressed as URLs plus HTML. Within Java’s network class
library, the URL class provides a simple, concise API to access information across the
Internet using URLs. Two examples of URLs are
http://www.osborne.com/ and http://www.osborne.com:80/ index.htm.
A URL specification is based on four components:
The first is the protocol to use, separated from the rest of the locator by a colon (:). Common
protocols are http, ftp, gopher, and file, although these days almost everything is being done
via HTTP (in fact, most browsers will proceed correctly if you leave off the “http://” from
your URL specification).
The second component is the host name or IP address of the host to use; this is delimited on
the left by double slashes (//) and on the right by a slash (/) or optionally a colon (:).
The third component, the port number, is an optional parameter, delimited on the left from
the host name by a colon (:) and on the right by a slash (/). (It defaults to port 80, the
predefined HTTP port; thus “:80” is redundant.)
The fourth part is the actual file path. Most HTTP servers will append a file named
index.html or index.htm to URLs that refer directly to a directory resource.
TCP/IP Server Sockets
The ServerSocket class is used to create servers that listen for either local or remote
client programs to connect to them on published ports. Since the Web is driving most of the
activity on the Internet, this section develops an operational web (http) server. ServerSockets
are quite different from normal Sockets. When you create a ServerSocket, it will register
itself with the system as having an interest in client connections.
The constructors for ServerSocket reflect the port number that you wish to accept
connections on and, optionally, how long you want the queue for said port to be. The queue
length tells the system how many client connections it can leave pending before it should
simply refuse connections. The default is 50. The constructors might throw an IOException
under adverse conditions. Here are the constructors:
ServerSocket has a method called accept( ), which is a blocking call that will wait for a client
to initiate communications, and then return with a normal Socket that is then used for
communication with the client.
Serve- Client Program in Java
Server Side Program (Server.java)
import java.io.*;
import java.net.*;
public class Server
{
private static Socket socket; public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
while(true)
{
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
{
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace(); }}}}