1. DCOER T.E. (IT)
Section I: - Core Java Programming
Assignment No.: 1 Date: 02-01-2012
Title: Implementation of Arithmetic Operations
AIM: Write a program to implement arithmetic operations
A. Use static input
B. Take input from command prompt (Use wrapper class)
OBJECTIVE:
To expose the concepts of java program, various data types and conversion
THEORY:
Basics of Java
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the
first working version. This language was initially called “Oak” but was renamed “Java”
in 1995. Object-oriented programming is at the core of Java. In fact, all Java programs are
object oriented—this isn’t an option the way that it is in C++, for example. OOP is so
integral to Java that you must understand its basic principles before you can write even
simple Java programs.
Data types, Variables
Fig 1 “Summary of Primitive Data Types”
Table 1 “Data types, their ranges & corresponding wrapper classes”
Data Width Minimum Value, Maximum Value Wrapper
Type (bits) Class
boolean Not true, false (no ordering implied) Boolean
Applicable
Byte 8 -27 to 2 7-1 Byte
Short 16 15 to 15 Short
-2 2 -1
SDTL P .R. Jaiswal
1
2. DCOER T.E. (IT)
Char 16 0x0, 0xffff Character
Int 32 31 to 31 Integer
-2 2 -1
Long 64 63 to 63 Long
-2 2 -1
Float 32 ±1.40129846432481707e-45f, Float
±3.402823476638528860e+38f
double 64 'b14.94065645841246544e-324, Double
'b11.79769313486231570e+308
Variable Declarations
A variable stores a value of a particular type. A variable has a name, a type, and
a value associated with it. In Java, variables can only store values of primitive data
types and references to objects. Variables that store references to objects are called
reference variables.
Declaring and Initializing Variables
Variable declarations are used to specify the type and the name of variables. This
implicitly determines their memory allocation and the values that can be stored in
them. We show some examples of declaring variables that can store primitive
values:
char a, b, c; // a, b and c are variables of type character
A declaration can also include initialization code to specify an appropriate initial
value for the variable:
int i = 10; // i is an int variable with initial value 10.
Object Reference Variables
An object reference is a value that denotes an object in Java. Such reference values can
be stored in variables and used to manipulate the object denoted by the reference value. A
variable declaration that specifies a reference type (i.e., a class, an array, or an interface
name) declares an object reference variable. Analogous to the declaration of variables
of primitive data types, the simplest form of reference variable declaration only
specifies the name and the reference type. The declaration determines what objects a
reference variable can denote. Before we can use a reference variable to manipulate an
object, it must be declared and initialized with the reference value of the object.
Pizza yummyPizza; // Variable yummyPizza can reference objects of class
It is important to note that the declarations above do not create any objects of class
Pizza. The declarations only create variables that can store references to objects of this
class. A declaration can also include an initialize to create an object whose reference can
be assigned to the reference variable:
Pizza yummyPizza = new Pizza("Hot&Spicy"); // Declaration with initializer.
SDTL P .R. Jaiswal
2
3. DCOER T.E. (IT)
Setting Environment Variable From Command Prompt
E:ZealSecond SemTE ITJava Programs>set path=%path%;C:Program Files
(x86)Javajdk1.6.0_01bin
E:ZealSecond SemTE ITJava Programs>
First Java Program:-
/* First java program, call this file as “Example.java” */
class Example {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
The main Method
The Java interpreter executes a method called main in the class specified on the
command line. Any class can have a main() method, but only the main() method of
the class specified to the Java interpreter is executed to start a Java application. The
main() method must have public accessibility so that the interpreter can call it. It is a
static method belonging to the class, so that no object of the class is required to start the
execution. It does not return a value, that is, it is declared void. It always has an array of
String objects as its only formal parameter. This array contains any arguments passed to
the program on the command line. All this adds up to the following definition of the
main() method:
public static void main(String args[]) {
// ….
}
The above requirements do not exclude specification of additional modifiers or any
throws clause The main() method can also be overloaded like any other method The Java
interpreter ensures that the main() method, that complies with the above definition is
the starting point of the program execution.
Compiling and Interpreting a Java Program From Windows Command Prompt
E:ZealSecond SemTE ITJava Programs>javac Example.java
E:ZealSecond SemTE ITJava Programs>java Example
Hello World
E:ZealSecond SemTE ITJava Programs>
Wrapper Classes
Wrapper class is a wrapper around a primitive data type. It represents primitive data types in
their corresponding class instances e.g. a boolean data type can be represented as a Boolean
class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned
a value to a wrapper class instance cannot be changed further.
Wrapper Classes are used broadly with Collection classes in the java.util package and with
the classes in the java.lang.reflect reflection package. Table 1 above shows primitive types
SDTL P .R. Jaiswal
3
4. DCOER T.E. (IT)
and their corresponding wrapper classes.
Features of the Wrapper Classes
Some of the sound features maintained by the Wrapper Classes are as under :
All the methods of the wrapper classes are static.
The Wrapper class does not contain constructors.
Once a value is assigned to a wrapper class instance it can not be changed, anymore.
Wrapper Classes: Methods
There are some of the methods of the Wrapper class which are used to manipulate the data.
Few of them are given below:
1. add(int, Object): inserts an element at the specified position.
2. add(Object): inserts an object at the end of a list.
3. addAll(ArrayList): inserts an array list of objects to another list.
4. get(): retrieves the elements contained with in an ArrayList object.
5. Integer.toBinaryString(): converts the Integer type object to a String object.
6. size(): gets the dynamic capacity of a list.
7. remove(): removes an element from a particular position specified by a index value.
8. set(int, Object): replaces an element at the position specified by a index value.
FAQs:
1. What's the difference between J2SDK 1.5 and J2SDK 5.0?
2. What environment variables do I need to set on my machine in order to be able to
run Java programs?
3. Do I need to import java.lang package any time? Why?
4. What is the difference between declaring a variable and defining a variable?
5. What is static in java?
6. What if I write static public void instead of public static void?
7. Can a .java file contain more than one java classes?
8. Is String a primitive data type in Java?
9. Is main a keyword in Java?
10. Is next a keyword in Java?
11. Is delete a keyword in Java?
12. Is exit a keyword in Java?
CONCLUSION:
Students should write down their own conclusion here.
SDTL P .R. Jaiswal
4
5. DCOER T.E. (IT)
Assignment No.: 2 Date: 09-01-2012
Title: String Operations
AIM: Write a program to implement string operations like length, reverse, palindrome, case
change etc.
OBJECTIVES:
To understand String class and its associated methods
To understand StringBuffer Class
To understand significance of hashCode()
THEORY:
In Java a string is a sequence of characters. But, unlike many other languages that
implement strings as character arrays, Java implements strings as objects of type String.
Implementing strings as built-in objects allows Java to provide a full complement of
features that make string handling convenient. For example, Java has methods to compare
two strings, search for a substring, concatenate two strings, and change the case of letters
within a string. Also, String objects can be constructed a number of ways, making it easy to
obtain a string when needed.
Somewhat unexpectedly, when you create a String object, you are creating a string that
cannot be changed. That is, once a String object has been created, you cannot change the
characters that comprise that string. The difference is that each time you need an altered
version of an existing string, a new String object is created that contains the modifications.
The original string is left unchanged. This approach is used because fixed, immutable
strings can be implemented more efficiently than changeable ones. For those cases in which
a modifiable string is desired, there is a companion class to String called StringBuffer,
whose objects contain strings that can be modified after they are created.
Both the String and StringBuffer classes are defined in java.lang. Thus, they are available
to all programs automatically. Both are declared final, which means that neither of these
classes may be subclassed. This allows certain optimizations that increase performance to
take place on common string operations.
The String Constructors
The String class supports several constructors. To create an empty String, you call the
default constructor. For example,
String s = new String();
will create an instance of String with no characters in it.
SDTL P .R. Jaiswal
5
6. DCOER T.E. (IT)
Frequently, you will want to create strings that have initial values. The String class provides
a variety of constructors to handle this. To create a String initialized by an array of
characters, use the constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
You can specify a subrange of a character array as an initializer using the following
constructor: String(char chars[ ], int startIndex, int numChars) Here, startIndex specifies the
index at which the subrange begins, and numChars specifies the number of characters to
use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
You can construct a String object that contains the same character sequence as another
String object using this constructor:
String(String strObj)
Here, strObj is a String object. Consider this example:
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
As you can see, s1 and s2 contain the same string.
String Length
The length of a string is the number of characters that it contains. To obtain this value, call
the length( ) method, shown here:
int length( )
The following fragment prints “3”, since there are three characters in the string s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Special String Operations
Because strings are a common and important part of programming, Java has added special
support for several string operations within the syntax of the language. These operations
SDTL P .R. Jaiswal
6
7. DCOER T.E. (IT)
include the automatic creation of new String instances from string literals, concatenation of
multiple String objects by use of the + operator, and the conversion of other data types to a
string representation. There are explicit methods available to perform all of these functions,
but Java does them automatically as a convenience for the programmer and to add clarity.
The earlier examples showed how to explicitly create a String instance from an array of
characters by using the new operator. However, there is an easier way to do this using a
string literal. For each string literal in your program, Java automatically constructs a String
object. Thus, you can use a string literal to initialize a String object. For example,
the following code fragment creates two equivalent strings:
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
Because a String object is created for every string literal, you can use a string literal any
place you can use a String object. For example, you can call methods directly on a quoted
string as if it were an object reference, as the following statement shows. It calls the length(
) method on the string “abc”. As expected, it prints “3”.
System.out.println("abc".length());
String Concatenation
In general, Java does not allow operators to be applied to String objects. The one exception
to this rule is the + operator, which concatenates two strings, producing a String object as
the result. This allows you to chain together a series of + operations.
For example, the following fragment concatenates three strings:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
This displays the string “He is 9 years old.”
String Conversion & toString()
When Java converts data into its string representation during concatenation, it does so by
calling one of the overloaded versions of the string conversion method valueOf( ) defined
by String. valueOf( ) is overloaded for all the simple types and for type Object. For the
simple types, valueOf( ) returns a string that contains the human-readable equivalent of the
value with which it is called. For objects, valueOf( ) calls the toString( ) method on the
object. We will look more closely at valueOf( ) later in this chapter. Here, let’s examine the
toString( ) method, because it is the means by which you can determine the string
representation for objects of classes that you create.
SDTL P .R. Jaiswal
7
8. DCOER T.E. (IT)
Every class implements toString( ) because it is defined by Object. However, the default
implementation of toString( ) is seldom sufficient. For most important classes that you
create, you will want to override toString( ) and provide your own string representations.
Fortunately, this is easy to do. The toString( ) method has this general form:
String toString( )
To implement toString( ), simply return a String object that contains the humanreadable
string that appropriately describes an object of your class. By overriding toString( ) for
classes that you create, you allow them to be fully integrated into Java’s programming
environment. For example, they can be used in print( ) and println( ) statements and in
concatenation expressions.
Character Extraction
The String class provides a number of ways in which characters can be extracted from a
String object. Each is examined here. Although the characters that comprise a string within
a String object cannot be indexed as if they were a character array, many of the String
methods employ an index (or offset) into the string for their operation. Like arrays, the
string indexes begin at zero.
charAt()
To extract a single character from a String, you can refer directly to an individual character
via the charAt( ) method. It has this general form:
char charAt(int where)
For example,
char ch;
ch = "abc".charAt(1);
assigns the value “b” to ch.
getChars()
If you need to extract more than one character at a time, you can use the getChars( )
method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
String Comparison
The String class includes several methods that compare strings or substrings within strings.
Equals & equalsIgnoreCase()
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object being compared with the invoking String object. It returns
true if the strings contain the same characters in the same order, and false otherwise. The
comparison is case-sensitive.
To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it
compares two strings, it considers A-Z to be the same as a-z. It has this general form:
SDTL P .R. Jaiswal
8
9. DCOER T.E. (IT)
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It, too,
returns true if the strings contain the same characters in the same order, and false otherwise.
startsWith() & endsWith()
String defines two routines that are, more or less, specialized forms of regionMatches( ).
The startsWith( ) method determines whether a given String begins with a specified string.
Conversely, endsWith( ) determines whether the String inquestion ends with a specified
string. They have the following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
Here, str is the String being tested. If the string matches, true is returned. Otherwise, false
is returned. For example,
"Foobar".endsWith("bar")
and
"Foobar".startsWith("Foo")
are both true.
Searching Strings
The String class provides two methods that allow you to search a string for a specified
character or substring:
■ indexOf( ) Searches for the first occurrence of a character or substring.
■ lastIndexOf( ) Searches for the last occurrence of a character or substring.
These two methods are overloaded in several different ways. In all cases, the methods return
the index at which the character or substring was found, or –1 on failure.To search for the
first occurrence of a character, use
int indexOf(int ch)
To search for the last occurrence of a character, use
int lastIndexOf(int ch)
Here, ch is the character being sought.
To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)
Here, str specifies the substring.
Modifying a String
Because String objects are immutable, whenever you want to modify a String, you must
either copy it into a StringBuffer or use one of the following String methods, which will
construct a new copy of the string with your modifications complete.
Substring
You can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
SDTL P .R. Jaiswal
9
10. DCOER T.E. (IT)
Here, startIndex specifies the index at which the substring will begin. This form returns a
copy of the substring that begins at startIndex and runs to the end of the invoking string.
he second form of substring( ) allows you to specify both the beginning and ending index
of the substring:
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point.
The string returned contains all the characters from the beginning index, up to, but not
including, the ending index.
Concat()
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents of str
appended to the end. concat( ) performs the same function as +. For example,
String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2. It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
Replace()
The replace( ) method replaces all occurrences of one character in the invoking string with
another character. It has the following general form:
trim()
The trim( ) method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed. It has this general form:
String trim( )
Here is an example:
String s = " Hello World ".trim();
This puts the string “Hello World” into s.
hashCode()
A hash table can only store objects that override the hashCode( ) and equals( )methods that
are defined by Object. The hashCode( ) method must compute andreturn the hash code for
the object. Of course, equals( ) compares two objects. Fortunately, many of Java’s built-in
classes already implement the hashCode( ) method. For example, the most common type of
Hashtable uses a String object as the key. String implements both hashCode( ) and
equals( ).
The Hashtable constructors are shown here:
Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
SDTL P .R. Jaiswal
10
11. DCOER T.E. (IT)
Hashtable(Map m)
FAQs:
1. Why is the String class declared final?
2. So the String class is final because its methods are complex?
3. How many objects are created for identical strings?
4. What’s the use of String constructor?
5. How should I use the String constructor?
6. What is the difference between String and StringBuffer?
7. When should I use StringBuffer instead of String?
8. What is a StringTokenizer for?
9. How can I check a string has numbers?
CONCLUSION:
Students should write down their own conclusion here.
SDTL P .R. Jaiswal
11
12. DCOER T.E. (IT)
Assignment No.: 3 Date: 16-01-2012
Title: Matrix Operations
AIM: Write a program to implement matrix operations like addition, subtraction,
multiplication, transpose etc.
OBJECTIVES:
To understand Arrays in java
To understand how to declare and initialize multi dimensional array
THEORY:
Basics of Array
An array is a group of like-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an
array is accessed by its index. Arrays offer a convenient means of grouping related
information.
One – Dimensional Array
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first must create an array variable of the desired type. The general form of a one dimensional
array declaration is
type var-name[ ];
Here, type declares the base type of the array. The base type determines the data type of
each element that comprises the array. Thus, the base type for the array determines what
type of data the array will hold. For example, the following declares an array named
month_days with the type “array of int”:
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no array
actually exists. In fact, the value of month_days is set to null, which represents an array
with no value. To link month_days with an actual, physical array of integers, you must
allocate one using new and assign it to month_days. new is a special operator that allocates
memory. You will look more closely at new in a later chapter, but you need to use it now to
allocate memory for arrays. The general form of new as it applies to one-dimensional arrays
appears as follows:
array-var = new type[size];
SDTL P .R. Jaiswal
12
13. DCOER T.E. (IT)
Here, type specifies the type of data being allocated, size specifies the number of elements
in the array, and array-var is the array variable that is linked to the array. That is, to use new
to allocate an array, you must specify the type and number of elements to allocate. The
elements in the array allocated by new will automatically be initialized to zero. This
example allocates a 12-element array of integers and links them to month_days.
month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Further, all
elements in the array will be initialized to zero. Let’s review: Obtaining an array is a two-
step process. First, you must declare a variable of the desired array type. Second, you must
allocate the memory that will hold the array, using new, and assign it to the array variable.
Thus, in Java all arrays are dynamically allocated. Once you have allocated an array, you
can access a specific element in the array by specifying its index within square brackets. All
array indexes start at zero. For example, this statement assigns the value 28 to the second
element of month_days.
month_days[1] = 28;
The next line displays the value stored at index 3.
System.out.println(month_days[3]);
Arrays can be initialized when they are declared. The process is much the same as that used
to initialize the simple types. An array initializer is a list of comma-separated expressions
surrounded by curly braces. The commas separate the values of the array elements. The
array will automatically be created large enough to hold the number of elements you specify
in the array initializer.
Here is one more example that uses a one-dimensional array. It finds the average of a set of
numbers.
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
SDTL P .R. Jaiswal
13
14. DCOER T.E. (IT)
}
Alternative Array Declaration
There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form is included as a convenience, and is also useful when
specifying an array as a return type for a method.
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect,
look and act like regular multidimensional arrays. However, as you will see, there are a
couple of subtle differences. To declare a multidimensional array variable, specify each
additional index using another set of square brackets. For example, the following declares a
two-dimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD.
The following program numbers each element in the array from left to right, top to bottom,
and then displays these values:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
SDTL P .R. Jaiswal
14
15. DCOER T.E. (IT)
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify the memory
for the first (leftmost) dimension. You can allocate the remaining dimensions separately. For
example, this following code allocates memory for the first dimension of twoD when it is
declared. It allocates the second dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
Transpose of Matrix
In linear algebra, the transpose of a matrix A is another matrix AT (also written A′, Atr or At)
created by any one of the following equivalent actions:
reflect A over its main diagonal (which runs top-left to bottom-right) to obtain AT
write the rows of A as the columns of AT
write the columns of A as the rows of AT
visually rotate A 90 degrees clockwise, and mirror the image in a vertical line to
obtain AT
Formally, the (i,j) element of AT is the (j,i) element of A.
If A is an m × n matrix then AT is a n × m matrix. The transpose of a scalar is the same
scalar.
SDTL P .R. Jaiswal
15
16. DCOER T.E. (IT)
FAQs:
1. How do we allocate an array dynamically in java?
2. Explain with example how to initialize an array of objects.
3. What is the difference between a Vector and Array? Discuss the advantages
and disadvantages of both.
4. If I do not provide any arguments on the command line, then the String array
of Main method will be empty or null?
CONCLUSION:
Students should write down their own conclusion here.
SDTL P .R. Jaiswal
16
17. DCOER T.E. (IT)
Assignment No.: 4 Date: 23-01-2012
Title: Inheritance and Interface
AIM: Write a program to implement the concepts of inheritance and interface for given
problem statement:
A class derived from Account that holds information about saving and current account
also implements overrides method and print summary of saving and current account.
OBJECTIVES:
To expose the concepts of inheritance and overriding
THEORY:
Basics of Inheritance
Inheritance is one of the cornerstones of object-oriented programming because it allows
the creation of hierarchical classifications. Using inheritance, you can create a general
class that defines traits common to a set of related items. This class can then be inherited
by other, more specific classes, each adding those things that are unique to it. In the
terminology of Java, a class that is inherited is called a super class. The class that does
the inheriting is called a subclass. Therefore, a subclass is a specialized version of a super
class. It inherits all of the instance variables and methods defined by the super class.
To inherit a class, you simply incorporate the definition of one class into another by
using the ‘extends’ keyword. To see how, let’s begin with a short example. The
following program creates a super class called A and a subclass called B. Notice
how the keyword extends is used to create a subclass of A.
The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
General Example of Simple Inheritance Is As Given Below
// Crate a base class
class A {
// body of base class
}
// Create a subclass by extending class A
class B extends A {
// body of derived class
}
class SimpleInheritance {
public static void main(String args[]) {
SDTL P .R. Jaiswal
17
18. DCOER T.E. (IT)
// … } }
You can only specify one super class for any subclass that you create. Java does not
support the inheritance of multiple super classes into a single subclass. (This differs from
C++, in which you can inherit multiple base classes.) You can, as stated, create a
hierarchy of inheritance in which a subclass becomes a super class of another subclass.
However, no class can be a super class of itself.
Using super
Whenever a subclass needs to refer to its immediate super class, it can do so by use
of the keyword super .super has two general forms. The first calls the super class’
constructor. The second is used to access a member of the super class that has been
hidden by a member of a subclass. Each use is examined here.
Using super to Call Super class Constructors
A subclass can call a constructor method defined by its super class by use of the following
form of super:
super(parameter-list);
A parameter-list specifies any parameters needed by the constructor in the super class
super( ) must always be the first statement executed inside a subclass’ constructor.
To see how super( ) is used, consider this example
// BoxWeight now uses super to initialize its Box attributes.
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using
super() BoxWeight(double w, double h, double
d, double m) { super(w, h, d); // call superclass
constructor
weight = m;
}
}
Here, BoxWeight( ) calls super( ) with the parameters w, h, and d. This causes the Box(
) constructor to be called, which initializes width, height, and depth using these
values. BoxWeight no longer initializes these values itself. It only needs to initialize the
value unique to it: weight. This leaves Box free to make these values private if
desired. In the preceding example, super( ) was called with three arguments. Since
constructors can be overloaded, super() can be called using any form defined by the
superclass. The constructor executed will be the one that matches the arguments. For
example, here is a complete implementation of BoxWeight that provides constructors
for the various ways that a box can be constructed. In each case, super( ) is called
using the appropriate arguments. Notice that width, height, and depth have been made
private within Box.
Overriding and Hiding Members
Under certain circumstances, a subclass may override non-static methods defined in
the super class that would otherwise be inherited. When the method is invoked on an
SDTL P .R. Jaiswal
18
19. DCOER T.E. (IT)
object of the subclass, it is the new method implementation in the subclass that is executed.
The overridden method in the super class is not inherited by the subclass, and the new
method in the subclass must uphold the following rules of method overriding:
The new method definition must have the same method signature (i.e., method name and
parameters) and the same return type.
Whether parameters in the overriding method should be final is at the discretion of the
subclass. A method's signature does not encompass the final modifier of parameters, only
their types and order.
The new method definition cannot narrow the accessibility of the method, but it can
widen it. The new method definition can only specify all or none, or a subset of the
exception classes (including their subclasses) specified in the throws clause of the
overridden method in the super class.
An instance method in a subclass cannot override a static method in the super class. The
compiler will flag this as an error. A static method is class-specific and not part of any
object, while overriding methods are invoked on behalf of objects of the subclass.
However, a static method in a subclass can hide a static method in the super class.
A final method cannot be overridden because the modifier final prevents method
overriding. An attempt to override a final method will result in a compile-time error.
However, an abstract method requires the non-abstract subclasses to override the
method, in order to provide an implementation.
Accessibility modifier private for a method means that the method is not accessible outside
the class in which it is defined; therefore, a subclass cannot override it. However, a
subclass can give its own definition of such a method, which may have the same signature
as the method in its super class.
Overriding vs. Overloading
Method overriding should not be confused with method overloading. Method overriding
requires the same method signature (name and parameters) and the same return type. Only
non-final instance methods in the superclass that are directly accessible from the subclass
are eligible for overriding. Overloading occurs when the method names are the same,
but the parameter lists differ. Therefore, to overload methods, the parameters must differ
in type, order, or number. As the return type is not a part of the signature, having
different return types is not enough to overload methods.
Interfaces
Using the keyword interface, you can fully abstract a class’ interface from its
implementation. That is, using interface, you can specify what a class must do, but not how
it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body. In practice, this means that you can define
interfaces which don’t make assumptions about how they are implemented. Once it is
defined, any number of classes can implement an interface. Also, one class can implement
any number of interfaces.
To implement an interface, a class must create the complete set of methods defined by the
interface. However, each class is free to determine the details of its own implementation. By
providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism. Interfaces are designed to support dynamic
method resolution at run time.
SDTL P .R. Jaiswal
19
20. DCOER T.E. (IT)
Normally, in order for a method to be called from one class to another, both classes need to
be present at compile time so the Java compiler can check to ensure that the method
signatures are compatible. This requirement by itself makes for a static and non extensible
classing environment. Inevitably in a system like this, functionality gets pushed up higher
and higher in the class hierarchy so that the mechanisms will be available to more and more
subclasses. Interfaces are designed to avoid this problem. They disconnect the definition of
a method or set of methods from the inheritance hierarchy. Since interfaces are in a different
hierarchy from classes, it is possible for classes that are unrelated in terms of the class
hierarchy to implement the same interface. This is where the real power of interfaces is
realized.
Defining Interface
An interface is defined much like a class. This is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Here, access is either public or not used. When no access specifier is included, then default
access results, and the interface is only available to other members of the package in which
it is declared. When it is declared as public, the interface can be used by any other code.
name is the name of the interface, and can be any valid identifier.
Notice that the methods which are declared have no bodies. They end with a semicolon after
the parameter list. They are, essentially, abstract methods; there can be no default
implementation of any method specified within an interface. Each class that includes an
interface must implement all of the methods.
Variables can be declared inside of interface declarations. They are implicitly final and
static, meaning they cannot be changed by the implementing class. They must also be
initialized with a constant value. All methods and variables are implicitly public if the
interface, itself, is declared as public.
Implementing an Interface
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface. The general form of a class that includes the
implements clause looks like this:
access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body
}
SDTL P .R. Jaiswal
20
21. DCOER T.E. (IT)
Here, access is either public or not used. If a class implements more than one interface, the
interfaces are separated with a comma. If a class implements two interfaces that declare the
same method, then the same method will be used by clients of either interface. The methods
that implement an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the interface
definition.
FAQs:
1. Can an inner class declared inside of method access local variables of this method?
2. What's the main difference between a Vector and an ArrayList?
3. You can create an abstract class that contains only abstract methods. On the other
hand, you can create an interface that declares the same methods. So can you
use abstract classes instead of interfaces?
4. What access level do you need to specify in the class declaration to ensure that only
classes from the same directory can access it?
5. When you declare a method as abstract method?
6. Can I call a abstract method from a non abstract method?
7. What is the difference between an Abstract class and Interface in Java? or can you
explain when you use Abstract classes ?
8. What is the purpose of garbage collection in Java, and when is it used?
9. What is the purpose of finalization?
10. What is the difference between static and non-static variables?
11. How are this() and super() used with constructors?
12. What are some alternatives to inheritance?
CONCLUSION:
Students should write their own conclusion here.
SDTL P .R. Jaiswal
21
22. DCOER T.E. (IT)
Assignment No.: 5 Date: 30-01-2012
Title: JDBC Connectivity
AIM: Write a program to connect to database using JDBC connectivity
OBJECTIVES:
To expose the concept of JDBC connectivity
To understand how JDBC connectivity helps to get connected with many database
systems though java program
THEORY:
Basics of JDBC
The JDBC (Java Database Connectivity) API defines interfaces and classes for writing
database applications in Java by making database connections. Using JDBC you can send
SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for
executing SQL statements and supports basic SQL functionality. It provides RDBMS access
by allowing you to embed SQL inside Java code. Because Java can run on a thin client,
applets embedded in Web pages can contain downloadable JDBC code to enable remote
database access. You will learn how to create a table, insert values into it, query the table,
retrieve results, and update the table with the help of a JDBC Program example.
Although JDBC was designed specifically to provide a Java interface to relational
databases, you may find that you need to write Java code to access non-relational databases
as well.
JDBC Connectivity Steps
Before you can create a java jdbc connection to the database, you must first import the
java.sql package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be imported.
1. Loading a database driver
In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver
class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to
Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore
JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in
java.lang package.
try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x){
System.out.println( “Unable to load the driver class!” );
}
SDTL P .R. Jaiswal
22
23. DCOER T.E. (IT)
2.Creating a oracle jdbc Connection
The JDBC DriverManager class defines objects which can connect Java applications to a
JDBC driver. DriverManager is considered the backbone of JDBC architecture.
DriverManager class manages the JDBC drivers that are installed on the system. Its
getConnection() method is used to establish a connection to a database. It uses a username,
password, and a jdbc url to establish a connection to the database and returns a connection
object. A jdbc Connection represents a session/connection with a specific database. Within
the context of a Connection, SQL, PL/SQL statements are executed and results are returned.
An application can have one or more connections with a single database, or it can have
many connections with different databases. A Connection object provides metadata i.e.
information about the database, tables, and fields. It also contains methods to deal with
transactions.
JDBC URL Syntax:: jdbc: <subprotocol>: <subname>
JDBC URL Example:: jdbc: <subprotocol>: <subname>•Each driver has its own
subprotocol
•Each subprotocol has its own syntax for the source. We’re using the jdbc odbc subprotocol,
so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
try{
Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}
3. Creating a jdbc Statement object
Once a connection is obtained we can interact with the database. Connection interface
defines methods for interacting with the database via the established connection. To execute
SQL statements, you need to instantiate a Statement object from your connection object by
using the createStatement() method.
Statement statement = dbConnection.createStatement();
A statement object is used to send and execute SQL statements to a database.
Three kinds of Statements
Statement: Execute simple sql queries without parameters.
Statement createStatement()
Creates an SQL Statement object.
Prepared Statement: Execute precompiled sql queries with or without parameters.
PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled
SQL statements.
Callable Statement: Execute a call to a database stored procedure.
CallableStatement prepareCall(String sql)
SDTL P .R. Jaiswal
23
24. DCOER T.E. (IT)
returns a new CallableStatement object. CallableStatement objects are SQL stored
procedure call statements.
4. Executing a SQL statement with the Statement object, and returning a jdbc
resultSet.
Statement interface defines methods that are used to interact with database via the execution
of SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to
use is executeQuery . For statements that create or modify tables, the method to use is
executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all
examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table
rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of
data. The next() method is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns
in a ResultSet. It is constructed from the Connection object.
Java JDBC Connection Example, JDBC Driver Example
import java.sql.*;
public class JDBCSample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ResultSet rs;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe","system","Oracle10g
");
Statement st = conn.createStatement();
rs = st.executeQuery("select * from studinfo");
while(rs.next())
SDTL P .R. Jaiswal
24
25. DCOER T.E. (IT)
System.out.println(rs.getString(1)+ "|" + rs.getInt(2)+ "|" +
rs.getString(3));
st.close();
conn.close();
}
catch(Exception e)
{ System.out.println(e);
}
}
}
Output:
javac JDBCSample.java
Java JDBCSample
ajay|100|te it
rahul|101|te it
payal|102|te it
manavi|103|te it
JDBC Drivers
Type I: “Bridge”
Type II: “Native”
Type III: “Middleware”
Type IV: “Pure”
JDBC Object Classes
DriverManager
Loads, chooses drivers
Driver
Connects to actual database
Connection
A series of SQL statement to and from the DB
Statement
A single SQL statement
ResultSet
The records returned from a statement
FAQs:
1. What are the steps involved in establishing a JDBC connection?
2. How can you load the drivers?
3. What will Class.forName do while loading drivers?
4. How can you make the connection?
SDTL P .R. Jaiswal
25
26. DCOER T.E. (IT)
5. How can you create JDBC statements and what are they?
6. How can you retrieve data from the ResultSet?
7. What are the different types of Statements?
8. How can you use PreparedStatement?
9. What does setAutoCommit do?
CONCLUSION:
Students should write their own conclusion here.
SDTL P .R. Jaiswal
26
27. DCOER T.E. (IT)
Section II:- Client Side Technologies
Assignment No.: 6 Date: 06-02-2012
Title: HTML – Scripting Language
AIM: Study of Hyper Text Markup Language and its’ tags. Create a HTML page to
display all information about bank account.
OBJECTIVES:
To expose the concepts of HTML, different tags.
THEORY:
What is Client-Side Programming
Browser is “Universal Client”
Want power and appearance of application
Increase functionality
Provide more capable Graphic User Interface
(GUI) Incorporate new types of information
Move functionality from server to client
Advantages
Reduce load on server, network traffic, network delay
Use client processing power and resources, scale with number of clients
Localize processing where it is needed
Can be simpler than using server side processing
Disadvantages
Possible need for client disk space and other resources
Increased complexity of client environment
Increased complexity of web pages Distribution and installation issues
Reduced portability
Security
Security Issues
Unauthorized access to machine resources: disk, cpu etc.
o (e.g. format disk) Unauthorized access to information
o (e.g. upload history, files) Denial of service
o (e.g. crash machine)
Techniques
Features of HTML 3.2 and extensions Browser-supported scripting languages Java
Applets
Combined approaches
Dynamic HTML
SDTL P .R. Jaiswal
27
28. DCOER T.E. (IT)
Client-side programming involves writing code that is interpreted by a browser such
as Internet Explorer or Mozilla Firefox or by any other Web client such as a cell phone.
The most common languages and technologies used in client-side programming are
HTML, JavaScript, Cascading Style Sheets (CSS) and Macromedia Flash.
Introduction to HTML
HTML (Hypertext Markup Language) is used to create document on the World Wide
Web. It is simply a collection of certain key words called ‘Tags’ that are helpful in writing
the document to be displayed using a browser on Internet. It is a platform independent
language that can be used on any platform such as Windows, Linux, Macintosh, and so on.
To display a document in web it is essential to mark-up the different elements (headings,
paragraphs, tables, and so on) of the document with the HTML tags. To view a mark-
up document, user has to open the document in a browser. A browser understands
and interprets the HTML tags, identifies the structure of the document (which part
are which) and makes decision about presentation (how the parts look) of the
document.HTML also provides tags to make the document look attractive using
graphics, font size and colors. User can make a link to the other document or the different
section of the same document by creating Hypertext Links also known as Hyperlinks.
HyperText Markup Language (HTML) is the language behind most Web pages. The
language is made up of elements that describe the structure and format of the content on a
Web page. Cascading Style Sheets (CSS) is used in HTML pages to separate
formatting and layout from content. Rules defining color, size, positioning and other
display aspects of elements are defined in the HTML page or in linked CSS pages.
HTML Skeleton
An HTML page contains what can be thought of as a skeleton - the main structure of the
page. It looks like this:
<html>
<head>
<title></title>
</head>
<body>
<!--Content that appears on the page-->
</body>
</html>
Elements in HTML Documents
The HTML instructions, along with the text to which the instructions apply, are called
HTML elements. The HTML instructions are themselves called tags, and look like
<element_name> - that is, they are simply the element name surrounded by left and right
angle brackets.
Most elements mark blocks of the document for particular purpose or formatting:
the above <element_name> tag marks the beginning of such as section. The end of
this section is then marked by the ending tag </element_name> -- note the leading
slash character "/" that appears in front of the element name in an end tag. End, or stop
tags are always indicated by this leading slash character.
For example, the heading at the top of this page is an H2 element, (a level 2 heading)
which is written as:
SDTL P .R. Jaiswal
28
29. DCOER T.E. (IT)
<H2> 2.1 Elements in HTML </H2>.
The <head> Element
The <head> element contains content that is not displayed on the page itself. Some
of the elements commonly found in the <head> are:
Title of the page (<title>). Browsers typically show the title in the "title bar" at the top of
the browser window. Meta tags, which contain descriptive information about the page
<meta />) Script blocks, which contain javascript or vbscript code for adding
functionality and interactivity to a page (<script>) Style blocks, which contain Cascading
Style Sheet rules (<style>). References (or links) to external style sheets (<link />).
The <body> Element
The <body> element contains all of the content that appears on the page itself. Body tags
will be covered thoroughly throughout this manual
Empty
Elements
Some elements are empty -- that is, they do not affect a block of the document in
some way. These elements do not require an ending tag. An example is the <HR>
element, which draws a horizontal line across the page. This element would simply be
entered as
<HR>
Upper and Lower
Case
Element names are case insensitive. Thus, the the horizontal rule element can be written
as any of <hr>, <Hr>or <HR>.
Elements can have Attributes
Many elements can have arguments that pass parameters to the interpreter handling this
element. These arguments are called attributes of the element. For example, consider
the element A, which marks a region of text as the beginning (or end) of a hypertext link.
This element can have several attributes. One of them, HREF, specifies the hypertext
document to which the marked piece of text is linked. To specify this in the tag for A you
write:
<A HREF="http://www.somewhere.ca/file.html"> marked text </a>.
where the attribute HREF is assigned the indicated value. Note that the A element is not
empty, and that it is closed by the tag </a>. Note also that end tags never take attributes -
- the attributes to an element are always placed in the start tag.
SDTL P .R. Jaiswal
29
30. DCOER T.E. (IT)
Various Tags of HTML
Tag Description
<!--...--> Defines a comment
<!DOCTYPE> Defines the document type
<a> Defines an anchor
<abbr> Defines an abbreviation
<acronym> Defines an acronym
<address> Defines contact information for the author/owner of a document
<applet> Deprecated. Defines an embedded applet
<area/> Defines an area inside an image-map
<b> Defines bold text
<base/> Defines a default address or a default target for all links on a page
<basefont/> Deprecated. Defines a default font, color, or size for the text in a
page
<bdo> Defines the text direction
<big> Defines big text
<blockquote> Defines a long quotation
<body> Defines the document's body
<br/> Defines a single line break
<button> Defines a push button
<caption> Defines a table caption
<center> Deprecated. Defines centered text
<cite> Defines a citation
<code> Defines computer code text
<col/> Defines attribute values for one or more columns in a table
<colgroup> Defines a group of columns in a table for formatting
<dd> Defines a description of a term in a definition list
<del> Defines deleted text
<dfn> Defines a definition term
<dir> Deprecated. Defines a directory list
<div> Defines a section in a document
<dl> Defines a definition list
<dt> Defines a term (an item) in a definition list
<em> Defines emphasized text
<fieldset> Defines a border around elements in a form
<font> Deprecated. Defines font, color, and size for text
<form> Defines an HTML form for user input
<frame/> Defines a window (a frame) in a frameset
<frameset> Defines a set of frames
SDTL P .R. Jaiswal
30
31. DCOER T.E. (IT)
<h1>to<h6> Defines HTML headings
<head> Defines information about the document
<hr/> Defines a horizontal line
<html> Defines an HTML document
<i> Defines italic text
<iframe> Defines an inline frame
<img/> Defines an image
<input/> Defines an input control
<ins> Defines inserted text
<isindex> Deprecated. Defines a searchable index related to a document
<kbd> Defines keyboard text
<label> Defines a label for an input element
<legend> Defines a caption for a fieldset element
<li> Defines a list item
<link/> Defines the relationship between a document and an external
resource
<map> Defines an image-map
<menu> Deprecated. Defines a menu list
<meta/> Defines metadata about an HTML document
<noframes> Defines an alternate content for users that do not support frames
<noscript> Defines an alternate content for users that do not support client-
side scripts
<object> Defines an embedded object
<ol> Defines an ordered list
<optgroup> Defines a group of related options in a select list
<option> Defines an option in a select list
<p> Defines a paragraph
<param/> Defines a parameter for an object
<pre> Defines preformatted text
<q> Defines a short quotation
<s> Deprecated. Defines strikethrough text
<samp> Defines sample computer code
<script> Defines a client-side script
<select> Defines a select list (drop-down list)
<small> Defines small text
<span> Defines a section in a document
<strike> Deprecated. Defines strikethrough text
<strong> Defines strong text
<style> Defines style information for a document
SDTL P .R. Jaiswal
31
32. DCOER T.E. (IT)
<sub> Defines subscripted text
<sup> Defines superscripted text
<table> Defines a table
<tbody> Groups the body content in a table
<td> Defines a cell in a table
<textarea> Defines a multi-line text input control
<tfoot> Groups the footer content in a table
<th> Defines a header cell in a table
<thead> Groups the header content in a table
<title> Defines the title of a document
<tr> Defines a row in a table
<tt> Defines teletype text
<u> Deprecated. Defines underlined text
<ul> Defines an unordered list
<var> Defines a variable part of a text
<xmp> Deprecated. Defines preformatted text
FAQs:
1. What is Client side programming?
2. What is the difference between client side and server side programming?
3. What is mark up language?
4. What is HTML?
5. What are the different html tags?
6. What is static and dynamic HTML?
CONCLUSION:
Students should write their own conclusion here.
SDTL P .R. Jaiswal
32
33. DCOER T.E. (IT)
Assignment No.: 7 Date: 13-02-2012
Title: Java Applets
AIM: Implement a Java Applet application to display all information about bank account.
OBJECTIVES:
To expose the concepts of Java Applet
THEORY:
Basics of Java Applet
Java is a programming language. Developed in the years 1991 to 1994 by Sun
Microsystems. Programs written in Java are called applets. First browser that could show
applets was introduced in 1994, as "WebRunner" - later known as "The HotJava Browser".
An Applet is a program written in the Java programming language that can be
included in an HTML page.
When you use a Java technology-enabled browser to view a page that contains an applet, the
applet's code is transferred to your system and executed by the browser's Java Virtual
Machine (JVM).
Applet
– Program that runs in
• appletviewer (test utility for applets)
• Web browser (IE, Communicator)
– Executes when HTML (Hypertext Markup Language) document containing applet
is opened and downloaded
– Applications run in command windows
SDTL P .R. Jaiswal
33
35. DCOER T.E. (IT)
FAQs:
1. What is an applet? How does applet differ from applications?
2. Explain with an example how we implement an applet into a web page using applet
tag.
3. What are the attributes of Applet tags? Explain the purposes.
4. How can we determine the width and height of my applet?
5. Explain how to set the background color within the applet area.
6. What are methods that controls an applet’s life cycle, i.e. init, start, stop and destroy?
CONCLUSION:
Students should write their own conclusion here.
SDTL P .R. Jaiswal
35
36. DCOER T.E. (IT)
Assignment No.: 8 Date: 20-02-2012
Title: Mini Project Based on Section I & II
AIM: To develop your own system using Java Swing
OBJECTIVES:
To expose the concepts of Java Swing and GUI design
THEORY:
Introduction to Java Swing
"Swing" refers to the new library of GUI controls (buttons, sliders, checkboxes, etc.) that
replaces the somewhat weak and inflexible AWT controls
Main New Features
Lightweight. Not built on native window-system windows.
Much bigger set of built-in controls. Trees, image buttons, tabbed panes, sliders,
toolbars,
color choosers, tables, text areas to display HTML or RTF, etc.
Much more customizable. Can change border, text alignment, or add image to
almost any
control. Can customize how minor features are drawn. Can separate internal
representation from visual appearance.
Pluggable" look and feel. Can change look and feel at runtime, or design own look
and feel.
Many miscellaneous new features. Double-buffering built in, tool tips, dockable tool
bars, keyboard accelerators, custom cursors, etc.
About JFC:-
Java Foundation Classes
o Enterprise-level Java functionality
o Designed to create sophisticated front-end apps
o Contained in Java 2
JFC includes these APIs:
AWT
2D API
Drag & drop
Assistive technology
Swing
About Swing
A GUI component framework
A set of Java classes and interfaces for creating graphical interfaces
A follow-on to AWT
SDTL P .R. Jaiswal
36
37. DCOER T.E. (IT)
The Swing API provides:
A rich set of predefined components
A basis for creating sophisticated custom components
Importance of Swing
Lightweight" components
Pure Java (no native counterpart)
Require less overhead
A much richer set of components, including:
Database-bound tables
Trees
Toolbars
Progress bars
Buttons, menus and lists that use graphics
More flexible than AWT
Lets you
Create non-rectangular components
Combine components
Customize look & feel (L&F)
Sophisticated built-in features:
Tooltips
Borders and insets
Double-buffering for cleaner displays
Slow-motion graphics for debugging
Additional Swing APIs for:
Sophisticated text editing (e.g. HTML, RTF)
Undo/redo
Project Description
The project developed should cover all features of swing and should be efficiently
utilized for further process.
Student should be able to develop a project by using the concept of inheritance and
be able to work with concept of oops with AWT and SWING.
Students should attach their project snaps along with the database schema
description
Swing vs. AWT
Swing is built on AWT
AWT provides interface to native components
JComponent extends java.awt.Container
Swing has replacements for most AWT components
E.g. JButton, JLabel replace Button, Label
What Swing uses from AWT:
Base classes
Component, Container
Top-level containers
Applet, Window, Frame, Dialog
SDTL P .R. Jaiswal
37
38. DCOER T.E. (IT)
FAQs:
1. What is the difference between Swing and AWT components?
2. Name the containers which use Border Layout as their default layout?
3. How can a GUI component handle its own events?
4. What is the difference between the paint() and repaint() methods?
5. Which package has light weight components?
6. What are peerless components?
7. What is a Container in a GUI?
8. Why does JComponent have add() and remove() methods but Component does not?
9. How would you create a button with rounded edges?
CONCLUSION & FUTURE SCOPE:
Student should write in brief functionality achieved and future scope of their project.
SDTL P .R. Jaiswal
38
39. DCOER T.E. (IT)
Section III:- Server Side Technologies
Assignment No.: 9 Date: 27-02-2012
Title: Servlets, JSP
AIM: Study of Servlets, JSP, JDBC API and tomcat server.
OBJECTIVES:
To expose the concepts & features of Java Servlets, JSP, Tomcat server.
THEORY:
Server Side Programming
Server-side scripting is a web server technology in which a user's request is fulfilled by
running a script directly on the web server to generate dynamic web pages. It is usually used to
provide interactive web sites that interface to databases or other data stores. This is different
from client-side scripting where scripts are run by the viewing web browser, usually in
JavaScript. The primary advantage to server-side scripting is the ability to highly customize the
response based on the user's requirements, access rights, or queries into data stores.
Server Side Programs for JAVA platforms
Java Servlets
Java Server Pages (JSPs)
Enterprise Java Beans (EJBs)
Basics of Servlets
A servlet is a Java programming language class used to extend the capabilities of servers
that host applications accessed via a request-response programming model. Although
servlets can respond to any type of request, they are commonly used to extend the
applications hosted by Web servers. For such applications, Java Servlet technology defines
HTTP-specific servlet classes.
The javax.servlet , javax.servlet.http packages provide interfaces and classes for writing
servlets. All servlets must implement the Servlet interface.When implementing a generic
service, you can use or extend the GenericServlet class provided with the Java Servlet API.
The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-
specific services.
Life cycle of servlets
The life cycle of a servlet is controlled by the container in which the servlet has been
deployed.
When a request is mapped to a servlet, the container performs the following steps.
If an instance of the servlet does not exist, the Web containerLoads the servlet class.
Creates an instance of the servlet class.
Initializes the servlet instance by calling the init method. Initialization is covered in
Initializing a Servlet.
Invokes the service method, passing a request and response object. .
SDTL P .R. Jaiswal
39
40. DCOER T.E. (IT)
If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's
destroy method.
Setting up a Servlet development environment
List of required softwares
1. JAVA 1.5 or 1.6
2. Tomcat 5.5.16
3. eclipse 3.3
First of all you need the Java software development kit 1.5 or 1.6 (JAVA SDK) installed.
Checking if JAVA is already installed in your system
Follow this step to check if Java software development kit (JDK) is already installed your
system. To determine if JAVA SDK is already installed in your system, run the following
command from command prompt.
> Java –version
If JAVA platform is already installed, it will display the version of the JAVA SDK. Below
screen shows JAVA version 1.6 running on a windows system. If command executes
successfully and shows JAVA version 1.6, you can skip the next step.otherwise download
and install the Java SDK as explained in next step.
Install JAVA SDK
First thing you need to install is Java software development kit (Java SDK) . Download the
Java development kit 6 (JDK 6) from Sun Java SE Download site. Current latest version is
JDK 6 update 6.
Set up the JAVA_HOME environment variable
Once the JAVA SDK is installed follow this step to set the JAVA_HOME environment
variable.
If JAVA_HOME variable is already set, you can skip this step.
Right click on My Computer icon on your desktop it will open a popup menu, click on
properties, it will open the system properties window, then click on advanced tab. Click on
environment variables button, it will open the environment variables window as shown in
figure below. Initially there will be no JAVA_HOME environment variable set as shown in
figure.Click on new button to add new system variable JAVA_HOME.
In the variable name filed, enter JAVA_HOME. Specify the path to root directory of JAVA
installation in variable value field and click OK button. Now JAVA_HOME will appear
under user variables.Next you need to add bin directory under the root directory of JAVA
installation in PATH environment variable.Select the PATH variable from System variables
and click on Edit button.
Add: ;%JAVA_HOME%bin; at the end of variable value field and click OK button.
Now verify that everything is correct by following the step: Checking if JAVA is already
installed in your system. It should show the version of the installed JAVA SDK.
Installing Tomcat
Tomcat is an opensource web container. it is also web container reference implementation.
You will need tomcat 5.5.16 installed on your system to test various servlet and JSP
SDTL P .R. Jaiswal
40
41. DCOER T.E. (IT)
examples given in other tutorials. Download the jakarta-tomcat-5.0.28.tar.gz and extract it to
the directory of your choice.
Note: This directory is referred as TOMCAT_HOME in other tutorials
That’s all, tomcat is installed. It’s very easy, isn’t it?
Starting and shutting down Tomcat
To start the tomcat server, open the command prompt, change the directory to TOMCAT
HOME/bin and run the startup.bat file. It will start the server.
> startup
To shut down the tomcat server, run the shutdown.bat file. It will stop the server.
> shutdown
Verifying Tomcat installation
To verify that tomcat is installed properly, start the server as explained above, open the web
browser and access the following URL.
http://localhost:8080/index.jsp
It should show the tomcat welcome page, if tomcat is installed properly and server is running.
Setting up the CLASSPATH
Now you need to create a new environment variable CLASSPATH if it is not already set. We
need to add the servlet-api.jar into the CLASSPATH to compile the Servlets. Follow the same
steps as you did to create the JAVA_HOME variable. Create a new variable CLASSPATH
under system variables. Add TOMCAT_HOME/lib/servlet-api.jar in variable value field.
Note: here TOMCAT_HOME refers to the tomcat installation directory.
Introduction to Java Servlets
Now you have the basic understanding of the HTTP protocol, web containers, and J2EE web
application structure. Before you start learning Servlet API, this tutorial provides the basic
understanding of the Java Servlets.
Basics of JSP
JavaServer Pages (JSP) technology provides a simplified, fast way to create dynamic web
content. JSP technology enables rapid development of web-based applications that are serverand
platform-independent.
JavaServer Pages (JSP) is a Java technology that helps software developers serve dynamically
generated web pages based on HTML, XML, or other document types
JSP pages typically comprise of:
Static HTML/XML components.
Special JSP tags
Optionally, snippets of code written in the Java programming language called "scriptlets."
JSP Advantages
Write Once Run Anywhere: JSP technology brings the "Write Once, Run Anywhere"
paradigm
to interactive Web pages. JSP pages can be moved easily across platforms, and across web
servers, without any changes.
SDTL P .R. Jaiswal
41
42. DCOER T.E. (IT)
Dynamic content can be served in a variety of formats: There is nothing that mandates the
static
template data within a JSP page to be of a certain format. Consequently, JSP can service a
diverse clientele ranging from conventional browsers using HTML/DHTML, to handheld
wireless devices like mobile phones and PDAs using WML, to other B2B applications using
XML.
Recommended Web access layer for n-tier architecture: Sun's J2EE Blueprints, which offers
guidelines for developing large-scale applications using the enterprise Java APIs,
categorically
recommends JSP over servlets for serving dynamic content.
Completely leverages the Servlet API: If you are a servlet developer, there is very little that
you
have to "unlearn" to move over to JSP. In fact, servlet developers are at a distinct advantage
because JSP is nothing but a high-level abstraction of servlets. You can do almost anything
that
can be done with servlets using JSP--but more easily!
JSP using scripting elements, page directive and standard tags.
List of the tags used in Java Server Pages:
Declaration tag
Expression tag
Directive tag
Scriptlet tag
Action tag
FAQs:
1. What are the ways to write comments in the JSP page? Give example.
2. Write Sample Code to pass control from one JSP page to another?
3. How will you handle the exception without sending to error page? How will you set a
4. message detail to the exception object?
5. What is JSP Fragment?
6. What is the difference between jsp and servlet life cycles?
7. Why we need web container to Deploy the servlet or jsp ?
8. Why main() is not written in servlets programs?
9. What is the difference between http session and application session?
10. Where do you declare methods in JSP?
11. How to disable browser "Back" and "Forward" button from a JSP page?
12. Can we use main method inside JSP? Why?
CONCLUSION:
Students should write their own conclusion here.
SDTL P .R. Jaiswal
42
43. DCOER T.E. (IT)
Assignment No.: 10 Date: 05-03-2012
Title: Main Project Based on Section I, II & III
AIM: To develop your own system by making use of Section I, II & III concepts and
features
OBJECTIVES:
To develop a web based system.
THEORY:
Project Description
The project developed should cover maximum features of core Java, Swing, AWT,
JSP, Servlets, JDBC Connectivity etc.
Students should attach their project snaps along with the database schema
description.
Java doc of complete system should be created.
Final project report should be presented.
CONCLUSION & FUTURE SCOPE:
Student should write in brief functionality achieved and future scope of their project.
SDTL P .R. Jaiswal
43