This document was ed by and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this report form. Report 2z6p3t
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
Fig: Through the JVM, 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. The Java platform is a software-only platform that runs on top of other hardware-based platforms like Windows, Mac, etc. 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. The bytecodes can be generated by compiling the java source code (.java file) using a java compiler. Bytecodes will be contained within .class files.
The Java Application Programming Interface (API) The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
Observations
Upon installing Java in any machine, 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. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. It constitutes the Java API component in the Java Platform. Java Runtime Environment (JRE) JRE is an implementation of Java Virtual Machine which actually runs the program. Typically, each JDK contains one (or more) JRE's along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.
ing and Installing Java You can the latest distribution of Java at its official website http://www.java.com/en//manual.jsp This site provides java distribution for Windows, Mac OS, Linux, and Solaris. and install latest version of Java on whichever the platform you are comfortable with. Installation procedure is pretty simple. Hopefully you don't encounter any blockage here. Give a try! After installing Java in your machine, please set the JAVA_HOME, PATH and CLASSPATH environment variables.
The JAVA_HOME is the variable that your operating system uses to locate the installation path of java.
The PATH is the variable that your operating system uses to locate needed executables from the command line or Terminal window.
The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for classes.
1.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, storage classes and goto statements and it doesn’t multiple inheritances.
Object oriented Java is purely an Object Oriented Programming language i.e., all the code of the Java language is written into the classes and objects.
Distributed Java is designed as distributed language because, for creating applications on network it has the ability to share the data and programs over the LAN (local area network). Java apps can open the remote objects on internet as easily they can do in local systems.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Multithreaded A Java program can be divided into multiple threads asg different tasks for different threads and have all the threads executing in parallel. Example for multithreaded application is a browser (multiple tabs can be opened; here each tab is a thread).
Dynamic The Java Virtual Machine (JVM) maintains a lot of runtime information about the program and the objects in the program. Libraries are dynamically linked during runtime. So, even if you make dynamic changes to pieces of code, the program is not affected.
Architecture neutral This means that the programs written on one platform can run on any other platform without having to rewrite or recompile them. In other words, it follows 'Write-once-run-anywhere' approach. 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.
Portable A C/C++ program may run slightly differently on different hardware platforms depending on how these platforms implement arithmetic operations. In Java, it has been simplified. Unlike C/C++, in Java the size of the primitive data types are machine independent. For example, an int in Java is always a 32-bit integer, and float is always a 32-bit IEEE 754 floating point number. These consistencies make Java programs portable among different platforms such as Windows, UNIX and Mac.
High performance Java programs are compiled to portable intermediate form known as bytecodes, rather than to native machine level instructions and JVM executes the bytecodes on any machine on which it is installed. 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.
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. Java’s features help to make the programs robust. Some of those features are: type checking, exception handling, etc
Secured Java provides data security through encapsulation. When we transfer the code from one machine to another, the JVM first check the code to check if it is affected by virus/threats or not. If the code is affected then it will never execute that code in that machine. Also we can write applets in Java which provides security. An applet is a small program which can be ed from a server using a browser. There is no need to worry about applets accessing the system resources which may compromise security.
1.3 Object oriented concepts Object An Object can be any real world entity we come across in our life. Example an Animal is an Object, also a Bank is an Object, a Human is an Object etc. An object is a software bundle of related state and behavior.
Class A class is a blueprint or prototype from which objects are created. It's just a template for an object. It describes an object. For Example, a class just describes how a Dog looks like. (Say, a dog has 4 legs, it barks, it eats etc.), but an Object refers to a real Dog.
Inheritance Generally, a process by which a child class acquires the state and behavior of its parent class is referred to as Inheritance. For example, Hyundai is a parent class whose properties are inherited by the classes named iTen, iTwenty, Verna, Getz etc.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Inheritance can also be referred to the concept of Generalization, which is the process of extracting common characteristics (states and behavior) from two or more classes, and combining them into a generalized super class.
Polymorphism The word "Polymorphism" refers to the ability to take more than one form. In of programming, the polymorphism refers to the process in which a member function of a class behaves differently for different inputs. For example, a function move() in the game of chess behaves differently for different pawns (for instance, it allows only sideways movement for camel and straight movement for elephant).
Encapsulation Encapsulation refers to the process of binding the data and the functions (that accesses these data) together. A class is an example for encapsulation. Through encapsulation a class can hide the internal details of how an object does something. Encapsulation helps to change the internal implementation of the object without affecting the overall functionality of the system. Encapsulation provides abstraction (Information hiding).
Interface An interface is a description of the actions that an object can do. For example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have. For example, anything that "ACTS LIKE" a light, should have a turn_on() method and a turn_off() method. So these two functions will be included within an interface. 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,Y,Z, etc.
Package A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You arrange all audio songs under a specific directory, and all video songs under another directory, etc. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.
1.4 Simple Java Programs My first Java Program Assumptions: Java has been installed and the environment variables are been properly set. Steps Step1: Open a text editor (notepad, edit plus, etc) and write the source code.
Step 2: Save this file as Hello.java in your local hard disk (where ever you wish)
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
Step 3: Open a command window and change the directory to the one where you just saved your Hello.java source file.
Step 4: Compile the source file using java compiler. i.e, by issuing a command as follows: javac Hello.java
If there are any compilation errors in your program, this command will not successfully executes, instead it will throw an error saying what went wrong. If your program is completely error free, the compilation process will be successful. You can observe that, the output of the compilation process is a .class file which is called the java "byte code". Step 5: Execute the .class file by giving it as an input to JVM through following command.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. java Hello
The program executes and the output can be seen in the console. Yes, you are done with your first Java program successfully. Congrats :)
Observations class Hello { public static void main (String arg[]) { System.out.println("Hello World. Welcome to the world of Java."); } }
Java's coding syntax closely resembles to that of C/C++.
All Java source files should have an extension of .java.
Java is case sensitive.
In C++, the class was optional. i.e., you can write a C++ program with or without a class. But in java it's not like that. Nothing can be written in Java without a class. So, you can observe the main function has been enclosed within a class.
Just like C/C++ which provides printf()/cout to print something on standard console, Java provides "println()" function to print something in the console. This println() method is a member of a class named "PrintStream", whose object is created and named as 'out' within a class called "System". Thus, println() function is referenced through a dot (.) notation (System.out.println)
Please focus on the signature of the main function. This signature can't be changed.
The keyword 'public' says that, the main function can be accessed even outside the defining class. This is like giving an access permission to JVM to execute the main function. If you mark it as private instead, 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. The keyword 'static' has a special meaning. Generally a class member is accessed through its object. So if JVM has to execute the main function, it has to get an object of the class enclosing the main function. But how will JVM get this object? Somehow, JVM has to execute the main function without having its object. The keyword 'static' comes as a solution for this. This keyword indicates that a function can be accessed without an object. The keyword 'void' indicates that a function returns nothing. In Java, you can't return anything from the main
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
function, so always the main function will be having a return type of void. 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. String arg[] within the main function parenthesis is used to hold command line arguments provided during the program execution. Let's see an example program at later point of time.
Comments in Java are of two types: Single line comments and Multiline comments. Single line comment starts with // followed by the comment string. Multi line comment starts with /* followed by the comment string and ends with */
There can be more than one class within a single .java file. The class that encloses the main function can be called as Main Class.
A java source file should be having the same name as the class name which contains the main function. You can't choose the name of your wish like in C/C++. This is to help the JVM to search for the main function.
In a single .java file where there are more than one classes, only one class can be marked as 'public' and this class should be the main class. All the other classes should either be marked as private or default. It enables a more efficient lookup of source (.java) and compiled (.class) files during compilation (import directives) and a more efficient class loading during execution.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
Practice Programs a. b. c. d. e. f. g. h. i.
j. k.
Program to illustrate data types, variables, and functions Program to illustrate classes and objects. Program to illustrate loops and control statements. Program to print the stars in left triangle pattern. Program to print the stars in right triangle pattern. Program to print the diamond pattern. Write a method named lastDigit that returns the last digit of an integer. For example, lastDigit(3572) should return 2. It should work for negative numbers as well. For example, lastDigit(-947) should return 7. Write a method named firstDigit that returns the first digit of an integer. For example, firstDigit(3572) should return 3. It should work for negative numbers as well. For example, firstDigit(-947) should return 9. Write a recursive function in java to print all natural numbers from 1 up to (n-1) . Write a Java program to print the command line arguments. Write a program to calculate the average among the elements {4,5,7,8}, using for each in java. How for each is different from for loop?
Program to illustrate data types, variables, and functions public class One { public static void main (String arg[]) { int a=10; String s = "Welcome"; System.out.println("Integer value is .... "+a); System.out.println("String value is .... "+s); int x=2, y=3; int res = add(x,y); System.out.println("Sum of "+x+" and "+y+" is .... "+res); } public static int add(int x, int y) { return x+y; } }
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Program to illustrate loops and control statements. class Three { public static void main (String arg[]) { for (int i=0; i<5; i++) { if (i%2==0) { System.out.println(i+" is a Even Number "); } else { System.out.println(i+" is a Odd Number "); } } } }
Program to print the stars in left triangle pattern class Four { public static void main (String arg[]) { int n=5; for (int i=0;i
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. 9742013378 or 9742024066 and lock your project at the earliest.
Program to print the stars in right triangle pattern class Five { public static void main (String arg[]) { int n=5; for (int i=0;i
=i;k--) System.out.print("\t"); for (int j=0;j<=i;j++) System.out.print("*\t"); System.out.println("\n"); } } }
Program to print the diamond pattern. class Six { public static void main (String arg[]) {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. int n=5; for (int i=0; i
=0;i--) { for (int j=0;j
Write a method named lastDigit that returns the last digit of an integer. For example, lastDigit(3572) should return 2. It should work for negative numbers as well. For example, lastDigit(-947) should return 7. class Seven { public static void main (String arg[]) { int n = -7676; int ld = lastDigit(n); System.out.println("Last Digit in "+n+" is .... "+ld); n = 3489; ld = lastDigit(n);
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. System.out.println("Last Digit in "+n+" is .... "+ld); } public static int lastDigit(int n) { return Math.abs(n%10); } }
Write a method named firstDigit that returns the first digit of an integer. For example, firstDigit(3572) should return 3. It should work for negative numbers as well. For example, firstDigit(-947) should return 9.
class Eight { public static void main (String arg[]) { int n = -7676; int ld = firstDigit(n); System.out.println("First Digit in "+n+" is .... "+ld); n = 3489; ld = firstDigit(n); System.out.println("First Digit in "+n+" is .... "+ld); } public static int firstDigit (int n) { n = Math.abs(n); while (n > 9) { n = n/10; } return n; } }
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
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; series(n); } public static void series(int x) { if (x > 0) series(--x); if (x != 0) System.out.print(x + " "); } }
Write a Java program to print the random number in between 0 and n import java.util.Random; public class Ten { public static void main(String args[]) { Random r = new Random(); int n = 100; int ran = r.nextInt(n); System.out.println("Random number in betwwen 0 and "+n+" is .... "+ran); n = 200; ran = r.nextInt(n); System.out.println("Random number in betwwen 0 and "+n+" is .... "+ran);
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. n = 300; ran = r.nextInt(n); System.out.println("Random number in betwwen 0 and "+n+" is .... "+ran); n = 400; ran = r.nextInt(n); System.out.println("Random number in betwwen 0 and "+n+" is .... "+ran); } }
Write a Java program to print the command line arguments public class Eleven
{
public static void main (String arg[]) { System.out.println("Command line arguments are .. "); for (String s : arg) { System.out.println(s); } } }
Write a program to calculate the average among the elements {4,5,7,8}, using for each in java. How for each is different from for loop? public class Twelve {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public static void main(String args[]) { int arr[] = {4,5,7,8}; int sum = 0; for (int ele : arr) { sum = sum + ele; } System.out.println("Average = "+ (float) sum/arr.length); } }
1.5 Variables and Data types 1.5.1 Variables Variable is the name or the identifier given to the known memory location. It is used to store some program data/value which might be referenced in future. To put it in the other way, the memory location will be accessed through the variable name. 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. i.e., its value will be unique to each instance of a class. Instance variables will not be having 'static' keyword prefixed. They are also called non static variables. Class Variables (Static) Variable which actually shares the value among all the instances of a class is called a Class Variable. It is created by prefixing the keyword 'static' while declaring a variable. 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. It is also called static variable. Local Variables Any method in java will store its temporary state in a local variable. A variable which can be accessed only within its defining block can be called as a local variable for that block. It can't be accessed anywhere else outside this block. There is no special keyword to designate a variable as local. 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.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. A Data type is the classification identifying one of the various types of data, which determines the possible values for that type. There are eight primitive data types and three reference data types in Java as described by the figure.
Fig: Data types in Java
Primitive Data types The Primitive data types are predefined data types, which always hold the value of the same data type, and the values of a primitive data type don't share the state with other primitive values. These data types are named by a reserved keyword in Java programming language.
byte: The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters
short: As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
int: For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead
long: Use this data type when you need a range of values wider than those provided by int.
float: The float data type is a single-precision 32-bit IEEE 754 floating point. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers.
double: The double data type is a double-precision 64-bit IEEE 754 floating point. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. Data type
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 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.40129846432481707e-45 to 3.40282346638528860e+38
double
64 bits (8 bytes)
4.94065645841246544e-324d to 1.79769313486231570e+308d
char
16 bits (2 bytes)
0 to 65,535
boolean
1 bit
true or false
String data type In addition to the eight primitive data types listed above, the Java programming language also provides special for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; For example, String s = "Ashok Kumar"; String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special given to it by the language; 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. These types of data type are not predefined like primitive data type. The reference data types are arrays, classes and interfaces that are made and handled according to a programmer need.
Array: An array is a special kind of object that contains collection of similar type of elements. The java array enables the to store the values of the same type in contiguous memory allocations. 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. All elements of an array must contain the same type of value i.e. if an array is a type of integer then all the elements must be of integer type.
It is a reference data type because the class named as Array implicitly extends
java.lang.Object. There are two different ways of declaring an array as shown below: datatype[] arr_name = new datatype[arraysize]; Ex: int[] arr = new int[50]; datatype[] arr_name = {element 1, element 2, ................. , element n} Ex: int[] arr = {5, 10, 15, 20, 25};
Class: The name of a class is treated as a type in a java program, so that you can declare a variable of an object-type, and a method which can be called using that object- type variable. Whenever a variable is created, a reference to an
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. object is also created using the name of a class for its type i.e. that variable can contain either null or a reference to an object of that class. It is not allowed to contain any other kind of values. Such type is called reference types in Java. The object becomes an instance when the memory is allocated to that object using new keyword. Ex: class Box { int h, w, l; double getArea() { } void setValues (int h, int w, int l) { } } Box b = new Box(); // here b is an object/instance, Box is a class type
Interface: The name of an interface can be used to specify the type of a reference. A value is not allowed to be assigned to a variable declared using an interface type until the object implements the specified interface. Hold on here, you will learn more about interfaces in later chapters.
1.5.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. Data Type
Default Value
byte
0
short
0
int
0
long
0L
float
0.0f
double
0.0d
char
'\u0000'
String (or any object)
null
boolean
false
1.5.4 Literals The new keyword isn't used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. As shown below, it's possible to assign a literal to a variable of a primitive type: boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000;
Integer Literal: An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. Please use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1. Following example shows the syntax for creating the literals in binary and hexadecimal number system. // The number 26, in decimalint decVal = 26; // The number 26, in hexadecimal int hexVal = 0x1a; // The number 26, in binary int binVal = 0b11010;
Floating-point Literal: A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d. The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal), and D or d (64-bit double literal; this is the default and by convention is omitted). Examples: double d1 = 123.4; // same value as d1, but in scientific notation double d2 = 1.234e2; float f1 = 123.4f;
Character and String Literals: Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as '\u0108' (capital C with circumflex), or "S\u00ED Se\u00F1or" (Sí Señor in Spanish). Always use 'single quotes' for char literals and "double quotes" for String literals.
There is a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. null is often used in programs as a marker to indicate that some object is unavailable.
Finally, there is another literal called a class literal, formed by taking a type name and appending ".class"; for example, String class. This refers to the object (of type Class) that represents the type itself.
1.5.5 Escape Characters Java s a few special escape sequences for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote),
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. \' (single quote), and \\ (backslash).
1.5.6 Creating and Destroying Objects We know that, a class is a template (blue print) for an object, and an object is an instance of the class.
Creating Objects (Object instantiation) Consider a class definition as follows, class Box { int w; int l; int h; // This is a constructor Box(int w, int l, int h) { this.w = w; this.h = h; this.l = l; } long
getArea() { return l*w*h;
} } Object of this class can be created as follows: Box b1 = new Box(5, 10, 15); The object creation statement above have three parts:
Declaration: LHS of the above statement constitutes the declaration. It is associated with variable name and object type. 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.
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; b2 = b1;
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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, so you don't need to delete the object that you've created. JVM does it for you automatically through Garbage Collection. We will see the concept of Garbage Collection in deep at later chapters.
1.5.7 Access specifiers in Java One of the concepts in object-oriented programming is encapsulation. It concerns about the hiding of data in a class and making this class available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via so-called access specifiers. Java provides four different types of access specifiers
public public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with Java source code can only contain one public class which should be a main class.
protected protected methods and fields can only be accessed within the same class to which the methods and fields belong, also within its subclasses but not from anywhere else. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes.
private private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation
default If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
1.6 Operators and Expressions 1.6.1 Operators Operators are such symbols that perform some operations on one or more operands. Operators are used to manipulate primitive data types. Once we declare and initialize the variables, we can use operators to perform certain tasks like asg a value, adding the numbers etc. Operators in Java are classified as follows: The list below is arranged in the order of their precedence (Highest to Lowest)
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
Example: public class Example { public static void main(String[] args) { int num1 = -5; num1 = num1 >> 2; System.out.println(num1); int num2 = 5; num2 = num2 >>> 2; System.out.println(num2); int num3 = 5; num3 = num3 << 2; System.out.println(num3); } }
Bitwise Operators
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise complement operator ~ inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".
Example public class Example { public static void main(String[] args) { int num1 = -5; num1 = num1 & 2; System.out.println(num1); int num2 = 5; num2 = num2 & 2;
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. System.out.println(num2); int num3 = 5; num3 = ~num3; System.out.println(num3); } }
Ternary Operator The ternary operator (also known as the conditional operator) can be used as an alternative to the Java if/then/else syntax, but it goes beyond that, and can even be used on the right hand side of Java statements. Syntax (condition) ? (truth block) : (false block) ; The condition gets evaluated first. If the condition evaluates to true, the truth block gets executed and returns, else the false block gets executed and returns. Example public class Example { public static void main(String[] args) { int a = 10; int b = 20; int min = (a < b) ? a: b; System.out.println("Min value is .. "+min); } }
Logical Operators public class Example { public static void main(String args[]) {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. boolean a = true; boolean b = false; System.out.println("a && b = " + (a && b)); System.out.println("a || b = " + (a || b)); System.out.println("!(a && b) = " + !(a && b)); } }
1.6.2 Expressions An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, which evaluates to a single value. Some examples of expressions are illustrated in bold below: int cadence = 0; anArray[0] = 100; System.out.println("Element 1 at index 0: " + anArray[0]); int result = 1 + 2; // result is now 3 if (value1 == value2) System.out.println("value1 == value2"); The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence=0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String. The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression: 1 * 2 * 3 In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first: x + y / 100
// ambiguous
You can specify exactly how an expression will be evaluated using balanced parenthesis: ‘(‘ and ‘)’. For example, to make the previous expression unambiguous, you could write the following: (x + y) / 100
// unambiguous, recommended
If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Therefore, the following two statements are equivalent: x + y / 100
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. x + (y / 100) // unambiguous, recommended When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice makes code easier to read and to maintain.
1.7 Control Statements Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements; Selection statements
If
if-else
switch
Iteration statements
while
do-while
for
Jump statements
break
continue
return
1.7.1 Selection Statements
The if statement The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression. Syntax: if (
) { <statements> } Example: public class Example {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } }
The if –else statement The if-else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression. Syntax: if (
) { <statements> } else { <statements> } Example: public class Example { public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); else System.out.println("b > a"); } }
The switch statement The switch case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. Structure of switch case:
The switch statement begins with a keyword, followed by an expression that equates to a no long integral value.
Following the controlling expression is a code block that contains zero or more labeled cases.
Each label must equate to an integer constant and each must be unique.
Working of switch case:
When the switch statement executes, it compares the value of the controlling expression to the values of each case label.
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.
If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
We can have a nested switch within a case block of an outer switch.
Syntax: switch (<non-long integral expression>) { case label1: <statement1> ; break; case label2: <statement2> ; break; … case labeln: <statementn> ; break; default: <statement> } Example: public class Example { public static void main(String[] args) { int a = 10, b = 20, c = 30; int status = -1; if (a > b && a > c) { status = 1; } else if (b > c) { status = 2; } else { status = 3; } switch (status) { case 1: System.out.println("a is the greatest"); break; case 2: System.out.println("b is the greatest"); break; case 3: System.out.println("c is the greatest"); break; default: System.out.println("Cannot be determined"); } } }
1.7.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. You can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression. Syntax: while (
) {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. <statements> } Example: public class Example { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); while (count <= 10) { System.out.println(count++); } } }
The do-while loop The do-while loop is similar to the while loop, 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. Syntax: do {
} while (
); Example: public class Example { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); do { System.out.println(count++); } while (count <= 10); } }
The for loop The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a counter controlled loop. Syntax: for (
;
;
) {
} Example: public class Example { public static void main(String[] args) {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. System.out.println("Printing Numbers from 1 to 10"); for (int count = 1; count <= 10; count++) { System.out.println(count); } } }
1.7.3 Jump Statements
The break statement The break statement transfers control out of the enclosing loop (for, while, do or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops. Syntax: break; // the unlabeled form break
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
MULTITHREADED PROGRAMMING 3.1 Multithreaded programming basics Definition of concurrency (multithreading) Concurrency is the ability to run multiple parts of the program in parallel. If a program can be divided into multiple independent parts, each performing a specific task, then executing these parts in parallel in an asynchronous way increases the throughput of the program. This type of programming is generally referred to as Concurrent Programming.
Process v/s Thread In Concurrent programming, there are two units of execution: Processes Threads Process
Thread
Definition: Process is an instance of an entire program in execution.
Definition: Thread is an execution path or the control flow of execution of a program.
A process has a separate execution environment. It has a complete, private set of basic run-time resources; each process has its own memory space
Threads exist within a process; every process has at least one thread. Threads share the process's resources, including memory and open files. Threads are called light-weight process
: Threads have their own call stack and can access shared data. 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. Access problem can occur if several threads tries to access and share the same shared data at the same time.
3.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. This default thread or the main thread will be created by JVM. You can also create child threads using this. Main thread is something which you should mark as important, 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.
Each thread in java is associated with an instance of the class java.lang.Thread.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Let's play with main thread for some time. , each thread will be having a name and priority (dealt later). A Thread can also sleep, meaning go to IDLE state for some specified amount of time. Below example does some exercise with the main thread. It first gets the access (reference) to main thread using currentThread() method in Thread class. It prints the name of the thread whose reference we have just got. It changes the name and priority of the thread using setName() and setPriority() methods respectively. It prints the numbers 0 through 4 with a delay of 1sec after each number. The thread is made to sleep for 1 sec after printing one number. A thread can be sent to sleep using Thread.sleep(long) method where the parameter is the amount of time in milliseconds. public class Example { public static void main(String arg[]) { Thread t = Thread.currentThread(); System.out.println("Hi Everyone .. I am a thread .. " + t); t.setName("NewMain"); t.setPriority(9); System.out.println("Hi Everyone .. I am the same thread .. " + t); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(i); } } catch (InterruptedException e) { e.printStackTrace(); } } } Output
When you simply print a thread reference t, you know that it will invoke t.getString() method which printed something like this: Thread[main, 5, main]. Here is what actually they are:
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
3.3 Creating a Thread Threads in java can be created in two possible ways 1. 2.
By implementing Runnable interface By extending Thread class
Creating a thread by implementing Runnable interface Step 1: Simply define your own class and implement it by java.lang.Runnable interface. Define run() method and include the business logic of the thread within the run() method, because run() is the entry point for a thread and when it returns from this function, the thread dies. To put it differently, a thread will be active till it lies in the context of run() method. Instance of this class is called Runnable object since it implements Runnable interface. class MyThread implements Runnable { public void run() { System.out.println("Child thread started.. "); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Child .. " + i); } System.out.println("Child thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } }
Step 2: Creating a child thread is nothing but creating an instance of Thread class and ing the runnable object as a parameter for its constructor. , at this point of time you have only created a child thread, but you haven't started its execution yet. To do so, you should invoke start() method of the thread object you just created. It causes the child thread to start its execution. The JVM calls run() method of the child thread. 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 is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. public class Example { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread(); // Create a child thread Thread t1 = new Thread(m1); // Start (run) a child thread t1.start(); try { for (int i = 0; i < 5; i++) {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Thread.sleep(1000); System.out.println("Main .. " + i); } System.out.println("Main thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } Output:
The order of execution of two threads is not the same always. The output you are seeing above can't be predicted. Since the main thread and the child thread both are executing in parallel you can't expect the same ordering all the time. It just gets mixed up.
Observation: As a component developer you should focus on both the business logic and the required resources to create a thread. An application developer will simply makes use of this. What I meant to tell is you should allow full freedom to the of this thread. You should encapsulate the process of creating a thread within the custom Thread class itself, as shown below; Here is the optimized version of above program class MyThread implements Runnable { Thread t; MyThread() { t = new Thread(this); t.start(); } public void run() { System.out.println("Child thread started.. "); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Child .. " + i); } System.out.println("Child thread exiting .. "); } catch (InterruptedException e) {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. e.printStackTrace(); } } } public class Test { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread(); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } System.out.println("Main thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } }
Creating a thread by extending Thread class Step 1: Simply extend your own class with java.lang.Thread. Define run() method and include the business logic of the thread within the run() method, because run() is the entry point for a thread and when it returns from this function, the thread dies. class MyThread extends Thread { public void run() { System.out.println("Child thread started.. "); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Child .. " + i); } System.out.println("Child thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } }
Step 2: Creating a thread is just creating an instance of the class defined in step 1. To begin the execution of the child thread, you should invoke the run() method of the object created. public class Test2 { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread(); // Start a thread m1.start(); try {
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } System.out.println("Main thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } }
Observation: As discusses previously, the logic of creating a thread should be encapsulated within the Thread class by the component developer. Here is the optimized version of the above program. class MyThread extends Thread { MyThread() { this.start(); } public void run() { System.out.println("Child thread started.. "); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Child .. " + i); } System.out.println("Child thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test2 { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread();
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Now that you have two different ways of creating a thread, which one would you prefer? Creating a thread by implementing Runnable interface is preferred over extending the Thread class for two reasons.
Inheritance should be done only if you are modifying or enhancing the base class behavior. Since our class doesn't modify or enhance the Thread class behavior, extending the Thread class is not recommended. If you extend the Thread class, you now don't have freedom of extending other classes (since multiple inheritances are not allowed). So we prefer implementing the Runnable interface and extending any other class.
Creating multiple threads You can create as many threads as you want. 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. One more thing you need to observe from below program is the method of asg a name to the child thread. Yes, you can set the name of a child thread by ing the name as a String argument to the Thread class constructor. class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); // 'name' is the child thread's name t.start(); } public void run() { System.out.println("New Thread started with the name .."+Thread.currentThread().getName()); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" .. " + i); } System.out.println(Thread.currentThread().getName()+" exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test { public static void // Runnable MyThread m1 MyThread m2 MyThread m3 MyThread m4
main(String arg[]) { Object = new MyThread("ChildOne"); = new MyThread("ChildTwo"); = new MyThread("ChildThree"); = new MyThread("ChildFour");
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Output
You can clearly see the order in which these threads execute can't be predicted. It depends on many things including the thread priority.
3.4 isAlive() and () Recall we had concluded that the main thread should be the last thread to terminate. But as we can see from the output of previous program, main thread is being terminated well before its child threads terminate. Right, the problem in discussion here is, 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. Let’s analyze each one of them.
Method 1: Make the main thread to sleep for some specified amount of time just before its termination, so that all its child threads can
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. terminate by that time. class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); t.start(); }
public void run() { System.out.println("New Thread started with the name .. "+Thread.currentThread().getName()); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" .. " + i); } System.out.println(Thread.currentThread().getName()+" exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test { public static void // Runnable MyThread m1 MyThread m2 MyThread m3 MyThread m4
main(String arg[]) { Object = new MyThread("ChildOne"); = new MyThread("ChildTwo"); = new MyThread("ChildThree"); = new MyThread("ChildFour");
try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } } catch (InterruptedException e) { e.printStackTrace(); } // Main Thread will sleep for 10 seconds try { Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } System.out.println("Main thread exiting .. "); } } Output:
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
You can observe the main thread is terminating at last. 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. You would end up choosing lesser time giving no time for some of its child threads to terminate.
Method 2: Using isAlive() method. Main thread can invoke isAlive() method on each of its child threads to see if it is still running or already terminated. This way, the main thread will be in a continuous loop until all the child threads gets terminated. isAlive() is a method defined in Thread class and have the signature as follows: final boolean isAlive()
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. It returns true if the thread upon which it is called is still running. It returns false otherwise. Example class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); t.start(); } public void run() { System.out.println("New Thread started with the name .. "+Thread.currentThread().getName()); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" .. " + i); } System.out.println(Thread.currentThread().getName()+" exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test { public static void // Runnable MyThread m1 MyThread m2 MyThread m3 MyThread m4
main(String arg[]) { Object = new MyThread("ChildOne"); = new MyThread("ChildTwo"); = new MyThread("ChildThree"); = new MyThread("ChildFour");
try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } } catch (InterruptedException e) { e.printStackTrace(); }
// Main Thread will come out of this loop only after all the threads terminates while (true) { if (m1.t.isAlive() || m2.t.isAlive() || m3.t.isAlive() || m4.t.isAlive()) { // loop again } else break; // come out of the loop } System.out.println("Main thread exiting .. "); } } Output
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
Drawback: This method has unspecified amount of continuous looping to check the status of the child threads thus wasting the runtime resources.
Method 3: Using () method. () is the method we mostly use to wait for a thread to finish its execution. () method is also defined in Thread class with the signature as follows: final void ( ) throws InterruptedException This method waits until the thread on which it is called terminates. Additional forms of ( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate. Example
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); t.start(); }
public void run() { System.out.println("New Thread started with the name .. "+Thread.currentThread().getName()); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" .. " + i); } System.out.println(Thread.currentThread().getName()+" exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Example { public static void // Runnable MyThread m1 MyThread m2 MyThread m3 MyThread m4
main(String arg[]) { Object = new MyThread("ChildOne"); = new MyThread("ChildTwo"); = new MyThread("ChildThree"); = new MyThread("ChildFour");
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
3.5 Thread priorities Each thread in Java will have an associated priority which is an integer value ranging from 1 (minimum) to 10 (maximum). Thread scheduler will use the thread priorities to determine the execution schedule of threads. Higher priority threads get the U much faster than the lower priority threads. If two threads have the same priority, the thread scheduler treats them equally and serves them based on First Come First Serve (FCFS) basis.
setPriority(int) and getPriority() Thread class defines two methods, one for setting the thread priority and the other for returning the current priority of a thread. Their signatures are as follows: void setPriority(int); sets the priority of a calling thread to the one ed as an argument. int getPriority(); returns the current priority of the calling thread
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Thread priority is an integer value ranging from 1 to 10. Thread class defines three integer constants to represent this: Priority value 1 5 10
Description Minimum priority of a thread Default priority of a thread Maximum priority of a thread
Example: class MyThread implements Runnable { Thread t; int count=0; MyThread(String name, int pri) { t = new Thread(this, name); t.setPriority(pri); t.start(); } public void run() { while (true) { count++; } } } public class Test { public static void // Runnable MyThread m1 MyThread m2
main(String arg[]) { Object = new MyThread("LowPriorityThread", Thread.MIN_PRIORITY); = new MyThread("HighPriorityThread", Thread.MAX_PRIORITY);
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
3.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. The process by which this is achieved is called synchronization. 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.
How synchronization works The block of code or in general any resources, which is shared among more than two threads and which needs to be synchronized, is called a monitor (also known as semaphore). Only one thread can access the monitor at any point of time. When a thread enters the monitor, we say that the thread has acquired the lock, and it prevents any other threads entering into the same monitor until it releases the lock by exiting the monitor.
Problem demonstration Below program has a class named Utility which defines a method called printMessage(String). It takes a string argument and prints it within the flower braces { and }. When two threads accesses this method at the same time each one ing a different string argument, the order in which these messages are printed are not jumbled (mixed up). class Utility { // this is the shared resource public void printMessage(String msg) { System.out.print("{"); System.out.print(msg); System.out.println("}"); } } class MyThread implements Runnable { Thread t; Utility util; String msg; MyThread(Utility util, String msg) { t = new Thread(this); this.util = util; this.msg = msg; t.start(); } public void run() { util.printMessage(msg); } } public class Example { public static void main(String arg[]) { Utility util = new Utility(); MyThread m1 = new MyThread(util, "Sachin"); MyThread m2 = new MyThread(util, "Kohli"); } }
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Output
Synchronization in Java can be achieved in two different ways: 1. 2.
Using synchronized methods Using synchronized blocks
Synchronized methods This solution is simple. Just prefix the keyword 'synchronized' to the shared resource which needs to be synchronized. The resource can be a method, variable or any other program elements. Here the shared resource is the printMessage() method. class Utility { // shared resource is synchronized synchronized public void printMessage(String msg) { System.out.print("{"); System.out.print(msg); System.out.println("}"); } } class MyThread implements Runnable { Thread t; Utility util; String msg; MyThread(Utility util, String msg) { t = new Thread(this); this.util = util; this.msg = msg; t.start(); } public void run() { util.printMessage(msg); } } public class Example { public static void main(String arg[]) { Utility util = new Utility(); MyThread m1 = new MyThread(util, "Sachin"); MyThread m2 = new MyThread(util, "Kohli"); } } Output
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
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. But, what if you are not the owner of Utility class? Meaning, you are not authorized to modify the class and you cannot add the synchronized keyword to its method. In these situations, you can go with synchronized blocks. Simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized statement: synchronized(object) { // statements to be synchronized } Here, object is a reference to the object being synchronized. 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. class Utility { public void printMessage(String msg) { System.out.print("{"); System.out.print(msg); System.out.println("}"); } } class MyThread implements Runnable { Thread t; Utility util; String msg; MyThread(Utility util, String msg) { t = new Thread(this); this.util = util; this.msg = msg; t.start(); } public void run() { synchronized (util) { util.printMessage(msg); } } } public class Test { public static void main(String arg[]) { Utility util = new Utility(); MyThread m1 = new MyThread(util, "Sachin"); MyThread m2 = new MyThread(util, "Kohli"); } } Output
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
3.7 Inter thread communication There are three methods defined in Object class namely notify(), notifyAll(), and wait() that constitutes for inter thread communication.
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().
notify(): This method wakes up the first thread that called wait() on the same object.
notifyAll(): This method wakes up all the threads that called wait() on the same object. The highest priority thread will run first.
These methods can be called only within a synchronized context.
3.8 Producer Consumer Implementation Below example shows an implementation of solution for producer-consumer problem. It consists of four classes. 1. Class Q, the queue you are trying to synchronize. 2. Producer, threaded object that is producing queue entries. 3. Consumer, threaded object that is consuming queue entries. 4. PC, tiny class that creates single Q, Producer, and Consumer. class Q { int n; boolean valueSet = false; synchronized int get() { while (!valueSet) try { wait(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); }
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. System.out.println("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { while (valueSet) try { wait(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); } } class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while (true) { q.put(i++); } } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while (true) { q.get(); } } } public class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } } Output:
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
3.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.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
EVENT HANDLING IN JAVA 3.10 Delegation Event Model Delegation Event Model constitutes of three entities: event, source, and listener.
Event Event is an object that describes the state change. These objects are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener and ing in the instance of the event subclass which defines the event type generated.
Source An Event Source is an object which originates or "fires" events. (Example, an Applet). A source must listeners in order for the listeners to receive notifications about a specific type of event.
ing a listener: Each type of event has its own registration method. Here is the general form: public void addTypeListener(TypeListener el) Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that s a keyboard event listener is called addKeyListener(). The method that s a mouse motion listener is called addMouseMotionListener().
Uning a listener: A source must also provide a method that allows a listener to un an interest in a specific type of event. The general form of such a method is this: public void removeTypeListener(TypeListener el) Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ).
Listener A listener is an object which will be notified when an event occurs. A Listener is an object that implements a specific EventListener interface extended from the generic java.util.EventListener. It has two major requirements:
First, it must have been ed with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
3.11 Event Almost for every possible type of event that can occur (Ex, click a button, scroll the mouse, etc), Java defines a separate class for it. java.util.EventObject is the root of all the event classes. The class java.awt.AWTEvent, is a subclass of EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model. The package java.awt.event defines various event classes to describe the events generated by various interface elements. Here are the few: Event class ActionEvent
Description Generated when a button is pressed, a list item is double-clicked, or a menu item is selected Generated when a scroll bar is manipulated. Generated when a component is hidden, moved, resized, or becomes visible Generated when a component is added to or removed from a container. Generated when a component gains or loses keyboard focus. Abstract superclass for all component input event classes. Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselected. Generated when input is received from the keyboard. Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component. Generated when the mouse wheel is moved. Generated when the value of a text area or text field is changed. Generated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.
Let's explore only KeyEvent and MouseEvent classes
KeyEvent A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants:
KEY_PRESSED KEY_RELEASED, and KEY_TYPED.
The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. , not all key presses result in characters. For example, pressing SHIFT does not generate a character. There are many other integer constants that are defined by KeyEvent.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. 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, but the most commonly used ones are getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns the key code. Their general forms are shown here: char getKeyChar( ) int getKeyCode( )
MouseEvent There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them: MOUSE_CLICKED MOUSE_DRAGGED MOUSE_ENTERED MOUSE_EXITED MOUSE_MOVED MOUSE_PRESSED MOUSE_RELEASED MOUSE_WHEEL
The clicked the mouse. The dragged the mouse. The mouse entered a component. The mouse exited from a component. The mouse moved. The mouse was pressed. The mouse was released. The mouse wheel was moved.
Two commonly used methods in this class are getX( ) and getY( ). These returns the X and Y coordinate of the mouse within the component when the event occurred. Their forms are shown here: int getX() int getY()
3.12 Event Source Table below lists some of the interface components that can generate the events described in the previous section. Event Source Button Check box Choice List Menu Item Scroll bar Text components Window
Description Generates action events when the button is pressed. Generates item events when the check box is selected or deselected. Generates item events when the choice is changed. Generates action events when an item is double-clicked; generates item events when an item is selected or deselected. Generates action events when a menu item is selected; generates item events when a checkable menu item is selected or deselected. Generates adjustment events when the scroll bar is manipulated.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
3.13 Event Listener Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Table below lists commonly used listener interfaces and provides a brief description of the methods that they define. Listener Interface ActionListener AdjustmentListener ComponentListener ContainerListener FocusListener ItemListener KeyListener MouseListener MouseMotionListener MouseWheelListener TextListener WindowFocusListener WindowListener
Description Defines one method to receive action events. Defines one method to receive adjustment events. Defines four methods to recognize when a component is hidden, moved, resized, or shown. Defines two methods to recognize when a component is added to or removed from a container. Defines two methods to recognize when a component gains or loses keyboard focus. Defines one method to recognize when the state of an item changes. Defines three methods to recognize when a key is pressed, released, or typed. Defines five methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed, or is released.
KeyListener interface This interface defines following methods void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke)
MouseMotionListener interface This interface defines following methods void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me)
3.14 Example programs Handling Mouse Events To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces. The following applet demonstrates the process. o It displays the current coordinates of the mouse in the applet’s status window.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. o o o o
Each time a button is pressed, the word “Down” is displayed at the location of the mouse pointer. Each time the button is released, the word “Up” is shown. If a button is clicked, the message “Mouse clicked” is displayed in the upper left corner of the applet display area. As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the applet display area. When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint(); } // Handle mouse moved. public void mouseMoved(MouseEvent me) { showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } Output:
Handling Keyboard Events To handle key board events, you will be implementing KeyListener interface. Before going to the program, Let's see how key events are generated. o When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed() event handler. o When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is executed. o If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( ) handler is invoked. Thus, each time the presses a key, at least two and often three events are generated. Here is the program to demonstrate the handling of key events. import java.awt.*; import java.awt.event.*;
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. import java.applet.*; public class KeyEventExample extends Applet implements KeyListener { String msg = ""; int X = 10, Y = 20; public void init() { addKeyListener(this); } public void keyPressed(KeyEvent ke) { showStatus("Key Down"); } public void keyReleased(KeyEvent ke) { showStatus("Key Up"); } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } public void paint(Graphics g) { g.drawString(msg, X, Y); } } Output
3.15 Adaptor Classes Java provides a special feature, called an adapter class, which can simplify the creation of event handlers.
Definition An adapter class provides an empty implementation of all methods in an event listener interface. 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. You can define a new
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested. Table below shows Commonly Used Listener Interfaces Implemented by Adapter Classes. Adaptor class ComponentAdapter ContainerAdapter FocusAdapter MouseAdapter MouseMotionAdapter WindowAdapter
Example for Adaptor class import java.awt.*; import java.awt.event.*; import java.applet.*; public class AdapterDemo extends Applet { public void init() { addMouseListener(new MyMouseAdapter(this)); addMouseMotionListener(new MyMouseMotionAdapter(this)); } } class MyMouseAdapter extends MouseAdapter { AdapterDemo adapterDemo; public MyMouseAdapter(AdapterDemo adapterDemo) { this.adapterDemo = adapterDemo; } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { adapterDemo.showStatus("Mouse clicked"); } } class MyMouseMotionAdapter extends MouseMotionAdapter { AdapterDemo adapterDemo; public MyMouseMotionAdapter(AdapterDemo adapterDemo) { this.adapterDemo = adapterDemo; } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { adapterDemo.showStatus("Mouse dragged"); } }
3.16 Inner Classes, 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Till now we have seen how to handle events by using “this” reference.
Inner classes Below example shows how to handle the events by using an inner class. import java.applet.*; import java.awt.event.*; public class InnerClassDemo extends Applet { public void init() { addMouseListener(new MyMouseAdapter()); } class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } } } Advantage of handling the event by using inner class is that, the inner class can directly call the showStatus() method, and there is no need to store a reference to the applet.
Anonymous Inner classes An anonymous inner class is one that is not assigned a name. This example illustrates how to use anonymous inner class to handle events. import java.applet.*; import java.awt.event.*; public class AnonymousInnerClassDemo extends Applet { public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } }); } } The syntax new MouseAdapter( ) { ... } indicates to the compiler that the code between the braces defines an anonymous inner class. Furthermore, that class extends MouseAdapter. This new class is not named, but it is automatically instantiated when this expression is executed.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
4.1 Basics In unit 2, we had seen how to build interfaces using AWT.
Limitations of AWT API AWT translates its various visual components into their corresponding, platform-specific equivalents, or peers. Therefore, the look and feel will be decided by the platform and not by Java. Therefore, AWT is referred to as heavyweight. 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. It caused some restrictions on usage of the components.
Definition Swing API is set of extensible GUI Components to ease developer's life to create JAVA based Front End/ GUI Applications. It is built on top of AWT API and it overcomes most of its limitations. Swing has almost every control corresponding to AWT controls.
AWT versus Swing AWT AWT components are platform-dependent AWT is called the abstract window tool AWT components are heavyweight components AWT occupies more memory space AWT require javax.awt package AWT is not MVC based AWT works slower
Swing Swing are platform independent Swing is part of the java foundation classes Swing components are lightweight components because swing sits on the top of AWT Swing occupies less memory space Swing requires javax.swing package Swing are MVC based architecture Swing works faster
4.2 Swing features Here are the two key features of swing.
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.
Pluggable look and feel (PLAF) Swing based GUI Application’s look and feel logic can be separated from the component’s business logic.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Advantages of PLAF
It is possible to define look and feel that is consistent across all platforms. Conversely, it is also possible to create a look and feel that acts like a specific platform. It is also possible to create a custom look and feel. Look and feel can be changed dynamically at runtime.
Other features of Swing
Rich controls Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls
Highly Customizable Swing controls can be customized in very easy way as visual appearance is independent of internal representation
4.3 Components and Containers Components
A component is an independent visual control such as push button or a slider. In general, all the swing components are derived from JComponent class (apart from four top level containers). JComponent class inherits the AWT classes Container and Component
Containers
A container holds a group of components. Thus, container is a special type of component that is designed to hold other components. There are two types of containers Top level containers (JFrame, JApplet, JWindow, and JDialog): These containers do not inherit the JComponent. They do directly inherit the AWT classes Component and Container. Therefore, they are heavyweight. They cannot be contained within any other component. Those who inherit JComponent are the second type of container: They are lightweight
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. JSpinner
4.5 A Simple Swing Application import javax.swing.*; class Example { Example() { // Create a new JFrame container. JFrame frame = new JFrame("My first Swing Application"); // Give the frame an initial size. frame.setSize(400, 200); // Terminate the program when the closes the application. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create a text-based label. JLabel label = new JLabel("WELCOME TO THE WORLD OF SWINGS. !!"); // Add the label to the content pane. frame.add(label); // Display the frame. frame.setVisible(true); }
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public static void main(String args[]) { new Example(); } } Output
4.6 Event Handling Basics Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of interaction with the graphical interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen. Foreground events: These events require the direct interaction of the . Example: Click on a button Background events: These don’t require the interaction of the . Example: OS interrupt. As we learnt in unit 3, delegation event model has the following key participants namely:
Event: Event is an object that describes the state change. Event Source: An Event Source is an object which originates or "fires" events. Event Listener: A listener is an object which will be notified when an event occurs.
Event handling example: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Example { private private private private
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. { statusLabel.setText("Ok Button clicked."); } else if (command.equals("Submit")) { statusLabel.setText("Submit Button clicked."); } else { statusLabel.setText("Cancel Button clicked."); } } } } Output
Steps involved in event handling 1. 2. 3. 4.
The 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. Event object is forwarded to the method of ed listener class. The method now gets executed and returns.
In order to design a listener class we have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class. 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.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
4.7 Create a Swing Applet Concept Swing-based applets are similar to AWT-based applets, but it extends JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes all of the functionality found in Applet and adds for Swing. Swing applets use the same four lifecycle methods as described in unit 2: init(), start(), stop(), and destroy() Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally override the paint() method.
Example: import javax.swing.*; import java.awt.*; import java.awt.event.*; /* This HTML can be used to launch the applet: */ public class Example extends JApplet { JButton button1; JButton button2; JLabel label; // Initialize the applet. public void init() { render(); // initialize the GUI } // This applet does not need to override start(), stop(), // or destroy(). // Set up and initialize the GUI. private void render() { // Set the applet to use flow layout. setLayout(new FlowLayout()); // Make two buttons. button1 = new JButton("Button1"); button2 = new JButton("Button2"); // Add action listener for Alpha. button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { label.setText("Button1 was pressed."); } }); // Add action listener for Beta. button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { label.setText("Button2 was pressed."); } }); // Add the buttons to the content pane. add(button1); add(button2);
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. // Create a text-based label. label = new JLabel("Press a button."); // Add the label to the content pane. add(label); } } Output
Let’s discuss some of the lightweight components derived from JComponent class.
4.8 JLabel and ImageIcon Description A JLabel object provides text instructions or information on a GUI — display a single line of read-only text, an image or both text and image. JLabel defines three constructors JLabel(Icon icon) JLabel(String str) JLabel(String str, Icon icon, int align) Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal alignment of the text and/or icon within the dimensions of the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. these constants are defined in the SwingConstants interface, along with several others used by the Swing classes. The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and encapsulates an image. Thus, an object of type ImageIcon can be ed as an argument to the Icon parameter of JLabel’s constructor
Example: import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render();
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. } private void render() { // Create an icon. ImageIcon imgIcon = new ImageIcon("logo.png"); // Create a label. JLabel label = new JLabel("This is a sample message", imgIcon, JLabel.LEFT); // Add the label to the content pane. add(label); } } Output
4.9 JTextField Description JTextField is an input area where the can type in characters. If you want to let the enter multiple lines of text, you cannot use JTextField’s unless you create several of them. The solution is to use JTextArea, which enables the to enter multiple lines of text. When the types data into them and presses the Enter key, an action event occurs. If the program s an event listener, 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, int cols) JTextField(String str) Here, str is the string to be initially presented, and
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. cols is the number of columns in the text field. If no string is specified, the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the specified string.
Example import java.awt.*; import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { JTextField textfield; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Add text field to content pane. textfield = new JTextField(15); add(textfield); textfield.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { // Show text when presses ENTER. showStatus(textfield.getText()); } }); } } Output
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
4.10 The Swing buttons Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton. All are subclasses of the AbstractButton class, 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. Other events are also possible.
JButton The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be associated with the push button. When the button is pressed, an ActionEvent is generated and it is handled by the actionPerformed() method of ed ActionListener It defines three constructors JButton(Icon icon) JButton(String str) JButton(String str, Icon icon) Here, str and icon are the string and icon used for the button Example: import java.awt.*; import java.awt.event.*;
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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 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.
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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.*;
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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 s that will be added to the tabbed pane. @SuppressWarnings("serial") class Sem1 extends J { public Sem1()
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. { JButton b1 add(b1); JButton b2 add(b2); JButton b3 add(b3); JButton b4 add(b4);
= new JButton("Mathematics 1"); = new JButton("C"); = new JButton("Basic Electronics"); = new JButton("Chemistry");
} } @SuppressWarnings("serial") class Sem2 extends J { public Sem2() { JButton b1 = new add(b1); JButton b2 = new add(b2); JButton b3 = new add(b3); JButton b4 = new add(b4); } }
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 J. 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 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, ing 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 . J jp = new J(); 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
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.
4.13 JList Description JList s the selection of one or more items from a list.
Example import javax.swing.*; import javax.swing.event.*; import java.awt.*; @SuppressWarnings("serial") public class Example extends JApplet { JList