Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Sdtl manual

337 views

Published on

sdtl

Published in: Education
  • Be the first to comment

  • Be the first to like this

Sdtl manual

  1. 1. DCOER T.E. (IT) Section I: - Core Java ProgrammingAssignment 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 conversionTHEORY: 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 -1SDTL P .R. Jaiswal 1
  2. 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. 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 PromptE:ZealSecond SemTE ITJava Programs>javac Example.javaE:ZealSecond SemTE ITJava Programs>java ExampleHello WorldE:ZealSecond SemTE ITJava Programs>Wrapper ClassesWrapper class is a wrapper around a primitive data type. It represents primitive data types intheir corresponding class instances e.g. a boolean data type can be represented as a Booleanclass instance. All of the primitive wrapper classes in Java are immutable i.e. once assigneda value to a wrapper class instance cannot be changed further.Wrapper Classes are used broadly with Collection classes in the java.util package and withthe classes in the java.lang.reflect reflection package. Table 1 above shows primitive typesSDTL P .R. Jaiswal 3
  4. 4. DCOER T.E. (IT)and their corresponding wrapper classes.Features of the Wrapper ClassesSome 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: MethodsThere 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. Whats 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. 5. DCOER T.E. (IT)Assignment No.: 2 Date: 09-01-2012 Title: String OperationsAIM: Write a program to implement string operations like length, reverse, palindrome, casechange 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 thatimplement 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 offeatures that make string handling convenient. For example, Java has methods to comparetwo strings, search for a substring, concatenate two strings, and change the case of letterswithin a string. Also, String objects can be constructed a number of ways, making it easy toobtain a string when needed.Somewhat unexpectedly, when you create a String object, you are creating a string thatcannot be changed. That is, once a String object has been created, you cannot change thecharacters that comprise that string. The difference is that each time you need an alteredversion 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, immutablestrings can be implemented more efficiently than changeable ones. For those cases in whicha 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 availableto all programs automatically. Both are declared final, which means that neither of theseclasses may be subclassed. This allows certain optimizations that increase performance totake place on common string operations.The String ConstructorsThe String class supports several constructors. To create an empty String, you call thedefault constructor. For example,String s = new String();will create an instance of String with no characters in it.SDTL P .R. Jaiswal 5
  6. 6. DCOER T.E. (IT)Frequently, you will want to create strings that have initial values. The String class providesa variety of constructors to handle this. To create a String initialized by an array ofcharacters, 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 followingconstructor: String(char chars[ ], int startIndex, int numChars) Here, startIndex specifies theindex at which the subrange begins, and numChars specifies the number of characters touse. 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 anotherString 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:JavaJavaAs you can see, s1 and s2 contain the same string.String LengthThe length of a string is the number of characters that it contains. To obtain this value, callthe 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 OperationsBecause strings are a common and important part of programming, Java has added specialsupport for several string operations within the syntax of the language. These operationsSDTL P .R. Jaiswal 6
  7. 7. DCOER T.E. (IT)include the automatic creation of new String instances from string literals, concatenation ofmultiple String objects by use of the + operator, and the conversion of other data types to astring 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 ofcharacters by using the new operator. However, there is an easier way to do this using astring literal. For each string literal in your program, Java automatically constructs a Stringobject. 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 literalBecause a String object is created for every string literal, you can use a string literal anyplace you can use a String object. For example, you can call methods directly on a quotedstring 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 ConcatenationIn general, Java does not allow operators to be applied to String objects. The one exceptionto this rule is the + operator, which concatenates two strings, producing a String object asthe 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 bycalling one of the overloaded versions of the string conversion method valueOf( ) definedby String. valueOf( ) is overloaded for all the simple types and for type Object. For thesimple types, valueOf( ) returns a string that contains the human-readable equivalent of thevalue with which it is called. For objects, valueOf( ) calls the toString( ) method on theobject. We will look more closely at valueOf( ) later in this chapter. Here, let’s examine thetoString( ) method, because it is the means by which you can determine the stringrepresentation for objects of classes that you create.SDTL P .R. Jaiswal 7
  8. 8. DCOER T.E. (IT)Every class implements toString( ) because it is defined by Object. However, the defaultimplementation of toString( ) is seldom sufficient. For most important classes that youcreate, 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 humanreadablestring that appropriately describes an object of your class. By overriding toString( ) forclasses that you create, you allow them to be fully integrated into Java’s programmingenvironment. For example, they can be used in print( ) and println( ) statements and inconcatenation expressions.Character ExtractionThe String class provides a number of ways in which characters can be extracted from aString object. Each is examined here. Although the characters that comprise a string withina String object cannot be indexed as if they were a character array, many of the Stringmethods employ an index (or offset) into the string for their operation. Like arrays, thestring indexes begin at zero.charAt()To extract a single character from a String, you can refer directly to an individual charactervia 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 ComparisonThe 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 returnstrue if the strings contain the same characters in the same order, and false otherwise. Thecomparison is case-sensitive.To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When itcompares two strings, it considers A-Z to be the same as a-z. It has this general form:SDTL P .R. Jaiswal 8
  9. 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 specifiedstring. 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, falseis returned. For example,"Foobar".endsWith("bar")and"Foobar".startsWith("Foo")are both true.Searching StringsThe String class provides two methods that allow you to search a string for a specifiedcharacter 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 returnthe index at which the character or substring was found, or –1 on failure.To search for thefirst occurrence of a character, useint indexOf(int ch)To search for the last occurrence of a character, useint lastIndexOf(int ch)Here, ch is the character being sought.To search for the first or last occurrence of a substring, useint indexOf(String str)int lastIndexOf(String str)Here, str specifies the substring.Modifying a StringBecause String objects are immutable, whenever you want to modify a String, you musteither copy it into a StringBuffer or use one of the following String methods, which willconstruct a new copy of the string with your modifications complete.SubstringYou can extract a substring using substring( ). It has two forms. The first isString substring(int startIndex)SDTL P .R. Jaiswal 9
  10. 10. DCOER T.E. (IT)Here, startIndex specifies the index at which the substring will begin. This form returns acopy 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 indexof 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 notincluding, 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 strappended 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 withanother character. It has the following general form:trim()The trim( ) method returns a copy of the invoking string from which any leading andtrailing 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 thatare defined by Object. The hashCode( ) method must compute andreturn the hash code forthe object. Of course, equals( ) compares two objects. Fortunately, many of Java’s built-inclasses already implement the hashCode( ) method. For example, the most common type ofHashtable uses a String object as the key. String implements both hashCode( ) andequals( ).The Hashtable constructors are shown here:Hashtable( )Hashtable(int size)Hashtable(int size, float fillRatio)SDTL P .R. Jaiswal 10
  11. 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. 12. DCOER T.E. (IT)Assignment No.: 3 Date: 16-01-2012 Title: Matrix OperationsAIM: 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 arrayTHEORY:Basics of ArrayAn array is a group of like-typed variables that are referred to by a common name. Arrays ofany type can be created and may have one or more dimensions. A specific element in anarray is accessed by its index. Arrays offer a convenient means of grouping relatedinformation.One – Dimensional ArrayA one-dimensional array is, essentially, a list of like-typed variables. To create an array, youfirst must create an array variable of the desired type. The general form of a one dimensionalarray declaration istype var-name[ ];Here, type declares the base type of the array. The base type determines the data type ofeach element that comprises the array. Thus, the base type for the array determines whattype of data the array will hold. For example, the following declares an array namedmonth_days with the type “array of int”:int month_days[];Although this declaration establishes the fact that month_days is an array variable, no arrayactually exists. In fact, the value of month_days is set to null, which represents an arraywith no value. To link month_days with an actual, physical array of integers, you mustallocate one using new and assign it to month_days. new is a special operator that allocatesmemory. You will look more closely at new in a later chapter, but you need to use it now toallocate memory for arrays. The general form of new as it applies to one-dimensional arraysappears as follows:array-var = new type[size];SDTL P .R. Jaiswal 12
  13. 13. DCOER T.E. (IT)Here, type specifies the type of data being allocated, size specifies the number of elementsin the array, and array-var is the array variable that is linked to the array. That is, to use newto allocate an array, you must specify the type and number of elements to allocate. Theelements in the array allocated by new will automatically be initialized to zero. Thisexample 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, allelements 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 mustallocate 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, youcan access a specific element in the array by specifying its index within square brackets. Allarray indexes start at zero. For example, this statement assigns the value 28 to the secondelement 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 usedto initialize the simple types. An array initializer is a list of comma-separated expressionssurrounded by curly braces. The commas separate the values of the array elements. Thearray will automatically be created large enough to hold the number of elements you specifyin the array initializer.Here is one more example that uses a one-dimensional array. It finds the average of a set ofnumbers.// 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. 14. DCOER T.E. (IT)}Alternative Array DeclarationThere 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 whenspecifying an array as a return type for a method.Multidimensional ArraysIn 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 acouple of subtle differences. To declare a multidimensional array variable, specify eachadditional index using another set of square brackets. For example, the following declares atwo-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. 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:012345678910 11 12 13 1415 16 17 18 19When you allocate memory for a multidimensional array, you need only specify the memoryfor the first (leftmost) dimension. You can allocate the remaining dimensions separately. Forexample, this following code allocates memory for the first dimension of twoD when it isdeclared. 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 MatrixIn 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 ATFormally, 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. 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. 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 overridingTHEORY: 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. 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 MembersUnder certain circumstances, a subclass may override non-static methods defined inthe super class that would otherwise be inherited. When the method is invoked on anSDTL P .R. Jaiswal 18
  19. 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 newmethod 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 andparameters) and the same return type.Whether parameters in the overriding method should be final is at the discretion of thesubclass. A methods signature does not encompass the final modifier of parameters, onlytheir types and order.The new method definition cannot narrow the accessibility of the method, but it canwiden it. The new method definition can only specify all or none, or a subset of theexception classes (including their subclasses) specified in the throws clause of theoverridden method in the super class.An instance method in a subclass cannot override a static method in the super class. Thecompiler will flag this as an error. A static method is class-specific and not part of anyobject, 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 methodoverriding. 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 themethod, in order to provide an implementation.Accessibility modifier private for a method means that the method is not accessible outsidethe class in which it is defined; therefore, a subclass cannot override it. However, asubclass can give its own definition of such a method, which may have the same signatureas the method in its super class.Overriding vs. OverloadingMethod overriding should not be confused with method overloading. Method overridingrequires the same method signature (name and parameters) and the same return type. Onlynon-final instance methods in the superclass that are directly accessible from the subclassare eligible for overriding. Overloading occurs when the method names are the same,but the parameter lists differ. Therefore, to overload methods, the parameters must differin type, order, or number. As the return type is not a part of the signature, havingdifferent return types is not enough to overload methods.InterfacesUsing the keyword interface, you can fully abstract a class’ interface from itsimplementation. That is, using interface, you can specify what a class must do, but not howit does it. Interfaces are syntactically similar to classes, but they lack instance variables, andtheir methods are declared without any body. In practice, this means that you can defineinterfaces which don’t make assumptions about how they are implemented. Once it isdefined, any number of classes can implement an interface. Also, one class can implementany number of interfaces.To implement an interface, a class must create the complete set of methods defined by theinterface. However, each class is free to determine the details of its own implementation. Byproviding the interface keyword, Java allows you to fully utilize the “one interface,multiple methods” aspect of polymorphism. Interfaces are designed to support dynamicmethod resolution at run time.SDTL P .R. Jaiswal 19
  20. 20. DCOER T.E. (IT)Normally, in order for a method to be called from one class to another, both classes need tobe present at compile time so the Java compiler can check to ensure that the methodsignatures are compatible. This requirement by itself makes for a static and non extensibleclassing environment. Inevitably in a system like this, functionality gets pushed up higherand higher in the class hierarchy so that the mechanisms will be available to more and moresubclasses. Interfaces are designed to avoid this problem. They disconnect the definition ofa method or set of methods from the inheritance hierarchy. Since interfaces are in a differenthierarchy from classes, it is possible for classes that are unrelated in terms of the classhierarchy to implement the same interface. This is where the real power of interfaces isrealized.Defining InterfaceAn 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 defaultaccess results, and the interface is only available to other members of the package in whichit 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 afterthe parameter list. They are, essentially, abstract methods; there can be no defaultimplementation of any method specified within an interface. Each class that includes aninterface must implement all of the methods.Variables can be declared inside of interface declarations. They are implicitly final andstatic, meaning they cannot be changed by the implementing class. They must also beinitialized with a constant value. All methods and variables are implicitly public if theinterface, itself, is declared as public.Implementing an InterfaceOnce an interface has been defined, one or more classes can implement that interface. Toimplement an interface, include the implements clause in a class definition, and then createthe methods defined by the interface. The general form of a class that includes theimplements clause looks like this:access class classname [extends superclass][implements interface [,interface...]] {// class-body}SDTL P .R. Jaiswal 20
  21. 21. DCOER T.E. (IT)Here, access is either public or not used. If a class implements more than one interface, theinterfaces are separated with a comma. If a class implements two interfaces that declare thesame method, then the same method will be used by clients of either interface. The methodsthat implement an interface must be declared public. Also, the type signature of theimplementing method must match exactly the type signature specified in the interfacedefinition.FAQs: 1. Can an inner class declared inside of method access local variables of this method? 2. Whats 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. 22. DCOER T.E. (IT)Assignment No.: 5 Date: 30-01-2012 Title: JDBC ConnectivityAIM: Write a program to connect to database using JDBC connectivityOBJECTIVES: To expose the concept of JDBC connectivity To understand how JDBC connectivity helps to get connected with many database systems though java programTHEORY:Basics of JDBCThe JDBC (Java Database Connectivity) API defines interfaces and classes for writingdatabase applications in Java by making database connections. Using JDBC you can sendSQL, PL/SQL statements to almost any relational database. JDBC is a Java API forexecuting SQL statements and supports basic SQL functionality. It provides RDBMS accessby 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 remotedatabase 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 relationaldatabases, you may find that you need to write Java code to access non-relational databasesas well.JDBC Connectivity StepsBefore you can create a java jdbc connection to the database, you must first import thejava.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 driverIn this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driverclass name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect toDatabase Server through JDBC Driver. Since most of the Database servers support ODBC driver thereforeJDBC-ODBC Bridge driver is commonly used.The return type of the Class.forName (String ClassName) method is “Class”. Class is a class injava.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. 23. DCOER T.E. (IT)2.Creating a oracle jdbc ConnectionThe JDBC DriverManager class defines objects which can connect Java applications to aJDBC driver. DriverManager is considered the backbone of JDBC architecture.DriverManager class manages the JDBC drivers that are installed on the system. ItsgetConnection() 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 connectionobject. A jdbc Connection represents a session/connection with a specific database. Withinthe 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 havemany connections with different databases. A Connection object provides metadata i.e.information about the database, tables, and fields. It also contains methods to deal withtransactions.JDBC URL Syntax:: jdbc: <subprotocol>: <subname>JDBC URL Example:: jdbc: <subprotocol>: <subname>•Each driver has its ownsubprotocol•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 objectOnce a connection is obtained we can interact with the database. Connection interfacedefines methods for interacting with the database via the established connection. To executeSQL statements, you need to instantiate a Statement object from your connection object byusing the createStatement() method.Statement statement = dbConnection.createStatement();A statement object is used to send and execute SQL statements to a database.Three kinds of StatementsStatement: 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 precompiledSQL statements.Callable Statement: Execute a call to a database stored procedure.CallableStatement prepareCall(String sql)SDTL P .R. Jaiswal 23
  24. 24. DCOER T.E. (IT)returns a new CallableStatement object. CallableStatement objects are SQL storedprocedure call statements.4. Executing a SQL statement with the Statement object, and returning a jdbcresultSet.Statement interface defines methods that are used to interact with database via the executionof SQL statements. The Statement class has three methods for executing statements:executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method touse is executeQuery . For statements that create or modify tables, the method to use isexecuteUpdate. Note: Statements that create a table, alter a table, or drop a table are allexamples of DDLstatements and are executed with the method executeUpdate. execute() executes an SQLstatement that is written as String object.ResultSet provides access to a table of data generated by executing a Statement. The tablerows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row ofdata. 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 columnsin a ResultSet. It is constructed from the Connection object.Java JDBC Connection Example, JDBC Driver Exampleimport 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. 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.javaJava JDBCSampleajay|100|te itrahul|101|te itpayal|102|te itmanavi|103|te itJDBC DriversType 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 statementFAQs: 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. 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. 27. DCOER T.E. (IT) Section II:- Client Side TechnologiesAssignment No.: 6 Date: 06-02-2012 Title: HTML – Scripting LanguageAIM: Study of Hyper Text Markup Language and its’ tags. Create a HTML page todisplay 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 HTMLSDTL P .R. Jaiswal 27
  28. 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 HTMLHTML (Hypertext Markup Language) is used to create document on the World WideWeb. It is simply a collection of certain key words called ‘Tags’ that are helpful in writingthe document to be displayed using a browser on Internet. It is a platform independentlanguage 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 understandsand interprets the HTML tags, identifies the structure of the document (which partare which) and makes decision about presentation (how the parts look) of thedocument.HTML also provides tags to make the document look attractive usinggraphics, font size and colors. User can make a link to the other document or the differentsection of the same document by creating Hypertext Links also known as Hyperlinks.HyperText Markup Language (HTML) is the language behind most Web pages. Thelanguage is made up of elements that describe the structure and format of the content on aWeb page. Cascading Style Sheets (CSS) is used in HTML pages to separateformatting and layout from content. Rules defining color, size, positioning and otherdisplay aspects of elements are defined in the HTML page or in linked CSS pages.HTML SkeletonAn HTML page contains what can be thought of as a skeleton - the main structure of thepage. 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. 29. DCOER T.E. (IT) <H2> 2.1 Elements in HTML </H2>.The <head> ElementThe <head> element contains content that is not displayed on the page itself. Someof 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 ofthe browser window. Meta tags, which contain descriptive information about the page<meta />) Script blocks, which contain javascript or vbscript code for addingfunctionality and interactivity to a page (<script>) Style blocks, which contain CascadingStyle Sheet rules (<style>). References (or links) to external style sheets (<link />).The <body> ElementThe <body> element contains all of the content that appears on the page itself. Body tagswill be covered thoroughly throughout this manualEmptyElementsSome elements are empty -- that is, they do not affect a block of the document insome 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 beentered as <HR>Upper and LowerCaseElement names are case insensitive. Thus, the the horizontal rule element can be writtenas any of <hr>, <Hr>or <HR>.Elements can have AttributesMany elements can have arguments that pass parameters to the interpreter handling thiselement. These arguments are called attributes of the element. For example, considerthe 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 hypertextdocument to which the marked piece of text is linked. To specify this in the tag for A youwrite: <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 notempty, 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. 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 documents 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 framesSDTL P .R. Jaiswal 30
  31. 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 documentSDTL P .R. Jaiswal 31
  32. 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 textFAQs: 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. 33. DCOER T.E. (IT)Assignment No.: 7 Date: 13-02-2012 Title: Java AppletsAIM: Implement a Java Applet application to display all information about bank account.OBJECTIVES: To expose the concepts of Java AppletTHEORY:Basics of Java AppletJava is a programming language. Developed in the years 1991 to 1994 by SunMicrosystems. Programs written in Java are called applets. First browser that could showapplets 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 beincluded in an HTML page.When you use a Java technology-enabled browser to view a page that contains an applet, theapplets code is transferred to your system and executed by the browsers Java VirtualMachine (JVM).Applet– Program that runs in• appletviewer (test utility for applets)• Web browser (IE, Communicator)– Executes when HTML (Hypertext Markup Language) document containing appletis opened and downloaded– Applications run in command windowsSDTL P .R. Jaiswal 33
  34. 34. DCOER T.E. (IT)SDTL P .R. Jaiswal 34
  35. 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. 36. DCOER T.E. (IT)Assignment No.: 8 Date: 20-02-2012 Title: Mini Project Based on Section I & IIAIM: To develop your own system using Java SwingOBJECTIVES: To expose the concepts of Java Swing and GUI designTHEORY:Introduction to Java Swing"Swing" refers to the new library of GUI controls (buttons, sliders, checkboxes, etc.) thatreplaces the somewhat weak and inflexible AWT controlsMain 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 2JFC includes these APIs:  AWT  2D API  Drag & drop  Assistive technology  SwingAbout SwingA GUI component framework  A set of Java classes and interfaces for creating graphical interfaces  A follow-on to AWTSDTL P .R. Jaiswal 36
  37. 37. DCOER T.E. (IT)The Swing API provides:  A rich set of predefined components  A basis for creating sophisticated custom componentsImportance of SwingLightweight" components  Pure Java (no native counterpart)  Require less overheadA much richer set of components, including:  Database-bound tables  Trees  Toolbars  Progress bars  Buttons, menus and lists that use graphics  More flexible than AWTLets 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 debuggingAdditional Swing APIs for:  Sophisticated text editing (e.g. HTML, RTF)  Undo/redoProject 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 descriptionSwing vs. AWTSwing is built on AWT  AWT provides interface to native components  JComponent extends java.awt.ContainerSwing has replacements for most AWT components  E.g. JButton, JLabel replace Button, LabelWhat Swing uses from AWT:  Base classesComponent, ContainerTop-level containers Applet, Window, Frame, DialogSDTL P .R. Jaiswal 37
  38. 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. 39. DCOER T.E. (IT) Section III:- Server Side TechnologiesAssignment No.: 9 Date: 27-02-2012 Title: Servlets, JSPAIM: Study of Servlets, JSP, JDBC API and tomcat server.OBJECTIVES: To expose the concepts & features of Java Servlets, JSP, Tomcat server.THEORY:Server Side ProgrammingServer-side scripting is a web server technology in which a users request is fulfilled byrunning a script directly on the web server to generate dynamic web pages. It is usually used toprovide interactive web sites that interface to databases or other data stores. This is differentfrom client-side scripting where scripts are run by the viewing web browser, usually inJavaScript. The primary advantage to server-side scripting is the ability to highly customize theresponse based on the users requirements, access rights, or queries into data stores.Server Side Programs for JAVA platformsJava ServletsJava Server Pages (JSPs)Enterprise Java Beans (EJBs)Basics of ServletsA servlet is a Java programming language class used to extend the capabilities of serversthat host applications accessed via a request-response programming model. Althoughservlets can respond to any type of request, they are commonly used to extend theapplications hosted by Web servers. For such applications, Java Servlet technology definesHTTP-specific servlet classes.The javax.servlet , javax.servlet.http packages provide interfaces and classes for writingservlets. All servlets must implement the Servlet interface.When implementing a genericservice, 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 servletsThe life cycle of a servlet is controlled by the container in which the servlet has beendeployed.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 inInitializing a Servlet.Invokes the service method, passing a request and response object. .SDTL P .R. Jaiswal 39
  40. 40. DCOER T.E. (IT)If the container needs to remove the servlet, it finalizes the servlet by calling the servletsdestroy method.Setting up a Servlet development environmentList of required softwares 1. JAVA 1.5 or 1.6 2. Tomcat 5.5.16 3. eclipse 3.3First 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 systemFollow this step to check if Java software development kit (JDK) is already installed yoursystem. To determine if JAVA SDK is already installed in your system, run the followingcommand from command prompt.> Java –versionIf JAVA platform is already installed, it will display the version of the JAVA SDK. Belowscreen shows JAVA version 1.6 running on a windows system. If command executessuccessfully and shows JAVA version 1.6, you can skip the next step.otherwise downloadand install the Java SDK as explained in next step.Install JAVA SDKFirst thing you need to install is Java software development kit (Java SDK) . Download theJava development kit 6 (JDK 6) from Sun Java SE Download site. Current latest version isJDK 6 update 6.Set up the JAVA_HOME environment variableOnce the JAVA SDK is installed follow this step to set the JAVA_HOME environmentvariable.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 onproperties, it will open the system properties window, then click on advanced tab. Click onenvironment variables button, it will open the environment variables window as shown infigure below. Initially there will be no JAVA_HOME environment variable set as shown infigure.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 JAVAinstallation in variable value field and click OK button. Now JAVA_HOME will appearunder user variables.Next you need to add bin directory under the root directory of JAVAinstallation in PATH environment variable.Select the PATH variable from System variablesand 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 alreadyinstalled in your system. It should show the version of the installed JAVA SDK.Installing TomcatTomcat 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 JSPSDTL P .R. Jaiswal 40
  41. 41. DCOER T.E. (IT)examples given in other tutorials. Download the jakarta-tomcat-5.0.28.tar.gz and extract it tothe directory of your choice.Note: This directory is referred as TOMCAT_HOME in other tutorialsThat’s all, tomcat is installed. It’s very easy, isn’t it?Starting and shutting down TomcatTo start the tomcat server, open the command prompt, change the directory to TOMCATHOME/bin and run the startup.bat file. It will start the server.> startupTo shut down the tomcat server, run the shutdown.bat file. It will stop the server.> shutdownVerifying Tomcat installationTo verify that tomcat is installed properly, start the server as explained above, open the webbrowser and access the following URL.http://localhost:8080/index.jspIt should show the tomcat welcome page, if tomcat is installed properly and server is running.Setting up the CLASSPATHNow you need to create a new environment variable CLASSPATH if it is not already set. Weneed to add the servlet-api.jar into the CLASSPATH to compile the Servlets. Follow the samesteps as you did to create the JAVA_HOME variable. Create a new variable CLASSPATHunder 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 ServletsNow you have the basic understanding of the HTTP protocol, web containers, and J2EE webapplication structure. Before you start learning Servlet API, this tutorial provides the basicunderstanding of the Java Servlets.Basics of JSPJavaServer Pages (JSP) technology provides a simplified, fast way to create dynamic webcontent. JSP technology enables rapid development of web-based applications that are serverandplatform-independent.JavaServer Pages (JSP) is a Java technology that helps software developers serve dynamicallygenerated web pages based on HTML, XML, or other document typesJSP pages typically comprise of:Static HTML/XML components.Special JSP tagsOptionally, snippets of code written in the Java programming language called "scriptlets."JSP AdvantagesWrite Once Run Anywhere: JSP technology brings the "Write Once, Run Anywhere"paradigmto interactive Web pages. JSP pages can be moved easily across platforms, and across webservers, without any changes.SDTL P .R. Jaiswal 41
  42. 42. DCOER T.E. (IT)Dynamic content can be served in a variety of formats: There is nothing that mandates thestatictemplate data within a JSP page to be of a certain format. Consequently, JSP can service adiverse clientele ranging from conventional browsers using HTML/DHTML, to handheldwireless devices like mobile phones and PDAs using WML, to other B2B applications usingXML.Recommended Web access layer for n-tier architecture: Suns J2EE Blueprints, which offersguidelines for developing large-scale applications using the enterprise Java APIs,categoricallyrecommends JSP over servlets for serving dynamic content.Completely leverages the Servlet API: If you are a servlet developer, there is very little thatyouhave to "unlearn" to move over to JSP. In fact, servlet developers are at a distinct advantagebecause JSP is nothing but a high-level abstraction of servlets. You can do almost anythingthatcan 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 tagFAQs: 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. 43. DCOER T.E. (IT)Assignment No.: 10 Date: 05-03-2012 Title: Main Project Based on Section I, II & IIIAIM: To develop your own system by making use of Section I, II & III concepts andfeaturesOBJECTIVES: 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

×