Java 7th Sem Ashokkumar



Comments



Description

VTU7th sem B.E (CSE/ISE) JAVA/ J2EE Notes prepared by Mr. Ashok Kumar K 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. Unit 1: INTRODUCTION TO JAVA Mr. Ashok Kumar K 9742024066 | [email protected] Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. 15 reasons to choose VTUPROJECTS.COM for your final year project work 1. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. No prerequisites required. 2. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 3. Study Materials We provide the most efficient study material for each and every module during the project development 4. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience in working on both product and service driven industries. 5. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. 6. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. 10. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Skype/ Team viewer support In case the student needs an emergency help when he/she is in their colleges, we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 13. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. 15. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. 1.1 Basics Java is both a programming language and a platform Java as a Programming Language In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the java compiler (javac). A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine (JVM). The java launcher tool then runs your application with an instance of the Java Virtual Machine. Java Program Execution. Executing a Java Program is a two steps process: Step 1: Compile the source file by issuing a command javac MyProgram.java Output of this step is MyProgram.class file (bytecodes) Step 2: Run the Program by giving the bytecoodes as an input to JVM java MyProgram Because the JVM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris Operating System (Solaris OS), Linux, or Mac OS. This is how java achieves “Compile once, Run anywhere” feature. Mr. Ashok Kumar K | 9742024066 | [email protected] Mac. As a platform-independent environment.www. the Java platform can be a bit slower than native code. However. Bytecodes will be contained within .com . Ashok Kumar K | 9742024066 | [email protected] files. It is grouped into libraries of related classes and interfaces. Ashok Kumar K.java file) using a java compiler. advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability. etc. Fig: Through the JVM. Mr. Registration started. these libraries are known as packages. The Java Application Programming Interface (API) The API is a large collection of ready-made software components that provide many useful capabilities. The Java platform is a software-only platform that runs on top of other hardware-based platforms like Windows. Contact 9742013378 or 9742024066 and lock your project at the earliest. The bytecodes can be generated by compiling the java source code (. The java platform has two components:  The Java Virtual Machine  The Java Application Programming Interface (API) The Java Virtual Machine (JVM) The JVM is one of the components of Java platform which executes the bytecodes on any machine in which it’s been installed.vtuprojects. the same application is capable of running on multiple platforms Java as a Platform A platform is the hardware or software environment in which a program runs.com | Final year IEEE project development and training from scratch by Mr.  The CLASSPATH variable is one way to tell applications.jsp This site provides java distribution for Windows.e.  The JAVA_HOME is the variable that your operating system uses to locate the installation path of java.com . PATH and CLASSPATH environment variables. you should be getting these two entities  Java Development Kit (JDK)  Java Runtime Environment (JRE) Java Development Kit (JDK) JDK is a bundle of ready-made software components that provide many useful capabilities. all the code of the Java language is written into the classes and objects.  The PATH is the variable that your operating system uses to locate needed executables from the command line or Terminal window.com | Final year IEEE project development and training from scratch by Mr. 1. development libraries. Java apps can open the remote objects on internet as easily they can do in local systems. Ashok Kumar K. Typically. Installation procedure is pretty simple.www. Mr. where to look for user classes. Download and install latest version of Java on whichever the platform you are comfortable with. Give a try! After installing Java in your machine.com/en/download/manual. Contact 9742013378 or 9742024066 and lock your project at the earliest. Linux. Object oriented Java is purely an Object Oriented Programming language i. Observations  Upon installing Java in any machine. Ashok Kumar K | 9742024066 | celestialcluster@gmail. including the JDK tools. It constitutes the Java API component in the Java Platform.. Registration started.  Downloading and Installing Java You can download the latest distribution of Java at its official website http://www. storage classes and goto statements and it doesn’t support multiple inheritances. etc.java. Hopefully you don't encounter any blockage here. please set the JAVA_HOME. Java Runtime Environment (JRE) JRE is an implementation of Java Virtual Machine which actually runs the program. It is grouped into libraries of related classes and interfaces.2 Java Buzzwords Simple Java is a simple Language because it contains many features of other Languages like C and C++ and removes complexity because it doesn’t use pointers. for creating applications on network it has the ability to share the data and programs over the LAN (local area network).vtuprojects. bundling and deployment tools. each JDK contains one (or more) JRE's along with the various development tools like the Java source compilers. Mac OS. Distributed Java is designed as distributed language because. and Solaris. debuggers. these libraries are known as packages. here each tab is a thread). a process by which a child class acquires the state and behavior of its parent class is referred to as Inheritance. but an Object refers to a real Dog. iTwenty. a Human is an Object etc. An object is a software bundle of related state and behavior. etc Secured Java provides data security through encapsulation. Getz etc. Dynamic The Java Virtual Machine (JVM) maintains a lot of runtime information about the program and the objects in the program. also a Bank is an Object.com . a class just describes how a Dog looks like. UNIX and Mac. It's just a template for an object. an int in Java is always a 32-bit integer. it has been simplified. An applet is a small program which can be downloaded from a server using a browser. a dog has 4 legs. Portable A C/C++ program may run slightly differently on different hardware platforms depending on how these platforms implement arithmetic operations. When we transfer the code from one machine to another. it follows 'Write-once-run-anywhere' approach.3 Object oriented concepts Object An Object can be any real world entity we come across in our life.www. Example an Animal is an Object. Some of those features are: type checking.). and float is always a 32-bit IEEE 754 floating point number. Hyundai is a parent class whose properties are inherited by the classes named iTen. in Java the size of the primitive data types are machine independent. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Unlike C/C++. Java programs are compiled into bytecode format which does not depend on any machine architecture but can be easily translated into a specific machine by a Java Virtual Machine (JVM) for that machine. Libraries are dynamically linked during runtime. This architecture means that Java programs are faster than programs/scripts written in purely interpreted languages but slower than C and C++ programs that compiled to native machine languages. If the code is affected then it will never execute that code in that machine. Multithreaded A Java program can be divided into multiple threads assigning different tasks for different threads and have all the threads executing in parallel. For example. In Java. exception handling. For example. In other words. These consistencies make Java programs portable among different platforms such as Windows. Also we can write applets in Java which provides security. Example for multithreaded application is a browser (multiple tabs can be opened. (Say. it barks. Java’s features help to make the programs robust. So. It describes an object. There is no need to worry about applets accessing the system resources which may compromise security. Mr.vtuprojects. Robust A Program or an application is said to be robust (reliable) when it is able to give some response in any kind of context. the JVM first check the code to check if it is affected by virus/threats or not. For Example. Ashok Kumar K. Architecture neutral This means that the programs written on one platform can run on any other platform without having to rewrite or recompile them. even if you make dynamic changes to pieces of code. Inheritance Generally. Class A class is a blueprint or prototype from which objects are created. High performance Java programs are compiled to portable intermediate form known as bytecodes. Contact 9742013378 or 9742024066 and lock your project at the earliest. 1. Verna.com | Final year IEEE project development and training from scratch by Mr. it eats etc. the program is not affected. Registration started. rather than to native machine level instructions and JVM executes the bytecodes on any machine on which it is installed. Inheritance can also be referred to the concept of Generalization. just that it does. it makes sense to keep things organized by placing related classes and interfaces into packages.Y. the polymorphism refers to the process in which a member function of a class behaves differently for different inputs. Contact 9742013378 or 9742024066 and lock your project at the earliest. A class is an example for encapsulation. Conceptually you can think of packages as being similar to different folders on your computer. Encapsulation Encapsulation refers to the process of binding the data members and the functions (that accesses these data) together. it allows only sideways movement for camel and straight movement for elephant). you don't care how. In terms of programming. In Object Oriented Programming. Encapsulation helps to change the internal implementation of the object without affecting the overall functionality of the system.www. and all video songs under another directory. which is the process of extracting common characteristics (states and behavior) from two or more classes. etc) and write the source code. For example. a function move() in the game of chess behaves differently for different pawns (for instance.Z. the light goes on. You arrange all audio songs under a specific directory. Through encapsulation a class can hide the internal details of how an object does something. should have a turn_on() method and a turn_off() method. etc. edit plus. an Interface is a description of all functions that an object must have. and combining them into a generalized super class. 1. For example.com . anything that "ACTS LIKE" a light.vtuprojects. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes.4 Simple Java Programs My first Java Program Assumptions: Java has been installed and the environment variables are been properly set. Encapsulation provides abstraction (Information hiding).java in your local hard disk (where ever you wish) Mr. Package A package is a namespace that organizes a set of related classes and interfaces. etc. Interface An interface is a description of the actions that an object can do. So these two functions will be included within an interface. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Ashok Kumar K. The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of TYPE T must have functions called X. Registration started.com | Final year IEEE project development and training from scratch by Mr. For example when you flip a light switch. Polymorphism The word "Polymorphism" refers to the ability to take more than one form. Steps Step1: Open a text editor (notepad. Step 2: Save this file as Hello. by issuing a command as follows: javac Hello. the output of the compilation process is a . Ashok Kumar K.com .www. i.vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest. Step 4: Compile the source file using java compiler. Ashok Kumar K | 9742024066 | celestialcluster@gmail. this command will not successfully executes. Step 3: Open a command window and change the directory to the one where you just saved your Hello.java If there are any compilation errors in your program.class file which is called the java "byte code".class file by giving it as an input to JVM through following command.e. Registration started. Mr. You can observe that. instead it will throw an error saying what went wrong.java source file. the compilation process will be successful. If your program is completely error free. Step 5: Execute the .com | Final year IEEE project development and training from scratch by Mr. This is like giving an access permission to JVM to execute the main function. JVM has to execute the main function without having its object. it has to get an object of the class enclosing the main function.  In C++. So if JVM has to execute the main function. So.  Just like C/C++ which provides printf()/cout to print something on standard console.e. it's like you are not allowing even JVM to execute the main function and JVM throws an error if you try to run the program in that way. In Java. Nothing can be written in Java without a class.  All Java source files should have an extension of . But how will JVM get this object? Somehow.").vtuprojects. you can't return anything from the main Mr. Registration started. whose object is created and named as 'out' within a class called "System".  Java is case sensitive. } }  Java's coding syntax closely resembles to that of C/C++.. But in java it's not like that. you can write a C++ program with or without a class. This println() method is a member of a class named "PrintStream". Ashok Kumar K.println("Hello World.println)  Please focus on the signature of the main function. the main function can be accessed even outside the defining class.java. the class was optional.  The keyword 'public' says that.  The keyword 'void' indicates that a function returns nothing.out. If you mark it as private instead.out.) notation (System.  The keyword 'static' has a special meaning. println() function is referenced through a dot (.com . Java provides "println()" function to print something in the console. Generally a class member is accessed through its object. i. This signature can't be changed. This keyword indicates that a function can be accessed without an object. you are done with your first Java program successfully. Congrats :) Observations class Hello { public static void main (String arg[]) { System. Contact 9742013378 or 9742024066 and lock your project at the earliest. Welcome to the world of Java. java Hello The program executes and the output can be seen in the console. The keyword 'static' comes as a solution for this. you can observe the main function has been enclosed within a class.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K | 9742024066 | [email protected]. Thus. Yes. Ashok Kumar K | 9742024066 | celestialcluster@gmail. All the other classes should either be marked as private or default.vtuprojects.com .  Multi line comment starts with /* followed by the comment string and ends with */  There can be more than one class within a single . It enables a more efficient lookup of source (.java) and compiled (.  A java source file should be having the same name as the class name which contains the main function. Mr. The class that encloses the main function can be called as Main Class.java file.  The Keyword 'main' is the name of the function and at this point of time you can think this as the entry point for a Java application. Ashok Kumar K. Registration started. only one class can be marked as 'public' and this class should be the main class. Let's see an example program at later point of time. You can't choose the name of your wish like in C/C++.com | Final year IEEE project development and training from scratch by Mr.  In a single . Contact 9742013378 or 9742024066 and lock your project at the earliest.class) files during compilation (import directives) and a more efficient class loading during execution. so always the main function will be having a return type of void.java file where there are more than one classes.  Comments in Java are of two types: Single line comments and Multiline comments.  Single line comment starts with // followed by the comment string.  String arg[] within the main function parenthesis is used to hold command line arguments provided during the program execution.www. This is to help the JVM to search for the main function. function. "+res). f. firstDigit(3572) should return 3. h.out. System.println("String value is . d.. int x=2. For example. Program to print the stars in right triangle pattern. Program to print the stars in left triangle pattern. It should work for negative numbers as well. Write a method named lastDigit that returns the last digit of an integer. int y) { return x+y. Write a Java program to print the command line arguments. variables. Write a method named firstDigit that returns the first digit of an integer. How for each is different from for loop? Program to illustrate data types. c. y=3. For example. int res = add(x. and functions public class One { public static void main (String arg[]) { int a=10. } public static int add(int x. Program to illustrate classes and objects.. e.7. Write a recursive function in java to print all natural numbers from 1 up to (n-1) .. System. Program to illustrate loops and control statements. lastDigit(-947) should return 7. } } Mr.com | Final year IEEE project development and training from scratch by Mr. For example.. Program to illustrate data types. Ashok Kumar K.println("Sum of "+x+" and "+y+" is . i. Ashok Kumar K | 9742024066 | [email protected]. Write a program to calculate the average among the elements {4.5.com . System. Practice Programs a. Program to print the diamond pattern. It should work for negative numbers as well. and functions b... "+s).out. j. Registration started. lastDigit(3572) should return 2.. using for each in java..www.y).println("Integer value is . variables.vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest. "+a).. String s = "Welcome". g. k. For example. firstDigit(-947) should return 9.8}. j<=i. class Three { public static void main (String arg[]) { for (int i=0. Contact 9742013378 or 9742024066 and lock your project at the earliest. } System. } else { System. Program to illustrate loops and control statements.out. for (int i=0. i<5.com . } } } Mr.com | Final year IEEE project development and training from scratch by Mr.www.println("\n"). Registration started.println(i+" is a Odd Number ").out.out.i<n.i++) { for (int j=0. i++) { if (i%2==0) { System. Ashok Kumar K | 9742024066 | [email protected](i+" is a Even Number ").j++) { System. } } } } Program to print the stars in left triangle pattern class Four { public static void main (String arg[]) { int n=5. Ashok Kumar K.print("*\t"). i<n. Ashok Kumar K | 9742024066 | celestialcluster@gmail. for (int i=0. class Six { public static void main (String arg[]) { Mr. System.j<=i.out. Ashok Kumar K. Program to print the stars in right triangle pattern class Five { public static void main (String arg[]) { int n=5.com | Final year IEEE project development and training from scratch by Mr.j++) System.out.k--) System.i++) { for (int k=n.www.vtuprojects. } } } Program to print the diamond pattern.print("\t").print("*\t").com . Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.println("\n").k>=i. for (int j=0.out. j++) System. Ashok Kumar K. i>=0. System. for (int i=0. For example. } } } Write a method named lastDigit that returns the last digit of an integer.j<n-i.out.out. n = 3489.out.com | Final year IEEE project development and training from scratch by Mr.www. For example. System.i--) { for (int j=0.. for (int p=1. int ld = lastDigit(n).out.println("\n"). Ashok Kumar K | 9742024066 | celestialcluster@gmail. for (int k=0.print("\t").out. class Seven { public static void main (String arg[]) { int n = -7676.p<i.com .vtuprojects. int n=5.p++) System. } for (int i=n.k<i.j++) System. lastDigit(3572) should return 2. for (int p=1. i<n.println("\n").k++) System.out. for (int k=0.print("\t")..p<i.out. "+ld).print("*\t"). It should work for negative numbers as well.out.k++) System. Contact 9742013378 or 9742024066 and lock your project at the earliest. Mr.print("*\t"). ld = lastDigit(n)..k<i.i++) { for (int j=0.print("*\t").println("Last Digit in "+n+" is . System.print("*\t").j<n-i.out. Registration started. lastDigit(-947) should return 7.p++) System. ....com | Final year IEEE project development and training from scratch by Mr.println("First Digit in "+n+" is .vtuprojects..out. Contact 9742013378 or 9742024066 and lock your project at the earliest.abs(n%10). "+ld). System.out. } } Write a method named firstDigit that returns the first digit of an integer. For example. class Eight { public static void main (String arg[]) { int n = -7676. Ashok Kumar K.. "+ld). System. } public static int firstDigit (int n) { n = Math. } return n. Registration started. ld = firstDigit(n). "+ld).abs(n). firstDigit(3572) should return 3.println("Last Digit in "+n+" is .. firstDigit(-947) should return 9. int ld = firstDigit(n). It should work for negative numbers as well.www.. while (n > 9) { n = n/10.out. Ashok Kumar K | 9742024066 | [email protected] . n = 3489.println("First Digit in "+n+" is .. } } Mr. } public static int lastDigit(int n) { return Math. System. For example. .nextInt(n). series(n).out. int n = 100. Ashok Kumar K | 9742024066 | celestialcluster@gmail.. Ashok Kumar K. "+ran). if (x != 0) System. int ran = r. Contact 9742013378 or 9742024066 and lock your project at the earliest. Mr. } public static void series(int x) { if (x > 0) series(--x).vtuprojects. ran = r. Registration started.nextInt(n).out. n = 200.. Write a recursive function in java to print all natural numbers from 1 up to (n-1) public class Nine { public static void main(String args[]) { int n = 10..util. System.com .www. } } Write a Java program to print the random number in between 0 and n import java.com | Final year IEEE project development and training from scratch by Mr. public class Ten { public static void main(String args[]) { Random r = new Random()..println("Random number in betwwen 0 and "+n+" is .println("Random number in betwwen 0 and "+n+" is . "+ran).Random.out..print(x + " "). System. out. "+ran). ran = r. "+ran). Ashok Kumar K | 9742024066 | celestialcluster@gmail. using for each in java. n = 300..println("Random number in betwwen 0 and "+n+" is .com | Final year IEEE project development and training from scratch by Mr.. Ashok Kumar K..println("Command line arguments are .out.7. System. n = 400.println(s).5.. } } Write a Java program to print the command line arguments public class Eleven { public static void main (String arg[]) { System. } } } Write a program to calculate the average among the elements {4. for (String s : arg) { System.vtuprojects.out. Contact 9742013378 or 9742024066 and lock your project at the earliest.nextInt(n).www. System..8}. ran = r.println("Random number in betwwen 0 and "+n+" is . Registration started. "). How for each is different from for loop? public class Twelve { Mr..out.nextInt(n).com .. com | Final year IEEE project development and training from scratch by Mr. } System.1 Variables Variable is the name or the identifier given to the known memory location.com . It tells the compiler that there is exactly one copy of this variable in existence regardless of how many times the class has been instantiated.println("Average = "+ (float) sum/arr. Registration started. int sum = 0..e. public static void main(String args[]) { int arr[] = {4. its value will be unique to each instance of a class.  Class Variables (Static) Variable which actually shares the value among all the instances of a class is called a Class Variable. i.8}. It is also called static variable. To put it in the other way.out.5.5. } } 1. It is created by prefixing the keyword 'static' while declaring a variable. the memory location will be accessed through the variable name. A variable by default becomes local if it's been defined within any block (open brace and closing brace)  Parameters Parameters are the input variables for a method within a class. Instance variables will not be having 'static' keyword prefixed.length).5.vtuprojects. There is no special keyword to designate a variable as local. It is used to store some program data/value which might be referenced in future.7.www.  Local Variables Any method in java will store its temporary state in a local variable.2 Data types Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. 1. Ashok Kumar K. They are also called non static variables. Java defines the following type of variables  Instance Variables (Non static) Variable for which a separate memory space will be created for each instance of a class is called a Instance variable. A variable which can be accessed only within its defining block can be called as a local variable for that block.5 Variables and Data types 1. for (int ele : arr) { sum = sum + ele. It can't be accessed anywhere else outside this block. Ashok Kumar K | 9742024066 | celestialcluster@gmail.  int: For integral values. which always hold the value of the same data type. in situations where the memory savings actually matters. Data type Size Possible values byte 8 bits (1 byte) -128 to +127 Mr.vtuprojects. For decimal values. There are eight primitive data types and three reference data types in Java as described by the figure. A Data type is the classification identifying one of the various types of data. Fig: Data types in Java Primitive Data types The Primitive data types are predefined data types. Registration started. this data type should never be used for precise values. but if you need a wider range of values. As with the recommendations for byte and short. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65.www.  boolean: The boolean data type has only two possible values: true and false.  double: The double data type is a double-precision 64-bit IEEE 754 floating point. the same guidelines apply: you can use a short to save memory in large arrays. Use this data type for simple flags that track true/false conditions.com | Final year IEEE project development and training from scratch by Mr. use long instead  long: Use this data type when you need a range of values wider than those provided by int. This data type will most likely be large enough for the numbers your program will use.  char: The char data type is a single 16-bit Unicode character. use a float (instead of double) if you need to save memory in large arrays of floating point numbers. As mentioned above.  float: The float data type is a single-precision 32-bit IEEE 754 floating point. this data type is generally the default choice unless there is a reason (like the above) to choose something else. such as currency. which determines the possible values for that type. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Contact 9742013378 or 9742024066 and lock your project at the earliest.com . where the memory savings actually matters  short: As with byte. and the values of a primitive data type don't share the state with other primitive values.  byte: The byte data type can be useful for saving memory in large arrays. this data type is generally the default choice.535 inclusive). Ashok Kumar K. These data types are named by a reserved keyword in Java programming language. com | Final year IEEE project development and training from scratch by Mr. Ex: int[] arr = new int[50]. short 16 bits (2 bytes) -32768 to +32767 int 32 bits (4 bytes) -2147483648 to +2147483647 long 64 bits (8 bytes) -9223372036854775808 to +9223372036854775807 float 36 bits (4 bytes) 1. and a method which can be called using that object.. classes and interfaces that are made and handled according to a programmer need. For example. The elements in an array are identified by an integer index which initially starts from 0 and ends with one less than number of elements available in the array.lang..  Array: An array is a special kind of object that contains collection of similar type of elements. There are two different ways of declaring an array as shown below: datatype[] arr_name = new datatype[arraysize].e. ... you'll probably tend to think of it as such. . Reference Data types A Reference data type is a variable that can contain the reference or an address of dynamically created object.. The String class is not technically a primitive data type.94065645841246544e-324d to 1.type variable.Object. but considering the special support given to it by the language. so that you can declare a variable of an object-type. 15. 20.com . 25}. String s = "Ashok Kumar". The java array enables the user to store the values of the same type in contiguous memory allocations. the Java programming language also provides special support for character strings via the java. 10.79769313486231570e+308d char 16 bits (2 bytes) 0 to 65. Contact 9742013378 or 9742024066 and lock your project at the earliest.vtuprojects. Ashok Kumar K | 9742024066 | celestialcluster@gmail... element n} Ex: int[] arr = {5. These types of data type are not predefined like primitive data type.lang...www..40129846432481707e-45 to 3. Whenever a variable is created..535 boolean 1 bit true or false String data type In addition to the eight primitive data types listed above. The reference data types are arrays. a reference to an Mr.String class. their values cannot be changed.  Class: The name of a class is treated as a type in a java program.. Ashok Kumar K. It is a reference data type because the class named as Array implicitly extends java. Registration started.40282346638528860e+38 double 64 bits (8 bytes) 4. element 2.. Enclosing your character string within double quotes will automatically create a new String object.. All elements of an array must contain the same type of value i.. if an array is a type of integer then all the elements must be of integer type. String objects are immutable.. which means that once created. datatype[] arr_name = {element 1. Box is a class type  Interface: The name of an interface can be used to specify the type of a reference. The object becomes an instance when the memory is allocated to that object using new keyword.5. Mr. Registration started. int w. literals are represented directly in your code without requiring computation.5. Ex: class Box { int h. they are not objects created from a class. Ashok Kumar K | 9742024066 | celestialcluster@gmail. you will learn more about interfaces in later chapters. object is also created using the name of a class for its type i.0f double 0. w. 1. Such type is called reference types in Java. A literal is the source code representation of a fixed value. Ashok Kumar K.com | Final year IEEE project development and training from scratch by Mr.www. that variable can contain either null or a reference to an object of that class.3 Default values It's not always necessary to assign a value when a variable (field) is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Primitive types are special data types built into the language. Contact 9742013378 or 9742024066 and lock your project at the earliest. double getArea() { } void setValues (int h.vtuprojects.e. A value is not allowed to be assigned to a variable declared using an interface type until the object implements the specified interface.0d char '\u0000' String (or any object) null boolean false 1. int l) { } } Box b = new Box(). Hold on here. It is not allowed to contain any other kind of values. Data Type Default Value byte 0 short 0 int 0 long 0L float 0. l. // here b is an object/instance.com .4 Literals The new keyword isn't used when initializing a variable of a primitive type. Following example shows the syntax for creating the literals in binary and hexadecimal number system.  Integer Literal: An integer literal is of type long if it ends with the letter L or l. byte b = 100.5. it's possible to assign a literal to a variable of a primitive type: boolean result = true. char capitalC = 'C'. \n (line feed). float f1 = 123.  Finally. Always use 'single quotes' for char literals and "double quotes" for String literals. String class. \t (tab). This refers to the object (of type Class) that represents the type itself. or "S\u00ED Se\u00F1or" (Sí Señor in Spanish). short s = 10000. in hexadecimal int hexVal = 0x1a. // The number 26.  Character and String Literals: Literals of types char and String may contain any Unicode (UTF-16) characters. \f (form feed).vtuprojects.  There is a special null literal that can be used as a value for any reference type. and D or d (64-bit double literal. in decimalint decVal = 26. int i = 100000. null may be assigned to any variable. Please use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1.  Floating-point Literal: A floating-point literal is of type float if it ends with the letter F or f.234e2.www. // The number 26. // The number 26. F or f (32-bit float literal). otherwise it is of type int. this is the default and by convention is omitted). Ashok Kumar K | 9742024066 | celestialcluster@gmail. \r (carriage return). formed by taking a type name and appending ". 1.class". If not. If your editor and file system allow it.5 Escape Characters Java supports a few special escape sequences for char and String literals: \b (backspace). \" (double quote). otherwise its type is double and it can optionally end with the letter D or d. Mr. you can use such characters directly in your code. Ashok Kumar K.com . Registration started. in binary int binVal = 0b11010. null is often used in programs as a marker to indicate that some object is unavailable. Contact 9742013378 or 9742024066 and lock your project at the earliest. // same value as d1. you can use a "Unicode escape" such as '\u0108' (capital C with circumflex). As shown below. Examples: double d1 = 123. there is another literal called a class literal. except variables of primitive types.4f.4. The floating point types (float and double) can also be expressed using E or e (for scientific notation). but in scientific notation double d2 = 1. for example.com | Final year IEEE project development and training from scratch by Mr. h = h. This object creation can be visualized as follows: Declaring a variable to refer to another object: A variable can be created to refer to another existing object as follows: Box b2. It is associated with variable name and object type.www.com | Final year IEEE project development and training from scratch by Mr. } long getArea() { return l*w*h. this. and \\ (backslash). this. \' (single quote). Ashok Kumar K | 9742024066 | celestialcluster@gmail. Contact 9742013378 or 9742024066 and lock your project at the earliest. 15).w = w. and an object is an instance of the class. Mr. class Box { int w. int h. // This is a constructor Box(int w.com . int l. } } Object of this class can be created as follows: Box b1 = new Box(5. 10. Registration started. The object creation statement above have three parts:  Declaration: LHS of the above statement constitutes the declaration. int h) { this.vtuprojects.l = l. int l. Ashok Kumar K. Creating Objects (Object instantiation) Consider a class definition as follows. b2 = b1.6 Creating and Destroying Objects We know that. a class is a template (blue print) for an object.5.  Instantiation: It is the new keyword in java that creates the object  Initialization: The new operator is followed by a call to a constructor. which initializes the new object. 1. method. methods. Java provides four different types of access specifiers public public classes. but not from outside this package. The only constraint is that a file with Java source code can only contain one public class which should be a main class. methods. method. Ashok Kumar K. Contact 9742013378 or 9742024066 and lock your project at the earliest. This can be visualized as follows: Destroying Objects Java provides a wonderful concept of Garbage Collection which performs automatic memory management. but not for unrelated classes. also within its subclasses but not from anywhere else. private private methods and fields can only be accessed within the same class to which the methods and fields belong. and fields via so-called access specifiers.5. and fields can be accessed from everywhere. or field belongs. private methods and fields are not visible within subclasses and are not inherited by subclasses. It concerns about the hiding of data in a class and making this class available only through methods. We will see the concept of Garbage Collection in deep at later chapters. so you don't need to delete the object that you've created. Mr. Registration started. So.7 Access specifiers in Java One of the concepts in object-oriented programming is encapsulation. It is mostly used for encapsulation default If you do not set access to specific level. 1. then such a class. Java allows you to control access to classes. protected protected methods and fields can only be accessed within the same class to which the methods and fields belong.vtuprojects. JVM does it for you automatically through Garbage Collection.com | Final year IEEE project development and training from scratch by Mr. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field. Ashok Kumar K | 9742024066 | celestialcluster@gmail. or field will be accessible from inside the same package to which the class. the private access specifier is opposite to the public access specifier.com . In this way the chance of making accidental mistakes in changing values is minimized.www. adding the numbers etc. <<=. >>>= Shift Operators  The signed left shift operator "<<" shifts a bit pattern to the left. +=.6. 1. Mr. Operators in Java are classified as follows: The list below is arranged in the order of their precedence (Highest to Lowest)  Postfix Operators exp++. ^=. Registration started. and  The signed right shift operator ">>" shifts a bit pattern to the right. |=. %=. !  Multiplicative Operators *. >. Operators are used to manipulate primitive data types.6 Operators and Expressions 1. <=. instanceof  Equality Operators ==. we can use operators to perform certain tasks like assigning a value. ~. /=. +expr. !=  Bitwise Operators Bitwise AND (&) Bitwise EXCLUSIVE OR (^) Bitwise OR (|)  Logical Operators Logical AND (&&) Logical OR (||)  Ternary Operators ?:  Assignment Operators =. -  Shift Operators <<. *=. %  Additive Operators +. -expr. Contact 9742013378 or 9742024066 and lock your project at the earliest. -=. Ashok Kumar K | 9742024066 | celestialcluster@gmail. >>>  Relational Operators <.com . --expr. >>=.www. >>.1 Operators Operators are such symbols that perform some operations on one or more operands. >=. Once we declare and initialize the variables. &=.com | Final year IEEE project development and training from scratch by Mr. /. Ashok Kumar K. exp--  Unary Operators ++expr.vtuprojects. int num2 = 5. Mr. For example. num2 = num2 >>> 2. The bit pattern is given by the left-hand operand. Ashok Kumar K.println(num3). num3 = num3 << 2. System.out. while the leftmost position after ">>" depends on sign extension.out.com . num1 = num1 >> 2. System.  The bitwise complement operator ~ inverts a bit pattern.println(num1). applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111". num2 = num2 & 2. int num3 = 5. System.www. a byte contains 8 bits.com | Final year IEEE project development and training from scratch by Mr. int num2 = 5.out. Registration started. making every "0" a "1" and every "1" a "0".  The unsigned right shift operator ">>>" shifts a zero into the leftmost position.vtuprojects. Example: public class Example { public static void main(String[] args) { int num1 = -5. num1 = num1 & 2. } } Bitwise Operators  The bitwise & operator performs a bitwise AND operation. and the number of positions to shift by the right-hand operand.out. it can be applied to any of the integral types. System.println(num1). Contact 9742013378 or 9742024066 and lock your project at the earliest.println(num2). Ashok Kumar K | 9742024066 | celestialcluster@gmail. Example public class Example { public static void main(String[] args) { int num1 = -5.  The bitwise ^ operator performs a bitwise exclusive OR operation. com | Final year IEEE project development and training from scratch by Mr.www.println(num3).println("Min value is . } } Ternary Operator The ternary operator (also known as the conditional operator) can be used as an alternative to the Java if/then/else syntax. int b = 20. int num3 = 5.. System. Syntax (condition) ? (truth block) : (false block) . } } Logical Operators public class Example { public static void main(String args[]) { Mr. else the false block gets executed and returns.com . System. and can even be used on the right hand side of Java statements. Example public class Example { public static void main(String[] args) { int a = 10.out. int min = (a < b) ? a: b. System. Ashok Kumar K.println(num2). the truth block gets executed and returns. but it goes beyond that.out.vtuprojects. If the condition evaluates to true. The condition gets evaluated first. num3 = ~num3. Ashok Kumar K | 9742024066 | celestialcluster@gmail. "+min). Contact 9742013378 or 9742024066 and lock your project at the earliest.out. Registration started. depending on whether you perform the addition or the division operation first: x + y / 100 // ambiguous You can specify exactly how an expression will be evaluated using balanced parenthesis: ‘(‘ and ‘)’.2 Expressions An expression is a construct made up of variables. the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order. which evaluates to a single value.out. The data type of the value returned by an expression depends on the elements used in the expression. in this case. the order is determined by the precedence assigned to the operators in use within the expression.com . you could write the following: (x + y) / 100 // unambiguous.vtuprojects.out. operators.println("Element 1 at index 0: " + anArray[0]). Therefore. System. System. Operators that have a higher precedence get evaluated first.println("!(a && b) = " + !(a && b)). boolean a = true. Contact 9742013378 or 9742024066 and lock your project at the earliest. cadence is an int. boolean b = false. For example. to make the previous expression unambiguous.6. the outcome is always the same. Some examples of expressions are illustrated in bold below: int cadence = 0. System. Registration started. which are constructed according to the syntax of the language. Here's an example of a compound expression: 1 * 2 * 3 In this particular example. For example.out. For example. this is not true of all expressions. // result is now 3 if (value1 == value2) System.com | Final year IEEE project development and training from scratch by Mr. the division operator has a higher precedence than does the addition operator.println("a || b = " + (a || b)). int result = 1 + 2. the following two statements are equivalent: x + y / 100 Mr. an expression can return other types of values as well. and method invocations. The expression cadence=0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand. recommended If you don't explicitly indicate the order for the operations to be performed.out.out.println("a && b = " + (a && b)). anArray[0] = 100. System. The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. As you can see from the other expressions.println("value1 == value2"). Ashok Kumar K. However. } } 1. Ashok Kumar K | 9742024066 | celestialcluster@gmail. the following expression gives different results.www. such as boolean or String. no matter in which order you apply the multiplications. 7.vtuprojects. Registration started. Selection statements  If  if-else  switch Iteration statements  while  do-while  for Jump statements  break  continue  return 1. 1. Note that the conditional expression must be a Boolean expression. based on data values and conditional logic. x + (y / 100) // unambiguous. Contact 9742013378 or 9742024066 and lock your project at the earliest. There are three main categories of control flow statements.7 Control Statements Java Control statements control the order of execution in a java program.com . This practice makes code easier to read and to maintain. Ashok Kumar K | 9742024066 | [email protected]. If the value is false. then the if block is skipped and execution continues with the rest of the program.com | Final year IEEE project development and training from scratch by Mr. recommended When writing compound expressions.1 Selection Statements The if statement The if statement executes a block of code only if the specified expression is true. You can either have a single statement or a block of code within an if statement. Ashok Kumar K. be explicit and indicate with parentheses which operators should be evaluated first. Syntax: if (<conditional expression>) { <statements> } Example: public class Example { Mr. if (a > b) System. A switch is easier to implement than a series of if/else statements.  Each label must equate to an integer constant and each must be unique. Structure of switch case:  The switch statement begins with a keyword.com | Final year IEEE project development and training from scratch by Mr. b = 20.out. Java includes a default label to use in cases where there are no matches. public static void main(String[] args) { int a = 10.out. If the statements in the if statement fails. Contact 9742013378 or 9742024066 and lock your project at the earliest. else System.println("a > b"). Note that the conditional expression must be a Boolean expression. if (a < b) System. Ashok Kumar K. Working of switch case:  When the switch statement executes.out.println("a > b"). You can either have a single statement or a block of code within if-else blocks. Registration started.vtuprojects.  If none of the case label values match. it compares the value of the controlling expression to the values of each case label. then none of the codes within the switch statement code block will be executed. Syntax: if (<conditional expression>) { <statements> } else { <statements> } Example: public class Example { public static void main(String[] args) { int a = 10. Ashok Kumar K | 9742024066 | celestialcluster@gmail. the statements in the else block are executed.  Following the controlling expression is a code block that contains zero or more labeled cases. Mr.out.  The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. } } The switch statement The switch case statement is a multi-way branch with several choices. followed by an expression that equates to a no long integral value. b = 20.com .www.println("b > a"). if (a > b) System.println("b > a"). } } The if –else statement The if-else statement is an extension of the if statement.  We can have a nested switch within a case block of an outer switch.println("b is the greatest"). case 2: System. You can either have a single statement or a block of code within the while loop.out. Syntax: while (<loop condition>) { Mr. case label2: <statement2> .com . … case labeln: <statementn> . break. break. The loop condition must be a boolean expression. break. Syntax: switch (<non-long integral expression>) { case label1: <statement1> . } else { status = 3. default: <statement> } Example: public class Example { public static void main(String[] args) { int a = 10. Contact 9742013378 or 9742024066 and lock your project at the earliest. The loop will never be executed if the testing expression evaluates to false. break. if (a > b && a > c) { status = 1. case 3: System. Ashok Kumar K.com | Final year IEEE project development and training from scratch by Mr. break.out.println("Cannot be determined"). c = 30.out.println("a is the greatest"). int status = -1.println("c is the greatest"). } else if (b > c) { status = 2.7. b = 20. } } } 1.2 Iteration Statements The while loop The while statement is a looping construct control statement that executes a block of code while a condition is true.vtuprojects. } switch (status) { case 1: System. Registration started.out. Ashok Kumar K | 9742024066 | [email protected]. break. default: System. out. except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once. <increment expression>) { <loop body> } Example: public class Example { public static void main(String[] args) { Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } } } The do-while loop The do-while loop is similar to the while loop. do { System. System.println("Printing Numbers from 1 to 10"). <loop condition>. <statements> } Example: public class Example { public static void main(String[] args) { int count = 1.vtuprojects.println(count++). Syntax: for (<initialization>.out.out. System. It’s a counter controlled loop.out. } while (count <= 10).println(count++). } } The for loop The for loop is a looping construct which can execute a set of instructions a specified number of times. Syntax: do { <loop body> } while (<loop condition>). Ashok Kumar K. while (count <= 10) { System. Example: public class Example { public static void main(String[] args) { int count = 1.www.println("Printing Numbers from 1 to 10").com . Contact 9742013378 or 9742024066 and lock your project at the earliest. Registration started.com | Final year IEEE project development and training from scratch by Mr. println("Printing Numbers from 1 to 10"). count <= 10.7.10"). and is usually only used when you wish to terminate the outermost loop in a series of nested loops. count++) { System. } } } 1. You can also provide a loop with a label and then use the label in your continue statement. and is usually only used when you wish to return to the outermost loop in a series of nested loops.println(i + "\t"). // the labeled form Example: public class Example { Mr. // Rest of loop body skipped when i is even System. ++i) { if (i == 11) break. for (int count = 1. Contact 9742013378 or 9742024066 and lock your project at the earliest.com | Final year IEEE project development and training from scratch by Mr.println("Numbers 1 . but you do not want to exit the loop itself. Syntax: break. You use a continue statement when you do not want to execute the remaining statements in the loop.out. // the labeled form Example: public class Example { public static void main(String[] args) { System. for (int i = 1. The label name is optional.3 Jump Statements The break statement The break statement transfers control out of the enclosing loop (for. do or switch statement).println(count). Ashok Kumar K. Syntax: continue. The label name is optional.com . do or for) and causes execution to resume at the top of the nearest enclosing loop. Registration started.vtuprojects. You use a break statement when you want to jump immediately to the statement following the enclosing control structure. // the unlabeled form break <label>..www. while.out. // the unlabeled form continue <label>. System. } } } The continue statement A continue statement stops the iteration of a loop (while.out.out. You can also provide a loop with a label. and then use the label in your break statement. Ashok Kumar K | 9742024066 | celestialcluster@gmail. System.  one that doesn't returns a value return. 20).vtuprojects. Example: public class Example { public static void main(String[] args) { int res = sum(10. i <= 10.out. // Rest of loop body skipped when i is even System. Registration started.println(i + "\t"). Contact 9742013378 or 9742024066 and lock your project at the earliest.out. ++i) { if (i % 2 == 0) continue.com | Final year IEEE project development and training from scratch by Mr. Syntax: The return statement has two forms:  One that returns a value return val.com . Ashok Kumar K.out.println("Odd Numbers").println(res).www. Ashok Kumar K | 9742024066 | celestialcluster@gmail. and control flow returns to where the method was invoked. int b) { return (a + b). } private static int sum(int a. for (int i = 1. } } Mr. public static void main(String[] args) { System. } } } The return statement The return statement exits from the current method. www. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K.com | Final year IEEE project development and training from scratch by Mr.vtuprojects. Ashok Kumar K | 9742024066 | [email protected] . Mr. Registration started. Ashok Kumar K 9742024066 | [email protected] (CSE/ISE) JAVA/ J2EE Notes prepared by Mr.com .VTU 7th sem B. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Ashok Kumar K 9742024066 | [email protected]. Registration started. Unit 2: Classes.com | Final year IEEE project development and training from scratch by Mr.com Mr. Inheritance.vtuprojects. Ashok Kumar K. Contact 9742013378 or 9742024066 and lock your project at the earliest. Exceptions.com . Applets Mr. 3. Study Materials We provide the most efficient study material for each and every module during the project development 4. He will be having a thorough experience in working on both product and service driven industries.com | Final year IEEE project development and training from scratch by Mr. Registration started. 15. 13. 10. No prerequisites required. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use.com . Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch.www. 5. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed Mr. Ashok Kumar K. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7.COM for your final year project work 1. 15 reasons to choose VTUPROJECTS. we will be helping out them through Skype/ Team viewer screen sharing 12.vtuprojects. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. 6. Skype/ Team viewer support In case the student needs an emergency help when he/she is in their colleges. Contact 9742013378 or 9742024066 and lock your project at the earliest. 2. but an Object refers to a real Dog Syntax A class can be declared through the following syntax: class <class_name> { type1 var1. Object An object is a real instance of a class. a dog has 4 legs. type2 var2.vtuprojects. typen methodN() { } } An object of the class can be created using the following syntax <class_name> obj_name = new <class_name> (<contructor arguments>). ...www. It can be any real world entity we come across in our life.. It's just a template for an object and describes an object’s behavior to the JVM. it barks.com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. A class just describes how a Dog looks like. in this topic we are going to explore the classes and objects concepts which are the basic building blocks of any object oriented programming language. 2. Registration started..1 CLASSES AND OBJECTS Here. typeN varN. type1 method1() { } type2 method2() { } . Ashok Kumar K | 9742024066 | [email protected] Basics Class A class is a blueprint or prototype from which objects are created.com . also a Bank is an Object. it eats etc. 2. Ashok Kumar K. (Say.)... a Human is an Object etc. Example an Animal is an Object. Example Mr. "Arun". Here the object is instantiated with using a new keyword in java. Registration started.out. public void setStudentDetails(int a. Object's members can be accessed using a dot operator as follows stud. Here ‘stud’ is just like a normal local variable (allocated in stack memory) for the defining block. A dynamic memory will be created in the heap memory and the reference for this will be assigned to the local variable created in step 1. Contact 9742013378 or 9742024066 and lock your project at the earliest. Observations  Memory allocation for an object For understanding purpose. name = s. The object will also be initialized by JVM. double score. String s.out. System. You can pass arguments to the constructor within the parenthesis following the Mr. lets break down the object creation statement into two steps: Step 1: Creating a variable of class type that can refer to an object Student stud. Creating a class class Student { int regno.com | Final year IEEE project development and training from scratch by Mr.www.println("Student score : " + score + "%").out.println("Student name : " + name). double d) { regno = a. 45.com . It will be initially pointing to a null object (literally meaning NOTHING). score = d. System. } } Creating an object Student stud = new Student().vtuprojects. It does so by making a call to the object's constructor (discussed later).89).setStudentDetails(24. } public void printStudentDetails() { System. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Step 2: Instantiation and Initialization stud = new Student().println("Student regno : " + regno).printStudentDetails(). Ashok Kumar K. String name. stud. We will see in detail with an example. who destroys them? Remember.com .vtuprojects. class name on RHS of the above statement. Mr. These two steps can be visualized as follows  Instance Variables and Class Variables Variables within the class created without the keyword 'static' prefixed are called instance variables or object variables or non-static variables. Ashok Kumar K | 9742024066 | celestialcluster@gmail. it's JVM. but only one class can be made as public and it should be the main class (main class is the one which contains the main function).  A single .www. a bit later. This type of variables actually shares the value among all the instances of a class.  The name of the . A separate memory space for these types of variables will be created for each instance of a class. Example program for Classes and Objects // Class Definition. Ashok Kumar K. You don't need to worry about object destruction. Contact 9742013378 or 9742024066 and lock your project at the earliest. Variables within the class created with the keyword 'static' prefixed are called class variables or static variables. Then.java file should be the name of the main class.  Class name can be any legal Identifier.  We learnt how to create an object. It will be done through a process called Garbage Collection (discussed later). Registration started.com | Final year IEEE project development and training from scratch by Mr.java file can contain any number of classes within it. System. 45.out.89).2 Constructors Definition: A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object. score = d. If you don't write a constructor.setStudentDetails(24.1. public class Example1 { // Main function public static void main(String[] args) { // Object creation Student s1 = new Student().println("Student score : " + score + "%"). It can be used to initialize the objects to required values at the time of object creation.out. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } } // Main Class.println("Student name : " + name). It is not mandatory for the coder to write a constructor for the class. Ashok Kumar K. } } Output 2. System. Registration started. s1.printStudentDetails(). Data Type Default Value Mr.www. name = s.println("Student regno : " + regno). String s. // Methods public void setStudentDetails(int a. Contact 9742013378 or 9742024066 and lock your project at the earliest. String name. Java provides a default constructor that initializes the object members to its default values. double d) { regno = a. s1.out.com | Final year IEEE project development and training from scratch by Mr.vtuprojects.com . "Arun". double score. class Student { // Instance variable int regno. } public void printStudentDetails() { System. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. Remember. String nm. So. name = nm. it implies the constructors can be overloaded.. // Three argument constructor Student (int rno. Ashok Kumar K. Ashok Kumar K | 9742024066 | celestialcluster@gmail. if you don't provide any constructor.com | Final year IEEE project development and training from scratch by Mr.vtuprojects. Example Student has one constructor: class Student { Student (int rno. } } Observations  Parameterized Constructor You can create more than one constructor for a class each having different signatures from one another. score = sc. Purpose of having the constructor overloaded is to provide more than one ways of initializing an object.www. double score. Registration started. double sc) { regno = rno. Sounds something familiar? Right.com . double sc) { .0f double 0.. the user of the object can initialize an object using any of the constructors provided. Java will provide a default zero argument constructors. byte 0 short 0 int 0 long 0L float 0. Contact 9742013378 or 9742024066 and lock your project at the earliest. Look at the below example..0d char '\u0000' String (or any object) null boolean false A class contains constructors that are invoked to create objects from the class blueprint. String name. class Student { int regno. String nm. Mr. } // Two argument constructor Student (String nm. Student stud1 = new Student(). Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K | 9742024066 | celestialcluster@gmail. he/she can use three argument constructor to create an object initializing it to these values. Registration started. If the user of a class doesn't have any idea about the initial values. sc)..www. and he can assign the values at any time later on.. // Three argument constructor Student (int rno. 89. Ashok Kumar K. Within an instance method or a constructor. class Student { int regno. Mr... double sc) { this(). } // Two argument constructor Student (String nm... double sc) { .. regno.com . double sc) { . 89. String name.com | Final year IEEE project development and training from scratch by Mr.. as follows: Student stud1 = new Student(009. he can simply go ahead and use the default zero argument constructor to create an object.56). "Neel". // Call two argument constructor . but we are very young at this point of time to explore everything.vtuprojects. } // Zero argument constructor Student () { . If the user of a class has only two values (name. } } If the user of a class has all the three values (name. If used. then he/she can use two argument constructor to create an object. Uses of "this" keyword There are many uses of 'this' keyword.56). // call zero argument constructor this(nm.  "this" keyword Java defines the 'this' keyword to be used within any method to refer to the current object.. double score. and score) for a particular student.. as follows: Student stud1 = new Student( "Neel". and score) and the regno should be auto generated by the class itself. String nm.. it must be the first statement in the constructor. You can refer to any member of the current object from within an instance method or a constructor by using 'this'. So let's see few uses of 'this' keyword which can be understood now:  'this' keyword can be used to call a constructor within another constructor of the same class. this is a reference to the current object — the object whose method or constructor is being called.. For now. 'this' keyword is actually a reference for the current object being used. } }  'this' can be used to return an object. This chain of constructor calls starting from an object continuing till Object class' constructor can be referred as Constructor Chaining.score = score. Contact 9742013378 or 9742024066 and lock your project at the earliest. } }  Constructor Chaining Like. So you can think Object class as the default parent (base class) for all the classes in Java. } // Zero argument constructor Student () { . public Student getStudent () { return this. class Student { int regno. } } Mr.. you can think of 'super' keyword as the way to make a call to base class constructor from its derived class. and so on. String name...regno = regno.name = name. this. the 'super' keyword is actually a reference to the parent class of the current object being used.. and the base class' constructor in turn can pass the call to its base class' constructor. Ashok Kumar K | 9742024066 | celestialcluster@gmail. double score) { this. Registration started.com | Final year IEEE project development and training from scratch by Mr.com .vtuprojects. We are going to deal with 'super' keyword in later point of time. If a class does not extend any parent class. and this class' is passing the constructor call to its base class' constructor.. The user of a class is invoking a class' constructor. this.. and 'this' can be used as a parameter for an object. double score. then by default it's going to extend an Object class (present in java. } }  'this' keyword can be used to resolve the name space collision.lang package). String name. // Three argument constructor Student(int regno. Ashok Kumar K. Name space collision is the situation where the member variables of a class and the local variables within a constructor have same names. class Student { .www. class Student { Student() { // pass the constructor call to its base class' constructor super(). vtuprojects. and Survivor 2 space)  Tenured or Old generation. Registration started.www. Ashok Kumar K | 9742024066 | celestialcluster@gmail. before getting collected. open sockets. String pool is created in Perm area of Heap. open database connections etc. Contact 9742013378 or 9742024066 and lock your project at the earliest. garbage collection can occur in perm space but depends upon JVM to JVM. The keyword protected is a specifier that prevents access to finalize() by code defined outside its class.com .  Object is created inside a block and reference goes out scope once control exit that block. 2. 2. When an object becomes eligible for Garbage Collection? An object could be eligible for Garbage Collection in any of these scenarios. Garbage Collection in Java is carried by a daemon thread called Garbage Collector.3 Garbage Collection Remember. Mr. These are  Young generation (further divided into three parts: Eden space. Observations Java Heap is divided into three generation for sake of garbage collection. Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation. Syntax to define a finalize() method is: protected void finalize() { // finalization code here } finalize() method is a special method in Java which is called just before the Garbage Collector reclaims this object.  All references of that object explicitly set to null. You cannot force Garbage collection in Java. when you instantiate an object using 'new' keyword. it will only trigger if JVM thinks it needs a garbage collection based on Java heap size. The intent is for finalize() to release system resources such as open files. Ashok Kumar K. Survivor 1.1.com | Final year IEEE project development and training from scratch by Mr. if an object holds reference of another object and when you set container object's reference null. Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput. Concept and Definition: Garbage collection is a mechanism provided by JVM to reclaim heap space from objects which are eligible for Garbage collection. child or contained object automatically becomes eligible for garbage collection. Garbage collection relieves java programmer from memory management and gives more time to focus on business logic. the memory for this object will be allocated in JVM heap. New objects are created into young generation and subsequently moved to old generation.  Parent object set to null.1. and  Perm area.4 "finalize()" method Concept and Definition Every object in Java can have a finalize() method defined within it. Registration started.sayHello(). // Initiates Garbage Collection } } Output: Mr. finalize() is not like a destructor in C++. you can initiate a Garbage Collection manually by making a call to System."). "). instead it will be called only when JVM performs a Garbage collection which is an undetermined process. the finalize() method is not called here. } } Can you really guess the output of this program? If you are expecting the output to be the execution of both 'sayHello()' and 'finalize()' method.println("Hello world .gc(). } // finalize method protected void finalize() { System. s1. then your understanding on finalize() concept is not perfect yet.com . Replace the main function in above example with the one below: public class Example { // Main funnction public static void main(String[] args) { Student s1 = new Student().. Remember.. As you can see.vtuprojects. Ashok Kumar K. s1.gc() method. There is an alternative to invoke finalize() method. } } public class Example { // Main function public static void main(String[] args) { Student s1 = new Student().println("Inside finalize method . Contact 9742013378 or 9742024066 and lock your project at the earliest.out. System.sayHello(). Ashok Kumar K | 9742024066 | celestialcluster@gmail. Example: class Student { public void sayHello() { System.out. Below is the output of the above program.www.com | Final year IEEE project development and training from scratch by Mr. finalize() method will not be called simply because the object moves out of scope. String n.5 “static” Keyword It is possible to create a member of a class that can be used by itself.com | Final year IEEE project development and training from scratch by Mr. When a member is declared static. let’s create an object 'stud1'. To create such a member. Example: class Student { int regno. String name. static String principalName. and without reference to any object. It tells the compiler that there is exactly one copy of this variable in existence regardless of how many times the class has been instantiated. Memory for static variables will be allocated in Code Segment of JVM memory. It is created by prefixing the keyword 'static' while declaring a variable. } } In the main function. Ashok Kumar K | 9742024066 | celestialcluster@gmail. looks like. Mr. Registration started. The keyword 'static' in Java can be prefixed to any of these:  Variables  Methods  Blocks Static Variables Static variables are also called class variables which actually shares the value among all the instances of a class. name = n. Memory allocation at this point.45). it can be accessed before any objects of its class are created.vtuprojects. double score.principalName = “Hemanth”. 2. double s) { regno = r.www. "Ajay". Contact 9742013378 or 9742024066 and lock your project at the earliest.com . Student stud1 = new Student(7. without reference to a specific instance. Ashok Kumar K. score = s. 76. Student(int r. precede its declaration with the keyword 'static'.1. Student. "Arun". Ashok Kumar K | 9742024066 | celestialcluster@gmail. Student. static methods are same as static variables. if you reassign a value to 'principalName' w. They are bound at class level and not at object level. Let’s create another object 'stud2'.24).t 'stud2'. Registration started. We prefix the main function with static keyword thus allowing JVM to execute this method without instantiating main class.com | Final year IEEE project development and training from scratch by Mr. The most familiar example for static method is our main function. Contact 9742013378 or 9742024066 and lock your project at the earliest.e. Example class Student { int regno. Student stud2 = new Student(9. the static variable 'principalName' is actually shared among 'stud1' and 'stud2'. The memory allocation now looks like. Static Methods Conceptually. 87.www. this change also reflects in 'stud1' as well.r. Ashok Kumar K. double score. Mr. meaning.. You can now realize from the above figure.principalName = “Chandrashekhar”. Static methods can be invoked without creating an instance of its defining class. and let’s change the principal’s name.vtuprojects.com . they are independent of any specific instance of an object. String name. i. . and they can appear anywhere in the class body. and proceeded by the static keyword. Example: class Student { int regno. " + name). A static initialization block is a normal block of code enclosed in braces. s1. Remember. Static Blocks Static blocks are also called Static initialization blocks.  They must only access static data. String name.printStudentDetails().println("Score . { }. System.. } // Non Static method.out. Restriction on static methods also applies to static blocks..out.. Syntax: static { // Logic } A class can have any number of static initialization blocks. this code will be executed when JVM loads the class. // Static method. // Wrong: Compiler throws an error here Student s1 = new Student(). // Right } } Restrictions on static methods  They can only call other static methods.sayHello().www.out. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K | 9742024066 | celestialcluster@gmail. // Right Student. double score.out. System.println("I am the static block in the Student class").  They cannot refer to 'this' or 'super' in any way. } } public class Test { // Main funnction public static void main(String[] args) { Student. !! This requires an object public void printStudentDetails() { System. Mr.vtuprojects.com .println("Reg no . static { System. Ashok Kumar K. JVM combines all these blocks into one single static block and then executes.out. " + regno). "). !! This can be called without creating an object public static void sayHello() { System.printStudentDetails().com | Final year IEEE project development and training from scratch by Mr.println("Name . The JVM guarantees that static initialization blocks are called in the order that they appear in the source code.println("Hello everybody. Registration started... " + score). Good Morning . println("I am the static block in the main class").println("Name . } } Output 2.println("Reg no . System. } } public class Example { // Main funnction public static void main(String[] args) { System. } ..out. " + score). Mr.. Good Morning . } public void printStudentDetails() { System.www. Student stud = new Student().println("Hello everybody.6 Inner Classes and Nested Classes Java allows you to define a class within another class.1. } static { System.com | Final year IEEE project development and training from scratch by Mr. Registration started.out.. Ashok Kumar K. } Nested classes are divided into two categories: static and non-static. Contact 9742013378 or 9742024066 and lock your project at the earliest.println("Score . Non-static nested classes are called inner classes..out..com .out. ").vtuprojects.out. } static { sayHello(). " + regno)..... Such a class is called a nested class as shown below: class OuterClass { class NestedClass { .out. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } public static void sayHello() { System. " + name). System.. Nested classes that are declared static are simply called static nested classes.println("I am the main function"). } A nested class is a member of its enclosing class. "). } class InnerClass { . even if they are declared private. Contact 9742013378 or 9742024066 and lock your project at the earliest. } public void sayGoodMorning() { System. } } Mr.com | Final year IEEE project development and training from scratch by Mr.. Non-static nested classes (inner classes) have access to other members of the enclosing class.......vtuprojects. Static nested classes do not have access to other members of the enclosing class.out. // RIGHT sayGoodMorning(). class OuterClass { static class StaticNestedClass { . Registration started. Ashok Kumar K. // RIGHT } } static class StaticNestedClass { public void makeCall() { sayHello(). Advantages of Nested Classes  It increases encapsulation  It constitutes to more readable and maintainable code Example: class OuterClass { class InnerClass { public void makeCall() { sayHello().www..com . // WORNG: static nested class can't access non static member } } public static void sayHello() { System...println("Hello World .out.println("Good Morning .. Ashok Kumar K | 9742024066 | celestialcluster@gmail. "). // RIGHT sayGoodMorning(). } . The class from which the subclass is derived is called a superclass (also a base class or a parent class). Classes can be derived from classes that are derived from classes that are derived from classes.2 INHERITANCE Here. extended class. 2. and so on. Verna. Below figure helps us to visualize the concept of Inheritance.out.www.Object. Ashok Kumar K. iTwenty.println("SLEEPING FOR 8 HOURS").lang. } public void sleep() { System. Getz etc.lang. Contact 9742013378 or 9742024066 and lock your project at the earliest.Object.lang. A class that is derived from another class is called a subclass (also a derived class.Object.lang. Excepting java. and combining them into a generalized super class.println("EATING THRICE A DAY"). Registration started. a process by which a child class acquires the properties (state and behavior) of its parent class is referred to as Inheritance. every class in Java has one and only one direct superclass.vtuprojects. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } Mr.out.com | Final year IEEE project development and training from scratch by Mr. Inheritance can also be referred to the concept of Generalization.Object. every class is implicitly a subclass of java. which has no superclass.com . and ultimately derived from the topmost class. class DerivedClass extends BaseClass { } Example class Animal { public void eat() { System. Hyundai is a parent class whose properties are inherited by the classes named iTen. 2. or child class). For example. Syntax Inheritance in Java can be done by using 'extends' keyword likewise in the following syntax. which is the process of extracting common characteristics (states and behavior) from two or more classes. In the absence of any explicit superclass. Such a class is said to be descended from all the classes in the inheritance chain stretching back to java.1 Basics Definition and Concept Generally.2. java. we are going to explore one of the most important characteristics of any object oriented programming language – Inheritance. so they are not inherited by subclasses. However.out. you can avoid this duplication of code by creating a general class that contains the duplicated code and having those classes extending this general class.www. } } Inheritance provides code reuse Idea behind inheritance is. animal. // RIGHT. Observations  A subclass inherits all the public and protected members (fields. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } class Dog extends Animal { public void bark() { System. } } class Cat extends Animal { public void meow() { System. From the above example you can see that eat() and sleep() are the codes that are common to both Dog and a Cat. Example: Mr. Ashok Kumar K.com . because all Dogs are Animals animal. these can also be used by the subclass. Thus.println("Meow Meow"). you are writing it only once in the general class. Constructors are not members. public class Example { public static void main(String[] args) { Animal animal = new Dog(). because all Animals are not Dogs } }  Using super  super can be used here to make a call to superclass constructor from the derived class constructor. when you have the same piece of code repeated in more than one class. Thus no need to write the duplicated code in all the subclasses.sleep(). and nested classes) from its superclass.  Superclass variable can reference a subclass object. if the superclass has public or protected methods for accessing its private fields.  A subclass does not inherit the private members of its parent class. methods. Registration started. but not vice-versa. Contact 9742013378 or 9742024066 and lock your project at the earliest. The duplication of the code is avoided by defining a general class Animal and having the eat() and sleep() method within it.vtuprojects. // WRONG. Dog dog = new Animal(). Cat and Dog just extends the Animal class.com | Final year IEEE project development and training from scratch by Mr.out.println("Bow Bow"). we can conclude that Inheritance provides Code Reusability.eat(). but the constructor of the superclass can be invoked from the subclass. out.out.com . String type_of_animmal. Registration started.bark(). } public void sleep() { System. } Mr. } }  super can also be used to refer to superclass member when there is a name collision between superclass member and a derived class member. String type_of_animal.name_of_dog = name_of_dog.num_of_legs = num_of_legs. Contact 9742013378 or 9742024066 and lock your project at the earliest. this. String type_of_animmal) { this. } } public class Test { // Main funnction public static void main(String[] args) { Dog dog = new Dog(4.out. dog.sleep(). Animal (int num_of_legs.println("Meow Meow"). "Jimmy").com | Final year IEEE project development and training from scratch by Mr. } public void eat() { System.type_of_animmal ). dog. Ashok Kumar K. // Invokes superclass constructor this.vtuprojects. } public void bark() { System. String name_of_dog) { super(num_of_legs. Example: class A { int i. Dog (int num_of_legs.type_of_animmal ). "Cornivorous".name_of_cat = name_of_cat. Ashok Kumar K | 9742024066 | celestialcluster@gmail. String name_of_cat) { super(num_of_legs.www.println("EATING THRICE A DAY").type_of_animal = type_of_animmal. dog. } public void meow() { System. class Animal { int num_of_legs.eat(). } } class Cat extends Animal { String name_of_cat. // Invokes superclass constructor this. String type_of_animmal.out. } } class Dog extends Animal { String name_of_dog.println("SLEEPING FOR 8 HOURS").println("Bow Bow"). Cat (int num_of_legs. // Refers to derived class member super.out.println("D's Constructor").println("A's Constructor").www. Registration started. class A { A() { System.vtuprojects.out.lang. where Object is the topmost superclass and class D is at the leaf level. // Refers to superclass member } }  Multilevel Inheritance As discussed before.out. B (int a. class B extends A { int i. Figure on the right gives an example for multilevel inheritance. int b) { this. Java does allows a class to extend another class which further extends another class and so on.i = a.Object. The point of interest here is the order of execution of constructors when we create an object of the class at the leaf level. } } Output Mr. eventually the top most class will be java. } } public class Test { // Main funnction public static void main(String[] args) { D d1 = new D().i = b. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } } class C extends B { C() { System.println("C's Constructor").com | Final year IEEE project development and training from scratch by Mr. } } class B extends A { B() { System. Ashok Kumar K.com .println("B's Constructor"). } } class D extends C { D() { System. This type of inheritance is called as Multilevel Inheritance (more than one level of inheritance).out. Ashok Kumar K | 9742024066 | celestialcluster@gmail. How multiple inheritance is achieved in Java? Java supports a limited form a multiple inheritance by allowing a class to inherit from one other class and an unlimited number of interfaces. Meaning.vtuprojects.com .t its object. the D's class constructor will be invoked which passes the call to its super class constructor C() which further passes to B().com | Final year IEEE project development and training from scratch by Mr. Multiple inheritance is NOT allowed in Java.  Multiple inheritance will be rarely used. Here. Ashok Kumar K.  Multiple Inheritance in Java No. For example. a class can extend only one class but it can implement unlimited number of interfaces. will be the first statement in every class' constructor: when you create an Object of class D.r.www. We can think of two reasons why Java doesn't allows multiple inheritance  To avoid ambiguity error Ambiguity error arises when Horse and Bird both defines a function with the same name and Pegasus runs into a situation of dilemma upon invoking that function w. the order of execution of constructors is in the same order as the derivation. This kind of inheritance given rise to many problems in C++ which can be thought of as a reason for Java discouraging it. Pegasus inherits from both horse and a flying bird. Contact 9742013378 or 9742024066 and lock your project at the earliest. Multilevel inheritance is when a class inherits from more than one superclass. Registration started. from superclass to subclass. This is because super(). and eventually it passes on the call to Object() where the initialization of the memory takes place to this program after which the constructor A() will be executed continuing till D() in the order of derivation. We can conclude from the output that. Example: Mr. println("Accelerating . Registration started. } public void accelerate() { System. Class A is a base class which has been inherited by class A along with implementing the other three interfaces namely P.www. } } interface Trainer { void moveRight(). void accelerate(). and nested types.com .println("Starting Car . Programming Example: Suppose if you are a newly joined student in car driving school.println("Moving Left . } void killEngine() { System. "). "). ").out. } } public class Example { public static void main(String [] args) { Trainer trainer = new Hyundai(). method signatures.. void moveLeft().. The question here is how to implement the access restriction to the student on the car object? Interface comes as a solution for this. // RIGHT Mr. trainer. } interface Student { void moveLeft().println("Applying brake . "). void moveRight(). Q.out. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces class Car { void start() { System.println("Moving Right ..out. There are no method bodies.moveLeft(). Ashok Kumar K | 9742024066 | celestialcluster@gmail. "). so that you can only use that feature of an object which is defined in the interface. Student { public void moveRight() { System. and R. Idea behind interface is. void brake(). use it through an interface.. } public void brake() { System. similar to a class that can contain only constants.vtuprojects. Ashok Kumar K. assume you are allowed only to use the steering wheel of the car on day 1 while only the trainer will be having access to brake and the accelerator. rather than using the object directly. } public void moveLeft() { System..println("Engine Killled . } class Hyundai extends Car implements Trainer.com | Final year IEEE project development and training from scratch by Mr. Definition: An interface is a reference type.out. ").out. Contact 9742013378 or 9742024066 and lock your project at the earliest.out.. Meaning. This way the user of the object invokes only one function move(). // ERROR: student have no access to accelerate() student.2. // RIGHT Student student = new Hyundai(). student.com | Final year IEEE project development and training from scratch by Mr. trainer. Method Overloading Concept: Consider a Chess application. int b) { System.brake(). This is what we call method overloading.out. The arguments list within the parenthesis should be differing either by type of parameters or the number of parameters. // RIGHT student. // ERROR: student have no access to brake() } } 2. "+(a+b)). the return type of the functions will not come into picture here. // RIGHT trainer. you can't call them as overloaded functions because return type alone can't decide it.accelerate().vtuprojects. move().moveRight(). we will pass 'King' object to call move() on king. and will observe different results depending on type of input. } Mr.moveLeft(). the polymorphism refers to the process in which a member function of a class behaves differently for different inputs At this point of time. Only thing that differs is the argument list within the parenthesis..com . you can think of two different ways in which Java provides the Polymorphism feature.brake(). here we will have to implement the move() operation for all the pawns. and so on. Definition: When you have more than one method with the same name but different arguments. Contact 9742013378 or 9742024066 and lock your project at the earliest. Example: class A { public void sum (int a. Registration started. We will pass 'Queen' object to call move() on queen.www. // RIGHT trainer. Are we going to select 9 different names for move() function of different pawns? How confusing it is.moveRight(). // RIGHT student. if two functions have same function name and argument list but with different return types. Ashok Kumar K | 9742024066 | [email protected](). we will define a different move() functions for different pawns but the name of all these functions will be the same. To make it so simple and achieve polymorphism. the methods are said to be overloaded. Ashok Kumar K.println("Sum of "+a+" and "+b+" is .2 Overloading and Overriding The word "Polymorphism" refers to the ability to take more than one form. In terms of programming. Please note. vtuprojects. float b) and void sum (float a.com | Final year IEEE project development and training from scratch by Mr. "+a+b). a1. Ashok Kumar K. Registration started. Ashok Kumar K | 9742024066 | celestialcluster@gmail. for instance sleep() method which makes the Animal to sleep for 8 hours. plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method. Note that an overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.. int b) Method Overriding Concept: Consider our very first example on Inheritance. a1.println("Concatenation of "+a+" and "+b+" is .www. String b) { System.  These are not overloaded functions. Dog and Cat extends Animal. How will you implement this change in sleep() function which should reflect only in Dog class alone? Overriding is a solution for this. "JMASTER"). Overriding is nothing but simply redefining the sleep() function again the subclass (Dog class) so that the new definition hides the previous definition for sleep() function in parent class (Animal class). 9). } } public class Test { public static void main(String [] args) { A a1 = new A (). Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest.out. Assume a situation where all the animals in our application sleep for 8 hours but only the Dog sleeps for 4 hours.sum(7.sum("AKLC ". Definition: An instance method in a subclass with the same signature (name.com . public void sum(String a. instead they lead to ambiguity errors void sum(int a) and int sum(int a) void sum(int a. } } Output More on Overloading:  Method overloading is called Static polymorphism because the call to the overloaded functions will be resolved at compile time. Here we can see the Animal class defines the common (general) characteristics of all its subclasses. } } Output More on Overriding:  Method overriding is called Dynamic polymorphism because a call to overridden functions is resolved at runtime.println("DOG SLEEPING FOR 4 HOURS").println("SLEEPING FOR 8 HOURS"). dog.println("Bow Bow"). Mr. } // Overridden method public void sleep() { System.println("EATING THRICE A DAY"). Ashok Kumar K. } } class Cat extends Animal { public void meow() { System.sleep().sleep(). Contact 9742013378 or 9742024066 and lock your project at the earliest. Registration started.  Method overriding occurs only when the names and the type signatures of the two methods are identical.vtuprojects. Cat cat = new Cat().com | Final year IEEE project development and training from scratch by Mr.www.out. Example: class Animal { public void eat() { System. } } class Dog extends Animal { // Overriding method public void sleep() { System. cat. } public void bark() { System. then the two methods are simply overloaded.println("Meow Meow"). } } public class Test { public static void main(String [] args) { Dog dog = new Dog().out.out. Ashok Kumar K | 9742024066 | [email protected]. If they are not.out.com . // calls Dog's sleep() animal3.com . } } public class Example { public static void main(String [] args) { Animal animal1 = new Animal(). The simple question I am going to answer in this topic is what if we call an overridden method on this object? Example: class Animal { public void eat() { System.vtuprojects.out.println("DOG SLEEPING FOR 2 HOURS"). Animal animal2 = new Dog().println("EATING THRICE A DAY"). Ashok Kumar K.www. Animal animal3 = new DomesticDog().sleep().sleep().sleep(). We know that a base class reference can be given to a derived class object.out. // calls Animal's sleep() animal2. } // Overridden method public void sleep() { System. Dynamic Method Dispatch Concept: Here we will focus on method overriding in bit detail. } public void bark() { System.out. Contact 9742013378 or 9742024066 and lock your project at the earliest. } } class WildDog extends Dog { public void sleep() { System. animal1.println("SLEEPING FOR 8 HOURS").out. Registration started. // calls DomesticDog's sleep() } } Mr.com | Final year IEEE project development and training from scratch by Mr.out. } } class Dog extends Animal { // Overriding method public void sleep() { System.println("DOG SLEEPING FOR 4 HOURS").out.println("Bow Bow").println("DOG SLEEPING FOR 6 HOURS"). Ashok Kumar K | 9742024066 | celestialcluster@gmail. } } class DomesticDog extends Dog { public void sleep() { System. 2. If final variable is used Mr. Note: If you want to invoke an overridden method (base class method) from the overriding method (derived class method).sleep().  Variables can be made final  Methods can be made final  Class can be made final 'final' variables Concept and Definition A final variable can be only once assigned a value. the JVM can make this decision only at runtime since the object will not be available at the compile time.www. it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed. class DomesticDog extends Dog { public void sleep() { super. Contact 9742013378 or 9742024066 and lock your project at the earliest. you should use 'super' keyword as illustrated in below example.vtuprojects. Following couple of topics deals with them. Since this decision should be made base on the type of the object. if a superclass contains a method that is overridden by a subclass.com | Final year IEEE project development and training from scratch by Mr. different versions of the method are executed. Therefore. then when different types of objects are referred to through superclass reference variable. It is completely dependent on your implementation.println("DOG SLEEPING FOR 6 HOURS"). How will you enforce a restriction that a particular method in base class should never be overridden in the derived class? 2. // calls Dog' sleep() System. } } Remember. Definition: Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time.com . 1. Ashok Kumar K. Registration started. it’s not mandatory that your class should override the base class method. How will you enforce a restriction that a particular method in base class should mandatorily be overridden in the derived class? Yes. This value cannot be changed latter. Ashok Kumar K | 9742024066 | celestialcluster@gmail. rather than compile time. 2.out. Java provides a feature to enforce such restrictions.3 "final" Keyword in Java You can use final keyword in java for three different uses. Output We can conclude from the above program. Two questions for you at this point of time. println("EATING TWICE A DAY"). // ERROR: Can't modify the final variable tails = tails + 1. A () { tails = 1. Attempting to change the value of final variable/field will generate error.com | Final year IEEE project development and training from scratch by Mr. // ERROR: Can't modify the final variable } } 'final' methods: To prevent Overriding Concept and Definition If you want to enforce a restriction like. A final method cannot be overridden by sub class.out.println("SLEEPING FOR 4 HOURS"). Contact 9742013378 or 9742024066 and lock your project at the earliest. // RIGHT: final variables can be assigned a value here final int tails. } // RIGHT public void sleep() { System.vtuprojects. Registration started. } } 'final' classes: To prevent Inheritance Concept and Definition Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail. final int legs = 4.com . Example class Animal { int age = 8.www. Syntax: final <datatype> <var_name>.out. simply prefix that method definition with the 'final' keyword. Ashok Kumar K. in a class then it must assigned a value in a class constructor.out. a particular method in the base class should never be overridden in the derived class. } } class Dog extends Animal { // WRONG: Cannot override a final method public void eat() { System.println("EATING THRICE A DAY"). // RIGHT: final variable can be assigned a value in constructor } void increment() { age = age + 10.out. } public void sleep() { System. legs = legs + 1. Example: class Animal { // This is a final method final public void eat() { System.println("SLEEPING FOR 8 HOURS"). www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. Unless a class definition has been prefixed with 'final', any other class can override it. There is no restriction on that. Java provides a feature where you can restrict a class from being inherited. This can be done by prefixing a class definition with 'final' keyword. A class declared final cannot be sub classed. Other classes cannot extend final class. It provides some benefit to security and thread safety. Example class Animal { } // RIGHT final class Dog extends Animal { } // WRONG: Cannot subclass the final class Dog class DomesticDog extends Dog { } 2.2.4 Abstract classes in Java Concept There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. To put it differently, you may encounter some situations where you need to enforce a restriction that some functions in the base class has to mandatorily overridden by the derived class. If you want to enforce this restriction on any method in base class, simply prefix its declaration with 'abstract' keyword. Remember, you should not give the definition for abstract functions in the base class because mandatorily it will be defined in derived classes. If a class contains one or more abstract methods, it's like a class containing one or more methods without any definition (just the declaration), so it's obvious that the class is not complete until any other class inherits it and gives the definition for these methods. The conclusion is you cannot create a direct objects of the abstract class, all you can do is having its reference to the object of the derived class. Definitions Abstract method An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon) like this: abstract void fun(int a); Abstract class An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. If a class includes abstract methods, the class itself must be declared abstract, as in: class A { abstract void fun(int a); } Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract Example: // abstract class abstract class Animal { void sleep() { System.out.println("Sleeping for 8 hours"); } abstract void sound(); // abstract function } class Dog extends Animal { public void sound() { System.out.println("BOW BOW"); } } class Cat extends Animal { public void sound() { System.out.println("MEOW MEOW"); } } public class Example { public static void main(String [] args) { Animal animal1 = new Animal(); // WRONG: Abstract class cannot be initiated Animal animal2 = new Dog(); // RIGHT Animal animal3 = new Cat(); // RIGHT } } Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. 2.3 EXCEPTIONS 2.3.1 Basics Concept There's always a tendency for erroneous situations to occur either within a program or beyond it. For example consider a program which tries to divide a number 10 by an input number entered by the user. What if the number entered by the user is 0 (zero)? The program attempts to divide 10 by 0 (zero) which causes the application to crash. Another example for erroneous situation is when you try to create an object and there isn't enough space in the JVM heap to allocate the memory for it. These kind of erroneous situations are called Exceptions. Java provides a wonderful exception handling mechanism to avoid an application crash. Definition Generally, Exceptions are such anomalous conditions which change the normal flow of execution of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. In Java, Exception is an object that describes an exceptional condition that has occurred in a piece of code. Java's default exception handling mechanism Let's see with the help of below example, what happens in Java if something goes wrong in the runtime. public class Test { public static void main(String[] args) { int a = 10; int b = 0; System.out.println("Before Division"); double res = a/b; System.out.println("After Division"); } } When an exception occurs within a method, the method creates (throws) an object to describe the exception. This object is called as Exception Object, which contains the complete information about what went wrong here, ex: type of exception, state of program, line number in the source where this exception occurred and so on. After a method throws an object, it will be caught by the block of code written to handle it. If you have not handled an exception in your program, the exception object will be caught by the runtime system and it handles it in its own way. i.e., default exception handling will come into picture which only does two things  Print the error message in the console  Terminate the program You can realize this in the following output to the program shown above Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. You can see a short description of what went wrong and then the program has been terminated. The S.O.P statement written after the division has not been executed. The description of the error printed in the console is called the stack trace of the exception which prints the method call hierarchy. You can see the method call stack for the modified version of above program. You should clearly observe the type of object that's been created is ArithmeticException. It is one of the inbuilt classes in Java used to represent an exception caused during arithmetic operations. There are various other types of classes in Java to represent different scenarios where an exception occurs. public class Test { public static void main(String[] args) { System.out.println("Before Division"); fun1(); System.out.println("After Division"); } public static void fun1() { fun2(); } public static void fun2 () { fun3(); } public static void fun3 () { fun4(); } public static void fun4() { int a = 10; int b = 0; double res = a/b; } } Output 2.3.2 Different Type of Exceptions Generally, Exceptions can be broadly classified into Checked Exceptions and Unchecked Exceptions  Checked Exceptions are also called as Compile time Exceptions which are checked by compiler to make sure the programmer has written the handler for these. If not, it will throw a compile time error. Mr. Ashok Kumar K | 9742024066 | [email protected] JVM will throw an object of the corresponding class which well describes the exception scenario. Ashok Kumar K. Example: ArithmeticException  Error class: Error class will be created and thrown when a serious problem occurs beyond the application scope which can't be controlled within an application. compiler is not able to check them for the handlers. Example: OutOfMemoryError will be thrown when JVM is running short of memory. It has two children. Exception and Error classes. Hence. whenever an exception occurs.lang.vtuprojects. Throwable. Ashok Kumar K | 9742024066 | celestialcluster@gmail.  Exception class: Object of its subclasses are created and thrown whenever unusual condition occur which can be caught and handled it programmatically.  Unchecked Exceptions are also called as Runtime Exceptions which are not known to the compiler at compile time. is the root of entire exception family. Below figure shows the exception class hierarchy. Checked Exception classes directly inherit the Exception class while Unchecked Exception inherits from a subclass of Exception called RuntimeException. Hence. You can see. For exception in Java. Arithmetic exception which we saw in previous topic is one among them.com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. Exception classes There may be various scenarios where an exception might occur. declared in java.www. there is a built in class used to represent the scenario. It can be either checked exceptions or unchecked exceptions. Throwable is the root of all the exceptions.com . Below table shows the complete list of all Checked Exception classes in Java Exception class Meaning ClassNotFoundException Class not found. Mr. Registration started. IllegalMonitorStateException Illegal monitor operation. NoSuchFieldException A requested field does not exist. Technically. NoSuchMethodException A requested method does not exist.com | Final year IEEE project development and training from scratch by Mr. UnsupportedOperationException An unsupported operation was encountered. TypeNotPresentException Type not found. NumberFormatException Invalid conversion of a string to a numeric format. IllegalAccessException Access to a class is denied.com . the corresponding exception class is created and thrown.3 Java's Exception handling in brief Java provides five keywords for exception handling. such as divide-by-zero. Below table shows the complete list of all Unchecked Exception classes in Java Exception class Meaning ArithmeticException Arithmetic error. NegativeArraySizeException Array created with a negative size. NullPointerException Invalid use of a null reference. EnumConstantNotPresentException An attempt is made to use an undefined enumeration value. throw A programmer can use throw keyword to manually throw an exception.www. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. try Program statements that you need to monitor for exception will be placed inside try block. Contact 9742013378 or 9742024066 and lock your project at the earliest. such as waiting on an unlocked thread. InterruptedException One thread has been interrupted by another thread. ClassCastException Invalid cast. catch A try block should be mandatorily followed by a catch block which will be executed if the exception object is thrown from the try block. IllegalStateException Environment or application is in incorrect state. IllegalThreadStateException Requested operation not compatible with current thread state. Registration started. They are dealt in detail in later topics. 2. ArrayStoreException Assignment to an array element of an incompatible type. we say that catch block catches the exception thrown by a try block. InstantiationException Attempt to create an object of an abstract class or interface. Here we will see them in brief. IllegalArgumentException Illegal argument used to invoke a method. IndexOutOfBoundsException Some type of index is out-of-bounds. Ashok Kumar K | 9742024066 | [email protected]. If any exception occurs within a try block. Ashok Kumar K. ArrayIndexOutOfBoundsException Array index is out-of-bounds.vtuprojects. throws Mr. SecurityException Attempt to violate security StringIndexOutOfBounds Attempt to index outside the bounds of a string. A catch block is mandatory for every try block.println("Exception occured").out.out. you can place such piece of code inside a finally block. Ashok Kumar K.www. Remember.println("Bye").out.3. int b = 2.out.out. } System.com | Final year IEEE project development and training from scratch by Mr.println("Bye").println("Before Division"). } Mr.vtuprojects. System.out. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Contact 9742013378 or 9742024066 and lock your project at the earliest.com . System. a single try block can have more than one catch block. All the checked exceptions thrown out of a particular method will be specified as such using the throws clause in the function signature. int res = a/b. 2.println("After Division"). Syntax try { // Piece of code which you are monitoring for exception } catch (Exception_Class ex) { // This block will be executed if an exception occurs in above try block } Example public class Example { public static void main(String[] args) { Output try { int a = 10. } catch (ArithmeticException e) { System.out. finally If you want some piece of code to be executed without depending on whether a exception occurs or not. int res = a/b. System. Exceptions thrown from the try block will be caught by the corresponding catch block. } } public class Example { public static void main(String[] args) { Output try { int a = 10. } catch (ArithmeticException e) { System. int b = 0.4 Using try and catch Concept Use try block to enclose the piece of code which you need to monitor for exceptions.println("Exception occured"). Registration started.out. } System.println("After Division"). System.println("Before Division"). println(e. Registration started.println("Exception occured"). catch (ArithmeticException e) { System. int b = 0.www. e.out.printStackTrace() as follows. In the first example there is no exception being thrown from the try block. System.getMessage()).getMessage() as follows.out. you are still able to catch it using a generic catch clause as follows. hence the catch block will simple be skipped.println("Exception occured"). Observations Displaying the description of the exception Exception description can be printed in the catch block using e. try { int a = 10. Mr.printStackTrace().out.com . catch (ArithmeticException e) { System. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Ashok Kumar K. } You can observe the above examples. which catches any type of exception thrown.vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest. int res = a/b. } Output Displaying the method call stack (stack trace) of the exception Call stack can be printed using e.com | Final year IEEE project development and training from scratch by Mr. In the second example there is an ArithmeticException thrown from the try block which is caught by the catch block which is capable of catching ArtithmeticException. } Output Catching Generic Exception If you are not sure about what kind of exception is thrown from a try block. one corresponding to each type of exception object thrown.println("Exception occured"). it is important to remember that exception subclasses must come before any of their super classes. Thus. Ashok Kumar K.6}. in the scenario where more than one type of exception will be thrown from a single try block.4. This is called unreachable code error in Java. below try block is capable of throwing ArithmeticException and ArrayIndexOutOfBoundsException. Contact 9742013378 or 9742024066 and lock your project at the earliest. Example Mr. Registration started.printStackTrace().printStackTrace().out. Example.out. } catch (ArrayIndexOutOfBoundsException e) { System.out.printStackTrace(). } Output Multiple catch clauses As mentioned earlier.println("Exception occured").out. a subclass would never be reached if it came after its superclass.println("Exception occured"). System. Hence I have written two catch blocks one for each of these exception. try { int arr[] = {2.com . } Output Unreachable code error When you use multiple catch statements. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses.println("No Exception").www. e.5. int b = 0. Ashok Kumar K | 9742024066 | celestialcluster@gmail. you can have more than one catch blocks. } catch (Exception e) { System. } catch (ArithmeticException e) { System. arr[10] = 90.out. e. e. int a = 10.vtuprojects. System. int res = a/b.println("No Exception").com | Final year IEEE project development and training from scratch by Mr. try { int arr[] = {2.5.println("Exception occured"). It is already handled by the System. 5. System. int a = 10. } catch (ArrayIndexOutOfBoundsException e) { System. Ashok Kumar K | 9742024066 | celestialcluster@gmail. int res = a / b.6}.out. Ashok Kumar K. arr[10] = 90.println("No Exception").com .out. Unreachable catch block for ArrayIndexOutOfBoundsExceptio } catch (Exception e) { n. then the Java run-time system will handle the exception. try { int a = 10.out. the stack is unwound and the next outer try statement’s catch handlers are inspected for a match.out.println(s.printStackTrace().println("No Exception"). 4. or until the entire nested try statements are exhausted. } catch (ArrayIndexOutOfBoundsException e) { System. catch block for Exception e. Contact 9742013378 or 9742024066 and lock your project at the earliest. e. int b = 0. int a = 10.5.println("Exception occured"). e. } try { int arr[] = {2.out.println("Exception occured").length()). int b = 0. int res = a/b.printStackTrace(). arr[2] = 90. arr[10] = 90.vtuprojects. } catch (Exception e) { System.6}. This continues until one of the catch statements succeeds. Example try { int arr[] = { 2. Each time a try statement is entered. Registration started. If an inner try statement does not have a catch handler for a particular exception.www.println("Exception occured"). 6 }. This kind of try blocks is called Nested try blocks. the context of that exception is pushed on the stack. } catch (ArithmeticException e) { Mr. System.com | Final year IEEE project development and training from scratch by Mr.printStackTrace(). int res = a/b.4.printStackTrace().out.4. int b = 20. System. String s = null. } Nested try catch blocks You can write a try block within another try block. If no catch statement matches. e.out. out. e. Mr. } System. e. only those objects which are subclasses of Throwable can be thrown. System. and finally throw keyword Concept Regardless of who throws an exception (JVM or a programmer) it's always thrown with the throw statement.vtuprojects.println("No Exception").out.www.println("Exception occured").printStackTrace(). Example try { ArithmeticException e = new ArithmeticException("This is thrown by me"). Remember.5 throw.println("Exception occured").com | Final year IEEE project development and training from scratch by Mr. Example public class Example { public static void main(String[] args) { try { Example ex = new Example(). Registration started.com .out.printStackTrace().println("Exception occured").out. Ashok Kumar K. } catch (ArrayIndexOutOfBoundsException e) { System.printStackTrace(). } catch (NullPointerException e) { System. e.3. throw e. It's also possible for you to throw an exception manually using throw statement. } catch (Exception e) { e. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } 2. } Output Observations  Not all the objects can be thrown. So far you have only been catching an exception thrown by Java runtime system.printStackTrace(). throws. Contact 9742013378 or 9742024066 and lock your project at the earliest. else it will give a compilation error.printStackTrace(). Mr.out.vtuprojects. Registration started. } } }  throw keyword will be mainly used for two purposes:  Re-throwing an exception object from the catch block  Throwing a custom exception (dealt later) Example for re-throwing an exception public class Example { public static void main(String[] args) { try { fun(). In this case. int res = a/b. Ashok Kumar K | 9742024066 | celestialcluster@gmail. the method which throws an exception should indicate to the compiler that the exception handling is not done within it but it's done in the caller of that method. throw e.println("Exception caught in sub function"). } } private static void fun() { try { int a = 10. } } } output throws keyword Concept Exception thrown by a method can be handled either within the same method or in the caller of that method. // ERROR: can't throw this object.println("Exception caught in main function"). } catch (ArithmeticException e) { System. } catch (Exception e) { e. throw ex.com . } catch (ArithmeticException e) { System.www. Contact 9742013378 or 9742024066 and lock your project at the earliest. We generally prefer the later one since caller of the method will be given full freedom to handle the exception in its own way.com | Final year IEEE project development and training from scratch by Mr.out. int b = 0. Ashok Kumar K. Therefore.www.com .txt' in the class path PrintWriter out = new PrintWriter(new FileWriter("sample. A method can indicate to the compiler that the exception handling is done in the caller of the method using throws clause in the method declaration. out. releasing the external resources (like SQL connection. System.out. hard disk files etc). Ashok Kumar K | 9742024066 | celestialcluster@gmail. } } private static void fun() throws IOException { // This tries to open a file 'sample. } } Observations  Since compiler is aware of only checked exceptions. Example public class Example { public static void main(String[] args) { try { fun().vtuprojects. } finally { System. } catch (Exception e) { System.printStackTrace(). int res = a/b.out.out. even when no exceptions are anticipated. Example public class Test { Output public static void main(String[] args) { try { int a = 10. Putting cleanup code in a finally block is always a good practice. However. Registration started. } } } public class Test { Output Mr.txt")).close(). int b = 0.println("No Exception occured").com | Final year IEEE project development and training from scratch by Mr. } catch (IOException e) { e. it will give a compilation error only for unhandled checked exceptions.println("Executing finally block"). Cleanup code meaning. This ensures that the finally block is executed regardless of exception occurs or not.println("Exception occured"). Contact 9742013378 or 9742024066 and lock your project at the earliest. there is no restriction like you should not specify unchecked exceptions in the throws clause finally keyword Concept The finally block always executes when the try block exits. Ashok Kumar K. only checked exceptions should be specified in the throws clause mandatorily. 6 Custom Exceptions Concept Java provides a wonderful feature where you can create your own exception class. Example. System. } catch (Exception e) { System. int b = 10. balance = openingBalance. Syntax: All you want to do is create a new class to represent the custom exception and extend it either directly the Throwable class or the Exception class or the RuntimeException class Example: class LowBalanceException extends Exception { double amt. Java doesn't have any built in exception class that describes this scenario. Ashok Kumar K | 9742024066 | [email protected]. Ashok Kumar K. int res = a/b. in a banking application. You need to define one. static final double minBalance = 5000. Account(long accnum.3.out. This is definitely required in your application where you wish to handle certain abnormal situation in your own way.com .accnum = accnum. Contact 9742013378 or 9742024066 and lock your project at the earliest. } } } 2.vtuprojects. } public String toString() { return "HOLD ON! LOW ON BALANCE ! YOU CAN ONLY WITHDRAW "+amt+ " AT THIS TIME".println("Exception occured"). public LowBalanceException(double amt) { this.println("No Exception occured"). Registration started. when a person tries to withdraw the amount even though he have lesser than the minimum balance.out.out. } Mr.amt = amt. } } class Account { long accnum.println("Executing finally block"). double balance = 0. int openingBalance) { this. } finally { System.com | Final year IEEE project development and training from scratch by Mr. public static void main(String[] args) { try { int a = 10. out.out.getBalance()).println("DEPOSITING 5000/-").println("WITHDRAWING 12000/-").www. acc.toString() } } } Output You can observe the above program.getBalance()).withdraw(3000).vtuprojects. Ashok Kumar K. System. // Calls e.println("OPENING BALANCE : " + acc.out. } catch (LowBalanceException e) { System.out. acc.println("WITHDRAWING 3000/-"). System. void deposit(double amt) { balance = balance + amt.println("NEW BALANCE: " + acc. class LowBalanceException extends Exception class thus it is a custom exception defined by us and it has overridden toString() method in Throwable class to print the appropriate exception message. Contact 9742013378 or 9742024066 and lock your project at the earliest.println("NEW BALANCE: " + acc.amt) < minBalance) { LowBalanceException e = new LowBalanceException (balance - minBalance). } void withdraw(double amt) throws LowBalanceException { if ((balance . 9000).out. System.getBalance()). System.out.out. acc. Mr.amt. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started. System.com . throw e. } } public class Example { public static void main(String[] args) { try { Account acc = new Account(1234.deposit(5000). } } double getBalance() { return balance. System.com | Final year IEEE project development and training from scratch by Mr. } else { balance = balance .println(e).withdraw(12000). } void deposit(double amt) { balance = balance + amt. Ashok Kumar K. balance = openingBalance.www. } else { balance = balance . thus recording the exact cause for an exception. Throwable(String. Throwable) This Constructor associates an exception with another exception that actually caused this exception. static final double minBalance = 5000.3. These are the methods and constructors added in Throwable class to support exception chaining: Throwable getCause() This method returns the underlying exception Throwable initCause(Throwable) This method associates an exception with another exception that actually caused this exception.com | Final year IEEE project development and training from scratch by Mr.accnum = accnum. int openingBalance) { this. } double getBalance() { return balance. That is. } } class EMIPaymentFailedException extends Exception { public String toString() { return "EMI PAYMENT FAILED DUE TO SOME REASONS. Mr.com . Ashok Kumar K | 9742024066 | celestialcluster@gmail. Account(long accnum.amt) < minBalance) { EMIPaymentFailedException e = new throw e. } } class Account { long accnum. Contact 9742013378 or 9742024066 and lock your project at the earliest. } void autoEMIPayment(double amt) throws EMIPaymentFailedException { try { if ((balance . 2.". Registration started.vtuprojects.7 Chained Exceptions Concept It is possible to associate one exception with another exception. Example class LowBalanceException extends Exception { public String toString() { return "HOLD ON! LOW ON BALANCE ! ". double balance = 0. String argument is the description of cause exception Throwable(Throwable) This Constructor associates an exception with another exception that actually caused this exception.amt. one exception causing another exception is called Exception Chaining. com | Final year IEEE project development and training from scratch by Mr. e. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Mr.println("OPENING BALANCE : " + acc. 9000). "+e. acc. Ashok Kumar K.println("Exception during EMI payment").out. System. System.com .. } catch (EMIPaymentFailedException e) { System.out. EMIPaymentFailedException is associated with LowBalanceException. System.getCause()).out.println("Toplevel Exception . } } } Output The above example is a slight modification of the previous example.println("Second EMI Payment Successful"). } } } public class Test { public static void main(String[] args) { Account acc = new Account(1234..println("Third EMI Payment Successful"). these two exceptions are in chain.getBalance()).println("Cause Exception . throw e.println("First EMI Payment Successful"). try { acc. You can see from the output.out. System. acc. "+e).autoEMIPayment(2000).autoEMIPayment(2000). Registration started.www.autoEMIPayment(2000). I have created another custom exception and added a new method within Account class. System.out. That is. Contact 9742013378 or 9742024066 and lock your project at the earliest. System.out.out.vtuprojects.initCause(e2). } } catch (EMIPaymentFailedException e) { LowBalanceException e2 = new LowBalanceException(). The first are those based directly on the Applet class.vtuprojects.3.  To use an applet.1 Basics Concept and Definition Applet is a Java program that can be embedded into HTML pages. Contact 9742013378 or 9742024066 and lock your project at the earliest. Applet is designed to run remotely on the client browser.applet package Two types of Applet 1. The class Applet is contained in java. One way to do this is by using the <APPLET> tag.www. Applet can't access system resources on the local computer. These applets use the Abstract Window Toolkit (AWT) to provide the graphic user interface. execution of an applet is started and controlled with an entirely different mechanism.  Applets are not stand-alone programs. The Applet class The list of all methods contained within Applet class is given below along with the description. Instead. Mr. 2. it is specified in an HTML file. Java applets run on the Java enables web browsers such as Mozilla and Internet explorer.  The applet will be executed by a Java-enabled web browser when it encounters the <APPLET> tag within the HTML file. Because JApplet inherits Applet. Ashok Kumar K. Registration started. 2. all the features of Applet are also available in JApplet.3 APPLETS 2. Observations  All applets are subclasses (either directly or indirectly) of Applet. Ashok Kumar K | 9742024066 | celestialcluster@gmail. so there are some restrictions on it. The class Applet provides the foundation for creating applets in Java.com . The second types are those based on the Swing class JApplet. Return type Method name and description void destroy() Called by the browser or applet viewer to inform this applet that it is being reclaimed and that it should destroy any resources that it has allocated. Instead.  Execution of an applet does not begin at main( ). Applets are used to make the web site more dynamic and entertaining.com | Final year IEEE project development and training from scratch by Mr. they run within either a web browser or an applet viewer. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Applet. AppletContext getAppletContext() Determines this applet's context.vtuprojects. Ashok Kumar K. URL getCodeBase() Gets the base URL. which allows the applet to query and affect the environment in which it runs. String name) Returns the AudioClip object specified by the URL and name arguments. AudioClip getAudioClip(URL url. Locale getLocale() Gets the locale of the applet. URL getDocumentBase() Gets the URL of the document in which this applet is embedded. String getAppletInfo() Returns information about this applet. String name) Returns an Image object that can then be painted on the screen. Boolean isActive() Determines if this applet is active.www.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail. String getParameter(String name) Returns the value of the named parameter in the HTML tag. AudioClip getAudioClip(URL url) Returns the AudioClip object specified by the URL argument.com . Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. Image getImage(URL url. Image getImage(URL url) Returns an Image object that can then be painted on the screen. void init() Called by the browser or applet viewer to inform this applet that it has been loaded into the system. String[][] getParameterInfo() Returns information about the parameters that are understood by this applet. Boolean isValidateRoot() Mr. *. Contact 9742013378 or 9742024066 and lock your project at the earliest. void play(URL url. void start() Called by the browser or applet viewer to inform this applet that it should start its execution. All swing components descend from the AWT container class.2 Applet Architecture Applets are event driven.*.awt. User initiates interaction with the applet (and not the other way around) An Applet skeleton import java.3. The AWT notifies the applet about an event by calling event handler that has been provided by the applet. int height) Requests that this applet be resized. void play(URL url) Plays the audio clip at the specified absolute URL. static AudioClip newAudioClip(URL url) Get an audio clip from the given URL. String name) Plays the audio clip given the URL and a specifier that is relative to it. /* <applet code="AppletSkel" width=300 height=100> Mr. Indicates if this container is a validate root. void setStub(AppletStub stub) Sets this applet's stub.applet. void resize(int width. void showStatus(String msg) Requests that the argument string be displayed in the "status window". 2. Ashok Kumar K. Ashok Kumar K | 9742024066 | [email protected] | Final year IEEE project development and training from scratch by Mr.vtuprojects. An Applet waits until an event occurs. The applet takes appropriate action and then quickly return control to AWT. void stop() Called by the browser or applet viewer to inform this applet that it should stop its execution. Registration started.www.com . void resize(Dimension d) Requests that this applet be resized. import java. 1. So. stop() 2. Registration started. following methods are called in sequence. paint() Mr. Whereas init() is called once . It is also called to restart an applet after it has been stopped. start( ) is called each time an applet’s HTML document is displayed onscreen. */ public void start() { // start or resume execution } // Called when the applet is stopped. after init(). init () 2. destroy() init() The init() method is the first method to be called. start() The start( ) method is called after init().vtuprojects. start() 3.com | Final year IEEE project development and training from scratch by Mr. paint() When an applet is terminated. Also called whenever the applet is restarted. public void init() { // initialization } /* Called second.the first time an applet is loaded. Contact 9742013378 or 9742024066 and lock your project at the earliest. 1. This is where you should initialize variables.com . Ashok Kumar K | 9742024066 | celestialcluster@gmail. */ public void destroy() { // perform shutdown activities } // Called when an applet's window must be restored. the applet resumes execution at start(). public void stop() { // suspends execution } /* Called when applet is terminated. </applet> */ public class AppletSkel extends Applet { // Called first. following methods are called in sequence. This method is called only once during the run time of your applet. if a user leaves a web page and comes back.www. Ashok Kumar K. This is the last method executed. public void paint(Graphics g) { // redisplay contents of window } } When an applet begins. 2. 10. use drawString( ).white).com | Final year IEEE project development and training from scratch by Mr.3. destroy() The destroy() method is called when the environment determines that your applet needs to be removed completely from memory. msg = "Inside init( ) --".vtuprojects. Ashok Kumar K.drawString(msg. Registration started. int x.com . } public void start() { msg += " Inside start( ) --". setForeground(Color. int y) Here. The paint() method is called each time your applet’s output must be redrawn.awt. /* <applet code="Sample" width=300 height=50> </applet> */ public class One extends Applet { String msg. public void init() { setBackground(Color. it is called from within either update( ) or paint( ). Contact 9742013378 or 9742024066 and lock your project at the earliest.y.applet. Typically. The stop() method is always called before destroy(). 30).*. stop() The stop() method is called when a web browser leaves the HTML document containing the applet .3 A simple applet that sets the foreground and background colors and outputs a string. import java. you should free up any resources the applet may be using. message is the string to be output beginning at x. which describes the graphics environment in which the applet is running. which is a member of the Graphics class. To output a string to an applet. g. import java. At this point. Ashok Kumar K | 9742024066 | celestialcluster@gmail. This parameter will contain the graphics context. It has the following general form: void drawString(String message. } } Output: Mr. } public void paint(Graphics g) { msg += " Inside paint( ) --".The paint() method has one parameter of type Graphics.blue).www.when it goes to another page.*. Example: Simple Banner Applet import java. int state. int x. calls paint(). Contact 9742013378 or 9742024066 and lock your project at the earliest. int width.*.com . Ashok Kumar K. in its default implementation. The repaint() method has four forms. which.*.awt.applet. left & top are the co-ordinates height & width are the region's height and width maxDelay specifies the maximum number of milliseconds that can elapse before update() is called. int top. int height) 3. Thread t = null. boolean stopFlag. Registration started. void repaint(long maxDelay. void repaint(long maxDelay) 4.com | Final year IEEE project development and training from scratch by Mr. import java. int height) Here. int width. Mr.4 Requesting Repainting The repaint() method is defined by the AWT. It causes the AWT run-time system to execute a call to your applet’s update() method.www.".vtuprojects. /* <applet code="SimpleBanner" width=300 height=50> </applet> */ public class SimpleBanner extends Applet implements Runnable { String msg = " A Simple Moving Banner. void repaint(int left. int y. Ashok Kumar K | 9742024066 | celestialcluster@gmail. 1.3. void repaint() 2. 2. charAt(0). showStatus() function can be used to print the message in the status bar of an applet Example: import java. msg += ch.awt. showStatus("This is shown in the status window.*.3.white).applet. public void run() { char ch. Mr. setForeground(Color. msg. stopFlag = false.) { try { repaint(). } // Entry point for the thread that runs the banner. t.blue). public void stop() { stopFlag = true. } // Start thread public void start() { t = new Thread(this). } // Display the banner.com . if (stopFlag) break. Thread. for (.length()).drawString(msg. 10. } } 2. 50.*.www.start().com | Final year IEEE project development and training from scratch by Mr. import java. 20).". /* <applet code="StatusWindow" width=300 height=50> </applet> */ public class StatusWindow extends Applet { public void init() { setBackground(Color. public void paint(Graphics g) { g.white).sleep(250). ch = msg."). 30). public void init() { setBackground(Color. Ashok Kumar K | 9742024066 | [email protected] Using the status window. } public void paint(Graphics g) { g. Registration started. } catch (InterruptedException e) { } } } // Pause the banner.vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest. msg = msg.. Ashok Kumar K.substring(1.blue). t = null.drawString("This is in the applet window. setForeground(Color. vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest. which is the directory that will be searched for the applet’s executable class file  CODE is a required attribute that gives the name of the file containing your applet’s compiled .com | Final year IEEE project development and training from scratch by Mr. Syntax of Applet tag is given below: < APPLET [CODEBASE = codebaseURL] CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = AttributeName VALUE = AttributeValue>] [< PARAM NAME = AttributeName2 VALUE = AttributeValue>] . Mr. } } Output: 2.www.  NAME is an optional attribute used to specify a name for the applet instance. Ashok Kumar K | 9742024066 | celestialcluster@gmail..  ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognizes the APPLET tag but can’t currently run Java applets.. [HTML Displayed in the absence of Java] </APPLET>  CODEBASE is an optional attribute that specifies the base URL of the applet code.class file.6 The HTML <applet> Tag Oracle currently recommends that the APPLET tag be used to start an applet from both an HTML document and from an applet viewer. Registration started.com .3. Ashok Kumar K.  WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area. valueOf(param). above and below the applet. fontName = getParameter("fontName"). Registration started.7 Passing parameters to Applets The <APPLET> tag in HTML allows you to pass parameters to your applet.com | Final year IEEE project development and training from scratch by Mr. use the getParameter() method.*.  VSPACE and HSPACE are optional.  PARAM NAME and VALUE: The PARAM tag allows you to specify applet-specific arguments in an HTML page. on each side of the applet.parseInt(param).www.com .drawString("Font name: " + fontName. 10). in pixels.applet.valueOf(param). import java.3. else leading = 0. /* <applet code="ParamDemo" width=300 height=80> <param name=fontName value=Courier> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> </applet> */ public class ParamDemo extends Applet { String fontName. 0. g. try { if (param != null) leading = Float.awt. } param = getParameter("leading"). To retrieve a parameter. Mr.vtuprojects. } catch (NumberFormatException e) { leading = -1. float leading. Ashok Kumar K. boolean active. else fontSize = 0. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } public void paint(Graphics g) { g. param = getParameter("fontSize"). Example: import java. 0. HSPACE specifies the space. if (fontName == null) fontName = "Not Found". } param = getParameter("accountEnabled"). Contact 9742013378 or 9742024066 and lock your project at the earliest.floatValue().*. It returns the value of the specified parameter in the form of a String object. int fontSize. 26). try { if (param != null) fontSize = Integer. in pixels.  ALIGN is an optional attribute that specifies the alignment of the applet. } catch (NumberFormatException e) { fontSize = -1.drawString("Font size: " + fontSize. VSPACE specifies the space. public void start() { String param. 2. if (param != null) active = Boolean.booleanValue(). Registration started.vtuprojects.drawString(msg.wav” loaded from applets parent directory. /* <applet code="Bases" width=300 height=50> </applet> */ public class Bases extends Applet { public void paint(Graphics g) { String msg.Applet. import java.drawString(msg.drawString("Account Active: " + active.applet. // get document base msg = "Document base: " + url. getCodeBase() returns the URL of the directory from which the applet’s class file was loaded. URL url = getCodeBase(). 58).toString(). 20).3. Contact 9742013378 or 9742024066 and lock your project at the earliest.applet.8 getDocumentBase() and getCodeBase() getDocumentBase() returns the URL of the directory holding the HTML file that started the applet.*.*. 42). g. g.www. } } 2. Ashok Kumar K | 9742024066 | celestialcluster@gmail. // get code base msg = "Code base: " + url.com . import java. Mr. 10.net. 0.9 Playing Audio files using AudioClip Interface Below example is a Java applet which continuously plays an audio clip named “anthem. 10. import java. g.*. g. } } Output: 2. Example: import java.toString(). 40). 0. url = getDocumentBase(). Ashok Kumar K.awt.com | Final year IEEE project development and training from scratch by Mr.3.drawString("Leading: " + leading. wav"). Contact 9742013378 or 9742024066 and lock your project at the earliest. public class LoadSoundApplet extends Applet { AudioClip audioClip.AudioClip. Ashok Kumar K. } } Necessary HTML file to run the above applet is given here: <html> <head> <title>Applet sound example</title> </head> <body> <applet code="LoadSoundApplet" width=100 height=50> </applet> </body> </html> Mr.loop().applet. public void init() { audioClip = getAudioClip(getCodeBase().awt. import java.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Registration started.Graphics. "anthem.www.com . } public void paint(Graphics g) { audioClip. import java. Ashok Kumar K | 9742024066 | celestialcluster@gmail. E (CSE/ISE) JAVA/ J2EE Notes prepared by Mr.VTU 7th sem B. Ashok Kumar K 9742024066 | [email protected] . Registration started. Ashok Kumar K 9742024066 | celestialcluster@gmail. Unit 3: Multithreaded Programming.com Mr.www. Ashok Kumar K. Event Handling Mr. Ashok Kumar K | 9742024066 | [email protected] | Final year IEEE project development and training from scratch by Mr.vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest.com . Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. 13. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. 5. 2. 10.vtuprojects.com . Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Study Materials We provide the most efficient study material for each and every module during the project development 4.com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 6. 3. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed Mr. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. 15 reasons to choose VTUPROJECTS. Ashok Kumar K. Skype/ Team viewer support In case the student needs an emergency help when he/she is in their colleges. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9.COM for your final year project work 1. He will be having a thorough experience in working on both product and service driven industries.www. 15. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. Strict SDLC Project development will be carried out as per the strict Software Development model 8. No prerequisites required. we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. every process environment. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started. Each thread in java is associated with an instance of the class java. 3.Thread.vtuprojects.com . It has a complete. Contact 9742013378 or 9742024066 and lock your project at the earliest. Main thread is something which you should mark as important. Mr.www.  Access problem can occur if several threads tries to access and share the same shared data at the same time. Process v/s Thread In Concurrent programming.1 Multithreaded programming basics Definition of concurrency (multithreading) Concurrency is the ability to run multiple parts of the program in parallel. These cause two problems  Visibility problem occurs if thread A reads shared data and thread B later changes this data and the thread A is unaware of this change.com | Final year IEEE project development and training from scratch by Mr. including memory and its own memory space open files. If a program can be divided into multiple independent parts. This type of programming is generally referred to as Concurrent Programming. This default thread or the main thread will be created by JVM. Threads are called light-weight process Remember: Threads have their own call stack and can access shared data. MULTITHREADED PROGRAMMING 3. Ashok Kumar K. A process has a separate execution Threads exist within a process. there are two units of execution:  Processes  Threads Process Thread Definition: Definition: Process is an instance of an entire program Thread is an execution path or the control in execution. flow of execution of a program.lang. each performing a specific task. then executing these parts in parallel in an asynchronous way increases the throughput of the program. You can also create child threads using this. private set of has at least one thread. each process has process's resources. Threads share the basic run-time resources. because:  It is the thread using which other threads (child threads) can be created  Ideally it must be the last thread to finish execution because it performs various shutdown operations.2 Threads in Java A separate process will be created for each Java program within which one default thread (called the Main thread) starts executing the main function. out. It first gets the access (reference) to main thread using currentThread() method in Thread class.vtuprojects. I am a thread . Registration started. " + t). you know that it will invoke t. 5.printStackTrace().println("Hi Everyone . Let's play with main thread for some time. main]. A thread can be sent to sleep using Thread.currentThread(). Remember.out. I am the same thread . It prints the numbers 0 through 4 with a delay of 1sec after each number. i < 5. Here is what actually they are: Mr. t. Ashok Kumar K | 9742024066 | celestialcluster@gmail... The thread is made to sleep for 1 sec after printing one number. each thread will be having a name and priority (dealt later).println(i). System. t.. try { for (int i = 0. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K. } } } Output When you simply print a thread reference t..setPriority(9). } } catch (InterruptedException e) { e.sleep(1000).com .println("Hi Everyone . Below example does some exercise with the main thread. " + t).www.com | Final year IEEE project development and training from scratch by Mr.getString() method which printed something like this: Thread[main. It changes the name and priority of the thread using setName() and setPriority() methods respectively. meaning go to IDLE state for some specified amount of time. System. It prints the name of the thread whose reference we have just got.setName("NewMain").out. i++) { Thread. System. public class Example { public static void main(String arg[]) { Thread t = Thread. A Thread can also sleep.sleep(long) method where the parameter is the amount of time in milliseconds. . To put it differently. try { for (int i = 0. Remember.com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. " + i). at this point of time you have only created a child thread.. System. } } } Step 2: Creating a child thread is nothing but creating an instance of Thread class and passing the runnable object as a parameter for its constructor. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run() method). It causes the child thread to start its execution. public class Example { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread(). a thread will be active till it lies in the context of run() method.out. By extending Thread class Creating a thread by implementing Runnable interface Step 1: Simply define your own class and implement it by java. class MyThread implements Runnable { public void run() { System.com . the thread dies. "). i++) { Mr.lang.println("Child .start(). It is never legal to start a thread more than once. but you haven't started its execution yet. i < 5.out.vtuprojects. // Create a child thread Thread t1 = new Thread(m1). you should invoke start() method of the thread object you just created. Define run() method and include the business logic of the thread within the run() method. } catch (InterruptedException e) { e. a thread may not be restarted once it has completed execution.. i < 5. Registration started. i++) { Thread. In particular.www. try { for (int i = 0.sleep(1000). 3. To do so.Runnable interface.3 Creating a Thread Threads in java can be created in two possible ways 1. By implementing Runnable interface 2. "). Ashok Kumar K. Ashok Kumar K | 9742024066 | celestialcluster@gmail. because run() is the entry point for a thread and when it returns from this function. // Start (run) a child thread t1.out. Instance of this class is called Runnable object since it implements Runnable interface. } System. The JVM calls run() method of the child thread.println("Child thread exiting .println("Child thread started.printStackTrace(). It just gets mixed up. } catch (InterruptedException e) { Mr. Ashok Kumar K | 9742024066 | [email protected]("Child thread exiting .sleep(1000).vtuprojects.println("Main .out. i < 5. What I meant to tell is you should allow full freedom to the user of this thread. Ashok Kumar K. System. Here is the optimized version of above program class MyThread implements Runnable { Thread t. MyThread() { t = new Thread(this).start().www.out. } public void run() { System. You should encapsulate the process of creating a thread within the custom Thread class itself..com . " + i). } catch (InterruptedException e) { e. } System...out. "). System. An application developer will simply makes use of this.printStackTrace().com | Final year IEEE project development and training from scratch by Mr.out.out. "). as shown below. Since the main thread and the child thread both are executing in parallel you can't expect the same ordering all the time.println("Main thread exiting . } } } Output: The order of execution of two threads is not the same always. } System. Thread. Contact 9742013378 or 9742024066 and lock your project at the earliest.sleep(1000).. try { for (int i = 0. i++) { Thread. The output you are seeing above can't be predicted. ").println("Child . Observation: As a component developer you should focus on both the business logic and the required resources to create a thread. t.println("Child thread started. " + i). Registration started.. . System. because run() is the entry point for a thread and when it returns from this function. try { for (int i = 0. i++) { Thread. To begin the execution of the child thread.printStackTrace().out. i < 5.println("Child thread started. Contact 9742013378 or 9742024066 and lock your project at the earliest.com | Final year IEEE project development and training from scratch by Mr. class MyThread extends Thread { public void run() { System. } catch (InterruptedException e) { e. " + i). // Start a thread m1.sleep(1000).println("Child .lang. "). } catch (InterruptedException e) { e.printStackTrace(). the thread dies. i++) { Thread.printStackTrace().vtuprojects.println("Child thread exiting .println("Main . try { Mr..Thread.println("Main thread exiting . public class Test2 { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread().start(). Ashok Kumar K | 9742024066 | [email protected]. "). you should invoke the run() method of the object created. System. i < 5. } } } Step 2: Creating a thread is just creating an instance of the class defined in step 1. Registration started.out. } } Creating a thread by extending Thread class Step 1: Simply extend your own class with java. } System. " + i)...com .sleep(1000).www. e. } } } public class Test { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread().out. ").out. } System. Define run() method and include the business logic of the thread within the run() method.. try { for (int i = 0. Ashok Kumar K. "). } catch (InterruptedException e) { e.println("Main thread exiting .println("Child . Registration started.. } System. " + i). " + i). Here is the optimized version of the above program. i < 5. Contact 9742013378 or 9742024066 and lock your project at the earliest. } System.out.. for (int i = 0.com | Final year IEEE project development and training from scratch by Mr. the logic of creating a thread should be encapsulated within the Thread class by the component developer. i++) { Thread.println("Child thread exiting .out.sleep(1000).println("Main . i++) { Thread. i < 5.printStackTrace().out. } catch (InterruptedException e) { e. class MyThread extends Thread { MyThread() { this. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } public void run() { System.. Ashok Kumar K. i++) { Thread. try { for (int i = 0.sleep(1000). System..printStackTrace().. "). " + i).start(). } } } Mr.println("Main thread exiting . } catch (InterruptedException e) { e. } } } public class Test2 { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread(). System.out. } } } Observation: As discusses previously..out.println("Child thread started. i < 5. try { for (int i = 0.vtuprojects. System.println("Main . } System.out. ").printStackTrace().com .out.sleep(1000).. ").www. out.  Inheritance should be done only if you are modifying or enhancing the base class behavior. } System.www. " + i).out.getName()+" . class MyThread implements Runnable { Thread t. So we prefer implementing the Runnable interface and extending any other class.vtuprojects. Ashok Kumar K. "). try { for (int i = 0. Since our class doesn't modify or enhance the Thread class behavior. MyThread m3 = new MyThread("ChildThree"). } } } public class Test { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread("ChildOne").currentThread(). Creating multiple threads You can create as many threads as you want. System. i < 5. i++) { Thread.currentThread().. MyThread(String name) { t = new Thread(this.println(Thread. i < 5. i++) { Thread.com | Final year IEEE project development and training from scratch by Mr. } catch (InterruptedException e) { e.printStackTrace(). } System. One more thing you need to observe from below program is the method of assigning a name to the child thread. try { for (int i = 0. you now don't have freedom of extending other classes (since multiple inheritances are not allowed).println("Main . you can set the name of a child thread by passing the name as a String argument to the Thread class constructor.currentThread().sleep(1000).println("Main thread exiting . MyThread m2 = new MyThread("ChildTwo").println("New Thread started with the name . extending the Thread class is not recommended. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } public void run() { System.getName()). ").com . Registration started.out..start(). System. Yes. } } } Mr. // 'name' is the child thread's name t."+Thread.sleep(1000).out. " + i).. name). Now that you have two different ways of creating a thread.. Contact 9742013378 or 9742024066 and lock your project at the earliest. Below example creates four threads and starts them so that the four child threads along with the main thread prints the numbers 0 to 4 concurrently. MyThread m4 = new MyThread("ChildFour").out. which one would you prefer? Creating a thread by implementing Runnable interface is preferred over extending the Thread class for two reasons. } catch (InterruptedException e) { e.getName()+" exiting .  If you extend the Thread class.printStackTrace()..println(Thread. Ashok Kumar K. But as we can see from the output of previous program.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Let’s analyze each one of them. what are the various ways to make the main thread to terminate at last? There are three possible methods to make the main thread wait till all its child threads get terminated. Contact 9742013378 or 9742024066 and lock your project at the earliest.4 isAlive() and join() Recall we had concluded that the main thread should be the last thread to terminate. Ashok Kumar K | 9742024066 | celestialcluster@gmail. 3. Method 1: Make the main thread to sleep for some specified amount of time just before its termination. It depends on many things including the thread priority.com . Registration started. Output You can clearly see the order in which these threads execute can't be predicted. the problem in discussion here is. Right. so that all its child threads can Mr.www. main thread is being terminated well before its child threads terminate. i++) { Thread. } catch (Exception e) { e. i < 5. System.println("Main thread exiting .println(Thread.vtuprojects. } System. } } catch (InterruptedException e) { e. } public void run() { System. " + i). ").start(). " + i). } catch (InterruptedException e) { e.getName()+" .. } } } public class Test { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread("ChildOne").getName()).println("Main .sleep(10000).www. Ashok Kumar K | 9742024066 | [email protected] | Final year IEEE project development and training from scratch by Mr. } // Main Thread will sleep for 10 seconds try { Thread... try { for (int i = 0. MyThread m2 = new MyThread("ChildTwo").printStackTrace().out.printStackTrace(). class MyThread implements Runnable { Thread t.. Registration started..printStackTrace(). "+Thread.out. "). name). } } Output: Mr.currentThread(). terminate by that time.println("New Thread started with the name .out. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K. i++) { Thread. MyThread m4 = new MyThread("ChildFour").sleep(1000). MyThread(String name) { t = new Thread(this. t.println(Thread.out.currentThread(). try { for (int i = 0.currentThread().out. MyThread m3 = new MyThread("ChildThree"). i < 5. } System.getName()+" exiting .sleep(1000). System.com . vtuprojects.  You would end up choosing lesser time giving no time for some of its child threads to terminate. Registration started.www. You can observe the main thread is terminating at last. This way.com . Main thread can invoke isAlive() method on each of its child threads to see if it is still running or already terminated. isAlive() is a method defined in Thread class and have the signature as follows: final boolean isAlive() Mr. Ashok Kumar K.com | Final year IEEE project development and training from scratch by Mr. Drawback: How will you choose the amount of time that the main thread should sleep to ensure the termination of all its child threads?  You would end up choosing some large amount of time therefore making the main thread sleep for some extra time even though all its child threads are already terminated. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Contact 9742013378 or 9742024066 and lock your project at the earliest. Method 2: Using isAlive() method. the main thread will be in a continuous loop until all the child threads gets terminated. currentThread().vtuprojects. Example class MyThread implements Runnable { Thread t.isAlive()) { // loop again } else break. " + i).com | Final year IEEE project development and training from scratch by Mr. i < 5. Ashok Kumar K | 9742024066 | [email protected](). System. "). "+Thread.out..sleep(1000). It returns false otherwise. try { for (int i = 0.start(). t. } } catch (InterruptedException e) { e. i++) { Thread.getName()+" . i < 5. System.getName()+" exiting .println(Thread.println(Thread. } public void run() { System.out. Ashok Kumar K. MyThread m2 = new MyThread("ChildTwo"). } // Main Thread will come out of this loop only after all the threads terminates while (true) { if (m1. MyThread m3 = new MyThread("ChildThree"). It returns true if the thread upon which it is called is still running. Contact 9742013378 or 9742024066 and lock your project at the earliest.out.. " + i).sleep(1000). Registration started. MyThread(String name) { t = new Thread(this.isAlive() || m4.out. ").println("Main thread exiting ..printStackTrace().com .isAlive() || m3. name). MyThread m4 = new MyThread("ChildFour")..println("New Thread started with the name . // come out of the loop } System.www. i++) { Thread.t. try { for (int i = 0..isAlive() || m2.currentThread().t.t.println("Main . } catch (InterruptedException e) { e. } } } public class Test { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread("ChildOne").t.printStackTrace().out. } } Output Mr.getName()). } System. join() method is also defined in Thread class with the signature as follows: final void join( ) throws InterruptedException This method waits until the thread on which it is called terminates.www. Contact 9742013378 or 9742024066 and lock your project at the earliest.vtuprojects. Additional forms of join( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started. Method 3: Using join() method. Drawback: This method has unspecified amount of continuous looping to check the status of the child threads thus wasting the runtime resources. join() is the method we mostly use to wait for a thread to finish its execution. Ashok Kumar K.com | Final year IEEE project development and training from scratch by Mr. Example Mr.com . i < 5. } catch (InterruptedException e) { e. Registration started.t. MyThread m4 = new MyThread("ChildFour"). name). } try { m1. " + i). try { for (int i = 0.println("Main .com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.. Ashok Kumar K | 9742024066 | celestialcluster@gmail.. "+Thread.printStackTrace().println("New Thread started with the name . } public void run() { System.getName()+" .getName()+" exiting .. MyThread m2 = new MyThread("ChildTwo"). } System. System. " + i).currentThread().println(Thread. i < 5.t.join().sleep(1000).println("Main thread exiting .t. m4.out. System. Contact 9742013378 or 9742024066 and lock your project at the earliest. } } Output: Mr.join().printStackTrace(). } catch (InterruptedException e) { e. m2.currentThread().out.start().www.sleep(1000).t. i++) { Thread..out. m3.join().getName()).out. class MyThread implements Runnable { Thread t.currentThread().join().. MyThread(String name) { t = new Thread(this. i++) { Thread. } System. } } catch (InterruptedException e) { e.vtuprojects. ").com . } } } public class Example { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread("ChildOne").printStackTrace(). MyThread m3 = new MyThread("ChildThree"). try { for (int i = 0.println(Thread. ").out. t. sets the priority of a calling thread to the one passed as an argument. Ashok Kumar K | 9742024066 | [email protected] .com | Final year IEEE project development and training from scratch by Mr. int getPriority(). returns the current priority of the calling thread Priority range Mr. setPriority(int) and getPriority() Thread class defines two methods. 3. Ashok Kumar K.www. Their signatures are as follows: void setPriority(int). one for setting the thread priority and the other for returning the current priority of a thread. If two threads have the same priority. Higher priority threads get the CPU much faster than the lower priority threads. the thread scheduler treats them equally and serves them based on First Come First Serve (FCFS) basis. Contact 9742013378 or 9742024066 and lock your project at the earliest. Thread scheduler will use the thread priorities to determine the execution schedule of threads.vtuprojects. Registration started.5 Thread priorities Each thread in Java will have an associated priority which is an integer value ranging from 1 (minimum) to 10 (maximum). com | Final year IEEE project development and training from scratch by Mr. "+m1.out.println("High priority thread's execution count . Mr.. } System.setPriority(pri).start(). System. try { Thread. } } Output: As you can see. Registration started. Thread.printStackTrace().NORM_PRIORITY Default priority of a thread 10 Thread..com . MyThread m2 = new MyThread("HighPriorityThread".count). Ashok Kumar K | 9742024066 | [email protected]_PRIORITY Minimum priority of a thread 5 Thread. t.println("Low priority thread's execution count .out. name).vtuprojects. Thread. int pri) { t = new Thread(this.count).MIN_PRIORITY). Thread class defines three integer constants to represent this: Priority value Integer Constant Description 1 Thread. t. Ashok Kumar K. for the duration of 10 seconds the high priority thread has been given more CPU cycles compared to the low priority thread. "+m2. } } } public class Test { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread("LowPriorityThread".MAX_PRIORITY Maximum priority of a thread Example: class MyThread implements Runnable { Thread t.www. MyThread(String name. int count=0. } catch (InterruptedException e) { e. Thread priority is an integer value ranging from 1 to 10.MAX_PRIORITY). Contact 9742013378 or 9742024066 and lock your project at the earliest. } public void run() { while (true) { count++.sleep(10000). } } Mr. MyThread m2 = new MyThread(util. Registration started. the order in which these messages are printed are not jumbled (mixed up). How synchronization works The block of code or in general any resources. this.com . this.msg = msg.print("{"). This is to avoid the following problems:  Visibility problem: It occurs if thread A reads shared data and thread B later changes this data and the thread A is unaware of this change.  Access problem: It occurs if several threads tries to access and share the same shared data at the same time.printMessage(msg). Ashok Kumar K. System. Utility util. MyThread m1 = new MyThread(util.start().vtuprojects.com | Final year IEEE project development and training from scratch by Mr.out. Problem demonstration Below program has a class named Utility which defines a method called printMessage(String).println("}").print(msg). String msg) { t = new Thread(this). } } public class Example { public static void main(String arg[]) { Utility util = new Utility(). } public void run() { util. Contact 9742013378 or 9742024066 and lock your project at the earliest. The process by which this is achieved is called synchronization.6 Synchronization Definition Whenever two or more threads accesses the shared resources we need some mechanism to make sure that only one thread is given access to the shared resource at any point of time. class Utility { // this is the shared resource public void printMessage(String msg) { System. which is shared among more than two threads and which needs to be synchronized.out. 3.www. and it prevents any other threads entering into the same monitor until it releases the lock by exiting the monitor. Ashok Kumar K | 9742024066 | celestialcluster@gmail. we say that the thread has acquired the lock. When two threads accesses this method at the same time each one passing a different string argument.out. "Sachin"). System. It takes a string argument and prints it within the flower braces { and }. MyThread(Utility util. Only one thread can access the monitor at any point of time. When a thread enters the monitor. } } class MyThread implements Runnable { Thread t. is called a monitor (also known as semaphore).util = util. t. String msg. "Kohli"). System. Using synchronized methods 2. MyThread m1 = new MyThread(util. String msg. Registration started. } } public class Example { public static void main(String arg[]) { Utility util = new Utility(). } } class MyThread implements Runnable { Thread t. Ashok Kumar K.print("{"). Using synchronized blocks Synchronized methods This solution is simple.util = util. System. class Utility { // shared resource is synchronized synchronized public void printMessage(String msg) { System. String msg) { t = new Thread(this). Contact 9742013378 or 9742024066 and lock your project at the earliest. "Kohli").vtuprojects.out. Here the shared resource is the printMessage() method. MyThread m2 = new MyThread(util.print(msg). Just prefix the keyword 'synchronized' to the shared resource which needs to be synchronized.out. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } public void run() { util. Output Synchronization in Java can be achieved in two different ways: 1. "Sachin"). t. Utility util. MyThread(Utility util.com .out.www. this.println("}").com | Final year IEEE project development and training from scratch by Mr.printMessage(msg). } } Output Mr.msg = msg. this.start(). The resource can be a method. variable or any other program elements. www.print("{"). } public void run() { synchronized (util) { util. String msg. Synchronized blocks The solution described above is simple and accepted as long as you have the access to Utility class so that you can modify it and add synchronized keyword. System. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor.out. t.printMessage(msg). "Sachin"). Registration started. this.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K | 9742024066 | [email protected](msg). } } } public class Test { public static void main(String arg[]) { Utility util = new Utility().util = util.println("}").msg = msg. object is a reference to the object being synchronized. Ashok Kumar K. Contact 9742013378 or 9742024066 and lock your project at the earliest. In these situations.vtuprojects.out. you are not authorized to modify the class and you cannot add the synchronized keyword to its method. you can go with synchronized blocks. String msg) { t = new Thread(this). class Utility { public void printMessage(String msg) { System. Simply put calls to the methods defined by this class inside a synchronized block. } } Output Mr. MyThread(Utility util. } } class MyThread implements Runnable { Thread t. MyThread m1 = new MyThread(util. This is the general form of the synchronized statement: synchronized(object) { // statements to be synchronized } Here.start(). "Kohli"). this. what if you are not the owner of Utility class? Meaning. MyThread m2 = new MyThread(util.com . But. Utility util. System. notifyAll(). Consumer.7 Inter thread communication There are three methods defined in Object class namely notify(). and wait() that constitutes for inter thread communication. 1. notify(): This method wakes up the first thread that called wait() on the same object.com | Final year IEEE project development and training from scratch by Mr.www. 3. synchronized int get() { while (!valueSet) try { wait().com . wait(): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify(). the queue you are trying to synchronize. class Q { int n. 3. 3.vtuprojects. It consists of four classes. and Consumer. Registration started. These methods can be called only within a synchronized context. Class Q. notifyAll(): This method wakes up all the threads that called wait() on the same object. Ashok Kumar K.println("InterruptedException caught"). threaded object that is consuming queue entries. Producer. } Mr. The highest priority thread will run first. tiny class that creates single Q. threaded object that is producing queue entries. } catch (InterruptedException e) { System.8 Producer Consumer Implementation Below example shows an implementation of solution for producer-consumer problem. Contact 9742013378 or 9742024066 and lock your project at the earliest. Producer. Ashok Kumar K | 9742024066 | celestialcluster@gmail. 2.out. PC. 4. boolean valueSet = false. Consumer(Q q) { this. } } } public class PCFixed { public static void main(String args[]) { Q q = new Q(). System. new Thread(this. } } } class Consumer implements Runnable { Q q. return n.put(i++). System. new Consumer(q). } } class Producer implements Runnable { Q q. notify(). new Thread(this. Ashok Kumar K.out. System.www. new Producer(q). } synchronized void put(int n) { while (valueSet) try { wait().q = q.println("Press Control-C to stop. } this. } catch (InterruptedException e) { System. "Producer"). "Consumer").println("Got: " + n). Producer(Q q) { this. } public void run() { int i = 0.n = n. Ashok Kumar K | 9742024066 | celestialcluster@gmail. valueSet = true.q = q.get(). Registration started. } public void run() { while (true) { q.out.com .com | Final year IEEE project development and training from scratch by Mr.out.start(). while (true) { q. valueSet = false.vtuprojects. } } Output: Mr.").start(). Contact 9742013378 or 9742024066 and lock your project at the earliest.out. notify().println("InterruptedException caught").println("Put: " + n). 3. Registration started.vtuprojects. Mr. Ashok Kumar K.com . Contact 9742013378 or 9742024066 and lock your project at the earliest.www. Ashok Kumar K | 9742024066 | [email protected] | Final year IEEE project development and training from scratch by Mr.9 Different states of a Thread Below figure shows the various states of a thread and its life cycle starting from New state to Terminated state. The method that registers a mouse motion listener is called addMouseMotionListener(). source. A source must register listeners in order for the listeners to receive notifications about a specific type of event. an Applet).10 Delegation Event Model Delegation Event Model constitutes of three entities: event. and listener. Contact 9742013378 or 9742024066 and lock your project at the earliest. These objects are encapsulated in a class hierarchy rooted at java.EventObject. and el is a reference to the event listener. and el is a reference to the event listener. you would call removeKeyListener( ).vtuprojects. Source An Event Source is an object which originates or "fires" events.util. Event Event is an object that describes the state change. A Listener is an object that implements a specific EventListener interface extended from the generic java. Listener A listener is an object which will be notified when an event occurs. Registration started. For example. (Example. it must implement methods to receive and process these notifications Mr. EVENT HANDLING IN JAVA 3. Ashok Kumar K.EventListener.www. the method that registers a keyboard event listener is called addKeyListener(). it must have been registered with one or more sources to receive notifications about specific types of events. Ashok Kumar K | 9742024066 | [email protected] . The general form of such a method is this: public void removeTypeListener(TypeListener el) Here. Type is the name of the event. It has two major requirements:  First. Registering a listener: Each type of event has its own registration method. Unregistering a listener: A source must also provide a method that allows a listener to unregister an interest in a specific type of event.  Second.com | Final year IEEE project development and training from scratch by Mr. For example. Type is the name of the event. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated.util. to remove a keyboard listener. Here is the general form: public void addTypeListener(TypeListener el) Here. is a subclass of EventObject. There are many other integer constants that are defined by KeyEvent.AWTEvent. not all key presses result in characters. Here are the few: Event class Description ActionEvent Generated when a button is pressed. For example.com . Ashok Kumar K. The class java. Contact 9742013378 or 9742024066 and lock your project at the earliest.www. or quit. or released. KeyEvent Generated when input is received from the keyboard.EventObject is the root of all the event classes. InputEvent Abstract superclass for all component input event classes. MouseEvent Generated when the mouse is dragged. a list item is double-clicked. ItemEvent Generated when a check box or list item is clicked. The package java. or a menu item is selected AdjustmentEvent Generated when a scroll bar is manipulated.11 Event Almost for every possible type of event that can occur (Ex.event defines various event classes to describe the events generated by various user interface elements. etc). also generated when the mouse enters or exits a component. also occurs when a choice selection is made or a checkable menu item is selected or deselected. closed. pressed. WindowEvent Generated when a window is activated. pressing SHIFT does not generate a character. Registration started. There are three types of key events. Let's explore only KeyEvent and MouseEvent classes KeyEvent A KeyEvent is generated when keyboard input occurs. click a button. or becomes visible ContainerEvent Generated when a component is added to or removed from a container. 3. Ashok Kumar K | 9742024066 | celestialcluster@gmail. and  KEY_TYPED. iconified. Mr. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model.util. scroll the mouse. deactivated.awt. ComponentEvent Generated when a component is hidden. deiconified. opened. moved.com | Final year IEEE project development and training from scratch by Mr.vtuprojects. The last event occurs only when a character is generated. MouseWheelEvent Generated when the mouse wheel is moved.awt. which are identified by these integer constants:  KEY_PRESSED  KEY_RELEASED. moved. java. TextEvent Generated when the value of a text area or text field is changed. clicked. Java defines a separate class for it. The first two events are generated when any key is pressed or released. resized. Remember. FocusEvent Generated when a component gains or loses keyboard focus. MOUSE_ENTERED The mouse entered a component. MOUSE_RELEASED The mouse was released. Ashok Kumar K | 9742024066 | celestialcluster@gmail. but the most commonly used ones are getKeyChar( ). MOUSE_PRESSED The mouse was pressed. The MouseEvent class defines the following integer constants that can be used to identify them: MOUSE_CLICKED The user clicked the mouse.vtuprojects. Their general forms are shown here: char getKeyChar( ) int getKeyCode( ) MouseEvent There are eight types of mouse events. MOUSE_MOVED The mouse moved. MOUSE_EXITED The mouse exited from a component. which returns the key code. which returns the character that was entered.  VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. generates item Text components events when a checkable menu item is selected or deselected. Check box Generates item events when the check box is selected or deselected. MOUSE_DRAGGED The user dragged the mouse. Choice Generates item events when the choice is changed.com | Final year IEEE project development and training from scratch by Mr. Window Generates adjustment events when the scroll bar is manipulated.12 Event Source Table below lists some of the user interface components that can generate the events described in the previous section. Contact 9742013378 or 9742024066 and lock your project at the earliest. Two commonly used methods in this class are getX( ) and getY( ). Mr. Their forms are shown here: int getX() int getY() 3. MOUSE_WHEEL The mouse wheel was moved. Ashok Kumar K. These returns the X and Y coordinate of the mouse within the component when the event occurred. and getKeyCode( ). List Generates action events when an item is double-clicked.  Here are some others: VK_ALT VK_DOWN VK_LEFT VK_RIGHT VK_CANCEL VK_ENTER VK_PAGE_DOWN VK_SHIFT VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP The KeyEvent class defines several methods. generates item Menu Item events when an item is selected or deselected. Scroll bar Generates action events when a menu item is selected. For example. Event Source Description Button Generates action events when the button is pressed.www.com . Registration started. is pressed.14 Example programs Handling Mouse Events To handle mouse events. ContainerListener moved. Contact 9742013378 or 9742024066 and lock your project at the earliest. KeyListener interface This interface defines following methods void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke) MouseListener interface This interface defines following methods void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me) MouseMotionListener interface This interface defines following methods void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me) 3. FocusListener Defines two methods to recognize when a component is added to ItemListener or removed from a container. WindowFocusListener Defines five methods to recognize when the mouse is clicked.www.awt. Registration started. Mr.com | Final year IEEE project development and training from scratch by Mr. MouseWheelListener Defines three methods to recognize when a key is pressed.vtuprojects. MouseMotionListener Defines one method to recognize when the state of an item changes. o It displays the current coordinates of the mouse in the applet’s status window. exits a component. KeyListener Defines two methods to recognize when a component gains or loses MouseListener keyboard focus. ComponentListener Defines four methods to recognize when a component is hidden. enters WindowListener a component.event package.13 Event Listener Listeners are created by implementing one or more of the interfaces defined by the java. The following applet demonstrates the process. released. the event source invokes the appropriate method defined by the listener and provides an event object as its argument. or is released. Listener Interface Description ActionListener Defines one method to receive action events. 3. TextListener or typed. AdjustmentListener Defines one method to receive adjustment events.com . or shown. Ashok Kumar K | 9742024066 | celestialcluster@gmail. resized. Table below lists commonly used listener interfaces and provides a brief description of the methods that they define. you must implement the MouseListener and the MouseMotionListener interfaces. Ashok Kumar K. When an event occurs. } // Handle mouse entered. Ashok Kumar K | 9742024066 | celestialcluster@gmail. public void mouseClicked(MouseEvent me) { // save coordinates mouseX = 0.getY(). mouseY = 10.event. repaint(). repaint(). public class MouseEventExample extends Applet implements MouseListener. o As the mouse enters or exits the applet window. public void mouseReleased(MouseEvent me) { // save coordinates mouseX = me.com . Each time the button is released. mouseY = me. import java. the word “Down” is displayed at the location of the mouse pointer. addMouseMotionListener(this). Ashok Kumar K. } // Handle mouse exited. mouseY = 10. public void mouseExited(MouseEvent me) { // save coordinates mouseX = 0.". } // Handle button pressed. import java. msg = "Up". Registration started.getX(). a * is shown.*.getX(). public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0. MouseMotionListener { String msg = "". } // Handle button released. } // Handle mouse clicked. msg = "Mouse exited.awt. import java. msg = "Mouse clicked. o If a button is clicked.". which tracks with the mouse pointer as it is dragged.*. mouseY = 0. o When dragging the mouse. mouseY = me. Contact 9742013378 or 9742024066 and lock your project at the earliest. the word “Up” is shown.".awt. msg = "Mouse entered. a message is displayed in the upper-left corner of the applet display area. repaint(). Mr. public void init() { addMouseListener(this).www.vtuprojects. repaint().applet.getY(). mouseY = 10. the message “Mouse clicked” is displayed in the upper left corner of the applet display area. o Each time a button is pressed. repaint().com | Final year IEEE project development and training from scratch by Mr. msg = "Down". int mouseX = 0. public void mousePressed(MouseEvent me) { // save coordinates mouseX = me.*. Ashok Kumar K.awt.drawString(msg. Registration started. showStatus("Dragging mouse at " + mouseX + ". o When a key is pressed.awt.com | Final year IEEE project development and training from scratch by Mr. public void paint(Graphics g) { g. mouseX.getX(). you will be implementing KeyListener interface. } } Output: Handling Keyboard Events To handle key board events.Y location.getX() + ".getY()).*.www. } // Handle mouse dragged. Let's see how key events are generated. } // Handle mouse moved. a KEY_RELEASED event is generated and the keyReleased( ) handler is executed. then a KEY_TYPED event is sent and the keyTyped( ) handler is invoked. " + mouseY). } // Display msg in applet window at current X. public void mouseMoved(MouseEvent me) { showStatus("Moving mouse at " + me. Contact 9742013378 or 9742024066 and lock your project at the earliest.*. msg = "*". mouseY = me. mouseY).event. public void mouseDragged(MouseEvent me) { // save coordinates mouseX = me. import java. repaint(). a KEY_PRESSED event is generated.com . This results in a call to the keyPressed() event handler. " + me. Before going to the program. import java. o When the key is released. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Here is the program to demonstrate the handling of key events. Thus. each time the user presses a key.vtuprojects. o If a character is generated by the keystroke. at least two and often three events are generated. Mr.getY(). Y). Adapter classes are useful when you want to receive and process ONLY some of the events that are handled by a particular event listener interface. } public void paint(Graphics g) { g. Ashok Kumar K | 9742024066 | [email protected] . Contact 9742013378 or 9742024066 and lock your project at the earliest. called an adapter class.15 Adaptor Classes Java provides a special feature.vtuprojects. You can define a new Mr. Ashok Kumar K. import java. Registration started. public void init() { addKeyListener(this). } } Output 3. } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(). X. public class KeyEventExample extends Applet implements KeyListener { String msg = "".com | Final year IEEE project development and training from scratch by Mr.*.drawString(msg. } public void keyPressed(KeyEvent ke) { showStatus("Key Down"). Y = 20. int X = 10. Definition An adapter class provides an empty implementation of all methods in an event listener interface.www. repaint(). } public void keyReleased(KeyEvent ke) { showStatus("Key Up").applet. which can simplify the creation of event handlers. *. Table below shows Commonly Used Listener Interfaces Implemented by Adapter Classes. public MyMouseAdapter(AdapterDemo adapterDemo) { this. public MyMouseMotionAdapter(AdapterDemo adapterDemo) { this. import java. } } class MyMouseMotionAdapter extends MouseMotionAdapter { AdapterDemo adapterDemo.*. public void mouseDragged(MouseEvent me) { adapterDemo.com | Final year IEEE project development and training from scratch by Mr. } // Handle mouse dragged. public void mouseClicked(MouseEvent me) { adapterDemo.vtuprojects.www. Ashok Kumar K.showStatus("Mouse clicked"). Registration started.16 Inner Classes. import java. Ashok Kumar K | 9742024066 | celestialcluster@gmail.*. Contact 9742013378 or 9742024066 and lock your project at the earliest.awt.com . } // Handle mouse clicked. } } class MyMouseAdapter extends MouseAdapter { AdapterDemo adapterDemo.awt. addMouseMotionListener(new MyMouseMotionAdapter(this)).event.adapterDemo = adapterDemo.applet.adapterDemo = adapterDemo. Anonymous Inner Classes We can handle events in an applet by using three different methods: By using “this” reference By using inner classes By using anonymous inner classes Mr.showStatus("Mouse dragged"). public class AdapterDemo extends Applet { public void init() { addMouseListener(new MyMouseAdapter(this)). class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested. Adaptor class Listener Interface ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener MouseAdapter KeyListener MouseMotionAdapter MouseListener WindowAdapter MouseMotionListener Example for Adaptor class import java. } } 3. event. } } } Advantage of handling the event by using inner class is that. This new class is not named.com | Final year IEEE project development and training from scratch by Mr. that class extends MouseAdapter. Till now we have seen how to handle events by using “this” reference.*.*. Ashok Kumar K.. import java.www. Contact 9742013378 or 9742024066 and lock your project at the earliest. This example illustrates how to use anonymous inner class to handle events. public class InnerClassDemo extends Applet { public void init() { addMouseListener(new MyMouseAdapter()). import java. Registration started. the inner class can directly call the showStatus() method. and there is no need to store a reference to the applet. Furthermore. } indicates to the compiler that the code between the braces defines an anonymous inner class. Anonymous Inner classes An anonymous inner class is one that is not assigned a name. } } The syntax new MouseAdapter( ) { . } class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"). but it is automatically instantiated when this expression is executed.*.applet..*.com .awt. Inner classes Below example shows how to handle the events by using an inner class.awt. import java. } }). import java.applet.vtuprojects. Ashok Kumar K | 9742024066 | [email protected]. Mr. public class AnonymousInnerClassDemo extends Applet { public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"). VTU 7th sem B.com . Ashok Kumar K 9742024066 | [email protected] (CSE/ISE) JAVA/ J2EE Notes prepared by Mr. Ashok Kumar K 9742024066 | celestialcluster@gmail. Ashok Kumar K | 9742024066 | [email protected]. Unit 4: Swings Mr.vtuprojects.com . Registration started. Ashok Kumar K. Contact 9742013378 or 9742024066 and lock your project at the earliest.com Mr.com | Final year IEEE project development and training from scratch by Mr. COM for your final year project work 1. 15. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9.vtuprojects. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed Mr. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Skype/ Team viewer support In case the student needs an emergency help when he/she is in their colleges. 15 reasons to choose VTUPROJECTS. 2. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews.com . 10. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Registration started. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. 3.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. we will be helping out them through Skype/ Team viewer screen sharing 12. No prerequisites required. Study Materials We provide the most efficient study material for each and every module during the project development 4. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. Contact 9742013378 or 9742024066 and lock your project at the earliest. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. He will be having a thorough experience in working on both product and service driven industries. 6. 5.www. 13. swing package AWT is not MVC based Swing are MVC based architecture AWT works slower Swing works faster 4. platform-specific equivalents.com . Lightweight Swing component are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls. Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. It is built on top of AWT API and it overcomes most of its limitations. Therefore. Registration started.  It caused some restrictions on usage of the components. Pluggable look and feel (PLAF) Swing based GUI Application’s look and feel logic can be separated from the component’s business logic.2 Swing features Here are the two key features of swing.awt package Swing requires javax. the look and feel will be decided by the platform and not by Java. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Definition Swing API is set of extensible GUI Components to ease developer's life to create JAVA based Front End/ GUI Applications. Limitations of AWT API AWT translates its various visual components into their corresponding.1 Basics In unit 2. we had seen how to build user interfaces using AWT. Swing has almost every control corresponding to AWT controls.vtuprojects. Therefore. 4. AWT versus Swing AWT Swing AWT components are platform-dependent Swing are platform independent AWT is called the abstract window tool Swing is part of the java foundation classes AWT components are heavyweight components Swing components are lightweight components because swing sits on the top of AWT AWT occupies more memory space Swing occupies less memory space AWT require javax.com | Final year IEEE project development and training from scratch by Mr. This led to following problems  Component might act differently on different platforms  Look and feel of each component was fixed and could not be easily changed by the program. AWT is referred to as heavyweight.www. or peers. Ashok Kumar K. com . Therefore. TabbedPane. table controls  Highly Customizable Swing controls can be customized in very easy way as visual appearance is independent of internal representation 4. Other features of Swing  Rich controls Swing provides a rich set of advanced controls like Tree. slider. They do directly inherit the AWT classes Component and Container.com | Final year IEEE project development and training from scratch by Mr.  In general.  There are two types of containers  Top level containers (JFrame.3 Components and Containers Components  A component is an independent visual control such as push button or a slider. Ashok Kumar K.www.  Conversely.  Those who inherit JComponent are the second type of container: They are lightweight Here are some of the Swing components: JApplet JButton JCheckBox JCheckBoxMenuItem JColorChooser JComboBox JComponent JDesktopPane JDialog JEditorPane JFileChooser JFormattedTextField JFrame JInternalFrame JLabel JLayeredPane JList JMenu JMenuBar JMenuItem JOptionPane JPanel JPasswordField JPopupMenu JProgressBar JRadioButton JRadioButtonMenuItem JRootPane JScrollBar JScrollPane JSeparator JSlider Mr.  JComponent class inherits the AWT classes Container and Component Containers  A container holds a group of components. all the swing components are derived from JComponent class (apart from four top level containers). JApplet. JWindow. they are heavyweight. and JDialog): These containers do not inherit the JComponent.vtuprojects. Advantages of PLAF  It is possible to define look and feel that is consistent across all platforms. colorpicker. They cannot be contained within any other component. Thus.  It is also possible to create a custom look and feel. container is a special type of component that is designed to hold other components.  Look and feel can be changed dynamically at runtime. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started. it is also possible to create a look and feel that acts like a specific platform. setDefaultCloseOperation(JFrame.plaf javax. // Add the label to the content pane.swing javax.5 A Simple Swing Application import javax.border javax.com .filechooser javax.synth javax.EXIT_ON_CLOSE).swing. // Terminate the program when the user closes the application.swing. !!").rtf javax.swing.swing. frame.setVisible(true).undo 4.setSize(400. Ashok Kumar K | 9742024066 | [email protected] | Final year IEEE project development and training from scratch by Mr.plaf.plaf. frame.multi javax.metal javax.swing.parser javax.table javax.event javax.html javax.swing. JSpinner JSplitPane JTabbedPane JTable JTextArea JTextField JTextPane JTogglebutton JToolBar JToolTip JTree JViewport JWindow 4.html.swing.text. // Create a text-based label.text javax. frame.text. JLabel label = new JLabel("WELCOME TO THE WORLD OF SWINGS. Ashok Kumar K. } Mr.colorchooser javax.swing.*.swing.swing. 200). Registration started.swing. Contact 9742013378 or 9742024066 and lock your project at the earliest.4 The Swing packages Java SE6 defines following swing packages javax.swing. // Give the frame an initial size.tree javax. class Example { Example() { // Create a new JFrame container.plaf.plaf. frame. JFrame frame = new JFrame("My first Swing Application").www.swing.swing.swing.basic javax.add(label). // Display the frame.vtuprojects.text.swing.  Event Source: An Event Source is an object which originates or "fires" events. public static void main(String args[]) { new Example().e. import java. private JPanel controlPanel. Events are generated as result of user interaction with the graphical user interface components.vtuprojects. private JLabel statusLabel. Ashok Kumar K | 9742024066 | celestialcluster@gmail.*. } } Output 4.swing.*. private JLabel headerLabel. Ashok Kumar K. Contact 9742013378 or 9742024066 and lock your project at the earliest.com .com | Final year IEEE project development and training from scratch by Mr.  Event Listener: A listener is an object which will be notified when an event occurs. delegation event model has the following key participants namely:  Event: Event is an object that describes the state change. As we learnt in unit 3. event describes the change in state of source. Foreground events: These events require the direct interaction of the user.awt. entering a character through keyboard. moving the mouse. clicking on a button.6 Event Handling Basics Change in the state of an object is known as event i. scrolling the page are the activities that causes an event to happen.*. Example: OS interrupt. import javax.www. For example. Example: Click on a button Background events: These don’t require the interaction of the user. public Example() Mr. public class Example { private JFrame mainFrame. Registration started. Event handling example: import java.awt. selecting an item from list.event. add(statusLabel). controlPanel.setActionCommand("Cancel"). mainFrame.exit(0). } private class ButtonClickListener implements ActionListener { public void actionPerformed(ActionEvent e) { String command = e. Ashok Kumar K. submitButton. mainFrame. cancelButton. 1)).setActionCommand("OK"). cancelButton. okButton. } public static void main(String[] args) { Example swingControlDemo = new Example(). 100). mainFrame. Registration started. JButton cancelButton = new JButton("Cancel"). if (command.addActionListener(new ButtonClickListener()). statusLabel.setVisible(true).equals("OK")) Mr.add(headerLabel).vtuprojects. mainFrame.add(okButton). Contact 9742013378 or 9742024066 and lock your project at the earliest. } private void render() { mainFrame = new JFrame("Java SWING Examples").setSize(350.setLayout(new FlowLayout()). statusLabel = new JLabel("". controlPanel.CENTER).www. mainFrame.setVisible(true). JLabel.CENTER). submitButton. { render().add(controlPanel).setActionCommand("Submit"). swingControlDemo. 400).com | Final year IEEE project development and training from scratch by Mr.setText("Control in action: Button"). JButton okButton = new JButton("OK").setSize(400. JLabel. } }).addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent) { System.add(submitButton). JButton submitButton = new JButton("Submit").getActionCommand(). Ashok Kumar K | 9742024066 | celestialcluster@gmail. controlPanel = new JPanel().addActionListener(new ButtonClickListener()).add(cancelButton).com . mainFrame. controlPanel. okButton.showEventDemo().setLayout(new GridLayout(3. } private void showEventDemo() { headerLabel.addActionListener(new ButtonClickListener()). controlPanel. mainFrame. mainFrame. headerLabel = new JLabel("". } else if (command. If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object. Ashok Kumar K | 9742024066 | [email protected] | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.").setText("Cancel Button clicked."). Registration started.equals("Submit")) { statusLabel. 2. { statusLabel.vtuprojects.setText("Ok Button clicked.com .setText("Submit Button clicked.www. Event object is forwarded to the method of registered listener class. The User clicks the button and the event is generated. Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object. These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class. Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. In order to design a listener class we have to develop some listener interfaces. The method now gets executed and returns. } else { statusLabel. } } } } Output Steps involved in event handling 1. 4. 3."). setText("Button2 was pressed. JLabel label. // Make two buttons. button2 = new JButton("Button2"). button1 = new JButton("Button1").com . Thus. // Initialize the applet. stop().").www. Swing applets use the same four lifecycle methods as described in unit 2: init(). button2. // or destroy().setText("Button1 was pressed. Registration started. stop(). // initialize the GUI } // This applet does not need to override start(). 4. start(). add(button1).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { label. private void render() { // Set the applet to use flow layout. import java. add(button2).swing. Ashok Kumar K | 9742024066 | celestialcluster@gmail.*.vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest. setLayout(new FlowLayout()). Example: import javax.com | Final year IEEE project development and training from scratch by Mr. } }). Ashok Kumar K.event. and a Swing applet will not normally override the paint() method. import java. Mr. but it extends JApplet rather than Applet. public void init() { render(). JButton button2. // Add action listener for Beta. // Add action listener for Alpha. // Set up and initialize the GUI. JApplet is derived from Applet. /* This HTML can be used to launch the applet: <object code="MySwingApplet" width=220 height=90> </object> */ public class Example extends JApplet { JButton button1. and destroy() Painting is accomplished differently in Swing than it is in the AWT. // Add the buttons to the content pane.*.awt. JApplet includes all of the functionality found in Applet and adds support for Swing. } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { label.awt.*.7 Create a Swing Applet Concept Swing-based applets are similar to AWT-based applets. button1."). along with several others used by the Swing classes."). LEADING. The easiest way to obtain an icon is to use the ImageIcon class. It must be one of the following values: LEFT.swing.vtuprojects. // Add the label to the content pane.*. Registration started.com | Final year IEEE project development and training from scratch by Mr. Thus. int align) Here. Ashok Kumar K. Mr. add(label). RIGHT. or TRAILING. Ashok Kumar K | 9742024066 | [email protected] JLabel and ImageIcon Description A JLabel object provides text instructions or information on a GUI — display a single line of read-only text.www. ImageIcon implements Icon and encapsulates an image. CENTER. these constants are defined in the SwingConstants interface. // Create a text-based label. str and icon are the text and icon used for the label. @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render(). The align argument specifies the horizontal alignment of the text and/or icon within the dimensions of the label. Contact 9742013378 or 9742024066 and lock your project at the earliest. an image or both text and image. 4.com . an object of type ImageIcon can be passed as an argument to the Icon parameter of JLabel’s constructor Example: import javax. JLabel defines three constructors JLabel(Icon icon) JLabel(String str) JLabel(String str. } } Output Let’s discuss some of the lightweight components derived from JComponent class. label = new JLabel("Press a button. Icon icon. JLabel. // Add the label to the content pane. The solution is to use JTextArea. Contact 9742013378 or 9742024066 and lock your project at the earliest. the listener processes the event and can use the data in the text field at the time of the event in the program JTextField defines three constructors JTextField(int cols) JTextField(String str.png"). } } Output 4.com | Final year IEEE project development and training from scratch by Mr.com . Ashok Kumar K. you cannot use JTextField’s unless you create several of them. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } private void render() { // Create an icon. an action event occurs. int cols) JTextField(String str) Here. // Create a label.vtuprojects. Registration started.LEFT). If the program registers an event listener. which enables the user to enter multiple lines of text.www. add(label). str is the string to be initially presented. and Mr. imgIcon. ImageIcon imgIcon = new ImageIcon("logo.9 JTextField Description JTextField is an input area where the user can type in characters. JLabel label = new JLabel("This is a sample message". When the user types data into them and presses the Enter key. If you want to let the user enter multiple lines of text. showStatus(textfield. import java. If the number of columns is not specified.*. add(textfield).swing.event.com .awt. Example import java.*.*. cols is the number of columns in the text field. setLayout(new FlowLayout()). Registration started.www. textfield.vtuprojects.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { // Show text when user presses ENTER. the text field is initially empty.getText()).com | Final year IEEE project development and training from scratch by Mr.awt. textfield = new JTextField(15). If no string is specified. Contact 9742013378 or 9742024066 and lock your project at the earliest. import javax. public void init() { render(). the text field is sized to fit the specified string. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Ashok Kumar K. } }). @SuppressWarnings("serial") public class Example extends JApplet { JTextField textfield. // Add text field to content pane. } private void render() { // Change to flow layout. } } Output Mr. JCheckBox. which extends JComponent The text associated with the button can be read and written via the following methods String getText() void setText(String str) A button generates an action event when it is pressed. 4.*. JButton The JButton class provides the functionality of a push button. Registration started.10 The Swing buttons Swing defines four types of buttons: JButton.vtuprojects. Ashok Kumar K.www. Mr. str and icon are the string and icon used for the button Example: import java.com .*. a string. Contact 9742013378 or 9742024066 and lock your project at the earliest. Icon icon) Here. JToggleButton. All are subclasses of the AbstractButton class. an ActionEvent is generated and it is handled by the actionPerformed() method of registered ActionListener It defines three constructors JButton(Icon icon) JButton(String str) JButton(String str. When the button is pressed. or both to be associated with the push button.com | Final year IEEE project development and training from scratch by Mr. JButton allows an icon.event. and JRadioButton. Other events are also possible.awt.awt. import java. Ashok Kumar K | 9742024066 | celestialcluster@gmail. www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet implements ActionListener { JLabel label; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Add buttons to content pane. ImageIcon aklcIcon = new ImageIcon("aklc.png"); JButton button1 = new JButton(aklcIcon); button1.setActionCommand("AKLC"); button1.addActionListener(this); add(button1); ImageIcon jmasterIcon = new ImageIcon("jmaster.png"); JButton button2 = new JButton(jmasterIcon); button2.setActionCommand("JMASTER"); button2.addActionListener(this); add(button2); // Create and add the label to content pane. label = new JLabel("Choose an institute"); add(label); } // Handle button events. public void actionPerformed(ActionEvent ae) { label.setText("You selected " + ae.getActionCommand()); } } Output Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. JToggleButton A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. That is, when you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed; it toggles between its two states. It generates an ItemEvent. Example: import java.awt.*; import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { JToggleButton toggleButton; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Make a toggle button. toggleButton = new JToggleButton("ON"); // Add an item listener for the toggle button. toggleButton.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (toggleButton.isSelected()) toggleButton.setText("OFF"); else Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. toggleButton.setText("ON"); } }); // Add the toggle button and label to the content pane. add(toggleButton); } } Output JCheckBox The JCheckBox class provides the functionality of a check box. When the user selects or deselects a check box, an ItemEvent is generated. Example import java.awt.*; import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet implements ItemListener { JLabel label; public void init() { render(); } private void render() { // Change to flow layout. Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. setLayout(new FlowLayout()); // Add check boxes to the content pane. JCheckBox cb = new JCheckBox("C"); cb.addItemListener(this); add(cb); cb = new JCheckBox("C++"); cb.addItemListener(this); add(cb); cb = new JCheckBox("Java"); cb.addItemListener(this); add(cb); // Create the label and add it to the content pane. label = new JLabel("Select languages"); add(label); } // Handle item events for the check boxes. public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox) ie.getItem(); if (cb.isSelected()) label.setText(cb.getText() + " is selected"); else label.setText(cb.getText() + " is cleared"); } } Output JRadioButton Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time. Example import java.awt.*; Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet implements ActionListener { JLabel label; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Create radio buttons and add them to content pane. JRadioButton b1 = new JRadioButton("Male"); b1.addActionListener(this); add(b1); JRadioButton b2 = new JRadioButton("Female"); b2.addActionListener(this); add(b2); // Define a button group. ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); // Create a label and add it to the content pane. label = new JLabel("Select your Gender"); add(label); } // Handle button selection. public void actionPerformed(ActionEvent ae) { label.setText("You selected " + ae.getActionCommand()); } } Output Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. 4.11 JTabbedPane Description A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. Procedure to use a tabbed pane  Create an instance of JTabbedPane.  Add each tab by calling addTab()  Add the tabbed pane to the content pane. Example: import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render(); } private void render() { JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("Sem 1", new Sem1()); tabbedPane.addTab("Sem 2", new Sem2()); add(tabbedPane); } } // Make the panels that will be added to the tabbed pane. @SuppressWarnings("serial") class Sem1 extends JPanel { public Sem1() Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. { JButton b1 = new JButton("Mathematics 1"); add(b1); JButton b2 = new JButton("CCP"); add(b2); JButton b3 = new JButton("Basic Electronics"); add(b3); JButton b4 = new JButton("Chemistry"); add(b4); } } @SuppressWarnings("serial") class Sem2 extends JPanel { public Sem2() { JButton b1 = new JButton("Mathematics 2"); add(b1); JButton b2 = new JButton("Civil"); add(b2); JButton b3 = new JButton("Basic Electricals"); add(b3); JButton b4 = new JButton("Physics"); add(b4); } } Output 4.12 JScrollPane Description JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled can either be an individual component, such as a table, or a group of components contained within another lightweight container, such as a JPanel. In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are automatically provided, and the component can be scrolled through the pane. Because JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll bars Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. Steps to use a scroll pane  Create the component to be scrolled.  Create an instance of JScrollPane, passing to it the object to be scrolled.  Add the scroll pane to the content pane Example import java.awt.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render(); } private void render() { // Add 400 buttons to a panel. JPanel jp = new JPanel(); jp.setLayout(new GridLayout(20, 20)); int b = 0; for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { jp.add(new JButton("Button " + b)); ++b; } } // Create the scroll pane. JScrollPane jsp = new JScrollPane(jp); // Add the scroll pane to the content pane. // Because the default border layout is used, // the scroll pane will be added to the center. add(jsp, BorderLayout.CENTER); } } Output Mr. Ashok Kumar K | 9742024066 | [email protected] list. "Dharwad". "Hassan".*.13 JList Description JList supports the selection of one or more items from a list. Ashok Kumar K.swing. "Chikamagalur". "Shimoga".vtuprojects. // Set the list selection mode to single selection. "Kolar". JLabel label.swing. Mr. import java. // Add the list to a scroll pane. public void init() { render().*.*.www.// Create a JList. scrollpane = new JScrollPane(list). "Mysore".awt. JScrollPane scrollpane. import javax.setSelectionMode(ListSelectionModel. 4. setLayout(new FlowLayout()). @SuppressWarnings("serial") public class Example extends JApplet { JList<Object> list.SINGLE_SELECTION). String Cities[] = { "Bangalore". Registration started. "Madikeri". Ashok Kumar K | 9742024066 | celestialcluster@gmail. "Dakshina Kannda".com . "Belgaum" }. Example import javax.com | Final year IEEE project development and training from scratch by Mr.event. } private void render() { // Change to flow layout. // Create an array of cities. "Mandya". list = new JList<Object>(Cities). Contact 9742013378 or 9742024066 and lock your project at the earliest. "Gulbarga". vtuprojects. label = new JLabel("Choose a City").event.*. Example import java. Mr. A combo box normally displays one entry. else // Otherwise. // Display selection.swing. } }). list.14 JComboBox Description JComboBox is a combination of a text field and a drop-down list.www.*. label.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent le) { // Get the index of the changed item. // Set the preferred size of the scroll pane. // Make a label that displays the selection. add(label). import java. int idx = list.com | Final year IEEE project development and training from scratch by Mr.com . if item was selected. reprompt.setPreferredSize(new Dimension(120. add(scrollpane). // Add selection listener for the list. if (idx != -1) label. Ashok Kumar K | 9742024066 | celestialcluster@gmail. but it will also display a drop- down list that allows a user to select a different entry. Registration started.*.awt. import javax.setText("Current selection: " + Cities[idx]). // Add the list and label to the content pane.setText("Choose a City"). } } Output 4.getSelectedIndex(). scrollpane.awt. Contact 9742013378 or 9742024066 and lock your project at the earliest. 90)). Ashok Kumar K. label.15 JTable Mr.png")).com . public void init() { render(). Ashok Kumar K.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String s = (String) comboBox. "jmaster" }.com | Final year IEEE project development and training from scratch by Mr. // Create a label and add it to the content pane. setLayout(new FlowLayout()). add(comboBox). } } Output 4.www.setIcon(new ImageIcon(s + ". comboBox = new JComboBox<Object>(flags). comboBox. @SuppressWarnings("serial") public class Example extends JApplet { JLabel label. // Instantiate a combo box and add it to the content pane.vtuprojects.png")). Contact 9742013378 or 9742024066 and lock your project at the earliest. String flags[] = { "aklc".getSelectedItem(). add(label). Registration started. } private void render() { // Change to flow layout. // Handle selections. JComboBox<Object> comboBox. label = new JLabel(new ImageIcon("aklc. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } }). Ashok Kumar K | 9742024066 | celestialcluster@gmail. or cell within the table.swing.  Add the table to the scroll pane  Add the scroll pane to the content pane. You can also drag a column to a new position. "Female" }. Description JTable is a component that displays rows and columns of data.vtuprojects. "Name". /* <applet code="JTableDemo" width=400 height=200> </applet> */ @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render(). Object[][] data = { { 7. JTable table = new JTable(data. // Add the scroll pane to the content pane. "Gender" }.*. it is also possible to select a row. // Initialize data. "Manoj". and to change the data within a cell. { 9. } private void render() { // Initialize column headings. specifying the table as the object to scroll. } } Output Mr. Depending on its configuration. "Ashok". column. Contact 9742013378 or 9742024066 and lock your project at the earliest.  Create a JScrollPane object. "Male" }. Example import javax. "Female" } }.  Create an instance of JTable.com | Final year IEEE project development and training from scratch by Mr.www. String[] colHeads = { "USN". { 12.com . JScrollPane jsp = new JScrollPane(table). Steps to setup a simple JTable. Ashok Kumar K. "Vidya". // Add the table to a scroll pane. "Rekha". { 44. colHeads). "Male" }. add(jsp). Registration started. You can drag the cursor on column boundaries to resize columns. a VTU 7th sem B. Ashok Kumar K 9742024066 | [email protected] .E (CSE/ISE) JAVA/ J2EE Notes prepared by Mr. the application will be deployed in a centralized sever. Ashok Kumar K. J2SE (Java to Standard Edition) is a Java platform designed for standalone applications. Contact 9742013378 or 9742024066 and lock your project at the earliest. IPADs. if you want to run a standalone application in a client’s machine. Example: Games (which requires installations). Mobile applications These are the application developed for hand held devices like PDAs. J2EE (Java to Enterprise Edition) is a Java platform designed for Web applications or server side applications. Registration started.com | Final year IEEE project development and training from scratch by Mr. Server processes multiple clients’ request and makes a response to each client request. etc. Ashok Kumar K | 9742024066 | celestialcluster@gmail. INTRODUCTION TO J2EE There are three kinds of applications we can think of 1. mobile phones..vtuprojects.com . Instead. IPODs. J2ME (Java to Micro Edition) is a Java platform designed for Mobile applications. else the application is not runnable. Web applications Here it is not required for the code to be present in every client’s machine.` Mr.e. 3. GTalk.www. etc 2. i. Standalone applications Standalone applications are those which works based on “where you write the code is where you run the code”. whereas the clients makes a request to access this application through a web browser. you need to have the code residing in that machine. Contact 9742013378 or 9742024066 and lock your project at the earliest. Example for Web tier component would be a servlet. the business logic is delegated to the next tier. They provide the application’s data to the upper tiers upon making a request. Ashok Kumar K.vtuprojects. Due to security perspective and other issues. J2EE Multi-tier Architecture J2EE is a multi-tier architecture (four layered architecture). Database tier The components in this tier are responsible for storing the application’s data. Example for client tier component would be a HTML page. Example for business logic tier component would be a EJB (Enterprise Java Bean). Example: MySQL. Registration started.com . etc Web tier Web tier component receives the request from the client tier component and forwards the request to the appropriate business logic tier to process it. and Sybase database. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Oracle. Business logic tier The components in this tier are responsible for implementing the core business logic for the request from client tier. The layers are named as follows:  Client tier  Web tier  Business logic tier  Database tier Client tier Any component that is capable of initiating a request to the server is said to sit in the client tier of the J2EE architecture. DB2. browser. It might make a connection to the fourth tier to perform various database operations.com | Final year IEEE project development and training from scratch by Mr. Mr.www. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Ashok Kumar K 9742024066 | celestialcluster@gmail. Registration started.www.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.com Mr.vtuprojects. Unit 5: Java to Data Base Connection (JDBC) Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest.com . www. No prerequisites required. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Study Materials We provide the most efficient study material for each and every module during the project development 4. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. 15 reasons to choose VTUPROJECTS. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 6. He will be having a thorough experience in working on both product and service driven industries. 10. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same.COM for your final year project work 1. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Ashok Kumar K. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed Mr.vtuprojects. 3. we will be helping out them through Skype/ Team viewer screen sharing 12. 15. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns.com . 2. 13. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. Registration started. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Skype/ Team viewer support In case the student needs an emergency help when he/she is in their colleges. Contact 9742013378 or 9742024066 and lock your project at the earliest.com | Final year IEEE project development and training from scratch by Mr. 5. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Ashok Kumar K | 9742024066 | celestialcluster@gmail. JDBC Components JDBC project by Javasoft comprises of two things: JDBC APIs and JDBC Driver JDBC APIs JDBC APIs are the library functions that performs common tasks associated with database usage like: Opening/ Closing the connection with the database.1 Basics Definition JDBC (Java Database Connectivity) is an API for the Java programming language that defines how a client may access the database. These drivers use a native client library specific to the data source to which they connect.vtuprojects. Ashok Kumar K.1 (Feb 19. Ashok Kumar K | 9742024066 | celestialcluster@gmail. These implementations are categorized as follows: Type 1 JDBC Driver: These drivers implement the JDBC API as a mapping to another data access API. Example: The JDBC-ODBC Bridge. 5. 5. 1997) and was developed by a team named Javasoft of Sun Microsystems.sql package. such as ODBC (Open Database Connectivity). because of the native code. Registration started. their portability is limited.2 JDBC Drivers There are many possible implementations of JDBC drivers.www. Executing that SQL queries in the database. JDBC classes are present in java. which limits their portability. Example: Oracle's OCI (Oracle Call Interface) client-side driver. JDBC is oriented towards relational databases. Mr. Type 2 JDBC Driver: These drivers are written partly in the Java programming language and partly in native code. Again.com . Drivers of this type are generally dependent on a native library. and Viewing & Modifying the resulting records JDBC Driver A JDBC driver is a software component enabling a Java application to interact with a database. Creating SQL statements. It is the actual implementation of the defined interfaces in the JDBC API for interacting with your database server. History JDBC was a part of JDK 1.com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. It provides methods for querying and updating data in a database. Ashok Kumar K | 9742024066 | [email protected]. or some other source of data with a corresponding JDBC driver. Mr. Step 1: Load the Driver Here you should load and initialize the class representing the MySQL JDBC Driver. The middleware server then communicates the client's requests to the data source. username. Ashok Kumar K.getConnection ("jdbc:mysql://localhost:3306/College". password) throws SQLException url is the path to the database username and password are the credentials to the database. Registration started. Sample code snippet is given below: Connection con = null. a legacy file system. The code snippet to do this is given below: try { Class. It is optional.println("Couldn't load the Driver"). We use the static getConnection() method in DriverManager class to get the connection. } Step 2: Establish the Connection Next. } catch (ClassNotFoundException e) { System. you need to establish a connection with the data source you want to use. try { con = DriverManager. 5. A data source can be a DBMS. "lordshiva").mysql.com . The client connects directly to the data source.com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. Type 3 JDBC Driver: These drivers use a pure Java client and communicate with a middleware server using a database-independent protocol.vtuprojects.www.3 JDBC Process Brief Overview of JDBC Process There are five steps in the JDBC process for a Java program to communicate with the database. "root". Its syntax is shown below: static Connection getConnection (url.forName("com.jdbc. Let's see them in brief and later elaborate each step. Type 4 JDBC Driver: These drivers are pure Java and implement the network protocol for a specific data source.Driver"). println(id + "\t" + name + "\t" + age + "\t" + aggregate).println("Error while closing the connection"). Contact 9742013378 or 9742024066 and lock your project at the earliest.println("Couldn't Obtain the connection").out. This releases the external resources like cursor.out. int age. } catch (SQLException e) { System. } Step 3: Create the SQL Statement and Execute the SQL Query 3a. PreparedStatement. 3b.com | Final year IEEE project development and training from scratch by Mr. while (rs. name.createStatement(). Ashok Kumar K.out. } catch (SQLException e) { System.) Executing the query Once the statement is ready. } Mr. Statement st = null. rs = st. String qry = "select * from student".println("Error while processing SQL results"). Here we use createStatement() method of Connection class to create the simple Statement. We should iterate over each record (or row) in order to print it in the console as demonstrated below: try { String id. you can execute the SQL query using executeQuery() method as demonstrated in the below code snippet. Statement object can be either Statement. Typically.getString("name"). Registration started.getInt("age").) Creating the query You should obtain any of the Statement object in order to execute the query. closing the connection should be done in the finally block. Ashok Kumar K | 9742024066 | [email protected]()) { id = rs. try { st = con.www.out. A ResultSet object contains zero or more records (or rows). name = rs.vtuprojects.close(). } Step 4: Process the result set The output of the SQL query will be encapsulated in ResultSet object.com . } Step 5: Close the connection At last.getString("id"). } catch (Exception e) { System. ResultSet rs = null.out. try { con. } } catch (SQLException e) { System. a very important step of all is to close the database connection.println("Error while processing SQL query").getDouble("aggr"). double aggregate. or CallableStatement which will be explained later. age = rs. System.executeQuery(qry). handlers etc. It returns a ResultSet object. aggregate = rs. the DriverManager class manages the establishment of Connections.4 Loading the JDBC Driver When you are using JDBC outside of an application server.Driver").jdbc. } catch (SQLException e) { System. the Java component can now obtain a connection to the external database associated with the driver.out. With MySQL. To do this.out.com | Final year IEEE project development and training from scratch by Mr.Driver interface.  subname: It is the name of the database. try { Class.jdbc. Contact 9742013378 or 9742024066 and lock your project at the earliest. "root".getConnection ("jdbc:mysql://localhost:3306/College".  subprotocol: It is the JDBC driver name. 5.  jdbc: It is the protocol being used.Driver. The easiest way to do this is to use Class. Registration started. Example: Connection con = null.Driver) is available in the classpath so that it can be loaded and initialized by the JVM.www.5 Establishing the Connection Concept Once the JDBC driver has been loaded and initialized. Ashok Kumar K.forName("com.jdbc. You should specify to the DriverManager which JDBC drivers it should try to make Connections with.println("Couldn't Obtain the connection"). the name of this class is com.  url: a database url of the form jdbc:subprotocol:subname  user: the database user on whose behalf the connection is being made  password: the user's password It returns a Connection object.println("Couldn't load the Driver").mysql.mysql.mysql. } Passing additional parameters for authentication Mr. user. "lordshiva").vtuprojects. password) throws SQLException Here. try { con = DriverManager.com . url is made of three components. 5. you must invoke getConnection() method of DriverManager class passing three arguments as shown in the syntax below: static Connection getConnection (url.sql.forName() on the class that implements the java. } catch (ClassNotFoundException e) { System. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } Make sure that the driver class (com. Some databases would require additional details other than username and password to grant the access to the database. To avoid this indefinite delay. stmt = con. props. Contact 9742013378 or 9742024066 and lock your project at the earliest.println("Couldn't Obtain the connection"). you can use setoginTimeout() method in DriverManager class whose syntax is given below: public static void setLoginTimeout(int seconds) Likewise. and they generate ResultSet objects. You need a Connection object to create a Statement object. Its syntax is shown below: public static int getLoginTimeout() 5. Ashok Kumar K. props). Properties props = new Properties(). try { FileInputStream fis = new FileInputStream( new File("DBProps. For example. } catch (FileNotFoundException e) { e.vtuprojects. } catch (SQLException e) { System. con = DriverManager. there are possibilities where the DBMS may not respond to it due to various reasons.com .getConnection( "jdbc:mysql://localhost:3306/college". To set the timeout period. There are three different kinds of statements: Statement: Used to implement simple SQL statements with no parameters. In this case.txt") ). The question here is how would you provide these additional propertied to DriverManager's getConnection() method. Ashok Kumar K | 9742024066 | [email protected]().com | Final year IEEE project development and training from scratch by Mr. the J2EE component will wait indefinitely till the DBMS responds to it. You execute Statement objects. Mr. you can use getLoginTimeout() method to retrieve the current timeout period that has been set. you can set a timeout period after which the DriverManager will stall (cancel) the attempt to connect to the DBMS. CallableStatement: (Extends PreparedStatement) Used to execute stored procedures that may contain both input and output parameters.createStatement(). Registration started. These input parameters will be given a value in the runtime. PreparedStatement: (Extends Statement) Used for precompiling SQL statements that might contain input parameters. } Setting Timeout Whenever a J2EE component requests connection with the external database.load(fis).out.www. This additional information must be associated with a Properties object which is passed as an argument in getConnection() method.printStackTrace(). which is a table of data representing a database result set.6 Statements in JDBC A Statement is an interface that represents a SQL statement. Example: Connection con = null. } catch (IOException e) { e. out. "lordshiva").executeQuery(qry).out. age = rs. Connection con = null.jdbc. an INSERT. it returns false..getString("name").println("\n\nDeleting those students having lesser than 35% Mr. try { Class.com .getInt("age").println(id + "\t" + name + "\t" + age + "\t" + aggregate). you need to create one using the Connection object's createStatement() method. } catch (SQLException e) { e. ResultSet rs = null.Driver"). Use this method when you expect to get a result set. as in the following example: Statement st = null.*. otherwise. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. } Once you've created a Statement object. System.out.  ResultSet executeQuery(String SQL) : Returns a ResultSet object. as you would with a SELECT statement. Use this method to execute SQL statements for which you expect to get a number of rows affected .getDouble("aggr"). UPDATE. String id. try { st = con. Statement The Statement object is used whenever a J2EE component needs to immediately execute a query without first having the query compiled. Registration started. while (rs. or DELETE statement.for example. } System.next()) { id = rs.getString("id"). for the same reason you should also close the Statement object. "root". Just as you close a Connection object to save database resources.sql. rs = st. con = DriverManager. int age. you can then use it to execute a SQL statement with one of its three execute methods.com | Final year IEEE project development and training from scratch by Mr. System. Before you can use a Statement object to execute a SQL statement.println("Table Data are as follows .forName("com. Ashok Kumar K | 9742024066 | celestialcluster@gmail. \n"). st = con. aggregate = rs.www.vtuprojects.  int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL statement. String qry = "select * from student".createStatement().getConnection("jdbc:mysql://localhost:3306/college". A simple call to the close() method will do the job. name.mysql. double aggregate. public class Example { public static void main(String arg[]) { Statement st = null.printStackTrace(). name = rs. Ashok Kumar K.createStatement(). Example: import java. Contact 9742013378 or 9742024066 and lock your project at the earliest.  boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved. Ashok Kumar K. If you forget to supply the values. ").close(). The PreparedStatement interface extends the Statement interface which gives you added functionality.out.setString(1.. } } } } Output: PreparedStatement The PreparedStatement is used to compile the query first before executing it. The first marker represents position 1.println(rows + " rows deleted .printStackTrace().com . Registration started.executeUpdate(qry2).vtuprojects.prepareStatement(qry). and executeUpdate() also work with the PreparedStatement object. aggregate . } catch (Exception e) { e. where XXX represents the Java data type of the value you wish to bind to the input parameter.www. int rows = st. ps. Example PreparedStatement ps = null. "1VK06IS009"). try { String qry = "update student set name=? where id=?". However. } finally { try { st. String qry2 = "delete from student where aggr < 35".\n"). Contact 9742013378 or 9742024066 and lock your project at the earliest.execute(). which is known as the place holder. ps. System. the methods are modified to use SQL statements that can take input the parameters.com | Final year IEEE project development and training from scratch by Mr. the next position 2. } catch (Exception e) { e. and so forth.. This statement gives you the flexibility of supplying input arguments dynamically. Ashok Kumar K | 9742024066 | celestialcluster@gmail. executeQuery(). Each parameter marker is referred to by its ordinal position. ps = con. } catch (SQLException e) { Mr. You must supply values for every parameter before executing the SQL statement. The setXXX() methods bind values to the parameters. All of the Statement object's methods for interacting with the database: execute(). ps..close(). "Ashok Kumar").setString(2. con.printStackTrace(). you will receive an SQLException. All parameters (arguments) are represented by the ? symbol. System. Types. for the same reason you should also close the PreparedStatement object. Ashok Kumar K. The stored procedure is a block of code and is identified by a unique name.com .com | Final year IEEE project development and training from scratch by Mr. A simple call to the close() method will do the job. try { String qry = "{CALL getStudName (?.  OUT: A parameter whose value is supplied by the SQL statement it returns. Registration started. cs.close().prepareCall(qry). String name = cs.println("Student name is .VARCHAR).getString(2).out.printStackTrace(). Ashok Kumar K | 9742024066 | [email protected](1. You bind values to IN parameters with the setXXX() methods. } catch (Exception e) { e.?) }". Contact 9742013378 or 9742024066 and lock your project at the earliest. "+name). } } Just as you close a Statement object. C. The stored procedure can be written in PL/SQL. "1VK06IS009"). Here is the simple MySQL stored procedure: CREATE OR REPLACE PROCEDURE getStudName (STUD_ID IN VARCHAR. e. CallableStatement CallableStatement object is used to execute a call to the stored procedure from within a J2EE object. You should register this parameter using registerOutParameter() method. You bind variables with the setXXX() methods and retrieve values with the getXXX() methods.registerOutParameter(2. } finally { try { ps.execute(). } catch (Exception e) { e.printStackTrace(). cs = con. Here three types of parameters exist:  IN: A parameter whose value is unknown when the SQL statement is created.printStackTrace(). STUDENT_NAME OUT VARCHAR) AS BEGIN SELECT name INTO STUDENT_NAME FROM Student WHERE ID = STUD_ID.www. cs.. or another programming language. Example CallableStatement cs = null.vtuprojects. Transact-SQL. END. } finally { try { Mr. You retrieve values from the OUT parameters with the getXXX() methods. cs.  INOUT: A parameter that provides both input and output values. Ashok Kumar K | 9742024066 | celestialcluster@gmail. cs.VARCHAR). ps.setString(2. PreparedStatement.createStatement(). cs. "1VK06IS009"). getStudName (?.com . There are various methods in the ResultSet interface. for the same reason you should also close the CallableStatement object.com | Final year IEEE project development and training from scratch by Mr. Registration started. and CallableStatement in brief Statement PreparedStatement CallableStatement The Statement object is used whenever a The PreparedStatement is used to CallableStatement object is used J2EE component needs to immediately compile the query first before to execute a call to the stored execute a query without first having the query executing it.vtuprojects. These methods can be grouped into three categories as follows  Get methods: used to view the data in the columns of the current row being pointed by the virtual cursor. "1VK06IS009"). "Ashok cs. procedure from within a J2EE object compiled No input/ output arguments can be supplied Input arguments can be supplied Both input and output arguments can dynamically be supplied dynamically createStatement() method of Connection prepareStatement() method of prepareCall() method of object is used to get the Statement object.  Navigational methods: used to move the virtual cursor around the virtual table.?) }".www. The virtual cursor is initially positioned above the first row of data when the ResultSet is returned by executeQuery() method. A ResultSet object maintains a virtual cursor that points to a row in the result set. Statement st = con. A simple call to the close() method will do the job. Contact 9742013378 or 9742024066 and lock your project at the earliest. } } Just as you close other Statement object. ps. Kumar").prepareCall(qry).  Update methods: used to update the data in the columns of the current row. 5. cs.setString(1.7 ResultSet in JDBC As you know. String qry = "update student String qry = "{CALL set name=? where id=?".registerOutParameter(2.printStackTrace(). Types.setString(1. The term "result set" refers to the virtual table of row and column data contained in a ResultSet object. CallableStatement object. the executeQuery() method is used to send the query to the DBMS and returns a ResultSet object that contains data that was requested by the query. Example: Example: Example: String qry = "select * from student".close(). con. Difference between Statement. Mr.prepareStatement(qry). } catch (Exception e) { e.executeQuery(qry). PreparedStatement ps = CallableStatement cs = rs = st. con. ps. Connection object is used to get the Connection object is used to get the PreparedStatement object.execute().execute(). Ashok Kumar K. name.printStackTrace().jdbc. Example: import java. Reading the ResultSet using Get methods There is a get method in ResultSet interface for each of the possible data types of the form getXXX() where XXX is the data type of the column.out.executeQuery(qry). Contact 9742013378 or 9742024066 and lock your project at the earliest. st = con. ResultSet rs = null.forName("com. Example: String name = rs. rs = st. Ashok Kumar K. con = DriverManager. Statement st = null.getString(2).www.vtuprojects.getString("name").Driver").println(id + "\t" + name + "\t" + age + "\t" + aggregate).com | Final year IEEE project development and training from scratch by Mr.getConnection ("jdbc:mysql://localhost:3306/college".sql. and each get method has two versions:  One that takes in a column name Example: String name = rs.*.getDouble(4).getInt("age"). String id. aggregate = rs. "lordshiva"). age = rs.getString("id"). Ashok Kumar K | 9742024066 | [email protected]. name = rs. System.createStatement(). } } catch (Exception e) { e. public class Example { public static void main(String arg[]) { try { Class.getString(1).next()) { id = rs. int age. while (rs. double aggregate. "root". Connection con = null.  One that takes in a column index. Registration started. } } } Output: Mr. String qry = "select * from student".com . Scrollable ResultSet Types of ResultSet Type of ResultSet Meaning ResultSet.CONCUR_UPDATABLE). You should pass this as an argument to createStatement() or preparedStatement() method. Contact 9742013378 or 9742024066 and lock your project at the earliest. Mr. st=con. Registration started.www. This is the default. They are: public void beforeFirst() throws SQLException 1 Moves the cursor to the front of this ResultSet object.TYPE_SCROLL_INSENSITIVE The cursor can scroll forwards and backwards.com . Concurrency of ResultSet Rows contained in ResultSet's virtual table can either be read only or be updatable.ResultSet. public void afterLast() throws SQLException 2 Moves the cursor to the end of this ResultSet object.TYPE_SCROLL_SENSITIVE The cursor can scroll forwards and backwards. This method has no effect if the result set contains no rows. This method has no effect if the result set contains no rows. Example 2: Statement st = null. Ashok Kumar K. st=con. You should specify one of the type of ResultSet while creating a Statement object.CONCUR_READ_ONLY Creates a read-only result set. Ashok Kumar K | 9742024066 | celestialcluster@gmail. This is the default.vtuprojects.ResultSet.CONCUR_UPDATABLE Creates an updateable result set Example 1: Statement st = null.com | Final year IEEE project development and training from scratch by Mr.createStatement(ResultSet. If you don't specify anything. and the result set is sensitive to changes made by others to the database that occur after the result set was created. Scrolling a ResultSet There are several methods in the ResultSet interface that involve moving the cursor. ResultSet concurrency Meaning ResultSet. This selection can be made by passing either one of the below as an argument to createStatement() or preparedStatement() method. just before the first row.CONCUR_UPDATABLE). public boolean first() throws SQLException 3 Moves the cursor to the first row in this ResultSet object public void last() throws SQLException 4 Moves the cursor to the last row in this ResultSet object. ResultSet. just after the last row.TYPE_FORWARD_ONLY The cursor can only move forward in the result set. ResultSet. ResultSet. the default one will be TYPE_FORWARD_ONLY.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE. and the result set is not sensitive to changes made by others to the database that occur after the result set was created.TYPE_SCROLL_INSENSITIVE. The first row is number 1. public boolean previous() throws SQLException Moves the cursor to the previous row in this ResultSet object.getConnection("jdbc:mysql://localhost:3306/college". the cursor is positioned before the first row. Ashok Kumar K. Registration started. public boolean next() throws SQLException Moves the cursor froward one row from its current position. the cursor moves to the given row number with respect to the beginning of the result set. It is essentially a buffer where a new row may be constructed by calling the updater methods prior to inserting the row into the result set public void moveToCurrentRow() throws SQLException 11 Moves the cursor to the remembered cursor position. public int getRow() throws SQLException 9 Retrieves the current row number. either positive or negative. If an input stream is open for the current row. 7 When a call to the previous method returns false. Here is the code snippet to test whether a driver supports a scrollable ResultSet try { Class. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. Ashok Kumar K | 9742024066 | celestialcluster@gmail. public void moveToInsertRow() throws SQLException 10 Moves the cursor to the insert row. The current cursor position is remembered while the cursor is positioned on the insert row. For example. A ResultSet cursor is initially positioned before the first row.Driver"). Mr. Attempting to move beyond the first/last row in the result set positions the cursor before/after the first/last row. but does not change the cursor position.jdbc. This method has no effect if the cursor is not on the insert row. and so on. usually the current row. the second number 2. the first call to the method next makes the first row the current row. "lordshiva"). The first row is row 1. Calling relative(0) is valid. If the row number is positive. and so on. Contact 9742013378 or 9742024066 and lock your project at the earliest. the cursor moves to an absolute row position with respect to the end of the result set. Note 1: Not all the Drivers are scrollable. An attempt to position the cursor beyond the first/last row in the result set leaves the cursor before the first row or after the last row. a call to the method previous will implicitly close it. The insert row is a special row associated with an updatable result set.com . and so on. the second call makes the second row the current 8 row. and so on. calling the method absolute(-1) positions the cursor on the last row. public boolean relative(int row) throws SQLException 6 Moves the cursor a relative number of rows. 5 If the given row number is negative. public boolean absolute(int row) throws SQLException Moves the cursor to the given row number in this ResultSet object. "root". Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.www. calling the method absolute(-2) moves the cursor to the next-to-last row.com | Final year IEEE project development and training from scratch by Mr. When a call to the next method returns false. A ResultSet object's warning change is cleared when a new row is read. the cursor is positioned after the last row. con = DriverManager.mysql. the second is row 2.vtuprojects.forName("com. Connection con = null. " +dbmeta..println("Supports TYPE_FORWARD_ONLY ? .jdbc. "Ashoka").supportsResultSetType(ResultSet.out. public void deleteRow() Deletes the current row from this ResultSet object and from the underlying database..getConnection("jdbc:mysql://localhost:3306/college".TYPE_SCROLL_SENSITIVE)). "lordshiva"). Registration started. Updating a row in the result set changes the columns of the current row in the ResultSet object (virtual table). "root". System.getMetaData(). This method cannot be called when the cursor is on the insert row. Connection con = null.forName("com. Statement st = con.mysql.out.TYPE_FORWARD_ONLY))..com . rs. con = DriverManager. As with the get methods.supportsResultSetType(ResultSet.printStackTrace(). " +dbmeta. you need to invoke one of the following methods. To update your changes to the row in the database. st. ResultSet rs = st. where XXX is the data type of the column:\  One that takes in a column name.println("Supports TYPE_SCROLL_SENSITIVE ? . System. Example.com | Final year IEEE project development and training from scratch by Mr. } Note 2: Setting the maximum number of rows returned in a ResultSet try { Class. This method cannot be called when the cursor is on the insert row. rs. Ashok Kumar K | 9742024066 | [email protected]("Supports TYPE_SCROLL_INSENSITIVE ? .TYPE_SCROLL_INSENSITIVE)).createStatement(). Ashok Kumar K. } catch (Exception e) { e.updateString("Name". public void updateRow() Updates the underlying database with the new contents of the current row of this ResultSet object.out.setFetchSize(200). " +dbmeta.www. Contact 9742013378 or 9742024066 and lock your project at the earliest.Driver").updateString(2. but not in the underlying database.  One that takes in a column index. "Ashoka"). Example. System.. Mr.vtuprojects. } catch (Exception e) { e. } Updating a ResultSet The ResultSet interface contains a collection of update methods for updating the data of a result set. DatabaseMetaData dbmeta = con.printStackTrace(). there are two updateXXX() methods for each data type.executeQuery("select * from student").supportsResultSetType(ResultSet. Any data written to the database must be valid according to all defined rules. } } 2. this method has no effect. including but not limited to constraints.vtuprojects. while (rs. public void refreshRow() Refreshes the current row with its most recent value in the database.8 Database Transaction Concept and Definition A Database Transaction consists of a set of SQL statements.deleteRow().getString("name").getString("name"). This method cannot be called when the cursor is on the insert row.com | Final year IEEE project development and training from scratch by Mr. A database transaction. consistent. To the outside world. "Ashok Kumar"). including power failures.next()) { if (rs. If one fails. cascades. Ashok Kumar K.equals("Prasad")) { rs. Examples: 1. isolated and durable. each of which must be successfully completed for the transaction to be completed.com . Registration started. public void insertRow() Inserts the contents of the insert row into this ResultSet object and into the database. the entire transaction fails. and any combination thereof.updateRow().www. triggers. The cursor must be on the insert row when this method is called. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Updating the ResultSet rs = st.  Atomicity: Atomicity requires that each transaction is "all or nothing": if one part of the transaction fails. An atomic system must guarantee atomicity in each and every situation. SQL statements that executed successfully up to that point in the transaction must be rolled back.equals("Ashok")) { rs. and crashes. while (rs. by definition. If no updates have been made or updateRow has already been called. public void cancelRowUpdates() Cancels the updates made to the current row in this ResultSet object.next()) { if (rs. Mr. and the database state is left unchanged. errors. a committed transaction appears (by its effects on the database) to be indivisible ("atomic").executeQuery(qry). This method may be called after calling an updater method(s) and before calling the method updateRow to roll back the updates made to a row. Deleting a Row rs = st.  Consistency: The consistency property ensures that any transaction will bring the database from one valid state to another.executeQuery(qry). rs.. and an aborted transaction does not happen.updateString("name". } } 5. must be atomic. Database practitioners often refer to these properties of database transactions using the acronym ACID. Contact 9742013378 or 9742024066 and lock your project at the earliest. Driver"). then the auto commit feature should be turned off. This is because of the auto commit feature of the database connection. commit() and rollback() methods A database transaction isn't completed until the J2EE component calls the commit() method of the Connection object. Below program executes two SQL queries. String qry1 = "update student set aggr=86. import java. none of the SQL statements can be rolled back.*. Connection con = null. con = DriverManager. Each SQL statement will be executed separately and a commit() method is called upon success. This can be done as follows: try { Class. even in the event of power loss. Most modern relational database management systems fall into the category of databases that support transactions. Contact 9742013378 or 9742024066 and lock your project at the earliest. try { Class.Driver"). con = DriverManager. } catch (Exception e) { e. To defend against power loss. Mr. Depending on concurrency control method.getConnection ("jdbc:mysql://localhost:3306/college". age=25 where id='1VK06IS009' ". Statement st1 = null. The commit() method must be called regardless if the SQL statement is part of a transaction or not.com . the results need to be stored permanently (even if the database crashes immediately thereafter). if any of the statement fails (throws an exception).mysql.  Isolation: The isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed serially. Providing isolation is the main goal of concurrency control. Registration started. A Transactional database is a DBMS where write transactions on the database are able to be rolled back if they are not completed properly (e. public class Example { public static void main(String arg[]) { Connection con = null. for instance. con. one after the other.www.e. Till now.g. or errors. crashes. However.forName("com.sql. the effects of an incomplete transaction might not even be visible to another transaction  Durability: Durability means that once a transaction has been committed. i. Ashok Kumar K | 9742024066 | [email protected]. "lordshiva"). we never issued a commit() on the database but still we were able to save the data in the database. once a group of SQL statements execute.printStackTrace().mysql.vtuprojects. "root".com | Final year IEEE project development and training from scratch by Mr. "root". In a relational database.getConnection("jdbc:mysql://localhost:3306/college". Ashok Kumar K. transactions (or their effects) must be recorded in a non-volatile memory. All SQL statements executed prior to the call to the commit() method can be rolled back. "lordshiva"). If a J2EE component is implementing a transaction.setAutoCommit(false). Statement st2 = null. both of which update the student's aggregate and age. con. once the commit() method is called. the transaction is rolled back by invoking rollback() method in the catch clause. due to power or connectivity loss).jdbc. it will remain so. } Let's see a simple transaction processing example.jdbc. However.setAutoCommit(false).forName("com. www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. String qry2 = "update student set aggr=71.13, age=27 where id='1VK04IS034' "; st1 = con.createStatement(); st2 = con.createStatement(); st1.execute(qry1); st2.execute(qry2); System.out.println("Transaction success .."); con.commit(); } catch (Exception e) { System.out.println("Transaction failed .."); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { st1.close(); st2.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } } } Using savepoints A transaction may consist of many tasks, some of which don't need to be rolled back when the transaction fails. The J2EE component can control the number of tasks that are rolled back by using savepoints. A savepoint is a virtual marker that defines the task at which the rollback stops. When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint. Example, Here we execute two SQL statements. After executing one SQL statement, a savepoint is set. The transaction is rolled back till this savepoint after executing both the statements. Thus only second SQL statement will be rolled back and the first SQL statement will be committed. import java.sql.*; public class Example { public static void main(String arg[]) { Connection con = null; Statement st1 = null; Statement st2 = null; try { Class.forName("com.mysql.jdbc.Driver"); Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. con = DriverManager.getConnection "jdbc:mysql://localhost:3306/college", "root", "lordshiva"); con.setAutoCommit(false); String qry1 = "insert into student values ('1VK08IS026', 'Naveen', 23, 46.8)"; String qry2 = "update student set aggr=86.17, age=25 where id='1VK06IS009' "; st1 = con.createStatement(); st2 = con.createStatement(); st1.execute(qry1); Savepoint sp1 = con.setSavepoint(); st2.execute(qry2); con.rollback(sp1); con.releaseSavepoint(sp1); System.out.println("Transaction success .."); con.commit(); } catch (Exception e) { System.out.println("Transaction failed .."); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { st1.close(); st2.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } } } Batching SQL statements Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance. The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together. The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement. A value of -1 indicates the failure of update statement. Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove Example import java.sql.*; public class Example { public static void main(String arg[]) { Connection con = null; Statement st1 = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/college", "root", "lordshiva"); con.setAutoCommit(false); String qry1 = "update student set aggr=86.17, age=25 where id='1VK06IS009' "; String qry2 = "update student set aggr=71.17, age=27 where id='1JB04IS034' "; String qry3 = "update student set aggr=42.55, age=23 where id='1VK08IS026' "; st1 = con.createStatement(); st1.addBatch(qry1); st1.addBatch(qry2); st1.addBatch(qry3); st1.executeBatch(); st1.clearBatch(); System.out.println("Transaction success .."); con.commit(); } catch (Exception e) { System.out.println("Transaction failed .."); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { st1.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } } } Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest. 5.9 Meta Data There are two types of metadata that can be retrieved from the DBMS.  DatabaseMetaData which is the data about the database  ResultSetMetaData which is the data about the Result Set DatabaseMetaData Meta data is the data about the data. A J2EE component can access the metadata by using the DatabaseMetaData interface. It is used to retrieve information about databases, tables, column, indexes, etc. getMetaData() method of Connection object is used to retrieve the metadata about the database. Here are some of the methods available in DatabaseMetaData interface: getDatabaseProductName(): Returns the product name of the DBMS getUserName(): Returns the username getURL(): Returns the URL for the database. getSchemas(): Returns all the schema names available in this database getPrimaryKeys(): Returns primary keys getProcedures(): Returns stored procedure names getTables(): Returns names of tables in the database Example import java.sql.*; public class Example { public static void main(String arg[]) { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/college", "root", "lordshiva"); DatabaseMetaData dbmetadata = con.getMetaData(); System.out.println("Database product name: .. " +dbmetadata.getDatabaseProductName()); System.out.println("Database user name: .. " +dbmetadata.getUserName()); System.out.println("Database URL: .. "+dbmetadata.getURL()); } catch (Exception e) { e.printStackTrace(); } finally { try { con.close(); } catch (Exception e) { e.printStackTrace(); } } } } Output: Mr. Ashok Kumar K | 9742024066 | [email protected] getColumnName(1)). } catch (Exception e) { e. getMetaData() method of the ResultSet object can be used to retrieve the Result set metadata. Ashok Kumar K | 9742024066 | [email protected](). " +rsmetadata. st = con..close()..vtuprojects.printStackTrace().getConnection ("jdbc:mysql://localhost:3306/college". try { Class. } finally { try { st. ResultSet rs = st. ResultSetMetaData rsmetadata = rs.forName("com. con = DriverManager.println("First Column name : .jdbc.getColumnCount()). Contact 9742013378 or 9742024066 and lock your project at the earliest.*. String qry = "select * from student".Driver"). Registration started.mysql.com | Final year IEEE project development and training from scratch by Mr.out. getColumnName(int number): Returns the name of the column specified by the column number.sql. System.createStatement(). con. System.close(). The most commonly used methods in ResultSetMetaData interface are: getColumnCount(): Returns the number of columns obtained in the ResultSet.www. ResultSetMetaData ResultSetMetaData interface describes the Result set (virtual database).getMetaData(). "root". public class Example { public static void main(String arg[]) { Connection con = null. Ashok Kumar K. " +rsmetadata. getColumnType(int number): Returns the data type of the column specified by the column number Example import java.out.executeQuery(qry). } catch (Exception e) { e. Statement st = null.println("Column count: . "lordshiva"). } } } } Output: Mr.com . com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest.com .10 Exceptions There are three kinds of exceptions that are thrown by JDBC methods.  SQLException: It commonly reflects a syntax error in the query and is thrown by many of the methods contained in java. Mr. The getWarning() method of the Connection object retrieves the warning and the getNextWarning() method retrieves the subsequent warnings.  SQLWarning: It throws warnings received by the connection from the DBMS.  DataTruncation: It is thrown whenever a data is lost due to the truncation of the data value. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Ashok Kumar K. Registration started.sql package. 5.vtuprojects.www. VTU 7th sem B.E (CSE/ISE) JAVA/ J2EE Notes prepared by Mr. Ashok Kumar K 9742024066 | [email protected] . Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.com .com | Final year IEEE project development and training from scratch by Mr.www.vtuprojects.com Mr. Unit 6: Servlet Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Ashok Kumar K 9742024066 | celestialcluster@gmail. Ashok Kumar K. 6. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed Mr. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. Registration started. Ashok Kumar K.COM for your final year project work 1. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. 5. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. He will be having a thorough experience in working on both product and service driven industries. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews.www. 15 reasons to choose VTUPROJECTS. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. 3. Skype/ Team viewer support In case the student needs an emergency help when he/she is in their colleges. 15. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. No prerequisites required. Study Materials We provide the most efficient study material for each and every module during the project development 4.com | Final year IEEE project development and training from scratch by Mr. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills.com . 13. 10.vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest. 2. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. vtuprojects. In CGI when a server receives a request it creates a new process to run the CGI program. Contact 9742013378 or 9742024066 and lock your project at the earliest.server computing. Later we had the era of Common Gateway Interface (CGI). It can communicate with applets. a web server passes requests to an external program and after executing the program the content is sent to the client as the output. But Servlets offer several advantages in comparison with the CGI. Mr.com . Servlets can share data among each other CGI does not provide sharing property Servlets can perform session tracking and caching of previous CGI cannot perform session tracking and caching computations. Java security manager on the server enforces a set of restrictions There is no support for Security Manager in CGI to protect the resources on a server machine. Defining a Servlet Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. scalability issues make it less than optimal solutions. databases. Servlets can read and set HTTP headers. each request is handled by a is handled by a lightweight Java thread. and each request In CGI.com | Final year IEEE project development and training from scratch by Mr. which limits the number of requests that can be processed concurrently. of previous computations. Using Servlets. Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). so creating a process for each request requires significant server resources and time. Servlets can link directly to the Web server CGI cannot directly link to Web server. 6. you can collect input from users through web page forms. Ashok Kumar K. handle tracking sessions cookies. the Java Virtual Machine stays up. CGI cannot read and set HTTP headers. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Advantages of Servlets over CGI Here is the brief comparison between Servlet and CGI. CGI applications are platform dependent. So servlets are trusted.www. tracking sessions. There is no doubt that CGI played a major role in the explosion of the Internet but its performance. The full functionality of the Java class libraries is available to a CGI has limited libraries servlet. handle cookies. Registration started. Servlet CGI Servlets is inexpensive in terms of memory usage CGI is more expensive than Servlets in terms of memory usage Servlet are platform independent CGI is platform dependent In Servlets. or other software via the sockets and RMI mechanisms that you have seen already. By using the CGI. The Common Gateway Interface was one of the practical techniques developed for creating dynamic content.1 History Earlier in client. each application had its own client program and it worked as a user interface and need to be installed on each user's personal computer. heavyweight operating system process. and create web pages dynamically. present records from a database or another source. Here are the steps to setup Tomcat on your machine: 1. For example in C:\apache- tomcat-7. Apache Tomcat is an open source software implementation of the Java Servlet and Java Server Pages (JSP) technologies and can act as a standalone server for testing servlets and can be integrated with the Apache Web Server.sh or /usr/local/apache-tomcat-5. Apache Tomcat is one of them. it would be deployed in a configured environment to test and run.org/.29/bin/startup. Although servlets can respond to any type of request. For such applications.29\bin\startup.2 Setting up Servlet Runtime Environment Prerequisite: JDK is installed and configured properly. or /usr/local/ apache-tomcat-7. Java Servlet technology defines HTTP-specific servlet classes.bat or C:\apache-tomcat-5. you need to compile a servlet by using the Java compiler javac and after compiling the servlet application.com . they are commonly used to extend the applications hosted by web servers.vtuprojects. 6. Download latest version of Tomcat from http://tomcat. Ashok Kumar K | 9742024066 | [email protected] on windows.sh After startup. Once you downloaded the installation.  In Windows %CATALINA_HOME%\bin\startup. Tomcat can be started by executing the following commands. the default web applications included with Tomcat will be available by visiting http://localhost:8080/.apache. Contact 9742013378 or 9742024066 and lock your project at the earliest.5. If everything is fine then it should display following result: Mr. Like any other Java program. A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model.bat  In Linux/ Unix $CATALINA_HOME/bin/startup. Registration started.0. you need a web server that supports Servlet. unpack the binary distribution into a convenient location.www.5.com | Final year IEEE project development and training from scratch by Mr. To run a Servlet.26 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.0. 2. Ashok Kumar K. www. Ashok Kumar K | 9742024066 | [email protected] Mr.29/bin/shutdown.com | Final year IEEE project development and training from scratch by Mr.vtuprojects. Registration started.com .5.29\bin\shutdown  In Linux $CATALINA_HOME/bin/shutdown.5. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K. Tomcat can be stopped by executing the following commands  In Windows %CATALINA_HOME%\bin\shutdown or C:\apache-tomcat-5.sh or /usr/local/apache-tomcat-5. The algorithms by which this determination is made are specific to each server. This method is called to process the HTTP request.vtuprojects.3 Servlet Life Cycle A servlet life cycle can be defined as the entire process from its creation till the destruction. Finally. Mr. The service() method is called for each HTTP request. Ashok Kumar K. The servlet is retrieved and dynamically loaded into the server address space 3. The following are the paths followed by a servlet. The server calls the destroy() method to relinquish any resources such as file handles that are allocated for the servlet. 5. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. the server may decide to unload the servlet from its memory. init() method of the servlet is called by the web server only when the servlet is first loaded into the memory. 1. You can visualize the servlet architecture through the following figure. 6. You may pass initialization parameters to this method to configure the Servlet. 4. Web server receives the request and maps this request to a particular Servlet.com . Contact 9742013378 or 9742024066 and lock your project at the earliest.www. etc) 2.com | Final year IEEE project development and training from scratch by Mr. Web server invokes service() method of the servlet. Registration started. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Browser sends a HTTP request to the web server (through URL. It is possible to read the parameters from the request and is also possible to send a response back to the browser. submitting a form. and other services.g. Examples for noncommercial web servers are Apache Tomcat. Web server A web server uses HTTP protocol to transfer data. Registration started. A web container implements the web component contract of the Java EE architecture. Mr. 6. JBoss. a user type in a URL (e.in) in browser (a client).  GenericServlet is just that. servlet.  HttpServlet is a servlet tied specifically to the HTTP protocol. Ashok Kumar K. etc Servlet Container Servlet container is the component of a web server that interacts with Java servlets. protocol-independent servlet. specifying a runtime environment for web components that includes security. Ashok Kumar K | 9742024066 | celestialcluster@gmail. www. Jetty.jmaster. a generic. GlassFish.4 Generic Servlet versus HTTP servlet There are two different kinds of servlet classes that you will come across at later point of time when we start coding the servlet examples. protocol. mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. transaction. HttpServlet defines a HTTP protocol specific independent servlet. A Servlet container is responsible for managing the lifecycle of servlets.www.vtuprojects. we will understand these two kinds of servlets. deployment. So what the server does is sending a web page to the client. GenericServlet HTTPServlet GenericServlet defines a generic. and get a web page to read.com . In a simple situation. lifecycle management. The transformation is in HTTP protocol which specifies the format of request and response message. concurrency.com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. In this section. UnavailableException Indicates a servlet is unavailable. ServletException Indicates a servlet error occurred. Keep in mind that these packages are not part of the Java core packages. Ashok Kumar K. Classes Mr. javax. service.vtuprojects.com | Final year IEEE project development and training from scratch by Mr.servlet package Interfaces Interface Description Servlet Declares life cycle methods for a servlet ServletConfig Allows servlets to get initialization parameters ServletContext Enables servlets to log events and access information about their environment.servlet. Contact 9742013378 or 9742024066 and lock your project at the earliest.http package Below are some of the classes and interfaces defined in javax.servlet.servlet.www. HttpSession Allows session data to be read and written. HttpSessionBindingListener Informs an object that it is bound to or unbound from a session.5 Servlet Libraries Two packages contain the classes and interfaces that are required to build servlets. and  javax. and of the methods in the ServletConfig interface 6.servlet package Below are some of the classes and interfaces defined in javax. Ashok Kumar K | 9742024066 | celestialcluster@gmail. ServletRequest Used to read data from a client request ServletResponse Used to write data to a client response Classes Class Description GenericServlet Implements the Servlet and ServletConfig interfaces. Instead. javax. ServletOutputStream Provides an output stream for writing responses to a client. Registration started.servlet. and destroy hence inherits the properties of GenericServlet. These are  javax. they are standard extensions provided by the web servers. HttpServletResponse Enables servlets to write data to an HTTP response. GenericServlet gives a blueprint and makes HttpServlet gives a blueprint for Http servlet and writing servlet easier makes writing them easier GenericServlet provides simple versions of the HttpServlet extends the GenericServlet and lifecycle methods init. ServletInputStream Provides an input stream for reading requests from a client.http package Interfaces Interface Description HttpServletRequest Enables servlets to read data from an HTTP request.com .http. They constitute the Servlet API. HttpSessionEvent Encapsulates a session-changed event.*. Ashok Kumar K | 9742024066 | [email protected] Servlet Examples Example 1: My first Servlet You would require writing three files to run a simple servlet  HelloServlet. or that a session attribute changed.com | Final year IEEE project development and training from scratch by Mr.aklc.io.*. public class HelloServlet extends GenericServlet { Mr.vtuprojects.java : A servlet. import java. which is a Java class file  hello.servlet. here is the structure of your dynamic web project created in Eclipse.www. Notice the placement of the above files in the project.html : A web page to invoke the servlet by sending a request  web. HttpServlet Provides methods to handle HTTP requests and responses. import javax. Contact 9742013378 or 9742024066 and lock your project at the earliest.com . HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session value. 6. Ashok Kumar K. Class Description Cookie Allows state information to be stored on a client machine. Step 1: Create HelloServlet. Registration started.servlet.java package com.xml : A deployment descriptor which will map the request from the web page to the servlet And. Ashok Kumar K | 9742024066 | [email protected] . </body> </html> Step 3: Update web.close().xml Add the below entry to web. IOException { // Set the response type (MIME Type) resp.com | Final year IEEE project development and training from scratch by Mr.servlet.println("<h1 style='color:blue. Registration started.setContentType("text/html"). // Enclose your response string inside println() method pw.xml <servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>com.vtuprojects. background-color:yellow. Ashok Kumar K. Contact 9742013378 or 9742024066 and lock your project at the earliest. Welcome to the world of Servlet</h1>").html on the server Here is the output you would see Mr.'> Hello World. } } Step 2: Create hello. ServletResponse resp) throws ServletException. public void service(ServletRequest req. // So you can write to the browser (client) using this writer object PrintWriter pw = resp.html <html> <body> <h2> Servlet Examples </h2> <a href='hello'>Click here</a> to run a simple servlet.r.getWriter().t the client. // Get the writer object w. // Close the writer object pw.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> Step 4: Run hello. You can directly run the project in any of the web browser by entering the below URL (provided that the application is deployed in tomcat server and it is up and running) http://localhost:8080/<Project_name>/<url_pattern> In the above the example.xml : A deployment descriptor which will map the request from the web page to the servlet And. You would require writing three files to run a simple servlet  ReadParamServlet.  web. Ashok Kumar K | 9742024066 | [email protected] : A servlet. the URL looks like. it takes you to the following screen. which is a Java class file. Ashok Kumar K.com .vtuprojects. http://localhost:8080/PractiseApp/hello. Mr.html Example 2: Reading request parameters The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a client request. It reads the parameters from the request. Upon clicking on 'Click here' link. Contact 9742013378 or 9742024066 and lock your project at the earliest.  passParam.html : A web page to invoke the servlet by sending a request.www. Registration started. Notice the placement of the above files in the project. It passes the parameters to the servlet.com | Final year IEEE project development and training from scratch by Mr. We will develop a servlet that illustrates their use. here is the structure of your dynamic web project created in Eclipse. IOException { resp.servlet.setContentType("text/html").getWriter().io. String name=req.html <html> <body> Passing parameters to a Servlet <form action='paramEx'> Enter your name: <input type='text' name='username' /> <br/> <br/> <input type='submit' value='Click me' /> Mr.com . Ashok Kumar K | 9742024066 | celestialcluster@gmail. Contact 9742013378 or 9742024066 and lock your project at the earliest.getParameter("username").vtuprojects. import javax. pw.com | Final year IEEE project development and training from scratch by Mr.println("<h2> Welcome. ServletResponse resp) throws ServletException. } } Step 2: Create passParam. Registration started.servlet.close(). PrintWriter pw = resp. public class ReadParamServlet extends GenericServlet { public void service(ServletRequest req.www.*. pw.*.java package com. import java.aklc. Ashok Kumar K. Step 1: Create ReadParamServlet. "+name+"</h2>"). xml Add the below entry to web. Ashok Kumar K | 9742024066 | [email protected] . Ashok Kumar K. You can enter the direct URL in the browser.vtuprojects.ReadParamServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ParamServlet</servlet-name> <url-pattern>/paramEx</url-pattern> </servlet-mapping> Step 4: Run passParam. Contact 9742013378 or 9742024066 and lock your project at the earliest. </form> </body> </html> Step 3: Update web.com | Final year IEEE project development and training from scratch by Mr.aklc.www. http://localhost:8080/PractiseApp/passParam.xml <servlet> <servlet-name>ParamServlet</servlet-name> <servlet-class>com.html Clicking on "Click me" button takes you to below screen Mr.html on the server. Registration started. 1 defines the following request methods:  GET: Retrieves the resource identified by the request URL  HEAD: Returns the headers identified by the request URL  POST: Sends data of unlimited length to the Web server  PUT: Stores a resource under the request URL  DELETE: Removes the resource identified by the request URL  OPTIONS: Returns the HTTP methods the server supports  TRACE: Returns the header fields sent with the TRACE request The HttpServlet class provides specialized methods that handle the various types of HTTP requests. Notice the placement of the above files in the project. here is the structure of your dynamic web project created in Eclipse. Ashok Kumar K | 9742024066 | celestialcluster@gmail. These methods are doDelete(). Ashok Kumar K. The servlet is invoked when a form on a web page is submitted.html: A web page to invoke the servlet by sending a request. etc) from a web server. and doTrace(). Registration started. doGet(). doHead(). doPost(). Example 3: HTTP Get request You would require writing three files  GetRequestServlet.com . Get me the file 'home. HTTP is a request/response protocol. Mr.www. Contact 9742013378 or 9742024066 and lock your project at the earliest. doPut(). A servlet developer typically overrides one of these methods. which is a Java class that extends HttpServlet  getRequest. and the web server sends back a response ("Here's the file". Http Get request and Http Post request Here we will develop a servlet that handles an HTTP GET request.vtuprojects.java: An HTTP servlet. HTTPServlet Whenever the web browser fetches a file (a page.html'). it does so using HTTP (Hypertext Transfer Protocol).com | Final year IEEE project development and training from scratch by Mr. which means your computer sends a request for some file (ex. followed by the file itself). HTTP 1. a picture. It sends a GET request  web. doOptions().xml : A deployment descriptor which will map the request from the web page to the servlet And. IOException { String un = req. HttpServletResponse resp) throws ServletException.println("<br/><h2> Your password is . resp. PrintWriter pw = resp. import javax.com | Final year IEEE project development and training from scratch by Mr. pw.com .www.servlet. Ashok Kumar K | 9742024066 | [email protected]("username"). "+pwd). pw.println("<h2> Welcome. Registration started. Ashok Kumar K.aklc. import java.. } } Mr.getWriter(). import javax.servlet. Contact 9742013378 or 9742024066 and lock your project at the earliest. "+un+"</h2>").*.*.getParameter("password").http. pw. public class GetRequestServlet extends HttpServlet { protected void doGet(HttpServletRequest req.*.java package com.setContentType("text/html"). Step 1: Create GetRequestServlet.servlet.close().vtuprojects. String pwd = req. aklc. it takes you to the below screen.html Upon clicking on "Click me" button.vtuprojects.xml Add the below entry to web.xml <servlet> <servlet-name>GetReqServlet</servlet-name> <servlet-class>com.www.GetRequestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetReqServlet</servlet-name> <url-pattern>/getReq</url-pattern> </servlet-mapping> Step 4: Run getRequest. Mr. Ashok Kumar K.com | Final year IEEE project development and training from scratch by Mr.html in the browser by entering the below URL http://localhost:8080/PractiseApp/getRequest.html <html> <body> Handling HTTP Get Request <br/> <form action='getReq' method='get'> Enter your name: <input type='text' name='username' /> <br/> <br/> Enter your password: <input type='password' name='password' /> <br/> <br/> <input type='submit' value='Click me' /> </form> </body> </html> Step 3: Create web. Registration started. Step 2: Create getRequest.com . Contact 9742013378 or 9742024066 and lock your project at the earliest.servlet. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Notice the placement of the above files in the project. Ashok Kumar K | 9742024066 | celestialcluster@gmail. which is a Java class that extends HttpServlet  postRequest.vtuprojects.html: A web page to invoke the servlet by sending a request. Example 4: HTTP Post Request Here we will develop a servlet that handles an HTTP POST request. Mr. Registration started.www. It sends a POST request  web. Ashok Kumar K.xml : A deployment descriptor which will map the request from the web page to the servlet And. You would require writing three files  PostRequestServlet. here is the structure of your dynamic web project created in Eclipse. Contact 9742013378 or 9742024066 and lock your project at the earliest.com | Final year IEEE project development and training from scratch by Mr.com . The servlet is invoked when a form on a web page is submitted.java: An HTTP servlet. *. import javax. import javax.www.getParameter("username").html <html> <body> Handling HTTP Post Request <br/> Mr.aklc.println("<br/><h2> Your password is . public class PostRequestServlet extends HttpServlet { protected void doPost(HttpServletRequest req. pw. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K. PrintWriter pw = resp.. pw.getWriter(). String pwd = req. } } Step 2: Create postRequest.io.http.java package com.servlet. Step 1: Create PostRequestServlet.com . Registration started.setContentType("text/html"). HttpServletResponse resp) throws ServletException. pw.com | Final year IEEE project development and training from scratch by Mr. "+pwd). resp. IOException { String un = req.servlet.vtuprojects. import java.servlet.close().println("<h2> Welcome. "+un+"</h2>").*.*.getParameter("password"). Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started.servlet.xml Add the below entry to web. it takes you to the below screen.www.xml <servlet> <servlet-name>PostReqServlet</servlet-name> <servlet-class>com.html in the browser by entering the below URL http://localhost:8080/PractiseApp/postRequest. Mr. Ashok Kumar K.com .PostRequestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>PostReqServlet</servlet-name> <url-pattern>/postReq</url-pattern> </servlet-mapping> Step 4: Run getRequest.vtuprojects. Ashok Kumar K | 9742024066 | [email protected] | Final year IEEE project development and training from scratch by Mr.aklc.html 1 Upon clicking on "Click me" button. Contact 9742013378 or 9742024066 and lock your project at the earliest. <form action='postReq' method='post'> Enter your name: <input type='text' name='username' /> <br/> <br/> Enter your password: <input type='password' name='password' /> <br/> <br/> <input type='submit' value='Click me' /> </form> </body> </html> Step 3: Create web. com | Final year IEEE project development and training from scratch by Mr.7 Cookies Concept Web applications are typically a series of HTTP requests and responses. By having the server read cookies it sent the client previously. Example 1: Creating a Cookie Mr. included as part of the URL that is sent to the web server. and so on.com . Web applications use cookies to store state information on the client. You can set the age of cookie by setMaxAge() method.vtuprojects. Ashok Kumar K | 9742024066 | [email protected]. Cookies are small bits of textual information that a Web server sends to a browser. the user's shopping cart. Cookies can be used to store information about the user. Ashok Kumar K. Difference between HTTP Get and HTTP Post requests HTTP Get Request HTTP Post Request Parameters for an HTTP GET request are included as Parameters for an HTTP POST request are NOT part of the URL that is sent to the web server. A servlet uses the getCookies() method of HTTPServletRequest class to retrieve cookies as request. and manipulate HTTP cookies on the web browser. create. The addCookie() method of HTTPServletResponse class sends a new cookie to the browser. Registration started. the site can provide visitors with a number of conveniences like  Identifying a user during e-commerce session  Avoiding username and password entered again and again  Customizing a site based on user's browsing history  Focusing Advertisement The Cookie class provides an easy way for servlet to read. Example: http://localhost:8080/PractiseApp/getReq? Example: http://localhost:8080/PractiseApp/postReq username=Ashok&password=lordshiva 6. information is not automatically saved between HTTP requests. Contact 9742013378 or 9742024066 and lock your project at the earliest. As HTTP is a stateless protocol. Ashok Kumar K.setContentType("text/html").java : An HTTP servlet.servlet. IOException { String id = req. You would require writing these three files:  WriteCookie. resp. Ashok Kumar K | 9742024066 | [email protected]. Registration started. PrintWriter pw = resp.vtuprojects. Mr.xml : A deployment descriptor which will map the request from the web page to the servlet And. Step 1: Create WriteCookie.getWriter().html : A web page to invoke the servlet by sending a request. Notice the placement of the above files in the project.java package com.servlet. import javax. resp.www. which is a Java class that extends HttpServlet  cookieWrite. Contact 9742013378 or 9742024066 and lock your project at the earliest.*.com . public class WriteCookieServlet extends HttpServlet { protected void doGet(HttpServletRequest req.*.addCookie(mycookie). here is the structure of your dynamic web project created in Eclipse. id).  web.getParameter("id").*. import java. Here we will develop a simple web application that creates a new Cookie variable by name 'RegID' in the browser.http. Cookie mycookie = new Cookie("RegID". HttpServletResponse resp) throws ServletException.com | Final year IEEE project development and training from scratch by Mr.aklc. import javax. vtuprojects. <br/><br/> <form action='writeCookie' > Enter your Reg ID: <input type='text' name='id' /> <br/><br/> <input type='submit' value='Click me' /> </form> </body> </html> Step 3: Update web.WriteCookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>WriteCookie</servlet-name> <url-pattern>/writeCookie</url-pattern> </servlet-mapping> Step 4: Run getRequest.xml <servlet> <servlet-name>WriteCookie</servlet-name> <servlet-class>com.aklc. } } Step 2: Create cookieWrite.close().. pw.com | Final year IEEE project development and training from scratch by Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest.. pw.xml Add the below entry to web. Registration started. Ashok Kumar K | 9742024066 | [email protected] <html> <body> Creating a cookie .www.html Mr.com .println("<h2> Cookie has been successfully created . </h2>"). Ashok Kumar K.html in the browser by entering the below URL http://localhost:8080/PractiseApp/cookieWrite. which is a Java class that extends HttpServlet  cookieRead. Mr. Example 2: Reading the previously created cookie Here we will develop a simple web application that creates a new Cookie variable by name 'RegID' in the browser.com | Final year IEEE project development and training from scratch by Mr. Notice the placement of the above files in the project. here is the structure of your dynamic web project created in Eclipse.www.  web.java : An HTTP servlet. You would require writing these three files:  ReadCookieServlet.com . Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K.xml : A deployment descriptor which will map the request from the web page to the servlet And. Registration started.html : A web page to invoke the servlet by sending a request. Ashok Kumar K | 9742024066 | [email protected]. getCookies(). String value="".*.com | Final year IEEE project development and training from scratch by Mr. Step 1: Create ReadCookieServlet. Contact 9742013378 or 9742024066 and lock your project at the earliest. } } Mr.www. Ashok Kumar K | 9742024066 | [email protected] .getValue().java package com. HttpServletResponse resp) throws ServletException. Ashok Kumar K.getName().*. String name="".equals("RegID")) { value=cookies[i].servlet. public class ReadCookieServlet extends HttpServlet { protected void doGet(HttpServletRequest req.length. Registration started. import javax. if (name. for (int i=0.i++) { name = cookies[i].servlet. break.*. import javax.aklc. IOException { Cookie[] cookies = req.i<cookies.vtuprojects. import java.http.servlet.io. resp. Ashok Kumar K | 9742024066 | celestialcluster@gmail. <br/><br/> <form action='readCookie' > <input type='submit' value='Click me' /> </form> </body> </html> Step 3: Update web.println("<h2> Welcome.setContentType("text/html")..xml <servlet> <servlet-name>readCookie</servlet-name> <servlet-class>com.com | Final year IEEE project development and training from scratch by Mr..html <html> <body> Reading a cookie . PrintWriter pw = resp. Registration started.com .html Mr. } } Step 2: Create cookieWrite. Ashok Kumar K.servlet. "+value+"</h2>").ReadCookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>readCookie</servlet-name> <url-pattern>/readCookie</url-pattern> </servlet-mapping> Step 4: Run getRequest.vtuprojects.xml Add the below entry to web. Stored RegID is .aklc.getWriter().html in the browser by entering the below URL http://localhost:8080/PractiseApp/cookieRead. pw. pw.www. Contact 9742013378 or 9742024066 and lock your project at the earliest.close(). com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail. the client opens a separate connection to the web server and the server does not keep any record of previous client request. Each time when web browser sends request back.vtuprojects. 6. how does the server know what's already in your cart? Even if servers did retain contextual information. how does the server remember what you were buying? There are some typical solutions to this problem. then session_id value can be used to keep the track of different web browsers. When you are doing on-line shopping.com . if the session is not maintained then it makes our shopping application problematic. Drawback: This may not be an effective way because many time browser does not support a cookie. Contact 9742013378 or 9742024066 and lock your project at the earliest.8 Session Handling As mentioned earlier.  URL Rewriting Mr. Ashok Kumar K. so hidden form fields also cannot support general session tracking. you'd still have problems with e-commerce. The question here is how can we maintain the session between the client and a server? What happens if we don't maintain the session between the client and the server? To understand this. HTTP is a "stateless" protocol which means each time when a client retrieves a web page.www. Drawback: Clicking on a regular (< a href='' > ) anchor link does not result in a form submission. (Different ways of tracking user activity in a web application)  Cookies A web server can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. When you add an entry to your cart. when the form is submitted. take an example of online shopping experience. When you move from the page where you specify what you want to buy (hosted on the regular web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL). Registration started.  Hidden fields A web server can send a hidden HTML form field along with a unique session ID as follows: <input type="hidden" name="sessionid" value="12345"> This entry means that. the specified name and value are automatically included in the request. java : An HTTP servlet.html : A web page to invoke the servlet by sending a request.getSession().html. across more than one connection or page request from the user. Example You would get HttpSession object by calling the public method getSession() of HttpServletRequest.xml : A deployment descriptor which will map the request from the web page to the servlet And.www. You can append some extra data on the end of each URL that identifies the session. The servlet container uses this interface to create a session between an HTTP client and an HTTP server.sessionid=12345. Ashok Kumar K. Ashok Kumar K | 9742024066 | celestialcluster@gmail. here is the structure of your dynamic web project created in Eclipse. You would require writing these three files:  SessionTrackServlet. which is a Java class that extends HttpServlet  sessionTrack.  web. Drawback: You would have generate every URL dynamically to assign a session ID though page is simple static HTML page  HttpSession Servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. with http://jmaster. and the server can associate that session identifier with data it has stored about that session. as below: HttpSession session = request.vtuprojects. the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client. Mr. For example.com . The session persists for a specified time period. Here we will develop a simple web application that demonstrates the session handling. Contact 9742013378 or 9742024066 and lock your project at the earliest.in/home. Notice the placement of the above files in the project.html.com | Final year IEEE project development and training from scratch by Mr. Registration started. Date lastAccessTime = new Date(session. import java. String title = "Welcome Back to my website". HttpServletResponse resp) throws ServletException. String userID="".util. Ashok Kumar K | 9742024066 | celestialcluster@gmail.*. Registration started. Mr.aklc. import javax.servlet. Step 1: Create SessionTrackServlet.io. public class SessionTrackServlet extends HttpServlet { public void doGet(HttpServletRequest req.com | Final year IEEE project development and training from scratch by Mr.*.getCreationTime()).www. import javax.java package com.getSession(true).*.com .servlet. import java. int visitCount = 0.getLastAccessedTime()).servlet.http. Ashok Kumar K. IOException { HttpSession session = req. Contact 9742013378 or 9742024066 and lock your project at the earliest.vtuprojects.*. Date createTime = new Date(session. Ashok Kumar K | 9742024066 | [email protected](). Registration started.vtuprojects.xml <servlet> <servlet-name>SessionTrack</servlet-name> <servlet-class>com.getAttribute("userID"). if (session. Ashok Kumar K. session.isNew()){ title = "Welcome to my website".com . pw.www. PrintWriter pw = resp.println("<h1>" + title + "</h1>" + "<h2>Session Infomation</h2>" + "<table border=\"1\" >" + "<tr bgcolor=\"#949494\">" + " <th>Session info</th><th>value</th>" + "</tr>" + "<tr>" + " <td>id</td>" + " <td>" + session.servlet. // Check if this is new comer on your web page. } } Step 2: Create sessionTrack.setAttribute("visitCount".xml Add the below entry to web. visitCount = visitCount + 1. } session.html <html> <body> Session Handling DEMO <br/><br/> <a href='sessionTrack'> Visit my website </a> </body> </html> Step 3: Update web.getAttribute("visitCount").setAttribute("userID".getId() + "</td>"+ "</tr>" + "<tr>" + " <td>Creation Time</td>" + " <td>" + createTime + " </td>"+ "</tr>" + "<tr>" + " <td>Time of Last Access</td>" + " <td>" + lastAccessTime + " </td>"+ "</tr>" + "<tr>" + " <td>User ID</td>" + " <td>" + userID + " </td>"+ "</tr>" + "<tr>" + " <td>Number of visits</td>" + " <td>" + visitCount + "</td>"+ "</tr>" + "</table>" ).setContentType("text/html"). resp. visitCount). } else { visitCount = (Integer)session. "ABCD"). userID = (String)session.aklc.com | Final year IEEE project development and training from scratch by Mr.SessionTrackServlet</servlet-class> </servlet> <servlet-mapping> Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. meaning visiting it again. you see the below page Mr. Refreshing it.com . Ashok Kumar K | 9742024066 | celestialcluster@gmail. you see the page shown below.html in the browser by entering the below URL http://localhost:8080/PractiseApp/sessionTrack.vtuprojects.www.html First time when you click on the link. Contact 9742013378 or 9742024066 and lock your project at the earliest. Registration started. Ashok Kumar K.com | Final year IEEE project development and training from scratch by Mr. <servlet-name>SessionTrack</servlet-name> <url-pattern>/sessionTrack</url-pattern> </servlet-mapping> Step 4: Run getRequest. Ashok Kumar K 9742024066 | [email protected] .E (CSE/ISE) JAVA/ J2EE Notes prepared by Mr.VTU 7th sem B. Remote Method Invocation Mr. Unit 7: Java Server Pages. Ashok Kumar K. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started.com Mr.com | Final year IEEE project development and training from scratch by Mr.vtuprojects.com . Ashok Kumar K 9742024066 | [email protected]. Study Materials We provide the most efficient study material for each and every module during the project development 4. 6. Strict SDLC Project development will be carried out as per the strict Software Development model 8. 5. Skype/ Team viewer support In case the student needs an emergency help when he/she is in their colleges. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 2. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed Mr. 3. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. He will be having a thorough experience in working on both product and service driven industries. No prerequisites required.vtuprojects.www. we will be helping out them through Skype/ Team viewer screen sharing 12. 15 reasons to choose VTUPROJECTS. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9.com | Final year IEEE project development and training from scratch by Mr.COM for your final year project work 1. 10. Registration started. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Contact 9742013378 or 9742024066 and lock your project at the earliest. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns.com . Ashok Kumar K | 9742024066 | celestialcluster@gmail. Ashok Kumar K. 15. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 13. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. For these reasons. Notice the application logic and presentation logic are coupled together which is not recommended.com . Java Server Pages (JSP) is a server side program that is similar in design and functionality to a java Servlet. the nature of which depends on the J2EE Application. Most servlets contain a little code that handles application logic and a lot more code that handles output formatting (presentation logic). Defining a JSP A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the client in a more powerful and flexible manner. This can make it difficult to separate and reuse portions of the code when a different output format is needed. Ashok Kumar K | 9742024066 | celestialcluster@gmail. web application developers turn towards JSP as their preferred servlet environment. Mr.vtuprojects. Most of a JSP file is a plain HTML but it also will be interspersed with special JSP tags.com | Final year IEEE project development and training from scratch by Mr. Registration started. Below is the snap shot of the servlet program that we have seen in previous chapter. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K. A JSP is called by client to provide a web service.1 Basics Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. In later sections we see how JSP helps in separating the application logic from the presentation logic. JAVA SERVER PAGES 7.www. it compiles this translation unit (the JSP page and other dependent files) into a class file that implements the servlet protocol. then the corresponding objects are HttpServletRequest and HttpServletResponse. Similar to above.JspPage. and actions comprised of formatted in HTML. page authors can provide their own implementation. recompilation is done automatically when changes are made to JSP pages. their implementation classes must actually implement the javax. Registration started. Ashok Kumar K | 9742024066 | [email protected] | Final year IEEE project development and training from scratch by Mr. wraps up the responses from the JSP page and delivers it to the client.JspPage interface contains two methods: public void jspInit() This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs. The javax. XML.jsp.jsp. or in the client’s responses are encoded as an output string object that is format that is interspersed with the scripting passed to the println() method. The container or the engine. JSP has no such tedious task to maintain.jsp.jsp.servlet.com .www. public void jspDestroy() This method is invoked when the JSP is about to be destroyed by the container. Java Beans and custom tags web application is simplified  Reduces Development time 7. CLASSPATH setting and packaging.  There is automatic deployment of a JSP.HttpJspPage interface contains one method: Mr. The output string object is elements. When a client requests for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object.  In a JSP page visual content and logic are separated.HttpJspPage interface. which is a sub interface of javax. Contact 9742013378 or 9742024066 and lock your project at the earliest.servlet. Difference between JSP and Servlet Servlet is written using Java programming language and JSP is written in HTML. XML.servlet.2 JSP Architecture A JSP page is executed in a JSP container (or JSP engine). The JSP page processes the request and modifies the response object to incorporate the communication with the client. Since most JSP pages use HTTP.  JSP needs no compilation. The underlying layer for a JSP is actually a servlet implementation. on getting the response. directives. The first time when the engine intercepts a request for a JSP.  Usually with JSP. If the protocol used is HTTP.servlet. which is not possible in a servlet.vtuprojects. The javax. If the dependent files are other JSPs they are compiled into their own classes. The abstraction of the request and response are the same as the ServletRequest and ServletResponse respectively. which is installed in a web server (or an application server). Ashok Kumar K. or whatever format are required by Java programming language and JSP syntax the client Advantages of JSPs over Servlet  Servlets use println statements for printing an HTML document which is usually very difficult to use. The request is processed and the JSP generates appropriate response.com . Ex: <%-- This is a JSP Comment --%> Declaration Statement Tag A Declaration statement tag opens with <%! and is followed by a Java declaration statements that define variables. Ex: <%! int a. Comment Tag 2.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. objects.and closes with --%>. and methods. and is followed by a comment that usually describes the functionality of statements that follow the comment tag.*” %>  Include It inserts a specified file into the JSP program replacing the include tag Ex: <%@ include file = ”Keogh\book.sql. Contact 9742013378 or 9742024066 and lock your project at the earliest. HttpServletResponse response) throws ServletException. Ashok Kumar K | 9742024066 | celestialcluster@gmail. String s.  Import Used to import java packages into JSP program Ex: <%@ page import = “java. Scriptlet Tag Comment Tag A comment tag opens with <%-. There are five types of JSP tags: 1.vtuprojects. IOException This method generated by the JSP container. Employee e = new Employee().html” %> Mr. There are three commonly used directives. This response is taken by the container and passed back to the client. Declaration statement Tag 3. Directive Tag 4.www. every time a request comes to the JSP. Expression Tag 5. 7. %> Directive Tag A Directive tag opens with <%@ and closes with %>.3 JSP Tags JSP tags define java code that is to be executed before the output of a JSP program is sent to the browser. is invoked. public void _jspService (HttpServletRequest request. b = 10.4 Implicit Objects in JSP JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. application This is the ServletContext object associated with application context.com | Final year IEEE project development and training from scratch by Mr. It closes with %> 7. out This is the PrintWriter object used to send output to the client. Ashok Kumar K. session This is the HttpSession object associated with the request.5 Example JSP Programs 1. Registration started.  Taglib It specifies a file that contains a tag library Ex: <%@ taglib uri = “myTags. JSP supports nine Implicit Objects which are listed below: Object Description request This is the HttpServletRequest object associated with the request. response This is the HttpServletResponse object associated with the response to the client. 7.tld” %> Expression Tag An expression tag opens with <%= and is used for an expression statement whose result replaces the expression tag.www. page This is simply a synonym for this.com . JSP to illustrate variables declarations and usage <html> <body> <%! Mr. Exception The Exception object allows the exception data to be accessed by designated JSP. It closes with %> Ex: <%! int a = 5. %> <%= a+b %> Scriptlet Tag A scriptlet tag opens with <% and contains commonly used java control statements and loops. config This is the ServletConfig object associated with the page. JSP Implicit Objects are also called pre-defined variables.vtuprojects. and is used to call the methods defined by the translated servlet class. Ashok Kumar K | 9742024066 | celestialcluster@gmail. pageContext This encapsulates use of server-specific features like higher performance JspWriters. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K | 9742024066 | [email protected]. String s = "TEST".i++) { %> HELLO WORLD <% } %> </body> </html> Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. %> <p> int value is <%= a %> String value is <%= s %> </p> </body> </html> 2. Registration started. int b) { return a+b. } %> <p> sum of 2 and 5 is <%=findSum(2. int a = 10.5) %> </p> </body> </html> 3. %> <% if (grade >= 70 ) {%> FCD <% } else if (grade<70 && grade>=60) { %> FC <% } else if (grade<60 && grade>=50) { %> SC <% } else if (grade<50 && grade>=35) { %> Just pass <% } else { %> FAIL <% } %> </body> </html> 4.i<10. JSP to illustrate looping statements <html> <body> <% for (int i=0. <html> <body> <%! int findSum(int a. JSP to illustrate control statements <html> <body> <%! int grade = 70. JSP that defines a method and illustrates its usage.www.com .com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. html  readParam. It returns multiple values from the field specified as an argument to this method. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started. Ex: <%! String[] games = request.www. Ashok Kumar K.getParameterValues(“favgames”).6 Request String The browser generates a user request string whenever the submit button is selected.getParameterValues() Multi valued fields (such as checkboxes and select menus) can be read using getParameterValues() method.jsp Mr. which is the name of the field whose value you want to retrieve. String pword = request.getParameter(“password”).getParameter(“username”). Ex: <%! String uname = request. A JSP can parse the query string in two ways: a) Using request.vtuprojects.com . Contact 9742013378 or 9742024066 and lock your project at the earliest.com | Final year IEEE project development and training from scratch by Mr. The user request string consists of: 1. 7. You would require writing these three files  param. URL 2. Query String Example Query String JSP program should parse the query string to extract the values of fields that are to be processed by a JSP.getParameter() getParameter() method requires an argument. %> b) Using request. %> Example Program Here we will develop a sample JSP to read the parameters from the client request. html <html> <body> <form action='readParam.getParameter("username"). Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K | 9742024066 | [email protected]("games"). String games[] = request.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. %> Welcome. And. Notice the placement of the above files in the project. <%= name %> <br/><br/> Your favourite games are : <br/> <% Mr.jsp'> Enter your name: <input type='text' name='username' /> <br /> <br /> Select your favourite games : <br/> <select name='games' multiple=multiple> <option value='Cricket'>Cricket</option> <option value='Football'>Football</option> <option value='Hockey'>Hockey</option> <option value='Tennis'>Tennis</option> </select> <br /> <br /> <input type='submit' value='Click me' /> </form> </body> </html> Step 2: Create readParam. here is the structure of your dynamic web project created in Eclipse.www. Registration started.vtuprojects.com . Step 1: Create param.jsp <html> <body> <% String name = request. vtuprojects. for (int i=0. Ashok Kumar K | 9742024066 | celestialcluster@gmail. URL A URL is divided into four parts:  Protocol It defines the rules that are used to transfer the request string from the browser to JSP program. Three commonly used protocols are HTTP. If the port is not specified. and FTP  Host It is the internet protocol address (IP) or name of the server that contains the JSP program. Whenever HTTP is used.www.i<games.com . Ashok Kumar K. Contact 9742013378 or 9742024066 and lock your project at the earliest. HTTPS.i++) { %> <%= games[i] %> <br/> <% } %> </body> </html> Step 3: Run param.html by entering the direct URL in the browser.length. the host will be monitoring the port 80  Virtual path to JSP program The server maps this virtual path to the physical path Example for URL: Mr. Registration started.com | Final year IEEE project development and training from scratch by Mr. it is defaulted to 80.  Port It is the port that the host monitors. Sample JSP program to create a Cookie <html> <body> <%! String cName = "userID".  This cycle continues where the JSP program processing the request string receives the userID as a parameter and then passes the userID to the next dynamically built HTML page as a hidden field. This newly generated HTML page has a form that contains hidden field which is assigned a userID along with other fields as well. 7. In this way.1 Hidden Fields A hidden field is a field in HTML form whose value isn’t displayed on the HTML page. Mr. Ashok Kumar K. Consider a login screen which asks for username and password. The question here is how can we maintain the session between the client and a server? As explained in the previous chapter. String cValue = "1VK06IS009". You can assign a value to the hidden field in a JSP program before the program sends the HTML page to the browser. Contact 9742013378 or 9742024066 and lock your project at the earliest.7.7.  When the user submits the form in the new HTML page. and user preferences. Cookies are used to store various kind of information such as username. 7. the userID stored in the hidden field and other information on the form are sent to the JSP program. each HTML page and subsequent JSP program has access to userID and therefore can track the session. the client opens a separate connection to the web server and the server does not keep any record of previous client request. etc. there are four possible ways to maintain the session between client and a server  Cookies  Hidden fields  URL Rewriting  HttpSession interface (session object) 7. Ashok Kumar K | 9742024066 | celestialcluster@gmail. cValue). Cookie myCookie = new Cookie (cName.vtuprojects.com .7 User Sessions in JSP As mentioned earlier.www. Registration started. the browser sends the username and password to the JSP program.com | Final year IEEE project development and training from scratch by Mr.2 Cookies A cookie is a small piece of information created by a JSP program that is stored in the client’s hard disk by the browser. Here is how the session is tracked using hidden field:  Upon submitting the form.  The JSP program then validates the username and password and generates another dynamic HTML page. password. HTTP is a "stateless" protocol which means each time when a client retrieves a web page. equals(cName)) { value = myCookies[i]. Sample JSP program to create a session attribute <html> <body> <%! String attName = "userID".vtuprojects. %> </body> </html> Sample JSP program to read the Cookie <html> <body> <%! String cName = "userID".addCookie(myCookie). Each time a session is created. Contact 9742013378 or 9742024066 and lock your project at the earliest.getName().com | Final year IEEE project development and training from scratch by Mr.7. %> </body> </html> Sample JSP program to read session attribute Mr. The unique ID enables JSP programs to track multiple sessions simultaneously while maintaining data integrity of each session. a session object is also used to store other types of information called attributes. String attValue = "1VK06IS009". In addition to session ID. } } if (found==1) { %> <p> Cookie Name: <%= cName %> </p> <p> Cookie Value: <%= value %> </p> <% } else { %> <p> Cookie NOT FOUND </p> <%>} %> </body> </html> 7.getCookies(). %> <% session. if (name. for (int i=0.com . %> <% response.setAttribute(attName.i<myCookies. String value.getValue(). String name. a unique ID is assigned to the session and stored as a cookie.i++) { name = myCookies[i].length. %> <% Cookie[] myCookies = request. found = 1. Ashok Kumar K. Ashok Kumar K | 9742024066 | celestialcluster@gmail. attValue). int found = 0.3 session object A JSP database system is able to share information among JSP programs within a session by using a session object.www. Registration started. getAttributeNames(). Ashok Kumar K.com | Final year IEEE project development and training from scratch by Mr.vtuprojects. Contact 9742013378 or 9742024066 and lock your project at the earliest.hasMoreElements()) { String name = (String) e. <html> <body> <%! Enumeration<String> e. Ashok Kumar K | 9742024066 | [email protected](name).www. %> <p> Attribute name : <%= name %></p> <p> Attribute value : <%= value %></p> <% } %> </body> </html> Mr.com . %> <% e = session. while (e. Registration started.nextElement(). String value = (String) session. com . The remote stub is the local proxy for the remote object.  A client is an application or component that requires the services of an object to fulfill a request. which is referred to as dynamic code loading Following fig visualizes the RMI process When client references a remote object.8 Basics Definition and concepts A Java object runs within a JVM. REMOTE METHOD INVOCATION 7. RMI is used for remote communication between Java applications and components. Ashok Kumar K | 9742024066 | celestialcluster@gmail. RMI is used to connect together a client and a server. The client calls the method on the local stub whenever the client wants to invoke one of the remote object’s methods. This is because a J2EE application and its components can invoke objects located on different JVM by using Java RMI system. both of which must be written in Java Programming language. objects used by a J2EE application do not need to run on the same JVM as the J2EE application. 7.vtuprojects.www. Registration started. the RMI passes a remote stub for the remote object. however.com | Final year IEEE project development and training from scratch by Mr. Design an object 2.  A server creates an object and makes the object available to the clients RMI handles transmission of requests and provides the facility to load the object’s bytecode. Compile the object Mr.9 The RMI Process There are three steps necessary to make an object available to remote clients 1. a J2EE application runs within JVM. Contact 9742013378 or 9742024066 and lock your project at the earliest. Likewise. Ashok Kumar K. public class Hello extends UnicastRemoteObject implements HelloInterface { public String say() throws RemoteException { System. 3.rmi.println(“Hello World”).rmi. Methods provide the business logic that fulfills a client’s request whenever the client remotely invokes them. Registration started. } Remote Object that implements the remote interface is shown below: Hello.java import java. public interface HelloInterface extends Remote { public String say() throws RemoteException.*.10 Server Side Server side of RMI consists of a remote interfaces and methods. Make sure the RMI remote object registry is running.  Compile the object using rmic compiler This will create a stub for the object Make the object available to remote client It is done by loading the object into a server. Example for Remote interface is shown below: HelloInterface. the developer must define a remote interface for the object. If not. import java. There are referred as server methods.com | Final year IEEE project development and training from scratch by Mr.*. Make the object accessible to remote clients over the network Designing an object Besides defining the business logic of an object.java import java. type the following at the command line: C:\> start rmiregistry 7. Contact 9742013378 or 9742024066 and lock your project at the earliest. while methods invoked by a client are called client methods. In addition to methods that can be invoked by remote clients.com .server.vtuprojects. Ashok Kumar K. which identifies methods that are available to remote clients. Compile the object Compilation of the object is a two-step process  Compile the object using the javac compiler This will create the byte codes for the objects. } } Mr.rmi.out. the developer must also define other methods that support the processing of client invoked methods. Remote interfaces provide the API for clients to access the methods.*.www. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } } } Mr.getSecurityManager() == null) System.println ("Server not connected: " + e). System. Ashok Kumar K.setSecurityManager(new RMISecurityManager()).say()).out.println("HelloClient exception: " + e). public class HelloClient { public static void main(String[] argv) { if (System.Naming.setSecurityManager(new RMISecurityManager()). } catch (Exception e) { System.out.println(hello. public class HelloServer { public static void main (String[] argv) { if (System.Naming.rebind("MyObj". HelloServer.out.201/MyObj"). try { Naming.rmi.println ("Server is connected").com . try { HelloInterface hello = (HelloInterface) Naming .com | Final year IEEE project development and training from scratch by Mr. HelloClient.10.getSecurityManager() == null) System. Ashok Kumar K | 9742024066 | [email protected]("//192. Registration started. It also illustrates how a client can use the remote object to call its methods. System.168.out. 7.rmi.vtuprojects. new Hello ()). } catch (Exception e) { System.java import java.11 Client Side Below example shows how a client can lookup the naming registry to get an instance of the remote object. } } } Clients can access the remote object by looking up the naming registry for the appropriate entry.www.java import java. Contact 9742013378 or 9742024066 and lock your project at the earliest. Below program in the server side makes the Remote object available to the clients by binding it to the naming registry. VTU 7th sem B.com . Ashok Kumar K 9742024066 | [email protected] (CSE/ISE) JAVA/ J2EE Notes prepared by Mr. Ashok Kumar K 9742024066 | celestialcluster@gmail. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started.com Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest.com | Final year IEEE project development and training from scratch by Mr.vtuprojects.www. Unit 8: Enterprise Java Beans (EJB) Mr.com . Ashok Kumar K. 5. 2. Study Materials We provide the most efficient study material for each and every module during the project development 4. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed Mr. 15 reasons to choose VTUPROJECTS. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. we will be helping out them through Skype/ Team viewer screen sharing 12. No prerequisites required. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. He will be having a thorough experience in working on both product and service driven industries. Contact 9742013378 or 9742024066 and lock your project at the earliest.com | Final year IEEE project development and training from scratch by Mr. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews.www. 3. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. 15. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. 10.COM for your final year project work 1. 6. Ashok Kumar K. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges.com .vtuprojects. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Skype/ Team viewer support In case the student needs an emergency help when he/she is in their colleges. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. 13. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started. com . Contact 9742013378 or 9742024066 and lock your project at the earliest. high scalability and high performance.  Application Server/ EJB container provides most of the system level services like transaction handling.  EJB container manages life cycle of EJB instances thus developer needs not to worry about when to create/delete EJB objects. Developer has to focus only on business logic of the application. persistence mechanism. which is a special case of a stateless session bean. Advantages of EJB  Simplifies the development of large scale enterprise level application. load balancing.1 Enterprise Java Beans Concept and Definition An Enterprise Java Bean (EJB) is a component of the J2EE architecture that primarily provides business logic to a J2EE application and interacts with other server side J2EE components.www. Ashok Kumar K. EJB provides an architecture to develop and deploy component based enterprise applications considering robustness. A session bean terminates once the session with their client server terminates.com | Final year IEEE project development and training from scratch by Mr.3 standard specification. Types of EJBs Session Bean Session bean contains business logic used to provide a service to a client and exists for the duration of the client server session.vtuprojects.. logging. User data can be saved to database via entity beans and later on can be retrieved from the database in the entity bean. exception handling and so on. An EJB application can be deployed on any of the application server compliant with J2EE 1. Message Driven Bean Message driven bean is designed for clients to invoke server side business logic using asynchronous communication. Registration started. The nature of business logic and the interaction with the other server side J2EE components are dependent on the J2EE application. Entity Bean Entity beans represent persistent data storage. Ashok Kumar K | 9742024066 | celestialcluster@gmail. 8. It is used to receive message from a JMS resource (Queue or Topic) Mr. which forwards the client’s request to the appropriate server. The home class is used to reference the bean class through the EJB’s remote class.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. 8. The session and entity beans must have two interfaces  Home interface or local interface The local clients that are on the same JVM as the EJB interact with the EJB using the home interface. Typically either the JSP or Servlet receives the client request and uses JNDI to look up the EJB resource.2 Deployment Descriptors Concept and Definition Deployment descriptor describes how EJBs are managed at runtime and enables the customization of EJB behavior without modification to the EJB code such as describing runtime attributes of transactional context.  Remote interface Remote interface is used by remote clients that are capable of accessing the EJB container from an application that is compliant with RMI and IIOP. Ashok Kumar K | 9742024066 | celestialcluster@gmail. Registration started. EJB Architecture EJB container is a vendor provided entity located on the EJB server that manages system level services for EJB. Many times an IDE (Integrated Development Environment) like Eclipse will automatically generates the deployment descriptor. The EJB object is returned and is used to get the EJB’s home or local class.com . each of which handles a J2EE component such as JSP or servlets. A client’s request for web services is made to a web server. EJB container is one of the several containers.www. Format of the deployment descriptor A deployment descriptor is written in a file using XML syntax. The deployment descriptor file is packaged in the Java Mr. Contact 9742013378 or 9742024066 and lock your project at the earliest. The behavior of an EJB can be modified within the deployment descriptor without having to modify the EJB class or the EJB interface.vtuprojects. 0 <!DOCTYPE ejb-jar > <ejb-jar> <enterprise-beans> <entity> <ejb-name>myEJB</ejb-name> <home>com.ejb.ejb.MyEJBHome</home> <remote>com. Registration started.aklc.MyEJBHomeLocal</local-home> <local>com.aklc. An EJB container references the deployment descriptor file to understand how to deploy and manage EJBs contained in the package.aklc.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K | 9742024066 | [email protected]</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.lang.aklc.1 <!DOCTYPE ejb-jar > <ejb-jar> <enterprise-beans> <entity> <ejb-name>myEJB</ejb-name> <home>com.aklc.String</prim-key-class> <reentrant>False</reentrant> </entity> </enterprise-beans> </ejb-jar> Description of the elements used Element Description <!DOCTYPE> Defines the URL for the DTD and the organization that defines the DTD <enterprise-bean> Describes one or more EJB contained within a JAR file <entity> Describes the type of EJB as entity bean <session> Describes the type of EJB as session bean <message-driven> Describes the type of EJB as message driven bean Mr. Deployment descriptor for EJB 1.MyEJBRemote</remote> <local-home>com.MyEJBLocal</local> <ejb-class>com.ejb.MyEJBHome</home> <remote>com.ejb.vtuprojects.ejb.ejb.www.lang.com .MyEJB</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.aklc.MyEJBRemote</remote> <ejb-class>com.aklc. Contact 9742013378 or 9742024066 and lock your project at the earliest. Archive (JAR) file along with other files that are required to deploy EJB.aklc.ejb.ejb. Ashok Kumar K.String</prim-key-class> <reentrant>False</reentrant> </entity> </enterprise-beans> </ejb-jar> Deployment descriptor for EJB 2. if (!supervisor) { throw new AccessDeniedException(). Contact 9742013378 or 9742024066 and lock your project at the earliest.isCallerInRole("Supervisor"). Ashok Kumar K | 9742024066 | [email protected] .com | Final year IEEE project development and training from scratch by Mr.lookup("java:comp/env/PassingGrade").vtuprojects. Ashok Kumar K. Integer grade = (Integer) jc. <ejb-name> Describes the name of session or entity bean <home> Describes the fully qualified class name of the session or entity bean remote home interface <remote> Describes the fully qualified class name of the session or entity bean remote interface <ejb-class> Describe the fully qualified class name of the session or entity bean class <persistence-type> Specifies either container managed persistence or bean managed persistence <prim-key-class> Describes the primary key class for entity beans <reentrant> Specifies that back (reentrant invocations) is allowed or not <local-home> Describes the fully qualified class name of the session or entity bean local home interface <local> Describes the fully qualified class name of the session or entity bean local interface Customizing the EJB behavior by defining the environment variables The <env-entry> element is used in the deployment descriptor to define values that an EJB can use to customize the EJB’s behavior Defining the environment variable <env-entry> <env-entry-name>PassingGrade</env-entry-name> <env-entry-type>java.www. Registration started.Integer</env-entry-type> <env-entry-value>35</env-entry-value> </env-entry> Accessing the environment variable InitialContext jc = new InitialContext(). Security elements Defining the <security-role> element <security-role-ref> <description>myEJB security role</description> <role-name>Supervisor</role-name> </security-role-ref> Verifying the role name from within EJB boolean supervisor = context. } Mr.lang.  Consistent: A transaction must keep the system in consistent state. EJB Transaction Attributes An EJB server will manage a transaction based on the EJB’s transaction attribute when the EJB is deployed. (That is. developer manages the life cycle of transaction states. Transactions can be managed by the container or by custom code handling in bean's code.com .  REQUIRES_NEW Indicates that a new transaction is to be started for the business method. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K.  SUPPORTS: Indicates that business method will execute as part of transaction.  Container Managed Transactions: In this type. container manages the transaction states. ACID stands for Atomic. EJB Container/Servers are transaction servers and handles transactions context propagation and distributed transactions.www.  NEVER: Indicates if business method executes as part of transaction then an exception will be thrown. Consistent. Isolated and Durable. 8.  MANDATORY: Indicates that business method will execute as part of transaction otherwise exception will be thrown.  Isolated: Each transaction executes independent of any other transaction.  Bean Managed Transactions: In this type. its data is not saved to a database) Types of Session Beans Session beans are of three types: stateful and stateless.vtuprojects. Mr. the complete unit is considered failed.  Atomic: If any of work items fails. A transaction attribute can apply at the EJB level or at the method level. Ashok Kumar K | 9742024066 | celestialcluster@gmail.  NOT_SUPPORTED: Indicates that business method should not be executed as part of transaction.3 Session Java Bean Concept and Definition A session bean contains business logic used to provide a service to a client and exists for the duration of the client server session. Success meant all items executes successfully. Transaction elements A transaction is a single unit of work items which follows the ACID properties. A session bean is not persistent. A session bean terminates once the session with the client server terminates. This is referred to as container managed.com | Final year IEEE project development and training from scratch by Mr.  Durable: Transaction should survive system failure if it has been executed or committed. Registration started. An EJB’s transaction attribute is defined in the deployment descriptor by assigning one of the following values to the transaction attribute:  REQUIRED Indicates that business method has to be executed within transaction otherwise a new transaction will be started for that method. SessionBean. Except during method invocation. If the client removes the bean. Because they can support multiple clients. import javax. When a client invokes the methods of a stateless bean. its session bean appears to terminate and is no longer associated with the client.com . A session bean is not shared. A stateless session bean can implement a web service. the session ends and the state disappear. This transient nature of the state is not a problem. import java. Stateful session bean Stateless session bean Retains state between the method calls Does not retain state between the method calls Cannot be shared between clients Can be shared between clients Its life time is controlled by clients Its life time is controlled by the container A code skeleton of a session bean import javax.ejb.rmi.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.  Stateful Session Beans A stateful session bean retains the state (data) between the method calls with a client during a session. there is no need to retain the state. the client-specific state should not be retained.  Stateless Session Beans A stateless session bean does not retain the state between method calls and typically performs business logic that doesn’t require data to be maintained during the session. however. Contact 9742013378 or 9742024066 and lock your project at the earliest. When the client terminates. Ashok Kumar K | 9742024066 | celestialcluster@gmail. change the state of instance variables in pooled stateless beans. The state is retained for the duration of the client/bean session. When the method is finished. Because the client interacts (“talks”) with its bean.SessionContext. import javax. stateless session beans can offer better scalability for applications that require large numbers of clients. all instances of a stateless bean are equivalent.ejb. because when the conversation between the client and the bean ends.www. Registration started.RemoteException. allowing the EJB container to assign an instance to any client. public class CalculatorBean implements SessionBean { Mr. That is. Clients may. a session bean is similar to an interactive session. and this state is held over to the next invocation of the pooled stateless bean. the state of a stateless session bean should apply across all clients. an application requires fewer stateless session beans than stateful session beans to support the same number of clients.vtuprojects. however. this state is often called the conversational state. As its name suggests.EJBException.ejb. in the same way that an interactive session can have only one user. it can have only one client. the bean’s instance variables may contain a state specific to that client but only for the duration of the invocation. but a stateful session bean cannot. Typically. www. RemoteException { } } 8.4 Entity Java Bean Concept and Definition Entity bean is used to manage a collection of data retrieved from a database and stored in memory. Skeleton of an entity bean class myEJB implements EntityBean { int iD.vtuprojects. } public void setProduct(Product prod) { myProduct = prod. Most vendors support automatic persistence between the entity bean and a relational database. and removes data while maintaining the integrity of the data. private Product myProduct. RemoteException { } public void ejbPassivate() throws EJBException.com . Mr. public void ejbPostCreate() { } public Product getProduct() { return myProduct. However. updates. Data collected and managed by an entity bean is referred to as persistent data and is managed in one of the two ways  Container managed persistence  Bean managed persistence Container managed persistence (CMP) A container managed persistence (CMP) bean requires the container to manage the persistence. RemoteException { } public void ejbRemove() throws EJBException. RemoteException { } public void ejbCreate() throws EJBException. Registration started. The EJB container synchronizes the state of the entity bean with the database. An entity bean inserts. Ashok Kumar K. EJB container support varies by vendor. public int add(int a.com | Final year IEEE project development and training from scratch by Mr. RemoteException { } public void ejbActivate() throws EJBException. Contact 9742013378 or 9742024066 and lock your project at the earliest. Ashok Kumar K | 9742024066 | celestialcluster@gmail. } public void setSessionContext(SessionContext sessionContext) throws EJBException. A CMP entity is heavily dependent on support from the EJB container. int b) throws RemoteException { return a + b. Contact 9742013378 or 9742024066 and lock your project at the earliest. prodDescription. FinderException.com . CreateException. String desc) { prodName = name.vtuprojects. } Accessing the CMP bean Mr. } Remote Interface public interface myEJBRemote extends EJBObject { public getProduct() throws RemoteException. public Product(String name. Ashok Kumar K. prodDescription = desc. } public void setEntityContext(EntityContext cntx) { } public void unsetEntityContext() { } public void ejbLoad() { } public void ejbStore() { } public void ejbActivate() { } public void ejbPassivate() { } public void ejbRemove() { } } The product object definition import java.io.Serializable. class Product implements Serializable { public String prodName.www.com | Final year IEEE project development and training from scratch by Mr. Registration started. public myEJB findByPrimaryKey(Integer prodID) throws RemoteException. Ashok Kumar K | 9742024066 | celestialcluster@gmail. public setProduct(Product prod) throws RemoteException. } } Home interface public interface myEJBHome extends EJBHome { public myEJB create(Integer prodID) throws RemoteException. the EJB container tells the BMP bean when to insert a new record. A BMP bean uses the JDBC API or another appropriate database API to interface with the database.5 Message Driven Bean Concept and Definition A message driven bean is designed for clients to invoke server side business logic using asynchronous communication.com | Final year IEEE project development and training from scratch by Mr. Object obj = jndiContext.lookup("java:comp/env/ejb/myEJBHome"). A skeleton of a BMP bean class myBMPEJB implements EntityBean { public void ejbLoad() { // Read data from a database } public void ejbStore() { // Save data to a database } public void ejbCreate() { // Insert a record into the database } public void ejbRemote() { // Remove a record from a database } public Product findProduct() { // Find the specified product } } 8. these interactions take place under the direction of the EJB container.naming. myEJB mybean = obj.lookup("java:comp/env/ejb/myEJBHome"). Ashok Kumar K | 9742024066 | celestialcluster@gmail. Mr. Object obj = jndiContext.getProduct(). Bean managed persistence (BMP) A bean managed persistence (CMP) bean requires a bean to manage the persistence.www. However. Ashok Kumar K.com . Product prod = obj. modify data. Calling the CMP using the home interface javax.naming. Contact 9742013378 or 9742024066 and lock your project at the earliest. That is. Registration started.create(4321).vtuprojects. Calling the CMP using the remote interface javax.Context jndiContext = new InitialContext(). or delete data.Context jndiContext = new InitialContext(). which is a special case of a stateless session bean. retrieve data. Registration started. and then followed by the path and names of files that will be archived. a MDB monitors Java Message Service (JMS) communications and reacts to messages sent by clients.com . MessageDrivenBean { public void setMessageDrivenContext(MessageDrivenContext mdc) { } public void ejbCreate() { } public void ejbRemove() { } public void onMessage(Message clientMessage) { } } The onMessage() method is where the MDB processes messages received indirectly from a client. Client don’t directly access a MDB.6 The JAR file Concept EJB classes and related files are packaged together into a Java Archive (JAR) file for deployment. however it is customary to keep the dependent classes and interfaces in different JAR files.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail. 8. Mr. The JAR file used to package an EJB must contain the following.  EJB classes  Dependent classes  Remote interface  Home interface  Dependent interface  Primary key class  Deployment descriptor You can use the JAR utility by entering jar cf followed by name of the JAR file. Ashok Kumar K. Instead. There isn’t any home interface or remote interface for a MDB.vtuprojects. Instead. Skeleton of a MDB class myMDB implements MessageListener. the MDB intercedes and processes requests anonymously.www. Contact 9742013378 or 9742024066 and lock your project at the earliest. This is possible because a MDB is stateless. The JAR file is a compressed file format that was originally designed to reduce the size of software so it could be easily be transported.
Copyright © 2024 DOKUMEN.SITE Inc.