Java 8 Units Notes

download Java 8 Units Notes

of 78

Transcript of Java 8 Units Notes

  • 8/4/2019 Java 8 Units Notes

    1/78

    UNIT 1

    Java Introduction:

    Java Programming Language was designed by James Gosling at SunMicrosystems in 1991. This language was initially called Oak but was renamed asJava in 1995. It follows both the C and C++ features.

    Java programming language was very useful on Internet Programming. Since, byusing this language we can easily transfer the information from server to the nodesthrough the network. Generally, In the case of network programs security and portabilityis the main active areas of concern. The java programs are classified into

    An Application is a program run on the computer under the operating system of thecomputer.

    An Applet is an application designed to be transmitted over the Internet and executed bya java-compatible web browser.

    Buzz Words:a) Platform Independent: Java is a platform independent language. Once we create

    the program in one operating system, that program will be worked on any otheroperating system that is transmitted to the operating system.

    b) Portable: The most significant contribution of java over other languages is itsportability.

    c) Object Oriented: java is a true object oriented language. Why because with outclass we cant run the program.

    d) Robust & Secure: java is a Robust Language. It provides many safe guards toensure reliable code. It designed as garbage collected language reliving theprogrammers, virtually all memory management problems.

    e) Distributed: Java is designed as distributed language for creating applications onnetwork. It has the ability to share both data and program.

    f) Simple & Small : Java is simple & small language. Many features of C and

    C++ that are sources are unreliable code are not part of Java.g) Multi Threaded : Java was designed to meet the real-world requirement of

    creating interactive, networked programs. Java supports multithreadedprogramming, which allows to handling multi tasks simultaneously.

    h) Dynamic : Java is a dynamic language. Java is capable on dynamically linkingin new class, libraries, methods and objects. Java supports functions written inother languages such as C and C++.

  • 8/4/2019 Java 8 Units Notes

    2/78

    i) Compile & Interpreted : Usually a Computer language is either compiled orinterpreted. Java combined both these approaches thus making. Java is atwo-stage system.

    j) High performance : Java performance is impressing for an interpretedlanguage due to the use of intermediate code.

    Basics of JAVA Environment :Phase 1Java program is type in a text editor(notepad, Edit plus) and maked corrections ifnecessary.Phase 2The programmer gives the command javac filename.java to compile the program.Phase 3This phase is called loading. The program must place in memory before it can beexecuted.Phase 4

    Byte code verifier confirms that all byte codes are valid and dont valid the Java SecurityInstructions.Phase 5Java Interpreter reads byte code and translates them into a language that the computer canunderstand and it can executes the code.

    Java Development Kit

    Syntax : javac filename.java

    Syntax : java filename

    Syntax : jdb filename

    Servletrunner : A simple web server to test servels

    Syntax : appletviewer filename.html

    Java Virtual Machine(JVM)Java provides both compiler and a software machine called JVM for each computermachine. The Java compiler translates the java source code into a intermediate codeknown as byte code.

    Just In time(JIT)The Java Virtual Machine is an interpreter that translates and runs each bytecodeinstruction separately whenever it is needed by the computer program.

    Java Standard Libray(JSL)The Java API is a collection of classes and methods grouped in the form of packages.The important packages in Java are

    a) java.langb) java.utilc) java.iod) java.awte) java.applet

  • 8/4/2019 Java 8 Units Notes

    3/78

    f) javax.swing

    Difference between C++ and Java1. Java does not include structure and union2. It is not possible to declare unsigned interger in Java.

    3. Pointers dont exist in java4. Java does not have a preprocessor.

  • 8/4/2019 Java 8 Units Notes

    4/78

    UNIT-2

    Java Tokens:Tokens are smallest individual units in a program. The compiler reads the sourceprogram one character at a time grouping the source program into a sequence of

    atomic units called Tokens.

    Keywords :The keywords or Reserved words are one which have a special and predefinedmeaning to the Java compiler. The reserved words currently used in java areAbstract Boolean break byte case catchChar class const continue default doDouble else extends final finally floatFor goto if implements import

    Datatype

    Datatypes are used to specify the type of data that a variable can attain. There are 2type of datatypes. 1. Primitive 2. Non-primitive

    1. Primitive Datatype : It is also called as standard, intrinsic or built in datatypes.There are eight primitive datatypes available in java. Those are byte, short int, long, char,float, double and Boolean. These can be classified into 4 groups.

    Integers : byte, short, int,longFloating point numbers : float, doubleCharacter s : char Boolean : Boolean

    2. Non- primitive datatype : These are known as Derived Datatype or Abstractdatatype or Reference type. These are built on primitive data types.

    Example : string, class, array

    Variable :The name given to the various elements to store the information is called an identifier orvariable. The rules are

    Variable must be begin with a letter , a dollar($) symbol or an underscore(_)followed by a sequence of letters.

    Variable names must be unique.

    Declaring a variable :

    All variables must be declared before they can be used . The basic form of a variabledeclaration isSyntax : type identifierWhere type represents datatype of the variable, identifier is the name of the variable.

    More than one variable of the same type can be declared by using a comma-separated list.Syntax : type identifier 1, identifier 2 identifier n

  • 8/4/2019 Java 8 Units Notes

    5/78

    Intiliazing a variable: variable can also be intiliazed with equal sign and a value.Syntax : type identifier = value.

    Scope & Life time of a variable :

    An identifier duration also called lifetime is the period during which that identifier existin memory. Identifer that represent local variables in a method i.e., parameters andvariables declared in the methods body have automatic duration.

    Class :A class is a non-primitive datatype that contains member variables and member functionsthat operates on the variables. A class is declared by the use of the class keyword.

    Object :Object is an instance of the class. By means of the object only. We can access the

    functionhs(methods)

    Comments in a program :Three types of comments are available in java.

    i) Single line comment(//) : For Single line comment we use double slash(//).ii) Multi line comment : For more that one line of information we use multi line

    comments. They starts with /* and ends with */iii) Documentation comment : For the documentation purpose we use. They starts

    with /** and ends with */.

    Input and Output Statements :Java.lang packages consists a class called system which contains console I/O. methods.If we want to take the information form the keyboard and display the information on thescreen, Java uses Stream objects. Those are

    a) System.inb) System.outc) System.err

    OperatorsOperator is a symbol that performs a speicified operation between the data items. Javaprovides different types of operators

    a) Arithmetic operators :+ addition

    - substraction* Multiplication/ Division

    b) Arithmetic Assignment Operators :Syntax : variable operator = expressionWhich is equivalent to

  • 8/4/2019 Java 8 Units Notes

    6/78

    Variable = variable operator expression+= a+=4 a=a+4-= a-=5 a=a-5

    Assignment operator : = is an assignment operator used to assign the value to a

    variable.Syntax : variable = value

    Increment and Decrement Operators : ++ and - - are Javas increment anddecrement operators. The increment operator increased its operand by one.

    CLASS & OBJECTS

    Class :A Class is a non-primitive datatype that contains member variables (data) andmember functions (methods) that operates on the variables. A class is declared by the

    use of the class keyword.

    Creating ObjectsAn object in Java is a block of memory that contains space to store all the instancevariables. Creating an object of a class is a two-step process.

    1. Declare a variable of the class type. At this stage, the variable refers to anobject only.

    2. Assigning an actual, physical copy of the object and assign it to thatvariable by means of new operator.

    Methods :

    Methods allows the programmer to modularize a program. All variables declared inmethod definition are local variables and method parameters are also local variables.

    Method Overloading :In Java it is possible to define two or more methods within the same class that share thesame name as long as these methods have different set of parameters(Based on thenumber of parameters, the type of the parameters and the order of the parameters). Thenthe methods are said to be overloaded, and the process is referred as MethodOverloading.

    ConstructorsA constructor is a special method of class, which is invoked automatically, whenever anobject of a class is created. A constructor has the following characteristics

    It doesnt have any return type not even void.

    The constructor can be declared as public

    It can be overloadedD

  • 8/4/2019 Java 8 Units Notes

    7/78

    Default constructor : A constructor that accepts no parameters is called the defaultconstructor.

    Parameterized constructor : A constructor that takes arguments as parameters is calledparameterized constructor.

    Constructor Overloading :

    An interesting feature of the constructor is that a class can have multiple constructors.This is called constructor overloading.

    Static Class MembersGenerally each class contains instance variables and instance methods. Every time theclass is instantiated, a new copy of each of them is created. They are accessed usingthe objects with the dot operator.

    this keywordJava define this keyword that can be used inside and method to refer the currentobject. this is always a reference to the object on which methods was invoked.

    Argument Passing :Arguments passed to a sub-routine(method) is falls into 2 categories1. Call by value2. Call by reference

    1. Call by value : Call by value copies the value of an argument into the formalparameter of the sub-routine.

    2. Call by reference : In this method, a reference to an argument is passed to theparameter. Inside the parameter, this reference is used to access the actualargument specified in the call.

    Strings :A String is a collection of characters. Java implements strings as object type of string.Java properties 3 types of string handling classes.1. String class2. StringBuffer Class3. StringTokenizer Class

    String and StringBuffer classes are defined in java.lang package. StringTokenizer aredefined in java.util package.

    String Class :A String is an object of class String. String literals or constants written as a sequence ofcharacters in double quotes.

  • 8/4/2019 Java 8 Units Notes

    8/78

    StringBuffer Class :Once a String object is created then its contents cannot be changed. But the StringBufferclass provides the features of creating and manipulating dynamic string information i.e.,mutable strings.

    StringBuffer Constructors :a) StringBuffer() : It is a default StringBuffer Constructor to create StringBufferwith no characters init and an initial capacity of 16 characters.

    b) StringBuffer(String str) : It takes a String argument to create a StringBuffercontaining the characters of the String argument. The Initial capacity is thenumber of arguments in the string argument +16.

    c) StringBuffer(int size) : It takes an integer argument and creates a StringBufferwith no characters init. The intial capacity is specified bythe integer.

    StringTokenizer Class :In programming languages, statements are divided into individual pieces like identifers,

    keywords, and operators etc., called Tokens Java provides StringTokenizer class thatbreaks a String into its component tokens.

    StringTokenizer Constructors :a) StringTokenizer(String str)b) StringTokenizer (String str, String delimiters)c) StringTokenizer(String str, String delimiters, Boolean delimiterAsToken)

  • 8/4/2019 Java 8 Units Notes

    9/78

    UNIT-3

    InheritanceThe mechanism of deriving a new class from an old one is called Inheritance. A class

    that is inherited (old class) is called a super class or base class or parent class.

    Types of InheritancesInheritance is classified into different forms.

    a) single Inheritance : Derivation a subclass from only one super class is calledsingle Inheritance.

    b) Hierarchical Inheritance : Derivation of several classes from a single super class iscalled Hierarchical Inheritance.

    c) Multilevel Inheritance : Derivation of a class from another derived class calledmultilevel Inheritance.

    d) Multiple Inheritance : Derivation of one class from two or more super classes is

    called Multiple Inheritance.e) Hybrid Inheritance: Derivation of a class involving more than one form of

    Inheritance is called Hybrid Inheritance.

    Defining a Sub class.A subclass is defined asSyntax : class subclass-name extends superclass-name{

    Variable declarationMethod declaration

    }

    Member Access Rules :1. By means of sub class object it is possible to access all the instance variables and

    instance methods of the super class.2. By means of sub class object it cannot be possible to access the instance variable

    of super class, if it is declared as private. Since the data is protected in that class.

    Super keyword :

    A subclass constructor is used to construct the instance variable of both the subclass and

    the super class. The subclass constructor uses the keyword super to invoke theconstructor method of the super class. The keyword super is used subject to thefollowing conditions.

    Super may be used only within the subclass constructor method.

    The call to super class constructor must appear as the first statement with in thesubclass constructor.

    If a parameterized constructor is used, then the signature is matched with theparameters passed to the super method as super(parameter-list)

  • 8/4/2019 Java 8 Units Notes

    10/78

    Method OverridingA method in a subclass has the same name, type of the variables and order of thevariables as method in its super class, then the method in the subclass is said to be

    override the method in the super class. The process is called Method Overriding.

    Note : Method Overriding occurs only when the name and type signature of the twomethods are identical.If method name is identical and the type signature is different then the process is said tobe Method Overloading.

    Final KeywordA final is a keyword used for three purposes. They are

    a) final as constant : A variable can be decalred as constant with the keyword final.b) Final to prevent overriding : A Method that is declared as final cannot be

    overridden in a subclass method.c) Final to prevent inheritance : The class that is declared as final implicitly declaresall of its methods as final.

    Object ClassJava provides a special class called Object class that is available in java.lang package.It is the super class of all other classes.

    Method PurposeObject clone() creates a new object that is the same as the object

    being cloned.Boolean equals(Object object) Determines whether one object is equal to anotherVoid finalize() Called before an unused object is recycled.Class getClass() Obtains the class of an object at run time.Int hascode() Returns the has code associated with the invoking

    object.

    Dynamic Method Dispatch :Dynamic Method Dispatch is the mechanism by which a class to an overridden method isresolved at runtime, rather than compile time. Dynamic method dispatch is importantbecause this is how Java implements run-time polymorphism.

  • 8/4/2019 Java 8 Units Notes

    11/78

    UNIT 4

    Creating and Using Packages

    To make types easier to find and use, to avoid naming conflicts, and to control access,programmers bundle groups of related types into packages.

    Definition: Apackage is a grouping of related types providing access protection andname space management. Note that types refers to classes, interfaces, enumerations, andannotation types. Enumerations and annotation types are special kinds of classes andinterfaces, respectively, so types are often referred to in this lesson simply as classes andinterfaces.

    The types that are part of the Java platform are members of various packages that bundleclasses by function: fundamental classes are in java.lang, classes for reading and writing(input and output) are in java.io, and so on. You can put your types in packages too.

    Suppose you write a group of classes that represent graphic objects, such as circles,

    rectangles, lines, and points. You also write an interface, Draggable, that classesimplement if they can be dragged with the mouse.

    //in the Draggable.java filepublic interface Draggable {

    . . .}

    //in the Graphic.java filepublic abstract class Graphic {

    . . .

    }

    //in the Circle.java filepublic class Circle extends Graphic implements Draggable {

    . . .}

    //in the Rectangle.java filepublic class Rectangle extends Graphic implements Draggable {

    . . .}

    //in the Point.java filepublic class Point extends Graphic implements Draggable {

    . . .}

    //in the Line.java filepublic class Line extends Graphic implements Draggable {

  • 8/4/2019 Java 8 Units Notes

    12/78

    . . .}

    You should bundle these classes and the interface in a package for several reasons,including the following:

    You and other programmers can easily determine that these types are related. You and other programmers know where to find types that can provide graphics-

    related functions. The names of your types won't conflict with the type names in other packages

    because the package creates a new namespace. You can allow types within the package to have unrestricted access to one another

    yet still restrict access for types outside the package.

    Creating a Package

    To create a package, you choose a name for the package (naming conventions are

    discussed in the next section) and put a package statement with that name at the top ofevery source file that contains the types (classes, interfaces, enumerations, and annotationtypes) that you want to include in the package.

    The package statement (for example, package graphics;) must be the first line in thesource file. There can be only one package statement in each source file, and it applies toall types in the file.

    Note: If you put multiple types in a single source file, only one can be public, and it musthave the same name as the source file. For example, you can define public class Circle inthe file Circle.java, define public interface Draggable in the file Draggable.java, define

    public enum Day in the file Day.java, and so forth.

    You can include non-public types in the same file as a public type (this is stronglydiscouraged, unless the non-public types are small and closely related to the public type),but only the public type will be accessible from outside of the package. All the top-level,non-public types will bepackage private.

    If you put the graphics interface and classes listed in the preceding section in a packagecalled graphics, you would need six source files, like this://in the Draggable.java filepackage graphics;

    public interface Draggable {. . .

    }

    //in the Graphic.java filepackage graphics;public abstract class Graphic {

    . . .

  • 8/4/2019 Java 8 Units Notes

    13/78

    }

    //in the Circle.java filepackage graphics;public class Circle extends Graphic implements Draggable {

    . . .}

    //in the Rectangle.java filepackage graphics;public class Rectangle extends Graphic implements Draggable {

    . . .}

    //in the Point.java filepackage graphics;

    public class Point extends Graphic implements Draggable {. . .}

    //in the Line.java filepackage graphics;public class Line extends Graphic implements Draggable {

    . . .}If you do not use a package statement, your type ends up in an unnamed package.Generally speaking, an unnamed package is only for small or temporary applications orwhen you are just beginning the development process. Otherwise, classes and interfacesbelong in named packages.Naming a Package

    With programmers worldwide writing classes and interfaces using the Java programminglanguage, it is likely that many programmers will use the same name for different types.In fact, the previous example does just that: It defines a Rectangle class when there isalready a Rectangle class in the java.awt package. Still, the compiler allows both classesto have the same name if they are in different packages. The fully qualified name of eachRectangle class includes the package name. That is, the fully qualified name of theRectangle class in the graphics package is graphics.Rectangle, and the fully qualifiedname of the Rectangle class in the java.awt package is java.awt.Rectangle.

    This works well unless two independent programmers use the same name for theirpackages. What prevents this problem? Convention.

    Naming Conventions

    Package names are written in all lowercase to avoid conflict with the names of classes orinterfaces.

  • 8/4/2019 Java 8 Units Notes

    14/78

    Companies use their reversed Internet domain name to begin their package namesforexample, com.example.orion for a package named orion created by a programmer atexample.com.

    Name collisions that occur within a single company need to be handled by convention

    within that company, perhaps by including the region or the project name after thecompany name (for example, com.company.region.package).

    Packages in the Java language itself begin with java. or javax.

    In some cases, the internet domain name may not be a valid package name. This canoccur if the domain name contains a hyphen or other special character, if the packagename begins with a digit or other character that is illegal to use as the beginning of a Javaname, or if the package name contains a reserved Java keyword, such as "int". In thisevent, the suggested convention is to add an underscore. For example:

    Legalizing Package NamesDomain Name Package Name Prefix

    clipart-open.org org.clipart_open

    free.fonts.int int_.fonts.free

    poetry.7days.com com._7days.poetry

    Using Package Members

    The types that comprise a package are known as thepackage members.

    To use a public package member from outside its package, you must do one of thefollowing:

    Refer to the member by its fully qualified name Import the package member Import the member's entire package

    Each is appropriate for different situations, as explained in the sections that follow.

    Referring to a Package Member by Its Qualified Name

    So far, most of the examples in this tutorial have referred to types by their simple names,such as Rectangle and StackOfInts. You can use a package member's simple name if the

    code you are writing is in the same package as that member or if that member has beenimported.

    However, if you are trying to use a member from a different package and that packagehas not been imported, you must use the member's fully qualified name, which includesthe package name. Here is the fully qualified name for the Rectangle class declared in thegraphics package in the previous example.

  • 8/4/2019 Java 8 Units Notes

    15/78

    graphics.RectangleYou could use this qualified name to create an instance of graphics.Rectangle:graphics.Rectangle myRect = new graphics.Rectangle();Qualified names are all right for infrequent use. When a name is used repetitively,however, typing the name repeatedly becomes tedious and the code becomes difficult to

    read. As an alternative, you can importthe member or its package and then use its simplename.

    Importing a Package Member

    To import a specific member into the current file, put an import statement at thebeginning of the file before any type definitions but after the package statement, if thereis one. Here's how you would import the Rectangle class from the graphics packagecreated in the previous section.import graphics.Rectangle;Now you can refer to the Rectangle class by its simple name.

    Rectangle myRectangle = new Rectangle();This approach works well if you use just a few members from the graphics package. Butif you use many types from a package, you should import the entire package.

    Importing an Entire Package

    To import all the types contained in a particular package, use the import statement withthe asterisk (*) wildcard character.import graphics.*;Now you can refer to any class or interface in the graphics package by its simple name.Circle myCircle = new Circle();

    Rectangle myRectangle = new Rectangle();The asterisk in the import statement can be used only to specify all the classes within apackage, as shown here. It cannot be used to match a subset of the classes in a package.For example, the following does not match all the classes in the graphics package thatbegin with A.import graphics.A*; //does not workInstead, it generates a compiler error. With the import statement, you generally importonly a single package member or an entire package.

    Note: Another, less common form of import allows you to import the public nestedclasses of an enclosing class. For example, if the graphics.Rectangle class containeduseful nested classes, such as Rectangle.DoubleWide and Rectangle.Square, you could

    import Rectangle and its nested classes by using the following two statements.import graphics.Rectangle;import graphics.Rectangle.*;Be aware that the second import statement will notimport Rectangle.

    Another less common form of import, thestatic import statement, will be discussed at theend of this section.

  • 8/4/2019 Java 8 Units Notes

    16/78

    For convenience, the Java compiler automatically imports three entire packages for eachsource file: (1) the package with no name, (2) the java.lang package, and (3) the currentpackage (the package for the current file).

    Apparent Hierarchies of Packages

    At first, packages appear to be hierarchical, but they are not. For example, the Java APIincludes a java.awt package, a java.awt.color package, a java.awt.font package, and manyothers that begin with java.awt. However, the java.awt.color package, the java.awt.fontpackage, and other java.awt.xxxx packages are not includedin the java.awt package. Theprefix java.awt (the Java Abstract Window Toolkit) is used for a number of relatedpackages to make the relationship evident, but not to show inclusion.

    Importing java.awt.* imports all of the types in the java.awt package, but it does notimportjava.awt.color, java.awt.font, or any other java.awt.xxxx packages. If you plan touse the classes and other types in java.awt.color as well as those in java.awt, you must

    import both packages with all their files:

    import java.awt.*;import java.awt.color.*;

    Summary of Creating and Using Packages

    To create a package for a type, put a package statement as the first statement in the sourcefile that contains the type (class, interface, enumeration, or annotation type).

    To use a public type that's in a different package, you have three choices: (1) use the fullyqualified name of the type, (2) import the type, or (3) import the entire package of which

    the type is a member.

    The path names for a package's source and class files mirror the name of the package.

    You might have to set your CLASSPATH so that the compiler and the JVM can find the.class files for your types.

    Implementing Interfaces

    Once an Interface has been defined, one or more classes can implement that interface.implements keyword used for implementing the classes. The syntax of implements is

    as follows.

    Syntax : class class-name implements interface 1, interface 2 , interface n{ // interface body}

  • 8/4/2019 Java 8 Units Notes

    17/78

    Note : 1. Interface methods are similar to the abstract classes so, that it cannot beinstantiated.

    3. Interface methods can also be accessed by the interface reference variable refer tothe object of subclass. The method will be resolved at run time. This process is

    similar to the super class reference to access a subclass object

    UNIT 5

    What Is an Exception?The term exception is shorthand for the phrase "exceptional event."

    Definition: An exception is an event, which occurs during the execution of a program,that disrupts the normal flow of the program's instructions.

  • 8/4/2019 Java 8 Units Notes

    18/78

    When an error occurs within a method, the method creates an object and hands it off tothe runtime system. The object, called an exception object, contains information about theerror, including its type and the state of the program when the error occurred. Creating anexception object and handing it to the runtime system is called throwing an exception.

    After a method throws an exception, the runtime system attempts to find something tohandle it. The set of possible "somethings" to handle the exception is the ordered list ofmethods that had been called to get to the method where the error occurred. The list ofmethods is known as the call stack(see the next figure).

    The call stack.

    The runtime system searches the call stack for a method that contains a block of code that

    can handle the exception. This block of code is called an exception handler. The searchbegins with the method in which the error occurred and proceeds through the call stack inthe reverse order in which the methods were called. When an appropriate handler isfound, the runtime system passes the exception to the handler. An exception handler isconsidered appropriate if the type of the exception object thrown matches the type thatcan be handled by the handler.

    The exception handler chosen is said to catch the exception. If the runtime systemexhaustively searches all the methods on the call stack without finding an appropriateexception handler, as shown in the next figure, the runtime system (and, consequently,the program) terminates.

  • 8/4/2019 Java 8 Units Notes

    19/78

    Searching the call stack for the exception handler.

    Using exceptions to manage errors has some advantages over traditional error-management techniques. You can learn more in theAdvantages of Exceptions section.

    The Catch or Specify Requirement

    Valid Java programming language code must honor the Catch or Specify Requirement.This means that code that might throw certain exceptions must be enclosed by either ofthe following:

    A try statement that catches the exception. The try must provide a handler for theexception, as described in Catching and Handling Exceptions.

    A method that specifies that it can throw the exception. The method must provide

    a throws clause that lists the exception, as described in Specifying the ExceptionsThrown by a Method.

    Code that fails to honor the Catch or Specify Requirement will not compile.

    Not all exceptions are subject to the Catch or Specify Requirement. To understand why,we need to look at the three basic categories of exceptions, only one of which is subjectto the Requirement.

    The Three Kinds of Exceptions

    The first kind of exception is the checked exception. These are exceptional conditions thata well-written application should anticipate and recover from. For example, suppose anapplication prompts a user for an input file name, then opens the file by passing the nameto the constructor for java.io.FileReader. Normally, the user provides the name of anexisting, readable file, so the construction of the FileReader object succeeds, and theexecution of the application proceeds normally. But sometimes the user supplies thename of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A

    http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/handling.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/handling.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/declaring.html
  • 8/4/2019 Java 8 Units Notes

    20/78

    well-written program will catch this exception and notify the user of the mistake, possiblyprompting for a corrected file name.

    Checked exceptions are subjectto the Catch or Specify Requirement. All exceptions arechecked exceptions, except for those indicated by Error, RuntimeException, and their

    subclasses.

    The second kind of exception is the error. These are exceptional conditions that areexternal to the application, and that the application usually cannot anticipate or recoverfrom. For example, suppose that an application successfully opens a file for input, but isunable to read the file because of a hardware or system malfunction. The unsuccessfulread will throw java.io.IOError. An application might choose to catch this exception, inorder to notify the user of the problem but it also might make sense for the program toprint a stack trace and exit.

    Errors are not subjectto the Catch or Specify Requirement. Errors are those exceptions

    indicated by Error and its subclasses.

    The third kind of exception is the runtime exception. These are exceptional conditionsthat are internal to the application, and that the application usually cannot anticipate orrecover from. These usually indicate programming bugs, such as logic errors or improperuse of an API. For example, consider the application described previously that passes afile name to the constructor for FileReader. If a logic error causes a null to be passed tothe constructor, the constructor will throw NullPointerException. The application cancatch this exception, but it probably makes more sense to eliminate the bug that causedthe exception to occur.

    Runtime exceptions are not subjectto the Catch or Specify Requirement. Runtimeexceptions are those indicated by RuntimeException and its subclasses.

    Errors and runtime exceptions are collectively known as unchecked exceptions.

    Bypassing Catch or Specify

    Some programmers consider the Catch or Specify Requirement a serious flaw in theexception mechanism and bypass it by using unchecked exceptions in place of checkedexceptions. In general, this is not recommended. The section Unchecked Exceptions The Controversy talks about when it is appropriate to use unchecked exceptions.

    Catching and Handling Exceptions

    This section describes how to use the three exception handler components the try,catch, and finally blocks to write an exception handler. The last part of this sectionwalks through an example and analyzes what occurs during various scenarios.

    The following example defines and implements a class named ListOfNumbers. Whenconstructed, ListOfNumbers creates a Vector that contains 10 Integer elements with

    http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html
  • 8/4/2019 Java 8 Units Notes

    21/78

    sequential values 0 through 9. The ListOfNumbers class also defines a method namedwriteList, which writes the list of numbers into a text file called OutFile.txt. This exampleuses output classes defined in java.io, which are covered inBasic I/O.

    //Note: This class won't compile by design!

    import java.io.*;import java.util.Vector;

    public class ListOfNumbers {

    private Vector vector;private static final int SIZE = 10;

    public ListOfNumbers () {vector = new Vector(SIZE);for (int i = 0; i < SIZE; i++) {

    vector.addElement(new Integer(i));}}

    public void writeList() {PrintWriter out = new PrintWriter(

    new FileWriter("OutFile.txt"));

    for (int i = 0; i < SIZE; i++) {out.println("Value at: " + i + " = " +

    vector.elementAt(i));

    }

    out.close();}

    }The first line in boldface is a call to a constructor. The constructor initializes an outputstream on a file. If the file cannot be opened, the constructor throws an IOException. Thesecond boldface line is a call to the Vector class's elementAt method, which throws anArrayIndexOutOfBoundsException if the value of its argument is too small (less than 0)or too large (more than the number of elements currently contained by the Vector).

    If you try to compile the ListOfNumbers class, the compiler prints an error messageabout the exception thrown by the FileWriter constructor. However, it does not display anerror message about the exception thrown by elementAt. The reason is that the exceptionthrown by the constructor, IOException, is a checked exception, and the one thrown bythe elementAt method, ArrayIndexOutOfBoundsException, is an unchecked exception.

    http://java.sun.com/docs/books/tutorial/essential/io/index.htmlhttp://java.sun.com/docs/books/tutorial/essential/io/index.htmlhttp://java.sun.com/docs/books/tutorial/essential/io/index.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/examples/ListOfNumbers.javahttp://java.sun.com/docs/books/tutorial/essential/io/index.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/examples/ListOfNumbers.java
  • 8/4/2019 Java 8 Units Notes

    22/78

    Now that you're familiar with the ListOfNumbers class and where the exceptions can bethrown within it, you're ready to write exception handlers to catch and handle thoseexceptions.

    The try BlockThe first step in constructing an exception handler is to enclose the code that might throwan exception within a try block. In general, a try block looks like the following.try { code}catch and finally blocks . . .

    The segment in the example labeled code contains one or more legal lines of code thatcould throw an exception. (The catch and finally blocks are explained in the next twosubsections.)

    To construct an exception handler for the writeList method from the ListOfNumbersclass, enclose the exception-throwing statements of the writeList method within a tryblock. There is more than one way to do this. You can put each line of code that mightthrow an exception within its own try block and provide separate exception handlers foreach. Or, you can put all the writeList code within a single try block and associatemultiple handlers with it. The following listing uses one try block for the entire methodbecause the code in question is very short.

    private Vector vector;private static final int SIZE = 10;

    PrintWriter out = null;

    try {System.out.println("Entered try statement");out = new PrintWriter(new FileWriter("OutFile.txt"));for (int i = 0; i < SIZE; i++) {

    out.println("Value at: " + i + " = "+ vector.elementAt(i));

    }}catch and finally statements . . .

    If an exception occurs within the try block, that exception is handled by an exceptionhandler associated with it. To associate an exception handler with a try block, you mustput a catch block after it; the next section shows you how.

    The catch Blocks

    You associate exception handlers with a try block by providing one or more catch blocksdirectly after the try block. No code can be between the end of the try block and thebeginning of the first catch block.

  • 8/4/2019 Java 8 Units Notes

    23/78

    try {} catch (ExceptionType name) {} catch (ExceptionType name) {

    }Each catch block is an exception handler and handles the type of exception indicated byits argument. The argument type,ExceptionType, declares the type of exception that thehandler can handle and must be the name of a class that inherits from the Throwableclass. The handler can refer to the exception with name.

    The catch block contains code that is executed if and when the exception handler isinvoked. The runtime system invokes the exception handler when the handler is the firstone in the call stack whoseExceptionType matches the type of the exception thrown. Thesystem considers it a match if the thrown object can legally be assigned to the exception

    handler's argument.

    The following are two exception handlers for the writeList method one for two typesof checked exceptions that can be thrown within the try statement.

    try {} catch (FileNotFoundException e) {

    System.err.println("FileNotFoundException: "+ e.getMessage());

    throw new SampleException(e);

    } catch (IOException e) {System.err.println("Caught IOException: "

    + e.getMessage());}Both handlers print an error message. The second handler does nothing else. By catchingany IOException that's not caught by the first handler, it allows the program to continueexecuting.

    The first handler, in addition to printing a message, throws a user-defined exception.(Throwing exceptions is covered in detail later in this chapter in the How to ThrowExceptionssection.) In this example, when the FileNotFoundException is caught itcauses a user-defined exception called SampleException to be thrown. You might want todo this if you want your program to handle an exception in this situation in a specificway.

    Exception handlers can do more than just print error messages or halt the program. Theycan do error recovery, prompt the user to make a decision, or propagate the error up to a

    http://java.sun.com/docs/books/tutorial/essential/exceptions/throwing.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/throwing.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/throwing.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/throwing.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/throwing.html
  • 8/4/2019 Java 8 Units Notes

    24/78

    higher-level handler using chained exceptions, as described in theChained Exceptionssection.

    The finally Block

    The finally blockalways executes when the try block exits. This ensures that the finally

    block is executed even if an unexpected exception occurs. But finally is useful for morethan just exception handling it allows the programmer to avoid having cleanup codeaccidentally bypassed by a return, continue, or break. Putting cleanup code in a finallyblock is always a good practice, even when no exceptions are anticipated.

    Note: If the JVM exits while the try or catch code is being executed, then the finallyblock will not execute. Likewise, if the thread executing the try or catch code isinterrupted or killed, the finally block will not execute even though the application as awhole continues.

    The try block of the writeList method that you've been working with here opens aPrintWriter. The program should close that stream before exiting the writeList method.

    This poses a somewhat complicated problem because writeList's try block can exit in oneof three ways.

    1. The new FileWriter statement fails and throws an IOException.2. The vector.elementAt(i) statement fails and throws an

    ArrayIndexOutOfBoundsException.3. Everything succeeds and the try block exits normally.

    The runtime system always executes the statements within the finally block regardless ofwhat happens within the try block. So it's the perfect place to perform cleanup.

    The following finally block for the writeList method cleans up and then closes thePrintWriter.

    finally {if (out != null) {

    System.out.println("Closing PrintWriter");out.close();

    } else {System.out.println("PrintWriter not open");

    }}

    In the writeList example, you could provide for cleanup without the intervention of afinally block. For example, you could put the code to close the PrintWriter at the end ofthe try block and again within the exception handler forArrayIndexOutOfBoundsException, as follows.

    try {

    http://java.sun.com/docs/books/tutorial/essential/exceptions/chained.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/chained.htmlhttp://java.sun.com/docs/books/tutorial/essential/exceptions/chained.html
  • 8/4/2019 Java 8 Units Notes

    25/78

    out.close(); //Don't do this; it duplicates code.

    } catch (FileNotFoundException e) { out.close(); //Don't do this; it duplicates code.

    System.err.println("Caught: FileNotFoundException: "

    + e.getMessage());throw new RuntimeException(e);} catch (IOException e) {

    System.err.println("Caught IOException: "+ e.getMessage());

    }However, this duplicates code, thus making the code difficult to read and error-proneshould you modify it later. For example, if you add code that can throw a new type ofexception to the try block, you have to remember to close the PrintWriter within the newexception handler.

    Important: The finally block is a key tool for preventing resource leaks. When closing afile or otherwise recovering resources, place the code in a finally block to insure thatresource is always recovered.

    Putting It All Together

    The previous sections described how to construct the try, catch, and finally code blocksfor the writeList method in the ListOfNumbers class. Now, let's walk through the codeand investigate what can happen.

    When all the components are put together, the writeList method looks like the following.

    public void writeList() {

    PrintWriter out = null;

    try {System.out.println("Entering try statement");out = new PrintWriter(

    new FileWriter("OutFile.txt"));for (int i = 0; i < SIZE; i++)

    out.println("Value at: " + i + " = "+ vector.elementAt(i));

    } catch (ArrayIndexOutOfBoundsException e) {

    System.err.println("Caught "+ "ArrayIndexOutOfBoundsException: "+ e.getMessage());

    } catch (IOException e) {

    System.err.println("Caught IOException: "+ e.getMessage());

  • 8/4/2019 Java 8 Units Notes

    26/78

    } finally {if (out != null) {

    System.out.println("Closing PrintWriter");out.close();

    }else {System.out.println("PrintWriter not open");

    }}

    }As mentioned previously, this method's try block has three different exit possibilities;here are two of them.

    1. Code in the try statement fails and throws an exception. This could be anIOException caused by the new FileWriter statement or an

    ArrayIndexOutOfBoundsException caused by a wrong index value in the forloop.2. Everything succeeds and the try statement exits normally.

    Let's look at what happens in the writeList method during these two exit possibilities.

    Scenario 1: An Exception Occurs

    The statement that creates a FileWriter can fail for a number of reasons. For example, theconstructor for the FileWriter throws an IOException if the program cannot create orwrite to the file indicated.

    When FileWriter throws an IOException, the runtime system immediately stopsexecuting the try block; method calls being executed are not completed. The runtimesystem then starts searching at the top of the method call stack for an appropriateexception handler. In this example, when the IOException occurs, the FileWriterconstructor is at the top of the call stack. However, the FileWriter constructor doesn'thave an appropriate exception handler, so the runtime system checks the next method the writeList method in the method call stack. The writeList method has two exceptionhandlers: one for IOException and one for ArrayIndexOutOfBoundsException.

    The runtime system checks writeList's handlers in the order in which they appear after

    the try statement. The argument to the first exception handler isArrayIndexOutOfBoundsException. This does not match the type of exception thrown, sothe runtime system checks the next exception handler IOException. This matches thetype of exception that was thrown, so the runtime system ends its search for anappropriate exception handler. Now that the runtime has found an appropriate handler,the code in that catch block is executed.

  • 8/4/2019 Java 8 Units Notes

    27/78

    After the exception handler executes, the runtime system passes control to the finallyblock. Code in the finally block executes regardless of the exception caught above it. Inthis scenario, the FileWriter was never opened and doesn't need to be closed. After thefinally block finishes executing, the program continues with the first statement after thefinally block.

    Here's the complete output from the ListOfNumbers program that appears when anIOException is thrown.

    Entering try statementCaught IOException: OutFile.txtPrintWriter not openThe boldface code in the following listing shows the statements that get executed duringthis scenario:public void writeList() { PrintWriter out = null;

    try {

    System.out.println("Entering try statement");

    out = new PrintWriter(

    new FileWriter("OutFile.txt"));

    for (int i = 0; i < SIZE; i++)out.println("Value at: " + i

    + " = " + vector.elementAt(i));

    } catch (ArrayIndexOutOfBoundsException e) {System.err.println("Caught "

    + "ArrayIndexOutOfBoundsException: "+ e.getMessage());

    } catch (IOException e) {System.err.println("Caught IOException: "

    + e.getMessage());

    } finally {

    if (out != null) {

    System.out.println("Closing PrintWriter");out.close();

    }else {

    System.out.println("PrintWriter not open");

    }

    }}

    Scenario 2: The try Block Exits Normally

  • 8/4/2019 Java 8 Units Notes

    28/78

    In this scenario, all the statements within the scope of the try block execute successfullyand throw no exceptions. Execution falls off the end of the try block, and the runtimesystem passes control to the finally block. Because everything was successful, thePrintWriter is open when control reaches the finally block, which closes the PrintWriter.Again, after the finally block finishes executing, the program continues with the first

    statement after the finally block.

    Here is the output from the ListOfNumbers program when no exceptions are thrown.

    Entering try statementClosing PrintWriterThe boldface code in the following sample shows the statements that get executed duringthis scenario.public void writeList() { PrintWriter out = null;

    try {

    System.out.println("Entering try statement");out = new PrintWriter(

    new FileWriter("OutFile.txt"));

    for (int i = 0; i < SIZE; i++)

    out.println("Value at: " + i + " = "

    + vector.elementAt(i));

    } catch (ArrayIndexOutOfBoundsException e) {System.err.println("Caught "

    + "ArrayIndexOutOfBoundsException: "+ e.getMessage());

    } catch (IOException e) {System.err.println("Caught IOException: "

    + e.getMessage());

    } finally {if (out != null) {

    System.out.println("Closing PrintWriter");

    out.close();

    }else {

    System.out.println("PrintWriter not open");}

    }}

    Processes and Threads

  • 8/4/2019 Java 8 Units Notes

    29/78

    In concurrent programming, there are two basic units of execution:processes andthreads. In the Java programming language, concurrent programming is mostlyconcerned with threads. However, processes are also important.

    A computer system normally has many active processes and threads. This is true even in

    systems that only have a single execution core, and thus only have one thread actuallyexecuting at any given moment. Processing time for a single core is shared amongprocesses and threads through an OS feature called time slicing.

    It's becoming more and more common for computer systems to have multiple processorsor processors with multiple execution cores. This greatly enhances a system's capacity forconcurrent execution of processes and threads but concurrency is possible even onsimple systems, without multiple processors or execution cores.

    Processes

    A process has a self-contained execution environment. A process generally has acomplete, private set of basic run-time resources; in particular, each process has its ownmemory space.

    Processes are often seen as synonymous with programs or applications. However, whatthe user sees as a single application may in fact be a set of cooperating processes. Tofacilitate communication between processes, most operating systems supportInterProcess Communication (IPC) resources, such as pipes and sockets. IPC is used not justfor communication between processes on the same system, but processes on differentsystems.

    Most implementations of the Java virtual machine run as a single process. A Javaapplication can create additional processes using a ProcessBuilderobject. Multiprocessapplications are beyond the scope of this lesson.

    Threads

    Threads are sometimes called lightweight processes. Both processes and threads providean execution environment, but creating a new thread requires fewer resources thancreating a new process.

    Threads exist within a process every process has at least one. Threads share the

    process's resources, including memory and open files. This makes for efficient, butpotentially problematic, communication.

    Multithreaded execution is an essential feature of the Java platform. Every applicationhas at least one thread or several, if you count "system" threads that do things likememory management and signal handling. But from the application programmer's pointof view, you start with just one thread, called the main thread. This thread has the abilityto create additional threads, as we'll demonstrate in the next section.

    http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html
  • 8/4/2019 Java 8 Units Notes

    30/78

    Thread Objects

    Each thread is associated with an instance of the class Thread. There are two basicstrategies for using Thread objects to create a concurrent application.

    To directly control thread creation and management, simply instantiate Thread

    each time the application needs to initiate an asynchronous task. To abstract thread management from the rest of your application, pass the

    application's tasks to an executor.

    This section documents the use of Thread objects. Executors are discussed with otherhigh-level concurrency objects.

    Defining and Starting a Thread

    An application that creates an instance of Thread must provide the code that will run inthat thread. There are two ways to do this:

    Provide a Runnable object. The Runnable interface defines a single method, run,meant to contain the code executed in the thread. The Runnable object is passedto the Thread constructor, as in the HelloRunnable example:

    public class HelloRunnable implements Runnable {

    public void run() { System.out.println("Hello from a thread!"); }

    public static void main(String args[]) {

    (new Thread(new HelloRunnable())).start(); }

    } Subclass Thread. The Thread class itself implements Runnable, though its run

    method does nothing. An application can subclass Thread, providing its ownimplementation of run, as in the HelloThread example:

    public class HelloThread extends Thread {

    public void run() { System.out.println("Hello from a thread!"); }

    public static void main(String args[]) { (new HelloThread()).start(); }

    }

    http://java.sun.com/javase/6/docs/api/java/lang/Thread.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Thread.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/highlevel.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Runnable.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/example/HelloRunnable.javahttp://java.sun.com/docs/books/tutorial/essential/concurrency/example/HelloThread.javahttp://java.sun.com/javase/6/docs/api/java/lang/Thread.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/highlevel.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Runnable.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/example/HelloRunnable.javahttp://java.sun.com/docs/books/tutorial/essential/concurrency/example/HelloThread.java
  • 8/4/2019 Java 8 Units Notes

    31/78

    Notice that both examples invoke Thread.start in order to start the new thread.

    Which of these idioms should you use? The first idiom, which employs a Runnableobject, is more general, because the Runnable object can subclass a class other thanThread. The second idiom is easier to use in simple applications, but is limited by the fact

    that your task class must be a descendant of Thread. This lesson focuses on the firstapproach, which separates the Runnable task from the Thread object that executes thetask. Not only is this approach more flexible, but it is applicable to the high-level threadmanagement APIs covered later.

    The Thread class defines a number of methods useful for thread management. Theseinclude static methods, which provide information about, or affect the status of, thethread invoking the method. The other methods are invoked from other threads involvedin managing the thread and Thread object. We'll examine some of these methods in thefollowing sections.

    Pausing Execution with SleepThread.sleep causes the current thread to suspend execution for a specified period. This isan efficient means of making processor time available to the other threads of anapplication or other applications that might be running on a computer system. The sleepmethod can also be used for pacing, as shown in the example that follows, and waitingfor another thread with duties that are understood to have time requirements, as with theSimpleThreads example in a later section.

    Two overloaded versions of sleep are provided: one that specifies the sleep time to themillisecond and one that specifies the sleep time to the nanosecond. However, these sleeptimes are not guaranteed to be precise, because they are limited by the facilities provided

    by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll seein a later section. In any case, you cannot assume that invoking sleep will suspend thethread for precisely the time period specified.

    The SleepMessages example uses sleep to print messages at four-second intervals:

    public class SleepMessages {public static void main(String args[]) throws InterruptedException {

    String importantInfo[] = {"Mares eat oats",

    "Does eat oats","Little lambs eat ivy","A kid will eat ivy too"

    };

    for (int i = 0; i < importantInfo.length; i++) {//Pause for 4 secondsThread.sleep(4000);

    http://java.sun.com/docs/books/tutorial/essential/concurrency/example/SleepMessages.javahttp://java.sun.com/docs/books/tutorial/essential/concurrency/example/SleepMessages.java
  • 8/4/2019 Java 8 Units Notes

    32/78

    //Print a messageSystem.out.println(importantInfo[i]);

    }}

    }

    Notice that main declares that it throws InterruptedException. This is an exception thatsleep throws when another thread interrupts the current thread while sleep is active. Sincethis application has not defined another thread to cause the interrupt, it doesn't bother tocatch InterruptedException.

    Synchronization

    Threads communicate primarily by sharing access to fields and the objects referencefields refer to. This form of communication is extremely efficient, but makes two kinds oferrors possible: thread interference and memory consistency errors. The tool needed to

    prevent these errors issynchronization.

    Thread Interference describes how errors are introduced when multiple threadsaccess shared data.

    Memory Consistency Errors describes errors that result from inconsistent views ofshared memory.

    Synchronized Methods describes a simple idiom that can effectively preventthread interference and memory consistency errors.

    Implicit Locks and Synchronization describes a more general synchronizationidiom, and describes how synchronization is based on implicit locks.

    Atomic Access talks about the general idea of operations that can't be interfered

    with by other threads.

    Difference between Multiprocessing and Multithreading

    Multiprocessing Multithreading1. More than one process running simultaneously 1. More than one thread runningsimultaneously.2. Its part of a program 2. Its part of a program3. Its a heavy wait process 3. Its a light wait process.

    Thread States(Life-Cycle of a Thread)The Life cycle of a thread contains several states. At any time the thread is falls into anyone of the states. At anytime a thread is said tobe in one or more states.

    The thread that was just created is in the born state.

    The thread remains in this state until the threads start methods Is called . Thiscauses the thread to enter the ready state.

    http://java.sun.com/docs/books/tutorial/essential/concurrency/interfere.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/memconsist.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/atomic.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/interfere.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/memconsist.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.htmlhttp://java.sun.com/docs/books/tutorial/essential/concurrency/atomic.html
  • 8/4/2019 Java 8 Units Notes

    33/78

    The highest priority ready thread enter the running state when the system assignsa processor to the thread i.e., the thread begins executing.

    When a running thread calls wait the thread enters into a waiting state for theparticular object on which wait was called. Every thread in the waiting state for agiven object becomes ready on a call to notify all by another thread associated

    with that object.

    Daemon threadsA daemon thread is one that is supposed to provide a general service in the backgroundas long as the program is running, but it not part of the essence of the program.

    UNIT 6

    EVENT HANDLING :

  • 8/4/2019 Java 8 Units Notes

    34/78

    Introduction :Events : An event is an object that describes a state change in a source. Even driven is aconsequence interaction of the user with the GUI.

    Event Sources :A source is an object that generates an event. This occurs when the internal state of thatobject changes in some way. Sources may generate more than one type of event.

    Delegation Event Model :In java 1.0 the action() method is used to perform any actions that are provided with thecontrols. But the action() method is now deprecated. The new technique in java1.1 andjava 2 is Event DelegationModel.

    Event Listeners :A listener is an object that is notified when an event occurs. It has 2 requirements.1. It must have been registered with one or more sources to receive notifications about thespecific type of events.2. It must implement methods to receive and process the notifications.

    Event Classes :Event classes are used to handle Java event handling mechanism. At the root of the Javaevent class hierarchy is EventObject. Which is in the java.util package. It is thesuperclass for all events. It provides a constructor asEventObject(Object x)

    MouseEvent Class :The MouseEvent Class defines types of mouse events. It defines the following integerconstants that can be used to identify them :MOUSE_CLICKED : The user clicked the mouseMOUSE_DRAGGED: The user dragged the mouseMOUSE_ENTERED : The mouse entered a component.

    KeyEvent Class :A KeyEvent is generated when keyboard input occurs. There are 3 types of key events.

    Which are identified by these integer constants.KEY_PRESSEDKEY_RELEASEDKEY_TYPED

    Key Listener Interface :The Interface defines three methods

    1. void keyPressed(KeyEvent me) : It invokes when a key is pressed

  • 8/4/2019 Java 8 Units Notes

    35/78

    2. void keyReleased(KeyEvent me) : it invokes when a key is released.

    Adapter Classes:An adapter class provides an empty implementation of all methods in an event listenerinterface. Adapter classes are useful when we want to receive and process only some of

    the events that are handled by a particular event listener interface.

    AWT CONTROLS

    Introduction:Controls are components that allow a user to interact with our application in variousways. A layout manager automatically positions components with in a container. Theappearance of window is determined by a combination of the controls that it contains andthe layout manager used to position them.

    The AWT supports the following types of controls :LabelsPush buttonsCheck boxesChoice listsListsScroll barsText editing

    Adding Controls :

    First created an instance of the desired controland hten add it to a window by callingadd() method, which is defined by Container.

    Syntax : component add(component obj)

    Removing controlsWe want to remove a control from a window when the control is no longer needed, callthe method remove(). This method is also defined by Container.Syntax : void remove ( component obj)

    Labels :Label is a text information that display on the GUI as a string. These are passive controlsthat do not support any interaction with the user. Label defines the followingconstructors:Label()Label(String str)Label(String str, int how)

  • 8/4/2019 Java 8 Units Notes

    36/78

    Buttons :

    A push button is a component that contains a label and that generates an event it ispressed. Push buttons are object of type Button.

    Handling Buttons :

    ActionEvent Class : An ActionEvent is generated when a button is pressed, a list item isdouble-clicked, or menu item is selected.

    Check Boxes:

    A Check Box is a control that is used to turn an option on or off. It consists of a smallbox that can either contain mark or not. There is a label associated with each check boxthat describes the option that box represents.Checkbox()Checkbox(String str)Checkbox(String str, Boolean on)Checkbox(String str, Boolean on, CheckboxGroup ch)

    Check boxGroup :

    Collection of check boxes is placed under one group is considered as checkboxGroup.These Checkboxes are often called radio buttons, since one choice is selected at any onetime.

    Choice Control :

    The choice class is used to create a pop-up of items from which the user may choose. Achoice control is a form of menu.

    Lists :

    The List class provides a compact, multiple-choice, scrolling section list, The list objectcan be constructed to show any number of choices in the visible window. It can also becreated to allow multiple selections. List provides these constructors.

    List()List(int nrows)List(int nrows, Boolean select)

    Scroll Bars :

  • 8/4/2019 Java 8 Units Notes

    37/78

    Scroll bars are used to select continuous values between a specified minimum andmaximum. Scroll bars may be oriented horizontally or vertically. A scroll bar isactually a composite of several individual parts.

    Text Area:

    TextField is useful to enter only one line of information. If we want to enter more thanone line of data it is not possible with the TextField. To handle these situaltions, theAWT includes a simple multiline editior called TextArea, Constructors of the TextAreaare :TextArea()TextArea(int nlines, int nchars)TextArea(String str)TextArea(String str, int nlines, int nchars)TextArea(string str, int nlines, int nchars, int sbars)

    LAYOUT MANAGER:

    Layout ManagerA Layout Mangeris an instance of any class that implements the LayoutManagerinterface. The layout manager is set by the setLayout() method. If no call to setLayout()is made, then the default layout manager is used. The SetLayout() method has thefollowing general form.Void setLayout(LayoutManger layoutObj)

    FlowLayoutThe default manager is FlowLayout.FlowLayout implements a simple layout style, which is similar to how words flow in atext editor. Components are laid out from the upper-left corner, left to right and top tobottom.

    BorderLayoutThe BorderLayout class implements a common layout style for top-level windows. It hasfour narrow, fixed-width components at the edges and one large area in the center.

    CardLayout:

    The CardLayout class is stores several different layout. Each layout can be thought of asbeing on a separate index card in a deck that can be shuffled so that any card is on top ata given time.

    UNIT-7

    APPLETS

  • 8/4/2019 Java 8 Units Notes

    38/78

    IntroductionJava programs are generally classified into 2 ways as Application programs and Appletprograms

    Application Programs : Application programs are those programs normally created,compiled and executed as similar to the other languages.

    Applet Programs : Applet programs are small programs that are primarily used inInternet programming. These programs are either developed in local systems or inremote systems and are executed by either a java compatible web browser orAppletviewer

    Local Applet : When a web page is trying to find a local applet, it does not need to usethe Internet and therefore the local system does not require the Internet connection.

    Applet Life CycleEvery java Applet inherits a set of default behaviors from the Applet class defined injva.applet package. When an applet is loaded, it undergoes a series of changes in itsstates.

    Exit of Browser :Note

    1. 1 : All the methods are automatically to called when any applet begin execution.2. The applet execution follows the above order.3. In every applet it doesnt need to place all the methods.4. class hierarchy of the applet is java.lang.object

    Passing Parameters to AppletsIt is also possible to supply user-defined parameters to an applet using tags.Each tag has a name attribute and value attribute. Inside the applet code, theapplet can refer to theat parameter by name to find its value. To retrieve the parameter,use the getparameter() method.

    Lesson: A Brief Introduction to the Swing Package

    This lesson gives you a brief introduction to the capabilities of the Java SE platform thatpertain to developing programs with graphical user interfaces (GUIs). Next, it shows youa demo (sample code provided) that showcases many of these features.

    The next lesson, Swing Features discusses these capabilities in more detail.

    What is Swing?

    http://java.sun.com/docs/books/tutorial/ui/features/index.htmlhttp://java.sun.com/docs/books/tutorial/ui/overview/intro.htmlhttp://java.sun.com/docs/books/tutorial/ui/features/index.htmlhttp://java.sun.com/docs/books/tutorial/ui/overview/intro.html
  • 8/4/2019 Java 8 Units Notes

    39/78

    The Swing toolkit, shipped as part of the Java SE platform, provides a rich set of GUIcomponents. But Swing offers much more functionality than a collection of standardwidgets. This section takes a look at Swing's rich functionality.

    A Swing Demo

    A rich multi-class Swing application, PasswordStore, is presented. The source code isprovided as a reference to the user.What is Swing?

    To create a Java program with a graphical user interface (GUI), you'll want to learn aboutSwing.

    The Swing toolkit includes a rich set of components for building GUIs and addinginteractivity to Java applications. Swing includes all the components you would expectfrom a modern toolkit: table controls, list controls, tree controls, buttons, and labels.

    Swing is far from a simple component toolkit, however. It includes rich undo support, ahighly customizable text package, integrated internationalization and accessibilitysupport. To truly leverage the cross-platform capabilities of the Java platform, Swingsupports numerous look and feels, including the ability to create your own look and feel.The ability to create a custom look and feel is made easier with Synth, a look and feelspecifically designed to be customized. Swing wouldn't be a component toolkit withoutthe basic user interface primitives such as drag and drop, event handling, customizablepainting, and window management.

    Swing is part of the Java Foundation Classes (JFC). The JFC also include other featuresimportant to a GUI program, such as the ability to add rich graphics functionality and the

    ability to create a program that can work in different languages and by users withdifferent input devices.

    The following list shows some of the features that Swing and the Java FoundationClasses provide.

    Swing GUI ComponentsThe Swing toolkit includes a rich array of components: from basic components, such asbuttons and check boxes, to rich and complex components, such as tables and text. Evendeceptively simple components, such as text fields, offer sophisticated functionality, suchas formatted text input or password field behavior. There are file browsers and dialogs to

    suit most needs, and if not, customization is possible. If none of Swing's providedcomponents are exactly what you need, you can leverage the basic Swing componentfunctionality to create your own.

    Java 2D APITo make your application stand out; convey information visually; or add figures, images,or animation to your GUI, you'll want to use the Java 2DTM API. Because Swing is builton the 2D package, it's trivial to make use of 2D within Swing components. Addingimages, drop shadows, compositing it's easy with Java 2D.

    http://java.sun.com/docs/books/tutorial/ui/overview/demo.htmlhttp://java.sun.com/docs/books/tutorial/ui/overview/demo.html
  • 8/4/2019 Java 8 Units Notes

    40/78

    Pluggable Look-and-Feel SupportAny program that uses Swing components has a choice of look and feel. The JFC classesshipped by Sun and Apple provide a look and feel that matches that of the platform. TheSynth package allows you to create your own look and feel. The GTK+ look and feelmakes hundreds of existing look and feels available to Swing programs.

    A program can specify the look and feel of the platform it is running on, or it can specifyto always use the Java look and feel, and without recompiling, it will just work. Or, youcan ignore the issue and let the UI manager sort it out.

    Data TransferData transfer, via cut, copy, paste, and drag and drop, is essential to almost anyapplication. Support for data transfer is built into Swing and works betweenSwing components within an application, between Java applications, and betweenJava and native applications.

    Internationalization

    This feature allows developers to build applications that can interact with usersworldwide in their own languages and cultural conventions. Applications can becreated that accept input in languages that use thousands of different characters,such as Japanese, Chinese, or Korean.

    Swing's layout managers make it easy to honor a particular orientation requiredby the UI. For example, the UI will appear right to left in a locale where the textflows right to left. This support is automatic: You need only code the UI once andthen it will work for left to right and right to left, as well as honor the appropriatesize of components that change as you localize the text.

    Accessibility APIPeople with disabilities use special software assistive technologies thatmediates the user experience for them. Such software needs to obtain a wealth ofinformation about the running application in order to represent it in alternatemedia: for a screen reader to read the screen with synthetic speech or render it viaa Braille display, for a screen magnifier to track the caret and keyboard focus, foron-screen keyboards to present dynamic keyboards of the menu choices andtoolbar items and dialog controls, and for voice control systems to know what theuser can control with his or her voice. The accessibility API enables theseassistive technologies to get the information they need, and to programmaticallymanipulate the elements that make up the graphical user interface.

    Undo Framework APISwing's undo framework allows developers to provide support for undo and redo.Undo support is built in to Swing's text component. For other components, Swingsupports an unlimitednumber of actions to undo and redo, and is easily adapted toan application. For example, you could easily enable undo to add and removeelements from a table.

    Flexible Deployment Support

  • 8/4/2019 Java 8 Units Notes

    41/78

    If you want your program to run within a browser window, you can create it as anapplet and run it using Java Plug-in, which supports a variety of browsers, such asInternet Explorer, Firefox, and Safari. If you want to create a program that can belaunched from a browser, you can do this with Java Web Start. Of course, yourapplication can also run outside of browser as a standard desktop application.

    For more information on deploying an application, see theDeployment trail inthis tutorial.

    This trail provides an overview of Swing capabilities, beginning with a demo thatshowcases many of these features. When you are ready to begin coding, theCreating a GUI with JFC/Swing trail provides the programming techniques totake advantage of these features.

    Next, a demo shows many of these features.

    A Swing DemoHere is an example of an application, PasswordStore, that illustrates some of Swing's richfeature set. PasswordStore allows the user to manage login information for various hosts.It also generates passwords, evaluates the effectiveness of a password, and allows you tostore notes about a particular host or assign an icon to represent the host.Text

    The Java 2D API has various text rendering capabilities including methods forrendering strings and entire classes for setting font attributes and performing text layout.

    If you just want to draw a static text string, the most direct way to render it directlythrough the Graphics class by using the drawString method. To specify the font, you use

    the setFont method of the Graphics class.

    If you want to implement your own text-editing routines or need more control over thelayout of the text than the text components provide, you can use the Java 2D text layoutclasses in the java.awt.font package.

    Fonts

    The shapes that a font uses to represent the characters in a string are called glyphs. Aparticular character or combination of characters might be represented as one or moreglyphs. For example, might be represented by two glyphs, whereas the ligaturefi might

    be represented by a single glyph.

    Afontcan be thought of as a collection of glyphs. A single font might have manyfaces,such as italic and regular. All of the faces in a font have similar typographic features andcan be recognized as members of the samefamily. In other words, a collection of glyphswith a particular style form afont face. A collection of font faces forms afont family. Thecollection of font families forms the set of fonts that are available on the system.

    http://java.sun.com/docs/books/tutorial/ui/overview/index.htmlhttp://java.sun.com/docs/books/tutorial/ui/overview/index.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/index.htmlhttp://java.sun.com/docs/books/tutorial/ui/overview/index.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/index.html
  • 8/4/2019 Java 8 Units Notes

    42/78

    When you are using the Java 2D API, you specify fonts by using an instance of Font.You can determine what fonts are available by calling the static methodGraphicsEnvironment.getLocalGraphicsEnvironment and then querying the returnedGraphicsEnvironment. The getAllFonts method returns an array that contains Fontinstances for all of the fonts available on the system. The getAvailableFontFamilyNames

    method returns a list of the available font families.

    Text Layout

    Before text can be displayed, it must be laid out so that the characters are represented bythe appropriate glyphs in the proper positions. The following are two Java 2Dmechanisms for managing text layout:

    The TextLayout class manages text layout, highlighting, and hit detection. Thefacilities provided by TextLayout handle the most common cases, includingstrings with mixed fonts, mixed languages, and bidirectional text. .

    You can create the own GlyphVector objects by using the Font class and thenrendering each GlyphVector object through the Graphics2D class. Thus, you cancompletely control how text is shaped and positioned. .

    Rendering Hints for Text

    The Java 2D API enables you to control the quality of shapes and text rendering by usingrendering hints. Rendering hints are encapsulated by the java.awt.RenderingHints class.

    As applied to text, this capability is used for antialiasing (which is also known as ansmooth edges). For example, the KEY_TEXT_ANTIALIASING hint enables you to

    control the antialiasing of text separately from the antialiasing of other shapes. To learnmore about rendering hints see theControlling Rendering Quality lesson.

    Images

    In the Java 2D API an image is typically a rectangular two-dimensional array of pixels,where eachpixelrepresents the color at that position of the image and where thedimensions represent the horizontal extent (width) and vertical extent (height) of theimage as it is displayed.

    The most important image class for representing such images is thejava.awt.image.BufferedImage class. The Java 2D API stores the contents of such images

    in memory so that they can be directly accessed.

    Applications can directly create a BufferedImage object or obtain an image from anexternal image format such as PNG or GIF.

    In either case, the application can then draw on to image by using Java 2D API graphicscalls. So, images are not limited to displaying photographic type images. Different

    http://java.sun.com/docs/books/tutorial/2d/advanced/quality.htmlhttp://java.sun.com/docs/books/tutorial/2d/advanced/quality.htmlhttp://java.sun.com/docs/books/tutorial/2d/advanced/quality.html
  • 8/4/2019 Java 8 Units Notes

    43/78

    objects such as line art, text, and other graphics and even other images can be drawn ontoan image (as shown on the following images).

    The Java 2D API enables you to apply image filtering operations to BufferedImage andincludes several built-in filters. For example, the ConvolveOp filter can be used to blur orsharpen images.

  • 8/4/2019 Java 8 Units Notes

    44/78

  • 8/4/2019 Java 8 Units Notes

    45/78

    UDP

    The UDP protocol provides for communication that is not guaranteed between twoapplications on the network. UDP is not connection-based like TCP. Rather, it sendsindependent packets of data, called datagrams, from one application to another. Sending

    datagrams is much like sending a letter through the postal service: The order of deliveryis not important and is not guaranteed, and each message is independent of any other.

    Definition: UDP(User Datagram Protocol) is a protocol that sends independent packetsof data, called datagrams, from one computer to another with no guarantees about arrival.UDP is not connection-based like TCP.

    For many applications, the guarantee of reliability is critical to the success of the transferof information from one end of the connection to the other. However, other forms ofcommunication don't require such strict standards. In fact, they may be slowed down bythe extra overhead or the reliable connection may invalidate the service altogether.

    Consider, for example, a clock server that sends the current time to its client whenrequested to do so. If the client misses a packet, it doesn't really make sense to resend itbecause the time will be incorrect when the client receives it on the second try. If theclient makes two requests and receives packets from the server out of order, it doesn'treally matter because the client can figure out that the packets are out of order and makeanother request. The reliability of TCP is unnecessary in this instance because it causesperformance degradation and may hinder the usefulness of the service.

    Another example of a service that doesn't need the guarantee of a reliable channel is theping command. The purpose of the ping command is to test the communication betweentwo programs over the network. In fact, ping needs to know about dropped or out-of-

    order packets to determine how good or bad the connection is. A reliable channel wouldinvalidate this service altogether.

    The UDP protocol provides for communication that is not guaranteed between twoapplications on the network. UDP is not connection-based like TCP. Rather, it sendsindependent packets of data from one application to another. Sending datagrams is muchlike sending a letter through the mail service: The order of delivery is not important andis not guaranteed, and each message is independent of any others.

    Note: Many firewalls and routers have been configured not to allow UDP packets. Ifyou're having trouble connecting to a service outside your firewall, or if clients are

    having trouble connecting to your service, ask your system administrator if UDP ispermitted.

    Understanding Ports

    Generally speaking, a computer has a single physical connection to the network. All datadestined for a particular computer arrives through that connection. However, the data

  • 8/4/2019 Java 8 Units Notes

    46/78

    may be intended for different applications running on the computer. So how does thecomputer know to which application to forward the data? Through the use ofports.

    Data transmitted over the Internet is accompanied by addressing information thatidentifies the computer and the port for which it is destined. The computer is identified by

    its 32-bit IP address, which IP uses to deliver data to the right computer on the network.Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to theright application.

    In connection-based communication such as TCP, a server application binds a socket to aspecific port number. This has the effect of registering the server with the system toreceive all data destined for that port. A client can then rendezvous with the server at theserver's port, as illustrated here:

    Definition: The TCP and UDP protocols use ports to map incoming data to a particularprocess running on a computer.

    In datagram-based communication such as UDP, the datagram packet contains the portnumber of its destination and UDP routes the packet to the appropriate application, asillustrated in this figure:

    Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers.The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. These ports are calledwell-known ports. Your applications should not attempt to bind to them.

    Networking Classes in the JDK

    Through the classes in java.net, Java programs can use TCP or UDP to communicate overthe Internet. The URL, URLConnection, Socket, and ServerSocket classes all use TCP tocommunicate over the network. The DatagramPacket, DatagramSocket, andMulticastSocket classes are for use with UDP.Lesson: Working with