SlideShare una empresa de Scribd logo
1 de 203
Core Java

                   Rajeev Gupta
                      MTech CS




1   Rajeev Gupta
Contents at a glance
       Java An Introduction
       Basic Java Constructs and Data Types and array
       OO Introduction
       Class object and related topics
       Inheritance
       Final ,Abstract Classes and interface
       String class, immutability, inner classes
       Exceptions Handling, assertions
       Streams and Input/output Files, serialization
       Java Thread
       Java Collections



    2                                                    Rajeev Gupta
Day-1
Session-1
-------------                                Session-2
    Introduction to Java                    -------------
    What is Java,Why Java?                     Object Oriented
    JDK,JRE and JVM discussion                       Object, class, Encapsulation,
    Installing JDK, editPlus, eclipse 3.6            Abstraction,
    Hello World application                          Inheritence,
    Procedural Programming                           Polymorphism,message passing
        If..else,switch, looping                 ( concepts only, implementation on day 2)
        Array

        Examples




 3                                                Rajeev Gupta
Day-2
 Session-1                                     Session-2
                                               -------------
 -------------
                                               Inheritance
Class and objects                              Type of inheritance, diamond problem
                                               InstanceOf operator
Creating Classes
                                               Final
Implementing Methods                           Final variable, final method , final class
Object: state, identity and behaviour                      Acess control: public,
                                                           private,protected and default
Constructors: default, parameterized and
  copy                                             Packages
Instance variable, static variable and local
   variable                                        Abstract class
                                                   Interface
Initialization block
                                               Polymorphism
Static method and applications                 Overloading
Packages and visibility modifier: public,      Overriding
   protected, private and default              Type of relationship bw objects
                                                         IS-A, HAS-A, USE-A
                                                   Rajeev Gupta
    4
Day-3
Session-1
-------------                             Session-2
String class: Immutability and usages,
                                          -------------
   stringbuilder and stringbuffer
                                          Exception handling
Wrapper classes and usages                            Try, catch, throw, throws,
     Java 5 Language Features (I):                    finally
                                                      Checked and
AutoBoxing and Unboxing, Enhanced
  For loop, Varargs, Static Import,                   Unchecked exception
  Enums                                               User defind exceptions
                                          design by contract- assertions
Inner classes
Regular inner class, method local inner
  class, annonymous inner class

 5                                             Rajeev Gupta
Day-4
Session-1                           Session-2
-------------                       -------------

     IO                             Multi-Threading

Char and byte oriented streams      Creating threads: using Thread class and Runnable
                                    interface
BufferedReader and BufferedWriter
                                    Thread life cycle
File handling
                                    Using sleep(), join(), thread priorities
Object Serialization and IO         Synchronization
  [ObjectInputStream /
  ObjectOutputStream]               Solving producer and consumer problem using
                                    wait() and notify()

                                    Deadlock introduction

                                    Concurrency Utilities Overview

                                           Executor Framework, Semaphore, Latches




 6                                      Rajeev Gupta
Day-5
Session-1
                                          Session-2
-------------
                                         -------------
Collections Framework                    Java 5 Language Features II
List, Map, Set usages introduction
                                                   Generics
Usages ArrayList, LinkedList, HashMap,             Annotations
   TreeMap, HashSet
Comparable, Comparator interface
  implementation                         Case study using collection, File
User define key in HashMap

                                         MCQ Exam 




    7                                        Rajeev Gupta
DAY-1




8           Rajeev Gupta
Session-1
       Introduction to Java
           What is Java,Why Java?
           JDK,JRE and JVM discussion
           Installing JDK, editPlus, eclipse 3.6
       Hello World application
       Procedural Programming
           If..else,switch, looping
           Array
       Examples





    9                                          Rajeev Gupta
What is Java?
    Java is not only an oo programming
      language



     It can be best described as


     OOPS+JVM+API


    10                              Rajeev Gupta
How Sun define Java?
    Simple and Powerful
    Object Oriented
    Portable
    Architecture Neutral
    Distributed
    Multi-threaded
    Robust, Secure/Safe
    Interpreted
    High Performance
    Dynamic programming language/platform.




    11                                        Rajeev Gupta
Versions

    JDK 1.0 (1995)
    JDK 1.1 (1997)
    J2SE 1.2 (1998) ) Playground
    J2SE 1.3 (2000)  Kestrel                      Called Java2
    J2SE 1.4 (2002)  Merlin
    J2SE 5.0 (2004)  Tiger
    Java SE 6 ( 2006)  Mustang       Version for the session
    Java SE 7 (2011) Dolphin



    12                                     Java 6
                                     Rajeev Gupta
Java 1.0       Java 1.1        Java 1.2        Java 1.3          Java 1.4       Java 1.5
8 packages     23 packages     59 packages     77 packages       103 packages 131 packages
212 classes    504 classes     1520 classes    1595 classes      2175 classes 2656 classes

               New Events      JFC/Swing       JNDI              Regular Exp   javax.activity,
                                                                 Logging       javax.
               Inner class     Drag and        Java Sound        Assertions    management
                               Drop                              NIO
               Object                          Timer
               Serialization Java2D                              java.nio, javax.imageio,
               Jar Files       CORBA                             javax.net, javax.print,
                                                                 javax.security, org.w3c
               International
               Reflection                      javax.naming, javax.sound,
                                               javax.transaction
               JDBC
               RMI

                               javax.accessibility, javax.swing, org.omg




               java.math, java.rmi, java.security, java.sql, java.text, java.beans

java.applet, java.awt, java.io, java.lang, java.net, java.util
Some common buzzwords
    JDK
      Java development kit, developer need it

    Byte Code
      Highly optimize instruction set, designed to run on JVM
      Platform independent

    JRE
      Java Runtime environment, Create an instance JVM, must be there on
        deployment machine.
      Platform dependent

     JVM
      Java Virtual Machine JVM
      Pick byte code and execute on client machine
      Platform dependent…




    14                                             Rajeev Gupta
Understanding JVM




15                  Rajeev Gupta
Installing JDK, editPlus, eclipse 3.6

    Follow me for configuration and running Java hello
     world!!!




    16                               Rajeev Gupta
Analysis of Hello World !!!




17                      Rajeev Gupta
Java Program Structure

             Documentation Section


              Package Statement


               Import Statements


              Interface Statements


               Class Declarations

               Main Method Class
               {
               }


18                             Rajeev Gupta
Java Data Type
    2 type
        Primitive data type
        Reference data type (latter)




    19                                  Rajeev Gupta
Primitive data type:


    boolean                 either true of false
    char                    16 bit Unicode 1.1
    byte                    8-bit integer (signed)
    short                   16-bit integer (signed)
    int                     32-bit integer (signed)
    long                    64-bit integer (singed)
    float                   32-bit floating point (IEEE 754-1985)
    double                  64-bit floating point (IEEE 754-1985)


Java uses Unicode to represent characters internally




    20                                                Rajeev Gupta
Procedural Programming
    if..else
    switch
    Looping; for, while, do..while as usual in Java as in C/C++

    Don’t mug the program/logic
    Follow dry run approach
        Try some programms:
            Create
            Factorial program
            Prime No check
            Date calculation

    21                                 Rajeev Gupta
Array
    One Dimensional array

        int x[]=new int[5]




    22                        Rajeev Gupta
Session-2
    Object Oriented ( concepts only)
         Object, class
    Basic principles of OO
        Encapsulation
        Abstraction
        modularity
        Inheritance/ Hierarchy
        Polymorphism, message passing




    23                                   Rajeev Gupta
So what is object orientation?




24                     Rajeev Gupta
What is an Object?




25                   Rajeev Gupta
What is an class?




26                  Rajeev Gupta
What is the relationship bw class and
objects?




27                     Rajeev Gupta
Basic principles of OO




28                       Rajeev Gupta
What is abstraction?




29                     Rajeev Gupta
What is encapsulation?




30                       Rajeev Gupta
What is modularity?




31                    Rajeev Gupta
What is Hierarchy?




32                   Rajeev Gupta
A bit about UML diagram…
    UML 2.0 aka modeling language has 12 type of diagrams
    Most important once are class diagram, use case diagram and sequence diagram.
    You should know how to read it correctly
    This is not UML session… 




    33                                            Rajeev Gupta
DAY-2




34           Rajeev Gupta
Session-1
    Class and objects
        Creating Classes and object
        Object: state, identity and behaviour
        Constructors: default, parameterized and copy
        Need of “this” , Constructor chaining
        Instance variable, static variable and local variable
        Initialization block
        Scanner and printf
        Parameter passing in Java
            Call by value / call by reference…




    35                                            Rajeev Gupta
What can goes inside an class?




36                    Rajeev Gupta
Creating Classes and object




37                    Rajeev Gupta
Correct way?




38             Rajeev Gupta
Constructors: default, parameterized
and copy
    Initialize state of the object
    Special method have same name as
     that of class
    Can’t return anything
    Can only be called once for an object
    Can be private
    Can’t be static*
    Can overloaded but cant overridden*
    Can be
      Default, parameterized and
       copy constructor




    39                                       Rajeev Gupta
Need of this?
                   Which id assigned to
                    which id?
                   “this” is an reference to
                    the current object
                    required to differentiate
                    local variables with
                    instance variables

                        Refer next slide…




40                      Rajeev Gupta
41   Rajeev Gupta
this : Constructor chaining?
    Calling one constructor
     from another ?




    42                         Rajeev Gupta
Static method/variable
    Instance variable –per object while
     static variable are per class


    Initialize and define before any
     objects


    Most suitable for counter for object


    Static method can only access static
     data of the class


    For calling static method we don’t
     need an object of that class


Now guess why main was static?
    43                                      Rajeev Gupta
Using static data..




44                    Rajeev Gupta
Initialization block
    We can put repeated
     constructor code in an
     Initialization block…

    Static Initialization block
     runs before any
     constructor and runs only
     once…




    45                             Rajeev Gupta
Initialization block




46                     Rajeev Gupta
Packages

    Packages are Java’s way of grouping a number of related classes
     and/or interfaces together into a single unit. That means,
     packages act as “containers” for classes.

    The benefits of organising classes into packages are:
        The classes contained in the packages of other programs/applications
         can be reused.
        In packages classes can be unique compared with classes in other
         packages. That two classes in two different packages can have the same
         name. If there is a naming clash, then classes can be accessed with their
         fully qualified name.
        Classes in packages can be hidden if we don’t want other packages to
         access them.
        Packages also provide a way for separating “design” from coding.


    47                                            Rajeev Gupta
Java Foundation Packages
    Java provides a large number of classes groped into different packages
     based on their functionality.
    The six foundation Java packages are:
        java.lang
            Contains classes for primitive types, strings, math functions, threads, and exception
        java.util
            Contains classes such as vectors, hash tables, date etc.
        java.io
            Stream classes for I/O
        java.awt
            Classes for implementing GUI – windows, buttons, menus etc.
        java.net
            Classes for networking
        java.applet
            Classes for creating and implementing applets




    48                                                       Rajeev Gupta
Accessing Classes from Packages
    There are two ways of accessing the classes stored in packages:
        Using fully qualified class name
            java.lang.Math.sqrt(x);
        Import package and use class name directly.
            import java.lang.Math
            Math.sqrt(x);
    Selected or all classes in packages can be imported:

                              import package.class;
                              import package.*;

    Implicit in all programs: import java.lang.*;
    package statement(s) must appear first




    49                                            Rajeev Gupta
Visibility Modifiers
    For instance variable and methods
        Public
        Protected
        Default (package level)
        Private
    For classes
        Public and default




    50                              Rajeev Gupta
Visibility Modifiers
    class A has default visibility hence can
     access in the same package only.


    Make class A public, then access it.


    Protected data can access in the same
     package and all the subclasses in other
     packages provide class itsef is public




    51                                          Rajeev Gupta
Visibility Modifiers

       Accessible to:    public   protected     Package      private
                                                (default)

     Same Class           Yes       Yes           Yes         Yes


     Class in package     Yes       Yes           Yes         No


     Subclass in          Yes       Yes           No          No
     different package

     Non-subclass         Yes       No            No          No
     different package




52                                            Rajeev Gupta
Packages and Name Clashing
    When packages are developed by different organizations, it is
     possible that multiple packages will have classes with the same
     name, leading to name classing.

                       package pack1;                          package pack2;

                            class Teacher                          class Student

                            class Student                          class Courses


    We can import and use these packages like:
        import pack1.*;
        import pack2.*;
        Student student1; // Generates compilation error

    53                                          Rajeev Gupta
Want to accept parameter from user?
java.util.Scanner (Java 1.5)



Scanner stdin = Scanner.create(System.in);

int n = stdin.nextInt();
String s = stdin.next();



boolean b = stdin.hasNextInt()
Missing powerful printf of C programming?

   System.out.printf( “format-string” [, arg1, arg2, … ] );
Call by value & call by reference
    Java don’t support call by reference.
    When you pass an object in an method copy of reference is passed so that we can mutate the
     state of the object but can’t delete original object itself




    56                                                  Rajeev Gupta
Session-2
    Inheritance
    Type of inheritance, diamond problem
    InstanceOf operator
    Final
    Final variable, final method , final class
            Acess control: public, private,protected and default
            Packages
            Abstract class
            Interface
    Polymorphism
    Overloading
    Overriding




    57                                                  Rajeev Gupta
Inheritance
    Inheritance is the inclusion
     of behaviour (i.e. methods)
     and state (i.e. variables) of
     a base class in a derived
     class so that they are
     accessible in that derived
     class.

    code reusability.

    Subclass and Super class
     concept




    58                               Rajeev Gupta
Diamond Problem?
    Hierarchy inheritance can leds to
     poor design..

Java don’t support it directly…
( Possible using interface )




    59                               Rajeev Gupta
Inheritance example
    Use extends keyword

    Use super to pass values
     to base class
     constructor.




    60                          Rajeev Gupta
Overloading
    Overloading deals with multiple methods in the same class with the same name but different
     method signatures.


    Both the above methods have the same method names but different method signatures, which
     mean the methods are overloaded.


    Overloading lets you define the same operation in
     different ways for different data.
     Constructor can be overloaded




Be careful of overloading ambiguity
*Overloading in case of var-arg and Wrapper objects…

    61                                                   Rajeev Gupta
Overriding…
    Overriding deals with two methods, one in the parent class and the other one in
     the child class and has the same name and signatures.


    Both the above methods have the same method names and the signatures but the
     method in the subclass MyClass overrides the method in the superclass BaseClass


    Overriding lets you define the same operation in different ways for different
     object types.




    62                                             Rajeev Gupta
Polymorphism
    Polymorphism=many forms of one things
    Substitutability
    Overriding
    Polymorphism means the ability of a single variable
     of a given type to be used to reference objects of
     different types, and automatically call the method that is
     specific to the type of object the variable references.




    63                                 Rajeev Gupta
Polymorphism
    Every animal sound but
     differently…
    We want to have Pointer of
     Animal class assigned by object
     of derived class




    64                                 Rajeev Gupta
Example…




65         Rajeev Gupta
Need of abstract class?
    Sound( ) method of Animal
     class don’t make any sense
     …i.e. it don’t have
     semantically valid definition

    Method sound( ) in Animal
     class should be abstract
     means incomplete

    Using abstract method
     Derivatives of Animal class
     forced to provide meaningful
     sound() method



    66                               Rajeev Gupta
Abstract class
    If an class have at least one
     abstract method it should be
     declare abstract class.


    Some time if we want to
     stop a programmer to create
     object of some class…


    Class has some default
     functionality that can be used
     as it is.


    Can implement only one
     abstract class 



    67                                Rajeev Gupta
Abstract class use cases…
    Want to have some default functionality from base class
     and class have some abstract functionality that cant be
     define at that moment.




    Don’t want to allow a programmer to create object of an
     class as it is too generic

    Interface vs. abstract class

    68                               Rajeev Gupta
More example…




69              Rajeev Gupta
Final
    Its final: i.e. cant be change!!!
    final
        Final method arguments
            Cant be change inside the method
        Final variable
            Become constant, once assigned then cant be changed
        Final method
            Cant overridden
        Final class
            Cant inherited
            Can be reuse

         Some examples….
    70                                          Rajeev Gupta
Final class
    Final class cant be subclass ie cant be extended
    No method of this class can be overridden
    Ex: String class in Java…
    Real question is in what situation somebody should
     declare a class final




    71                                                  Rajeev Gupta
Final Method
    Final Method Can’t overridden
    Class containing final method can be extended
    Killing substitutability




    72                              Rajeev Gupta
Interface?
   Interface : contract bw two parties
   Interface method
       Only declaration, no method definition
       No method implementation please !
   Interface variable
       Public static and final constant
           Its how java support global constant
    Break the hierarchy
   Solve diamond problem
   Callback in Java*

Some Example ….
 73                                                Rajeev Gupta
Interface?
    Rules
        All interface methods are always public and abstract, whether
         we say it or not.
        Variable declared inside interface are always public static and
         final
        Interface method can’t be static or final
        Interface cant have constructor
        An interface can extends other interface
        Can be used polymorphically
        An class implementing an interface must implement all of its
         method otherwise it need to declare abstract class…


    74                                      Rajeev Gupta
Implementing an interface…




75                   Rajeev Gupta
Note
    Following interface constant declaration are identical
        int i=90;
        public static int i=90;
        public int i=90;
        Public static int i=90;
        Public static final int i=90;
    Following interface method declaration don’t compile
        final void bounce();
        static void bounce();
        private void bounce();
        protected void bounce();

    76                                   Rajeev Gupta
You must be clear up to this…




77                    Rajeev Gupta
Type of relationship bw objects
    USE-A
    HAS-A
    IS-A (Most costly ? )



ALWAYS GO FOR LOOSE COUPLING AND HIGH
 COHESION…

But HOW?


    78                       Rajeev Gupta
IS-A   VS                  HAS-A




79          Rajeev Gupta
Self Reading ..will discuss latter..
    Implementation inheritance (Already done)
    Interface inheritance with composition(Google it)




    80                           Rajeev Gupta
Just for fun!!!




81                Rajeev Gupta
DAY-3




82           Rajeev Gupta
Session-1
    String class
        Immutability and usages,
        stringbuilder and stringbuffer
    Wrapper classes and usages
    Java 5 Language Features (I):
        AutoBoxing and Unboxing
        Enhanced For loop
        Varargs
        Static Import
        Enums
    Inner classes
        Regular inner class
        method local inner class
        anonymous inner class


    83                                    Rajeev Gupta
String
    Immutable i.e. once assigned then cant be changed
    Only class in java for which object can be created with or
     without using new operator

     Ex: String s=“india”;
         String s1=new String(“india”); What is the difference?

        String concatenation can be in two ways:
            String s1=s+”paki”;         Operator overloading
            String s3=s1.concat(“paki”);



    84                                           Rajeev Gupta
Some common string methods…
    charAt()
        Returns the character located at the specified index
    concat()
        Appends one String to the end of another ( "+" also works)
    equalsIgnoreCase()
        Determines the equality of two Strings, ignoring case
    length()
        Returns the number of characters in a String
    replace()
        Replaces occurrences of a character with a new character
    substring()
        Returns a part of a String
    toLowerCase()
        Returns a String with uppercase characters converted
    toString()
        Returns the value of a String
    toUpperCase()
        Returns a String with lowercase characters converted
    trim()
        Removes whitespace from the ends of a String



    85                                                                Rajeev Gupta
String comparison
    Two string should never be checked for equality using ==
     operator          WHY?

    Always use equals( ) method….

String s1=“india”;
String s2=“paki”;


     if(s1.equals(s2))
             …..
             …..




    86                               Rajeev Gupta
Immutability
   Immutability means something that cannot be
    changed.
   Strings are immutable in Java. What does this mean?
        String literals are very heavily used in applications and they also
         occupy a lot of memory.
        Therefore for efficient memory management, all the strings are
         created and kept by the JVM in a place called string pool (which
         is part of Method Area).
        Garbage collector does not come into string pool.
        How does this save memory?



    87                                         Rajeev Gupta
Wrapper classes
    Helps treating primitive data as an object
    But why we should convert primitive to objects?
      We can’t store primitive in java collections
      Object have properties and methods
      Have different behavior when passing as method argument
      Eight wrapper for eight primitive
      Integer, Float, Double, Character,
     Boolean etc…

     Integer it=new Integer(33);
     int temp=it.intValue();
     ….

    88                                 Rajeev Gupta
Boxing / Unboxing                       Java 1.5
  Boxing
-----------
         Integer iWrapper = 10;
         Prior to J2SE 5.0, we use
         Integer a = new Integer(10);


  Unboxing
-------------
     int iPrimitive = iWrapper;
     Prior to J2SE 5.0, we use
     int b = iWrapper.intValue();

    89                                  Rajeev Gupta
Java 5 Language Features (I)

    AutoBoxing and Unboxing
     Enhanced For loop
    Varargs
    Static Import
    Enums




    90                         Rajeev Gupta
Enhanced For loop

    Provide easy looping construct to loop through array and
     collections




    91                               Rajeev Gupta
Varargs

    Java start supporting variable argument method in Java 1.5




    Discuss function overloading in case of Varargs and
     wrapper classes

    92                               Rajeev Gupta
Static Import
    Handy feature in Java 1.5 that allow something like this:
         import static java.lang.Math.PI;
         import static java.lang.Math.cos;

    Now rather then using
        double r = Math.cos(Math.PI * theta);
    We can use something like
        double r = cos(PI * theta); – looks more readable ….

        Avoid abusing static import like
            import static java.lang.Math.*;

General guidelines to use static java import:
        1) Use it to declare local copies of java constants
        2) When you require frequent access to static members from one or two java
         classes

    93                                             Rajeev Gupta
Enums
    Enum is a special type of classes.
    enum type used to put restriction on the instance values




    94                               Rajeev Gupta
Inner classes
    A class define inside another
        Why to define it?




    95                               Rajeev Gupta
top level inner class




96                      Rajeev Gupta
Method local inner class
    Class define inside an
     method

    Can not access local
     data define inside
     method

    Declare local data
     static to access it



    97                        Rajeev Gupta
Anonymous Inner class
interface Cookable
{
     void cook();
}


class Food
{
     Cookable c=new Cookable() {


             @Override
             public void cook() {
                          System.out.print("cooked ...");


             }
     };
}



    98                                                      Rajeev Gupta
Session-2

    Exception handling
        Try, catch, throw, throws, finally
        Checked and Unchecked exception
        User defined exceptions


    assertions




    99                                    Rajeev Gupta
What is Exception?
An exception is an abnormal condition that arises while running
a program.

Examples:
 Attempt to divide an integer by zero causes an exception to be thrown at run
  time.
 Attempt to call a method using a reference that is null.
 Attempting to open a nonexistent file for reading.
 JVM running out of memory.



    Exception handling do not correct abnormal condition rather
     it make our program robust i.e. make us enable to take
     remedial action when exception occurs…Help in recovering…

    100                                       Rajeev Gupta
Type of exceptions
    RuntimeEx: Unchecked
     Exception
    CompiletimeEx: Checked

     Error: Should not to be handled
     by programmer..like JVM crash

    all problem happens at run time
     in programming and also in real
     life.....
    for checked ex, we need to tell
     java we know about those
     problems for example readLine()
     throws IOException

    101                                 Rajeev Gupta
Exception Hierarchy
                  java.lang.Throwable

    Our focus!


    java.lang.Exception           java.lang.Error


checked
                      java.lang.VirtualMachineError
          unchecked
   Throwable class is super class for all exceptions in Java.
    When an exception occurs in a method, an object
    of Throwable type is thrown.
   The 2 subclasses –Error and Exception
    102                             Rajeev Gupta
java.lang.Error

    java.lang.Exception
                              unchecked exception

unchecked exception
java.lang.RuntimeException               java.io.IOException

                                     java.sql.SQLException

   java.lang.ArithmeticException
                                          checked exception
   java.lang.NullPointerException              many more classes …

   many more classes…
                                     Rajeev Gupta
                        103
Without Error Handling – Example 1


           class NoErrorHandling{
                  public static void main(String[] args){
                          int a,b;
                          a = 7;
                          b = 0;
Program does not reach here
                            System.out.println(“Result is “ + a/b);
                            System.out.println(“Program reached this line”);
                  }
           }
                No compilation errors. While running it reports an error and stops without
                executing further statements:
     104        java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
                                                       Rajeev Gupta
Without Error Handling – Example 2


      class WithErrorHandling{
             public static void main(String[] args){
                     int a,b;
                     a = 7; b = 0;
                     if (b != 0){
                              System.out.println(“Result is “ + a/b);
                     }
Program reaches here
                     else{
                              System.out.println(“ B is zero);
                     }
                     System.out.println(“Program is complete”);
             }
      }
   105                                   Rajeev Gupta
Exceptions and their Handling

    When the JVM encounters an error such as divide by
     zero, it creates an exception object and throws it – as
     a notification that an error has occurred.

    If the exception object is not caught and handled
     properly, the interpreter will display an error and
     terminate the program.

    If we want the program to continue with execution
     of the remaining code, then we should try to catch
     the exception object thrown by the error condition
     and then take appropriate corrective actions. This
     task is known as exception handling.

    106                             Rajeev Gupta
Common Java Exceptions
    ArithmeticException
    ArrayIndexOutOfBoundException
    ArrayStoreException
    FileNotFoundException
    IOException – general I/O failure
    NullPointerException – referencing a null object
    OutOfMemoryException
    SecurityException – when applet tries to perform an action
     not allowed by the browser’s security setting.
    StackOverflowException
    StringIndexOutOfBoundException


    107                                Rajeev Gupta
Exceptions in Java
    A method can signal an error condition by throwing an
     exception – throws
    The calling method can transfer control to a exception
     handler by catching an exception - try, catch
    Clean up can be done by - finally




    108                              Rajeev Gupta
With Exception Handling -
   Example 3

         class WithExceptionHandling{
                public static void main(String[] args){
                        int a,b; float r;
                        a = 7; b = 0;
                        try{
                            r = a/b;
                            System.out.println(“Result is “ + r);
Program Reaches here
                        }
                        catch(ArithmeticException e){
                                System.out.println(“ B is zero);
                        }
                        System.out.println(“Program reached this line”);
                }
     109                                   Rajeev Gupta
         }
Multiple Catch Statements
    If a try block is likely to raise more than one type of exceptions, then multiple catch
     blocks can be defined as follows:
     …
     …
     try {
          // statements
     }
     catch( Exception-Type1 e)
     {
          // statements to process exception 1
     }
     ..
     ..
     catch( Exception-TypeN e)
     {
          // statements to process exception N
     }
     …



    110                                               Rajeev Gupta
finally block
    Java supports definition of another block called finally that be used to handle any
     exception that is not caught by any of the previous statements. It may be added
     immediately after the try block or after the last catch block:
     …
     try {
          // statements
     }
     catch( Exception-Type1 e)
     {
          // statements to process exception 1
     }
     ..
     ..
     finally {
        ….
     }
    When a finally is defined, it is executed regardless of whether or not an exception
     is thrown. Therefore, it is also used to perform certain house keeping operations
     such as closing files and releasing system resources.

    111                                               Rajeev Gupta
Catching and Propagating
Exceptions
    Exceptions raised in try block can be caught and then
     they can be thrown again/propagated after performing
     some operations. This can be done by using the keyword
     “throw” as follows:
         throw exception-object;
         OR
         throw new Throwable_Subclass;




    112                                   Rajeev Gupta
With Exception Handling -
   Example 4

        class WithExceptionCatchThrow{
                public static void main(String[] args){
                        int a,b; float r; a = 7; b = 0;
                        try{
                            r = a/b;
                            System.out.println(“Result is “ + r);
                        }
 Program Does Not
     reach here
                        catch(ArithmeticException e){
when exception occurs           System.out.println(“ B is zero);
                                throw e;
                        }
                        System.out.println(“Program is complete”);
                }
    113                                      Rajeev Gupta
        }
With Exception Handling -
   Example 5
       class WithExceptionCatchThrowFinally{
                public static void main(String[] args){
                         int a,b; float r; a = 7; b = 0;
                         try{
                              r = a/b;
                              System.out.println(“Result is “ + r);
                         }
Program reaches here catch(ArithmeticException e){
                                    System.out.println(“ B is zero);
                                    throw e;
                         }
                         finally{
                          System.out.println(“Program is complete”);
                         }
                }
       }
     114                                       Rajeev Gupta
User-Defined Exceptions
     Problem Statement :
         Consider the example of the Account class
         Account class had the following constructor


                    public Account (int id, double balance)
                    {
                                ....
                             ......
                      }



         How would we ensure that the initial balance is not
          negative?


    115                                           Rajeev Gupta
User-Defined Exceptions in
standard format
class MyException extends Exception
{
        MyException(String message)
        {
            super(message); // pass to superclass if parameter is not handled by used defined exception
        }
}
class TestMyException {
…
  try {
        ..
        throw new MyException(“This is error message”);
        }
        catch(MyException e)
        {
            System.out.println(“Message is: “+e.getMessage());
        }
    }
}
                                                Get Message is a method defined in a standard
                                                               Exception class.
    116                                                                       Rajeev Gupta
design by contract?
    Design by contract specifies the obligations of a calling-
     method and called-method to each other.
    Valuable technique to have well designed interface
    Help programmer clearly to think what a function does
     and what are pre and post condition that must satisfied.
    Java uses the assert statement to implement pre- and
     post-conditions.
    Java’s exceptions handling also support design by contract
    especially checked exceptions



    117                               Rajeev Gupta
    Preconditions
         Contract the calling-method must agree to.
         Conditions that must be true before a called method can execute.
         Preconditions involve the system state and the arguments passed into the method at the
          time of its invocation.
         If a precondition fails then there is a bug in the calling-method or calling software
          component.
    Post conditions
         contract the called-method agrees to.
         What must be true after a method completes successfully.
         Post conditions can be used with assertions in both public and non-public
          methods.
         The post conditions involve the old system state, the new system state, the method
          arguments and the method’s return value.
         If a post condition fails then there is a bug in the called-method or called
          software component.


    118                                                       Rajeev Gupta
Preconditions




119             Rajeev Gupta
Post condition




120              Rajeev Gupta
Class invariants

     what must be true about each instance of a class?
     A class invariant as an internal invariant that can specify the relationships among multiple
      attributes, and should be true before and after any method completes.
     If an invariant fails then there could be a bug in either calling-method or called-
      method.
     It is convenient to combine all the expressions required for checking invariants into a single
      internal method that can be called by assertions.
     For example if you have a class, which deals with negative integers then you define the
      isNegative() convenient internal method




121                                                         Rajeev Gupta
DAY-4




122           Rajeev Gupta
Session-1
    Char and byte oriented streams
    BufferedReader and BufferedWriter
    File handling
    Object Serialization
           [ObjectInputStream / ObjectOutputStream]




    123                            Rajeev Gupta
Stream
    Stream is an abstraction that either produces or
     consumes information.
    A stream is linked to a physical device by the Java I/O
     system.
    All streams behave in the same manner, even if the actual
     physical devices to which they are linked differ.
    2 types of streams:
         byte : for binray data
             All byte stream class are like XXXXXXXXStream
         character: for text data
             All char stream class are like XXXXXXXXReader/ XXXXXXWriter


    124                                        Rajeev Gupta
Classification of Java Stream
Classes



         Byte Stream     Character Stream
           classes            classes




125                    Rajeev Gupta
Some important classes form java.io




126                   Rajeev Gupta
System class in java
    System class defined in java.lang package
    It encapsulate many aspect of JRE

    System class also contain 3 predefine stream variables
         in
              System.in (InputStream)
         Out
              System.out(PrintStream)
         Err
              System.err(console)



    127                                  Rajeev Gupta
File
    File abstraction that                                FileReader
     represent file and
                                                            char[] in = new char[50]; // to store input
     directories                                            int size = 0;
                                                            FileReader fr =new FileReader(file);
         File f=new File("....");
         boolean flag= file.createNewFile();               size = fr.read(in); // read the whole file!

         boolean flag= file.mkDir();                       System.out.print(size + " "); // how many
                                                            bytes read
         boolean flag=file.exists();
    FileWriter                                             for(char c : in) // print the array
                                                                  System.out.print(c);
     File file = new File( "fileWrite2.txt");
     FileWriter fw =new FileWriter(file);                   fr.close(); // again, always close
     fw.write("howdynfolksn"); // write characters to
     fw.flush(); // flush before closing
     fw.close(); // close file when done




    128                                                     Rajeev Gupta
BufferedReader and BufferedWriter
    Reading form console
             BufferedReader br=new BufferedReader(new
              InputStreamReader(System.in));
    Reading form file
             BufferedReader br=new BufferedReader(new InputStreamReader(new
              File(“foo.txt”)));




    129                                        Rajeev Gupta
Serialization

    Storing the state of the object on a file along some
     metadata….so that it Can be recovered back………..
    Serialization used in RMI (Remote method invocation )
     while sending an object from one place to another in
     network…




    130                             Rajeev Gupta
What actually happens during
Serialization
    The state of the object from heap is sucked and written
     along with some meta data in an file….




    131                              Rajeev Gupta
De- Serialization
    When an object is de-serialized, the JVM attempts to
     bring object back to the life by making an new object on
     the heap that have the same state as original object
    Transient variable don’t get saved during serialization
     hence come with null !!!




    132                              Rajeev Gupta
Hello world Example…




133                    Rajeev Gupta
Session-2
    Multi-Threading
         Creating threads: using Thread class and Runnable interface
         Thread life cycle
         Using sleep(), join(), thread priorities
         Synchronization
         Solving producer and consumer problem using wait() and notify()
         Deadlock introduction
         Concurrency Utilities Overview
           Executor Framework, Semaphore, Latches




    134                                       Rajeev Gupta
What is threads? LWP




135                    Rajeev Gupta
Basic fundamentals

         Thread: class in java.lang
         thread: separate thread of execution

What happens during multithreading?
1. JVM calls main() method
2. main() starts a new thread. Main thread is tempory
   frozen while new thread start running so JVM switch
   between created thread and main thread till both
   complets


    136                                 Rajeev Gupta
Creating threads in
Java?
    Implements Runnable interface
    Extending Thread class……..

    Job and Worker analogy…




    137                              Rajeev Gupta
Thread life cycle…
    If a thread is blocked ( put to
     sleep) specified no of ms
     should expire
    If thread waiting for IO that
     must be over..
    If a thred calls wait() then
     another thread must call
     notify() or notifyAll()
    If an thred is suspended()
     some one must call resume()




    138                                Rajeev Gupta
Java.lang.Thread
    Thread()
             construct new thread
    void run()
             must be overriden
    void start()
             start thread call run method
    static void sleep(long ms)
             put currently executing thread to sleep for specified no of millisecond
    boolean isAlive()
             return true if thread is started but not expired
    void stop()
    void suspend() and void resume()
             Suspend thread execution….


    139                                                 Rajeev Gupta
Java.lang.Thread

    void join(long ms)
         Main thread Wait for specified thread to complete or till
          specified time is not over
    void join()
         Main thread Wait for specified thread to complete
    static boolean interrupted()
    boolean inInterrupted()
    void interrupt()
         Send interrupt request to a thread




    140                                        Rajeev Gupta
Creating Threads

    By extending Thread class
     class MyThread extends Thread
          {
                             public void run()
                                            {
                                            }
     }



    Implementing the Runnable interface
     class MyRunnable implements Runnable
          {
                             public void run()
                                            {
                                            }
     }




    141                                          Rajeev Gupta
package com;

class MyThread3 extends Thread
{
                public MyThread3() {
                                  super("Dmeo thread3");
                                  start();
                }
                public void run()
                {
                                  try
                                  {
                                                  for(int i=0;i<5;i++)
                                                  {
                                                                     System.out.println("Child thread:"+i);
                                                                     Thread.sleep(500);

                                                      }
                                    }
                                    catch(InterruptedException ex){}
                                    System.out.println("Main exited...");
                  }
}

public class DemoThreadExtendsThread {
                 public static void main(String[] args) {
                                    new MyThread3();
                                    try
                                    {
                                                      for(int i=0;i<5;i++)
                                                      {
                                                                         System.out.println("Main thread:"+i);
                                                                         Thread.sleep(500);
                                                      }
                                    }
                                    catch(InterruptedException ex){}
                                    System.out.println("Eixting main thread");
                 }

}


            142                                                                                      Rajeev Gupta
package com;
class MyThread implements Runnable
{
            Thread t;
            String name;
            public MyThread(String name) {
                         // TODO Auto-generated constructor stub
                         this.name=name;
                         t=new Thread(this,name);
            }
            public void run()
            {
                         for(int i=0;i<5;i++)
                         {
                                       System.out.println(Thread.currentThread().getName()+":"+i);
                                       try
                                       {
                                                   Thread.sleep(500);
                                       }
                                       catch(InterruptedException ex){}
                         }
            }
}
public class DemoThread2 {
            public static void main(String[] args) {
                         MyThread ot1=new MyThread("A");
                         MyThread ot2=new MyThread("B");
                         MyThread ot3=new MyThread("C");
                         ….
                         ….
}       143                                                          Rajeev Gupta
Understanding join( )




144                     Rajeev Gupta
Using isAlive() and join()
      package com;
      class MyThread implements Runnable
      {
                        Thread t;
                        String name;
                        public MyThread(String name) {
                                             // TODO Auto-generated constructor stub
                                             this.name=name;
                                             t=new Thread(this,name);
                        }
                        public void run()
                        {
                                             for(int i=0;i<5;i++)
                                             {
                                                                  System.out.println(Thread.currentThread().getName()+":"+i);
                                                                  try
                                                                  {
                                                                                      Thread.sleep(500);
                                                                  }
                                                                  catch(InterruptedException ex){}
                                             }
                        }
      }
      public class DemoThread2 {
                        public static void main(String[] args) {
                                             MyThread ot1=new MyThread("A");
                                             MyThread ot2=new MyThread("B");
                                             MyThread ot3=new MyThread("C");
                                             System.out.println("Status of thread1"+ot1.t.isAlive());
                                             System.out.println("Status of thread1"+ot2.t.isAlive());
                                             System.out.println("Status of thread1"+ot3.t.isAlive());
                                             try
                                             {
                                                                  Thread.sleep(1000);
                                             }
                                             catch(InterruptedException ex){}

                                             //applying join

                                             try
                                             {
                                                                  ot1.t.join();
                                                                  ot2.t.join();
                                                                  ot3.t.join();
                                             }
                                             catch(InterruptedException ex){}
                                             System.out.println("Main exit");

                         }
    145
      }                                                                                            Rajeev Gupta
Checking thread priorities




 146                         Rajeev Gupta
Understanding thread synchronization




147                  Rajeev Gupta
Synchronization
   Synchronization
       Mechanism to controls the order in which threads
        execute
       Competition vs. cooperative synchronization
   Mutual exclusion of threads
       Each synchronized method or statement is guarded by
        an object.
       When entering a synchronized method or statement,
        the object will be locked until the method is finished.
       When the object is locked by another thread, the
        current thread must wait.

                                      Rajeev Gupta   148
Thread Synchronization example bank account
problem


   Example --- bank accounts
    Public class Account {
      private long balance;
      public boolean withdraw(long amount) {
          if (amount <= balance) {
              long newBalance = balance – amount;
              balance = newBalance;
              return true;
          } else {
              return false;
          }
      }
      // other methods and fields
    }



• What might happen in the presence of multiple threads?

    149                                             Rajeev Gupta
Example (Cont.)                                    if (amount <= balance) {
                                                      long newBalance = balance – amount;
                                                      balance = newBalance;
                                                      return true;
                                                   }
    Possible scenario
      Assume that the initial balance is $1,000,000, and two withdraw
      requests of $1,000,000 are made almost simultaneously.


      time balance      withdraw 1              withdraw 2

      t1   1,000,000   amount<=balance
      t2   1,000,000                           amount<=balance
      t3   1,000,000   newbalance=...;
      t4   1,000,000                           newbalance=...;
      t5   0           balance=...;
      t6   0                                   balance=...;
      t7   0           return true;
      t8   0                                   return true;

    150                                         Rajeev Gupta
Example
 public class Account {
   private long balance;
   public synchronized boolean withdraw(long amount) {
       if (amount <= balance) {
           long newBalance = balance – amount;
           balance = newBalance;
           return true;
       } else {
           return false;
       }
   }
   // other methods and fields
 }




                                          Rajeev Gupta   151
Exercise
 Make withdraw method synchronized by using the
 synchronized statement.
 public class Account {
   private long balance;
   public boolean withdraw(long amount) {
     // WRITE YOUR CODE HERE…

         if (amount <= balance) {
             long newBalance = balance – amount;
             balance = newBalance;
             return true;
         } else {
             return false;
         }

     }
 }
                                             Rajeev Gupta   152
Using thread synchronization




153              Rajeev Gupta
Inter thread communication
    Java have elegant Interprocess communication using wait()
     notify() and notifyAll() methods
    All these method defined final in the Object class
    Can be only called from a synchronized context




    154                              Rajeev Gupta
wait() and notify(), notifyAll()

    wait()
         Tells the calling thread to give up the monitor and go to the
          sleep until some other thread enter the same monitor and
          call notify()


    notify()
         Wakes up the first thread that called wait() on same object
    notifyAll()
         Wakes up all the thread that called wait() on same object,
          highest priority thread is going to run first


    155                                     Rajeev Gupta
Incorrect implementation of produce
consumer …
class Q
                                          class Producer implements Runnable
{
                                          {
          int n;
          synchronized int get()
                                              Q q;
          {                                   public Producer(Q q) {
                                                       this.q=q;
          System.out.println("got:"+n);                new Thread(this,"Producer").start();
                        return n;
                                              }
          }
                                              public void run()
          synchronized void put(int n)
          {
                                              {
                        this.n=n;                      int i=0;
                                                       while(true)
          System.out.println("Put:"+n);                q.put(i++);
          }
                                              }
}
                                          }




    156                                          Rajeev Gupta
Incorrect implementation of produce consumer …


public class PandC {
public static void main(String[] args) {
   Q q=new Q();
   new Producer(q);
   new Consumer(q);
   System.out.println("ctrol C for exit");
}
}




  157                                        Rajeev Gupta
Correction needed in Queue class…
class Q
{
          int n;
          boolean valueSet=false;
          synchronized int get()
          {
                        if(!valueSet)
                                         try
                                         {
                                                     wait();
                                         }
                         catch(InterruptedException ex){}
                         System.out.println("got:"+n);
                         valueSet=false;
                         notify();
                         return n;
          }
          synchronized void put(int n)
          {
                        if(valueSet)
                                         try
                                         {
                                                     wait();
                                        }
                         catch(InterruptedException ex){}
                         this.n=n;
                         valueSet=true;
                         System.out.println("Put:"+n);
  158                                                          Rajeev Gupta
                         notify();
DAY-5




159           Rajeev Gupta
Session-1
    Session-1
         Object class in Java
         Collections Framework
         List, Map, Set usages introduction
         Usages
             ArrayList, LinkedList, HashMap, TreeMap, HashSet
         Comparable, Comparator interface implementation
         User define key in HashMap




    160                                           Rajeev Gupta
Object
    Object is an special class in java defined in java.lang
    Every class automatically inherit this class whether we say
     it or not…




    Why Java has provided this class?

    161                               Rajeev Gupta
Method defined in Object class…
   String toString()
   boolean equals()
   int hashCode()
   clone()
   void finalize()
   getClass()
   Method that can’t be overridden
         final void notify()
         final void notifyAll()
         final void wait()


    162                               Rajeev Gupta
toString( )
    If we don’t overriding
     toString() method of Object
     class it print Object ID no by
     default
    Override it to print some
     useful information….




    163                               Rajeev Gupta
toString()




164          Rajeev Gupta
equals
    What O/P do you expect in this
     case……




    O/P would be two employees are
     not equals.... ???
    Problem is that using == java
     compare object id of two object
     and that can never be equals, so we
     are getting meaningless result…
    165                               Rajeev Gupta
Overriding equals()
    Don’t forget DRY run…..




    166                        Rajeev Gupta
hashCode()
   Whenever you override equals()for an type don’t forget
    to override hashCode() method…
   hashCode() make DS efficient
   What hashCode does
       HashCode divide data into buckets
       Equals search data from that bucket…




    167                                   Rajeev Gupta
clone()
    Lets consider an object that creation is very complicated, what we can do
     we can make an clone of that object and use that
    Costly , avoid using cloning if possible, internally depends on serialization
    Must make class supporting cloning by implementing an marker interface ie
     Cloneable




    168                                          Rajeev Gupta
finalize()
    As you are aware ..Java don’t support destructor
    Programmer is free from memory management 
    Memory mgt is done by an component of JVM ie called
     Garbage collector GC
    GC runs as low priority thread..
    We can override finalize() to request java “Please run this
     code before recycling this object”
    Cleanup code can be written
    Not reliable, better not to use…

    Demo programm
         WAP to count total number of employee object in the memory at any moment of time if an object is nullified then reduce count….


    169                                                                                       Rajeev Gupta
Java collection
    Java collections can be considered aka readymade data
     structure, we should know how to use it….



    collection
         Name of topic
    Collection
         Base interface
    Collections
         Static utility class provide various useful algorith


    170                                        Rajeev Gupta
collection
    Collection
         Why it is called an framework?
         Readymade Data structure in Java…




    171                                       Rajeev Gupta
172   Rajeev Gupta
ArrayList: aka growable array…




173                  Rajeev Gupta
ArrayList of user defined object




174                     Rajeev Gupta
Comparable and Comparator interface
    We need to teach Java how to sort user define object
    Comparable and Comparator interface help us to tell java
     how to sort user define object….




    175                             Rajeev Gupta
Implementing Comparable




176                 Rajeev Gupta
Comparator
    Don’t need to change Employee class 




    177                            Rajeev Gupta
Useful stuff




178            Rajeev Gupta
Useful examples…




179                Rajeev Gupta
Useful examples…




180                Rajeev Gupta
LinkedList : AKA Doubly Link list………..
can move back and forth.......




 181                               Rajeev Gupta
Useful examples…




182                Rajeev Gupta
fundamental diff bw ArrayList and
LinkedList
    ArrayLists manage arrays internally.
          [0][1][2][3][4][5] ....
    List<Integer> arrayList = new ArrayList<Integer>();

     LinkedLists consists of elements where each element has
     a reference to the previous and next element
                 [0]->[1]->[2] ....
                   <- <-




    183                              Rajeev Gupta
ArrayList vs LinkedList
    Java implements ArrayList as array internally
         Hence good to provide starting size
             i.e. List<String> s=new ArrayList<String>(20); is better then
              List<String> s=new ArrayList<String>(20);
    Removing element from starting of arraylist is very slow?
         list.remove(0);
         if u remove first element, java internally copy all the element
          (shift by one)

         Adding element at middle in ArrayList is very inefficient…



    184                                             Rajeev Gupta
Performance ArrayList vs LinkedList !!!




185                    Rajeev Gupta
HashMap
    Key ---->Value
    declaring an hashmap
             HashMap<Integer, String> map = new HashMap<Integer, String>();
    populating values
              map.put(5, "Five");
              map.put(8, "Eight");
              map.put(6, "Six");
              map.put(4, "Four");
              map.put(2, "Two");
    getting value
          String text = map.get(6);
         System.out.println(text);

    186                                          Rajeev Gupta
Looping through HashMap
for(Integer key: map.keySet())
   {
           String value = map.get(key);


           System.out.println(key + ": " + value);
       }




 187                                                 Rajeev Gupta
   LinkedHashMap
       aka dll
       key and value are in same order in which u hv inserted.......


   TreeMap
       sort keys in natural order(what is natural order?)
       for int
           1,2,3..........
       for string
           "a","b".............
       For user define key
           Define sorting order using Comparable /Comparator
 188                                         Rajeev Gupta
set
    Don’t allow duplicate element




    189                              Rajeev Gupta
Assignment




190          Rajeev Gupta
User define key in HashMap
    If you are using user define key in hashmap don’t forget to
     override hashcode for that class… otherwise you may
     not find that content again…

    Demo




    191                               Rajeev Gupta
HashMap vs Hashtable
    Hashtable is threadsafe, slow as compared to HashMap
    Better to use HashMap

    Some more intresting difference
         Hashtable give runtime exception if key is “null” while
          HashMap don’t




    192                                      Rajeev Gupta
Session-2

    Java 5 Language Features II
         Generics
         Annotations




    193                            Rajeev Gupta
Generics
    Before Java 1.5
         List list=new ArrayList();
             Can add anything in that list
             Problem while retrieving


    Now Java 1.5 onward
         List<String> list=new ArrayList<String>();
          list.add(“foo”);//ok
          list.add(22);// compile time error

         Generics provide type safety
         Generics is compile time phenomena…
    194                                       Rajeev Gupta
Issues with Generics
    Try not to mix non Generics code and Generics code…we
     can have strange behaviour.




    195                            Rajeev Gupta
Polymorphic behaviour




196                     Rajeev Gupta
<? extends XXXXXX>




197                  Rajeev Gupta
<? Super XXXXX>




198               Rajeev Gupta
Generic class




199             Rajeev Gupta
Generic method




200              Rajeev Gupta
Annotation
    @ magic !!!
    Annotations in Java is all about adding meta-data facility to the Java
     Elements.

    Like Classes, Interfaces or Enums, Annotations define a type in Java and they
     can be applied to several Java Elements.

    Tools which will read and interpret the Annotations will implement a lot of
     functionalities from the meta-information obtained.

    For example, they can ensure the consistency between classes, can check
     the validity of the paramters passed by the clients at run-time and can
     generate lot of base code for a project.


    201                                           Rajeev Gupta
Built-in Annotations in Java
    There are some pre-defined annotations available in the
     Java Programming language. They are,
         Override
         Deprecated
         SuppressWarnings


    Demo user define annotation and its need…




    202                              Rajeev Gupta
References:-
    Head first java
    SCJP katthy
    Google
         Stackoverflow.com
         …..
         …..




    203                       Rajeev Gupta

Más contenido relacionado

La actualidad más candente

Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVAHome
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIwhite paper
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming languagemasud33bd
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat SheetGlowTouch
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateAnton Keks
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Sagar Verma
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsAnton Keks
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick GuideAnton Shchastnyi
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 
Java session02
Java session02Java session02
Java session02Niit Care
 
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Arun Kumar
 
8 most expected java interview questions
8 most expected java interview questions8 most expected java interview questions
8 most expected java interview questionsPoonam Kherde
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Kernel Training
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Rittercatherinewall
 

La actualidad más candente (17)

Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVA
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming language
 
Core java1
Core java1Core java1
Core java1
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick Guide
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
Java session02
Java session02Java session02
Java session02
 
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
 
8 most expected java interview questions
8 most expected java interview questions8 most expected java interview questions
8 most expected java interview questions
 
Introducing Java 7
Introducing Java 7Introducing Java 7
Introducing Java 7
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 

Destacado

Call by value
Call by valueCall by value
Call by valueDharani G
 
Microservices Architecture: Labs
Microservices Architecture: LabsMicroservices Architecture: Labs
Microservices Architecture: Labsgjuljo
 
Workshop MSF4J - Getting Started with Microservices and Java
Workshop MSF4J - Getting Started with Microservices and JavaWorkshop MSF4J - Getting Started with Microservices and Java
Workshop MSF4J - Getting Started with Microservices and JavaEdgar Silva
 
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"SE2016 Java Valerii Moisieienko "Apache HBase Workshop"
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"Inhacking
 
Container Days - AWS Microservice Workshop
Container Days - AWS Microservice WorkshopContainer Days - AWS Microservice Workshop
Container Days - AWS Microservice WorkshopTara Walker
 
HATEOAS 101 - Opinionated Introduction to a REST API Style
HATEOAS 101 - Opinionated Introduction to a REST API StyleHATEOAS 101 - Opinionated Introduction to a REST API Style
HATEOAS 101 - Opinionated Introduction to a REST API StyleApigee | Google Cloud
 

Destacado (7)

Java 7
Java 7Java 7
Java 7
 
Call by value
Call by valueCall by value
Call by value
 
Microservices Architecture: Labs
Microservices Architecture: LabsMicroservices Architecture: Labs
Microservices Architecture: Labs
 
Workshop MSF4J - Getting Started with Microservices and Java
Workshop MSF4J - Getting Started with Microservices and JavaWorkshop MSF4J - Getting Started with Microservices and Java
Workshop MSF4J - Getting Started with Microservices and Java
 
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"SE2016 Java Valerii Moisieienko "Apache HBase Workshop"
SE2016 Java Valerii Moisieienko "Apache HBase Workshop"
 
Container Days - AWS Microservice Workshop
Container Days - AWS Microservice WorkshopContainer Days - AWS Microservice Workshop
Container Days - AWS Microservice Workshop
 
HATEOAS 101 - Opinionated Introduction to a REST API Style
HATEOAS 101 - Opinionated Introduction to a REST API StyleHATEOAS 101 - Opinionated Introduction to a REST API Style
HATEOAS 101 - Opinionated Introduction to a REST API Style
 

Similar a Core java 5 days workshop stuff

Java 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaJava 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaManjula Kollipara
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & RailsPeter Lind
 
Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Arun Gupta
 
JRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMJRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMRaimonds Simanovskis
 
Powering the Next Generation Services with Java Platform - Spark IT 2010
Powering the Next Generation Services with Java Platform - Spark IT 2010Powering the Next Generation Services with Java Platform - Spark IT 2010
Powering the Next Generation Services with Java Platform - Spark IT 2010Arun Gupta
 
Why JRuby? - RubyConf 2012
Why JRuby? - RubyConf 2012Why JRuby? - RubyConf 2012
Why JRuby? - RubyConf 2012Charles Nutter
 
Scotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloScotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloJulian Arocena
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby.toster
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxMurugesh33
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxMurugesh33
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoopSeo Gyansha
 
Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel Fomitescu
 

Similar a Core java 5 days workshop stuff (20)

Java 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaJava 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kollipara
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & Rails
 
Java J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus ChecklistJava J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus Checklist
 
Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011
 
Javamschn3
Javamschn3Javamschn3
Javamschn3
 
JRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMJRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVM
 
Powering the Next Generation Services with Java Platform - Spark IT 2010
Powering the Next Generation Services with Java Platform - Spark IT 2010Powering the Next Generation Services with Java Platform - Spark IT 2010
Powering the Next Generation Services with Java Platform - Spark IT 2010
 
Complete java
Complete javaComplete java
Complete java
 
Why JRuby? - RubyConf 2012
Why JRuby? - RubyConf 2012Why JRuby? - RubyConf 2012
Why JRuby? - RubyConf 2012
 
Java J2EE Training in Chennai, Tambaram
Java J2EE  Training in Chennai, TambaramJava J2EE  Training in Chennai, Tambaram
Java J2EE Training in Chennai, Tambaram
 
Scotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloScotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao Pablo
 
Jvm fundamentals
Jvm fundamentalsJvm fundamentals
Jvm fundamentals
 
Struts2
Struts2Struts2
Struts2
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby
 
Practical JRuby
Practical JRubyPractical JRuby
Practical JRuby
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016Manuel - SPR - Intro to Java Language_2016
Manuel - SPR - Intro to Java Language_2016
 

Más de Rajiv Gupta

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepRajiv Gupta
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with javaRajiv Gupta
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentalsRajiv Gupta
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2Rajiv Gupta
 
Weblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastWeblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastRajiv Gupta
 
Lab work servlets and jsp
Lab work servlets and jspLab work servlets and jsp
Lab work servlets and jspRajiv Gupta
 
Spring aop with aspect j
Spring aop with aspect jSpring aop with aspect j
Spring aop with aspect jRajiv Gupta
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injectionRajiv Gupta
 
Java spring framework
Java spring frameworkJava spring framework
Java spring frameworkRajiv Gupta
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jRajiv Gupta
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notesRajiv Gupta
 

Más de Rajiv Gupta (16)

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by step
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentals
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Weblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastWeblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencast
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
 
Lab work servlets and jsp
Lab work servlets and jspLab work servlets and jsp
Lab work servlets and jsp
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Spring aop with aspect j
Spring aop with aspect jSpring aop with aspect j
Spring aop with aspect j
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injection
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Jsp Notes
Jsp NotesJsp Notes
Jsp Notes
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4j
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 

Último

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 

Último (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

Core java 5 days workshop stuff

  • 1. Core Java Rajeev Gupta MTech CS 1 Rajeev Gupta
  • 2. Contents at a glance  Java An Introduction  Basic Java Constructs and Data Types and array  OO Introduction  Class object and related topics  Inheritance  Final ,Abstract Classes and interface  String class, immutability, inner classes  Exceptions Handling, assertions  Streams and Input/output Files, serialization  Java Thread  Java Collections 2 Rajeev Gupta
  • 3. Day-1 Session-1 ------------- Session-2  Introduction to Java -------------  What is Java,Why Java?  Object Oriented  JDK,JRE and JVM discussion  Object, class, Encapsulation,  Installing JDK, editPlus, eclipse 3.6  Abstraction,  Hello World application  Inheritence,  Procedural Programming  Polymorphism,message passing  If..else,switch, looping ( concepts only, implementation on day 2)  Array  Examples 3 Rajeev Gupta
  • 4. Day-2 Session-1 Session-2 ------------- ------------- Inheritance Class and objects Type of inheritance, diamond problem InstanceOf operator Creating Classes Final Implementing Methods Final variable, final method , final class Object: state, identity and behaviour Acess control: public, private,protected and default Constructors: default, parameterized and copy Packages Instance variable, static variable and local variable Abstract class Interface Initialization block Polymorphism Static method and applications Overloading Packages and visibility modifier: public, Overriding protected, private and default Type of relationship bw objects IS-A, HAS-A, USE-A Rajeev Gupta 4
  • 5. Day-3 Session-1 ------------- Session-2 String class: Immutability and usages, ------------- stringbuilder and stringbuffer Exception handling Wrapper classes and usages Try, catch, throw, throws, Java 5 Language Features (I): finally Checked and AutoBoxing and Unboxing, Enhanced For loop, Varargs, Static Import, Unchecked exception Enums User defind exceptions design by contract- assertions Inner classes Regular inner class, method local inner class, annonymous inner class 5 Rajeev Gupta
  • 6. Day-4 Session-1 Session-2 ------------- ------------- IO Multi-Threading Char and byte oriented streams Creating threads: using Thread class and Runnable interface BufferedReader and BufferedWriter Thread life cycle File handling Using sleep(), join(), thread priorities Object Serialization and IO Synchronization [ObjectInputStream / ObjectOutputStream] Solving producer and consumer problem using wait() and notify() Deadlock introduction Concurrency Utilities Overview Executor Framework, Semaphore, Latches 6 Rajeev Gupta
  • 7. Day-5 Session-1 Session-2 ------------- ------------- Collections Framework Java 5 Language Features II List, Map, Set usages introduction Generics Usages ArrayList, LinkedList, HashMap, Annotations TreeMap, HashSet Comparable, Comparator interface implementation Case study using collection, File User define key in HashMap  MCQ Exam  7 Rajeev Gupta
  • 8. DAY-1 8 Rajeev Gupta
  • 9. Session-1  Introduction to Java  What is Java,Why Java?  JDK,JRE and JVM discussion  Installing JDK, editPlus, eclipse 3.6  Hello World application  Procedural Programming  If..else,switch, looping  Array  Examples  9 Rajeev Gupta
  • 10. What is Java?  Java is not only an oo programming language It can be best described as OOPS+JVM+API 10 Rajeev Gupta
  • 11. How Sun define Java?  Simple and Powerful  Object Oriented  Portable  Architecture Neutral  Distributed  Multi-threaded  Robust, Secure/Safe  Interpreted  High Performance  Dynamic programming language/platform. 11 Rajeev Gupta
  • 12. Versions  JDK 1.0 (1995)  JDK 1.1 (1997)  J2SE 1.2 (1998) ) Playground  J2SE 1.3 (2000)  Kestrel Called Java2  J2SE 1.4 (2002)  Merlin  J2SE 5.0 (2004)  Tiger  Java SE 6 ( 2006)  Mustang Version for the session  Java SE 7 (2011) Dolphin 12 Java 6 Rajeev Gupta
  • 13. Java 1.0 Java 1.1 Java 1.2 Java 1.3 Java 1.4 Java 1.5 8 packages 23 packages 59 packages 77 packages 103 packages 131 packages 212 classes 504 classes 1520 classes 1595 classes 2175 classes 2656 classes New Events JFC/Swing JNDI Regular Exp javax.activity, Logging javax. Inner class Drag and Java Sound Assertions management Drop NIO Object Timer Serialization Java2D java.nio, javax.imageio, Jar Files CORBA javax.net, javax.print, javax.security, org.w3c International Reflection javax.naming, javax.sound, javax.transaction JDBC RMI javax.accessibility, javax.swing, org.omg java.math, java.rmi, java.security, java.sql, java.text, java.beans java.applet, java.awt, java.io, java.lang, java.net, java.util
  • 14. Some common buzzwords  JDK  Java development kit, developer need it  Byte Code  Highly optimize instruction set, designed to run on JVM  Platform independent  JRE  Java Runtime environment, Create an instance JVM, must be there on deployment machine.  Platform dependent  JVM  Java Virtual Machine JVM  Pick byte code and execute on client machine  Platform dependent… 14 Rajeev Gupta
  • 15. Understanding JVM 15 Rajeev Gupta
  • 16. Installing JDK, editPlus, eclipse 3.6  Follow me for configuration and running Java hello world!!! 16 Rajeev Gupta
  • 17. Analysis of Hello World !!! 17 Rajeev Gupta
  • 18. Java Program Structure Documentation Section Package Statement Import Statements Interface Statements Class Declarations Main Method Class { } 18 Rajeev Gupta
  • 19. Java Data Type  2 type  Primitive data type  Reference data type (latter) 19 Rajeev Gupta
  • 20. Primitive data type:  boolean either true of false  char 16 bit Unicode 1.1  byte 8-bit integer (signed)  short 16-bit integer (signed)  int 32-bit integer (signed)  long 64-bit integer (singed)  float 32-bit floating point (IEEE 754-1985)  double 64-bit floating point (IEEE 754-1985) Java uses Unicode to represent characters internally 20 Rajeev Gupta
  • 21. Procedural Programming  if..else  switch  Looping; for, while, do..while as usual in Java as in C/C++  Don’t mug the program/logic  Follow dry run approach  Try some programms:  Create  Factorial program  Prime No check  Date calculation 21 Rajeev Gupta
  • 22. Array  One Dimensional array  int x[]=new int[5] 22 Rajeev Gupta
  • 23. Session-2  Object Oriented ( concepts only)  Object, class  Basic principles of OO  Encapsulation  Abstraction  modularity  Inheritance/ Hierarchy  Polymorphism, message passing 23 Rajeev Gupta
  • 24. So what is object orientation? 24 Rajeev Gupta
  • 25. What is an Object? 25 Rajeev Gupta
  • 26. What is an class? 26 Rajeev Gupta
  • 27. What is the relationship bw class and objects? 27 Rajeev Gupta
  • 28. Basic principles of OO 28 Rajeev Gupta
  • 29. What is abstraction? 29 Rajeev Gupta
  • 31. What is modularity? 31 Rajeev Gupta
  • 32. What is Hierarchy? 32 Rajeev Gupta
  • 33. A bit about UML diagram…  UML 2.0 aka modeling language has 12 type of diagrams  Most important once are class diagram, use case diagram and sequence diagram.  You should know how to read it correctly  This is not UML session…  33 Rajeev Gupta
  • 34. DAY-2 34 Rajeev Gupta
  • 35. Session-1  Class and objects  Creating Classes and object  Object: state, identity and behaviour  Constructors: default, parameterized and copy  Need of “this” , Constructor chaining  Instance variable, static variable and local variable  Initialization block  Scanner and printf  Parameter passing in Java  Call by value / call by reference… 35 Rajeev Gupta
  • 36. What can goes inside an class? 36 Rajeev Gupta
  • 37. Creating Classes and object 37 Rajeev Gupta
  • 38. Correct way? 38 Rajeev Gupta
  • 39. Constructors: default, parameterized and copy  Initialize state of the object  Special method have same name as that of class  Can’t return anything  Can only be called once for an object  Can be private  Can’t be static*  Can overloaded but cant overridden*  Can be  Default, parameterized and copy constructor 39 Rajeev Gupta
  • 40. Need of this?  Which id assigned to which id?  “this” is an reference to the current object required to differentiate local variables with instance variables  Refer next slide… 40 Rajeev Gupta
  • 41. 41 Rajeev Gupta
  • 42. this : Constructor chaining?  Calling one constructor from another ? 42 Rajeev Gupta
  • 43. Static method/variable  Instance variable –per object while static variable are per class  Initialize and define before any objects  Most suitable for counter for object  Static method can only access static data of the class  For calling static method we don’t need an object of that class Now guess why main was static? 43 Rajeev Gupta
  • 44. Using static data.. 44 Rajeev Gupta
  • 45. Initialization block  We can put repeated constructor code in an Initialization block…  Static Initialization block runs before any constructor and runs only once… 45 Rajeev Gupta
  • 46. Initialization block 46 Rajeev Gupta
  • 47. Packages  Packages are Java’s way of grouping a number of related classes and/or interfaces together into a single unit. That means, packages act as “containers” for classes.  The benefits of organising classes into packages are:  The classes contained in the packages of other programs/applications can be reused.  In packages classes can be unique compared with classes in other packages. That two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name.  Classes in packages can be hidden if we don’t want other packages to access them.  Packages also provide a way for separating “design” from coding. 47 Rajeev Gupta
  • 48. Java Foundation Packages  Java provides a large number of classes groped into different packages based on their functionality.  The six foundation Java packages are:  java.lang  Contains classes for primitive types, strings, math functions, threads, and exception  java.util  Contains classes such as vectors, hash tables, date etc.  java.io  Stream classes for I/O  java.awt  Classes for implementing GUI – windows, buttons, menus etc.  java.net  Classes for networking  java.applet  Classes for creating and implementing applets 48 Rajeev Gupta
  • 49. Accessing Classes from Packages  There are two ways of accessing the classes stored in packages:  Using fully qualified class name  java.lang.Math.sqrt(x);  Import package and use class name directly.  import java.lang.Math  Math.sqrt(x);  Selected or all classes in packages can be imported: import package.class; import package.*;  Implicit in all programs: import java.lang.*;  package statement(s) must appear first 49 Rajeev Gupta
  • 50. Visibility Modifiers  For instance variable and methods  Public  Protected  Default (package level)  Private  For classes  Public and default 50 Rajeev Gupta
  • 51. Visibility Modifiers  class A has default visibility hence can access in the same package only.  Make class A public, then access it.  Protected data can access in the same package and all the subclasses in other packages provide class itsef is public 51 Rajeev Gupta
  • 52. Visibility Modifiers Accessible to: public protected Package private (default) Same Class Yes Yes Yes Yes Class in package Yes Yes Yes No Subclass in Yes Yes No No different package Non-subclass Yes No No No different package 52 Rajeev Gupta
  • 53. Packages and Name Clashing  When packages are developed by different organizations, it is possible that multiple packages will have classes with the same name, leading to name classing. package pack1; package pack2; class Teacher class Student class Student class Courses  We can import and use these packages like:  import pack1.*;  import pack2.*;  Student student1; // Generates compilation error 53 Rajeev Gupta
  • 54. Want to accept parameter from user? java.util.Scanner (Java 1.5) Scanner stdin = Scanner.create(System.in); int n = stdin.nextInt(); String s = stdin.next(); boolean b = stdin.hasNextInt()
  • 55. Missing powerful printf of C programming?  System.out.printf( “format-string” [, arg1, arg2, … ] );
  • 56. Call by value & call by reference  Java don’t support call by reference.  When you pass an object in an method copy of reference is passed so that we can mutate the state of the object but can’t delete original object itself 56 Rajeev Gupta
  • 57. Session-2  Inheritance  Type of inheritance, diamond problem  InstanceOf operator  Final  Final variable, final method , final class  Acess control: public, private,protected and default  Packages  Abstract class  Interface  Polymorphism  Overloading  Overriding 57 Rajeev Gupta
  • 58. Inheritance  Inheritance is the inclusion of behaviour (i.e. methods) and state (i.e. variables) of a base class in a derived class so that they are accessible in that derived class.  code reusability.  Subclass and Super class concept 58 Rajeev Gupta
  • 59. Diamond Problem?  Hierarchy inheritance can leds to poor design.. Java don’t support it directly… ( Possible using interface ) 59 Rajeev Gupta
  • 60. Inheritance example  Use extends keyword  Use super to pass values to base class constructor. 60 Rajeev Gupta
  • 61. Overloading  Overloading deals with multiple methods in the same class with the same name but different method signatures.  Both the above methods have the same method names but different method signatures, which mean the methods are overloaded.  Overloading lets you define the same operation in different ways for different data. Constructor can be overloaded Be careful of overloading ambiguity *Overloading in case of var-arg and Wrapper objects… 61 Rajeev Gupta
  • 62. Overriding…  Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.  Both the above methods have the same method names and the signatures but the method in the subclass MyClass overrides the method in the superclass BaseClass  Overriding lets you define the same operation in different ways for different object types. 62 Rajeev Gupta
  • 63. Polymorphism  Polymorphism=many forms of one things  Substitutability  Overriding  Polymorphism means the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. 63 Rajeev Gupta
  • 64. Polymorphism  Every animal sound but differently…  We want to have Pointer of Animal class assigned by object of derived class 64 Rajeev Gupta
  • 65. Example… 65 Rajeev Gupta
  • 66. Need of abstract class?  Sound( ) method of Animal class don’t make any sense …i.e. it don’t have semantically valid definition  Method sound( ) in Animal class should be abstract means incomplete  Using abstract method Derivatives of Animal class forced to provide meaningful sound() method 66 Rajeev Gupta
  • 67. Abstract class  If an class have at least one abstract method it should be declare abstract class.  Some time if we want to stop a programmer to create object of some class…  Class has some default functionality that can be used as it is.  Can implement only one abstract class  67 Rajeev Gupta
  • 68. Abstract class use cases…  Want to have some default functionality from base class and class have some abstract functionality that cant be define at that moment.  Don’t want to allow a programmer to create object of an class as it is too generic  Interface vs. abstract class 68 Rajeev Gupta
  • 69. More example… 69 Rajeev Gupta
  • 70. Final  Its final: i.e. cant be change!!!  final  Final method arguments  Cant be change inside the method  Final variable  Become constant, once assigned then cant be changed  Final method  Cant overridden  Final class  Cant inherited  Can be reuse Some examples…. 70 Rajeev Gupta
  • 71. Final class  Final class cant be subclass ie cant be extended  No method of this class can be overridden  Ex: String class in Java…  Real question is in what situation somebody should declare a class final 71 Rajeev Gupta
  • 72. Final Method  Final Method Can’t overridden  Class containing final method can be extended  Killing substitutability 72 Rajeev Gupta
  • 73. Interface?  Interface : contract bw two parties  Interface method  Only declaration, no method definition  No method implementation please !  Interface variable  Public static and final constant  Its how java support global constant  Break the hierarchy  Solve diamond problem  Callback in Java* Some Example …. 73 Rajeev Gupta
  • 74. Interface?  Rules  All interface methods are always public and abstract, whether we say it or not.  Variable declared inside interface are always public static and final  Interface method can’t be static or final  Interface cant have constructor  An interface can extends other interface  Can be used polymorphically  An class implementing an interface must implement all of its method otherwise it need to declare abstract class… 74 Rajeev Gupta
  • 76. Note  Following interface constant declaration are identical  int i=90;  public static int i=90;  public int i=90;  Public static int i=90;  Public static final int i=90;  Following interface method declaration don’t compile  final void bounce();  static void bounce();  private void bounce();  protected void bounce(); 76 Rajeev Gupta
  • 77. You must be clear up to this… 77 Rajeev Gupta
  • 78. Type of relationship bw objects  USE-A  HAS-A  IS-A (Most costly ? ) ALWAYS GO FOR LOOSE COUPLING AND HIGH COHESION… But HOW? 78 Rajeev Gupta
  • 79. IS-A VS HAS-A 79 Rajeev Gupta
  • 80. Self Reading ..will discuss latter..  Implementation inheritance (Already done)  Interface inheritance with composition(Google it) 80 Rajeev Gupta
  • 81. Just for fun!!! 81 Rajeev Gupta
  • 82. DAY-3 82 Rajeev Gupta
  • 83. Session-1  String class  Immutability and usages,  stringbuilder and stringbuffer  Wrapper classes and usages  Java 5 Language Features (I):  AutoBoxing and Unboxing  Enhanced For loop  Varargs  Static Import  Enums  Inner classes  Regular inner class  method local inner class  anonymous inner class 83 Rajeev Gupta
  • 84. String  Immutable i.e. once assigned then cant be changed  Only class in java for which object can be created with or without using new operator Ex: String s=“india”; String s1=new String(“india”); What is the difference?  String concatenation can be in two ways:  String s1=s+”paki”; Operator overloading  String s3=s1.concat(“paki”); 84 Rajeev Gupta
  • 85. Some common string methods…  charAt()  Returns the character located at the specified index  concat()  Appends one String to the end of another ( "+" also works)  equalsIgnoreCase()  Determines the equality of two Strings, ignoring case  length()  Returns the number of characters in a String  replace()  Replaces occurrences of a character with a new character  substring()  Returns a part of a String  toLowerCase()  Returns a String with uppercase characters converted  toString()  Returns the value of a String  toUpperCase()  Returns a String with lowercase characters converted  trim()  Removes whitespace from the ends of a String 85 Rajeev Gupta
  • 86. String comparison  Two string should never be checked for equality using == operator WHY?  Always use equals( ) method…. String s1=“india”; String s2=“paki”; if(s1.equals(s2)) ….. ….. 86 Rajeev Gupta
  • 87. Immutability  Immutability means something that cannot be changed.  Strings are immutable in Java. What does this mean?  String literals are very heavily used in applications and they also occupy a lot of memory.  Therefore for efficient memory management, all the strings are created and kept by the JVM in a place called string pool (which is part of Method Area).  Garbage collector does not come into string pool.  How does this save memory? 87 Rajeev Gupta
  • 88. Wrapper classes  Helps treating primitive data as an object  But why we should convert primitive to objects?  We can’t store primitive in java collections  Object have properties and methods  Have different behavior when passing as method argument  Eight wrapper for eight primitive  Integer, Float, Double, Character, Boolean etc… Integer it=new Integer(33); int temp=it.intValue(); …. 88 Rajeev Gupta
  • 89. Boxing / Unboxing Java 1.5  Boxing ----------- Integer iWrapper = 10; Prior to J2SE 5.0, we use Integer a = new Integer(10);  Unboxing ------------- int iPrimitive = iWrapper; Prior to J2SE 5.0, we use int b = iWrapper.intValue(); 89 Rajeev Gupta
  • 90. Java 5 Language Features (I)  AutoBoxing and Unboxing  Enhanced For loop  Varargs  Static Import  Enums 90 Rajeev Gupta
  • 91. Enhanced For loop  Provide easy looping construct to loop through array and collections 91 Rajeev Gupta
  • 92. Varargs  Java start supporting variable argument method in Java 1.5  Discuss function overloading in case of Varargs and wrapper classes 92 Rajeev Gupta
  • 93. Static Import  Handy feature in Java 1.5 that allow something like this: import static java.lang.Math.PI; import static java.lang.Math.cos;  Now rather then using  double r = Math.cos(Math.PI * theta);  We can use something like  double r = cos(PI * theta); – looks more readable ….  Avoid abusing static import like  import static java.lang.Math.*; General guidelines to use static java import:  1) Use it to declare local copies of java constants  2) When you require frequent access to static members from one or two java classes 93 Rajeev Gupta
  • 94. Enums  Enum is a special type of classes.  enum type used to put restriction on the instance values 94 Rajeev Gupta
  • 95. Inner classes  A class define inside another  Why to define it? 95 Rajeev Gupta
  • 96. top level inner class 96 Rajeev Gupta
  • 97. Method local inner class  Class define inside an method  Can not access local data define inside method  Declare local data static to access it 97 Rajeev Gupta
  • 98. Anonymous Inner class interface Cookable { void cook(); } class Food { Cookable c=new Cookable() { @Override public void cook() { System.out.print("cooked ..."); } }; } 98 Rajeev Gupta
  • 99. Session-2  Exception handling  Try, catch, throw, throws, finally  Checked and Unchecked exception  User defined exceptions  assertions 99 Rajeev Gupta
  • 100. What is Exception? An exception is an abnormal condition that arises while running a program. Examples:  Attempt to divide an integer by zero causes an exception to be thrown at run time.  Attempt to call a method using a reference that is null.  Attempting to open a nonexistent file for reading.  JVM running out of memory.  Exception handling do not correct abnormal condition rather it make our program robust i.e. make us enable to take remedial action when exception occurs…Help in recovering… 100 Rajeev Gupta
  • 101. Type of exceptions  RuntimeEx: Unchecked Exception  CompiletimeEx: Checked  Error: Should not to be handled by programmer..like JVM crash  all problem happens at run time in programming and also in real life.....  for checked ex, we need to tell java we know about those problems for example readLine() throws IOException 101 Rajeev Gupta
  • 102. Exception Hierarchy java.lang.Throwable Our focus! java.lang.Exception java.lang.Error checked java.lang.VirtualMachineError unchecked  Throwable class is super class for all exceptions in Java. When an exception occurs in a method, an object of Throwable type is thrown.  The 2 subclasses –Error and Exception 102 Rajeev Gupta
  • 103. java.lang.Error java.lang.Exception unchecked exception unchecked exception java.lang.RuntimeException java.io.IOException java.sql.SQLException java.lang.ArithmeticException checked exception java.lang.NullPointerException many more classes … many more classes… Rajeev Gupta 103
  • 104. Without Error Handling – Example 1 class NoErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; Program does not reach here System.out.println(“Result is “ + a/b); System.out.println(“Program reached this line”); } } No compilation errors. While running it reports an error and stops without executing further statements: 104 java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10) Rajeev Gupta
  • 105. Without Error Handling – Example 2 class WithErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; if (b != 0){ System.out.println(“Result is “ + a/b); } Program reaches here else{ System.out.println(“ B is zero); } System.out.println(“Program is complete”); } } 105 Rajeev Gupta
  • 106. Exceptions and their Handling  When the JVM encounters an error such as divide by zero, it creates an exception object and throws it – as a notification that an error has occurred.  If the exception object is not caught and handled properly, the interpreter will display an error and terminate the program.  If we want the program to continue with execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then take appropriate corrective actions. This task is known as exception handling. 106 Rajeev Gupta
  • 107. Common Java Exceptions  ArithmeticException  ArrayIndexOutOfBoundException  ArrayStoreException  FileNotFoundException  IOException – general I/O failure  NullPointerException – referencing a null object  OutOfMemoryException  SecurityException – when applet tries to perform an action not allowed by the browser’s security setting.  StackOverflowException  StringIndexOutOfBoundException 107 Rajeev Gupta
  • 108. Exceptions in Java  A method can signal an error condition by throwing an exception – throws  The calling method can transfer control to a exception handler by catching an exception - try, catch  Clean up can be done by - finally 108 Rajeev Gupta
  • 109. With Exception Handling - Example 3 class WithExceptionHandling{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); Program Reaches here } catch(ArithmeticException e){ System.out.println(“ B is zero); } System.out.println(“Program reached this line”); } 109 Rajeev Gupta }
  • 110. Multiple Catch Statements  If a try block is likely to raise more than one type of exceptions, then multiple catch blocks can be defined as follows: … … try { // statements } catch( Exception-Type1 e) { // statements to process exception 1 } .. .. catch( Exception-TypeN e) { // statements to process exception N } … 110 Rajeev Gupta
  • 111. finally block  Java supports definition of another block called finally that be used to handle any exception that is not caught by any of the previous statements. It may be added immediately after the try block or after the last catch block: … try { // statements } catch( Exception-Type1 e) { // statements to process exception 1 } .. .. finally { …. }  When a finally is defined, it is executed regardless of whether or not an exception is thrown. Therefore, it is also used to perform certain house keeping operations such as closing files and releasing system resources. 111 Rajeev Gupta
  • 112. Catching and Propagating Exceptions  Exceptions raised in try block can be caught and then they can be thrown again/propagated after performing some operations. This can be done by using the keyword “throw” as follows:  throw exception-object;  OR  throw new Throwable_Subclass; 112 Rajeev Gupta
  • 113. With Exception Handling - Example 4 class WithExceptionCatchThrow{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } Program Does Not reach here catch(ArithmeticException e){ when exception occurs System.out.println(“ B is zero); throw e; } System.out.println(“Program is complete”); } 113 Rajeev Gupta }
  • 114. With Exception Handling - Example 5 class WithExceptionCatchThrowFinally{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } Program reaches here catch(ArithmeticException e){ System.out.println(“ B is zero); throw e; } finally{ System.out.println(“Program is complete”); } } } 114 Rajeev Gupta
  • 115. User-Defined Exceptions  Problem Statement :  Consider the example of the Account class  Account class had the following constructor public Account (int id, double balance) { .... ...... }  How would we ensure that the initial balance is not negative? 115 Rajeev Gupta
  • 116. User-Defined Exceptions in standard format class MyException extends Exception { MyException(String message) { super(message); // pass to superclass if parameter is not handled by used defined exception } } class TestMyException { … try { .. throw new MyException(“This is error message”); } catch(MyException e) { System.out.println(“Message is: “+e.getMessage()); } } } Get Message is a method defined in a standard Exception class. 116 Rajeev Gupta
  • 117. design by contract?  Design by contract specifies the obligations of a calling- method and called-method to each other.  Valuable technique to have well designed interface  Help programmer clearly to think what a function does and what are pre and post condition that must satisfied.  Java uses the assert statement to implement pre- and post-conditions.  Java’s exceptions handling also support design by contract  especially checked exceptions 117 Rajeev Gupta
  • 118. Preconditions  Contract the calling-method must agree to.  Conditions that must be true before a called method can execute.  Preconditions involve the system state and the arguments passed into the method at the time of its invocation.  If a precondition fails then there is a bug in the calling-method or calling software component.  Post conditions  contract the called-method agrees to.  What must be true after a method completes successfully.  Post conditions can be used with assertions in both public and non-public methods.  The post conditions involve the old system state, the new system state, the method arguments and the method’s return value.  If a post condition fails then there is a bug in the called-method or called software component. 118 Rajeev Gupta
  • 119. Preconditions 119 Rajeev Gupta
  • 120. Post condition 120 Rajeev Gupta
  • 121. Class invariants  what must be true about each instance of a class?  A class invariant as an internal invariant that can specify the relationships among multiple attributes, and should be true before and after any method completes.  If an invariant fails then there could be a bug in either calling-method or called- method.  It is convenient to combine all the expressions required for checking invariants into a single internal method that can be called by assertions.  For example if you have a class, which deals with negative integers then you define the isNegative() convenient internal method 121 Rajeev Gupta
  • 122. DAY-4 122 Rajeev Gupta
  • 123. Session-1  Char and byte oriented streams  BufferedReader and BufferedWriter  File handling  Object Serialization [ObjectInputStream / ObjectOutputStream] 123 Rajeev Gupta
  • 124. Stream  Stream is an abstraction that either produces or consumes information.  A stream is linked to a physical device by the Java I/O system.  All streams behave in the same manner, even if the actual physical devices to which they are linked differ.  2 types of streams:  byte : for binray data  All byte stream class are like XXXXXXXXStream  character: for text data  All char stream class are like XXXXXXXXReader/ XXXXXXWriter 124 Rajeev Gupta
  • 125. Classification of Java Stream Classes Byte Stream Character Stream classes classes 125 Rajeev Gupta
  • 126. Some important classes form java.io 126 Rajeev Gupta
  • 127. System class in java  System class defined in java.lang package  It encapsulate many aspect of JRE  System class also contain 3 predefine stream variables  in  System.in (InputStream)  Out  System.out(PrintStream)  Err  System.err(console) 127 Rajeev Gupta
  • 128. File  File abstraction that FileReader represent file and char[] in = new char[50]; // to store input directories int size = 0; FileReader fr =new FileReader(file);  File f=new File("....");  boolean flag= file.createNewFile(); size = fr.read(in); // read the whole file!  boolean flag= file.mkDir(); System.out.print(size + " "); // how many bytes read  boolean flag=file.exists();  FileWriter for(char c : in) // print the array System.out.print(c); File file = new File( "fileWrite2.txt"); FileWriter fw =new FileWriter(file); fr.close(); // again, always close fw.write("howdynfolksn"); // write characters to fw.flush(); // flush before closing fw.close(); // close file when done 128 Rajeev Gupta
  • 129. BufferedReader and BufferedWriter  Reading form console  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  Reading form file  BufferedReader br=new BufferedReader(new InputStreamReader(new File(“foo.txt”))); 129 Rajeev Gupta
  • 130. Serialization  Storing the state of the object on a file along some metadata….so that it Can be recovered back………..  Serialization used in RMI (Remote method invocation ) while sending an object from one place to another in network… 130 Rajeev Gupta
  • 131. What actually happens during Serialization  The state of the object from heap is sucked and written along with some meta data in an file…. 131 Rajeev Gupta
  • 132. De- Serialization  When an object is de-serialized, the JVM attempts to bring object back to the life by making an new object on the heap that have the same state as original object  Transient variable don’t get saved during serialization hence come with null !!! 132 Rajeev Gupta
  • 133. Hello world Example… 133 Rajeev Gupta
  • 134. Session-2  Multi-Threading  Creating threads: using Thread class and Runnable interface  Thread life cycle  Using sleep(), join(), thread priorities  Synchronization  Solving producer and consumer problem using wait() and notify()  Deadlock introduction  Concurrency Utilities Overview  Executor Framework, Semaphore, Latches 134 Rajeev Gupta
  • 135. What is threads? LWP 135 Rajeev Gupta
  • 136. Basic fundamentals  Thread: class in java.lang  thread: separate thread of execution What happens during multithreading? 1. JVM calls main() method 2. main() starts a new thread. Main thread is tempory frozen while new thread start running so JVM switch between created thread and main thread till both complets 136 Rajeev Gupta
  • 137. Creating threads in Java?  Implements Runnable interface  Extending Thread class……..  Job and Worker analogy… 137 Rajeev Gupta
  • 138. Thread life cycle…  If a thread is blocked ( put to sleep) specified no of ms should expire  If thread waiting for IO that must be over..  If a thred calls wait() then another thread must call notify() or notifyAll()  If an thred is suspended() some one must call resume() 138 Rajeev Gupta
  • 139. Java.lang.Thread  Thread()  construct new thread  void run()  must be overriden  void start()  start thread call run method  static void sleep(long ms)  put currently executing thread to sleep for specified no of millisecond  boolean isAlive()  return true if thread is started but not expired  void stop()  void suspend() and void resume()  Suspend thread execution…. 139 Rajeev Gupta
  • 140. Java.lang.Thread  void join(long ms)  Main thread Wait for specified thread to complete or till specified time is not over  void join()  Main thread Wait for specified thread to complete  static boolean interrupted()  boolean inInterrupted()  void interrupt()  Send interrupt request to a thread 140 Rajeev Gupta
  • 141. Creating Threads  By extending Thread class class MyThread extends Thread { public void run() { } }  Implementing the Runnable interface class MyRunnable implements Runnable { public void run() { } } 141 Rajeev Gupta
  • 142. package com; class MyThread3 extends Thread { public MyThread3() { super("Dmeo thread3"); start(); } public void run() { try { for(int i=0;i<5;i++) { System.out.println("Child thread:"+i); Thread.sleep(500); } } catch(InterruptedException ex){} System.out.println("Main exited..."); } } public class DemoThreadExtendsThread { public static void main(String[] args) { new MyThread3(); try { for(int i=0;i<5;i++) { System.out.println("Main thread:"+i); Thread.sleep(500); } } catch(InterruptedException ex){} System.out.println("Eixting main thread"); } } 142 Rajeev Gupta
  • 143. package com; class MyThread implements Runnable { Thread t; String name; public MyThread(String name) { // TODO Auto-generated constructor stub this.name=name; t=new Thread(this,name); } public void run() { for(int i=0;i<5;i++) { System.out.println(Thread.currentThread().getName()+":"+i); try { Thread.sleep(500); } catch(InterruptedException ex){} } } } public class DemoThread2 { public static void main(String[] args) { MyThread ot1=new MyThread("A"); MyThread ot2=new MyThread("B"); MyThread ot3=new MyThread("C"); …. …. } 143 Rajeev Gupta
  • 144. Understanding join( ) 144 Rajeev Gupta
  • 145. Using isAlive() and join() package com; class MyThread implements Runnable { Thread t; String name; public MyThread(String name) { // TODO Auto-generated constructor stub this.name=name; t=new Thread(this,name); } public void run() { for(int i=0;i<5;i++) { System.out.println(Thread.currentThread().getName()+":"+i); try { Thread.sleep(500); } catch(InterruptedException ex){} } } } public class DemoThread2 { public static void main(String[] args) { MyThread ot1=new MyThread("A"); MyThread ot2=new MyThread("B"); MyThread ot3=new MyThread("C"); System.out.println("Status of thread1"+ot1.t.isAlive()); System.out.println("Status of thread1"+ot2.t.isAlive()); System.out.println("Status of thread1"+ot3.t.isAlive()); try { Thread.sleep(1000); } catch(InterruptedException ex){} //applying join try { ot1.t.join(); ot2.t.join(); ot3.t.join(); } catch(InterruptedException ex){} System.out.println("Main exit"); } 145 } Rajeev Gupta
  • 146. Checking thread priorities 146 Rajeev Gupta
  • 148. Synchronization  Synchronization  Mechanism to controls the order in which threads execute  Competition vs. cooperative synchronization  Mutual exclusion of threads  Each synchronized method or statement is guarded by an object.  When entering a synchronized method or statement, the object will be locked until the method is finished.  When the object is locked by another thread, the current thread must wait. Rajeev Gupta 148
  • 149. Thread Synchronization example bank account problem  Example --- bank accounts Public class Account { private long balance; public boolean withdraw(long amount) { if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; } else { return false; } } // other methods and fields } • What might happen in the presence of multiple threads? 149 Rajeev Gupta
  • 150. Example (Cont.) if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; }  Possible scenario Assume that the initial balance is $1,000,000, and two withdraw requests of $1,000,000 are made almost simultaneously. time balance withdraw 1 withdraw 2 t1 1,000,000 amount<=balance t2 1,000,000 amount<=balance t3 1,000,000 newbalance=...; t4 1,000,000 newbalance=...; t5 0 balance=...; t6 0 balance=...; t7 0 return true; t8 0 return true; 150 Rajeev Gupta
  • 151. Example public class Account { private long balance; public synchronized boolean withdraw(long amount) { if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; } else { return false; } } // other methods and fields } Rajeev Gupta 151
  • 152. Exercise Make withdraw method synchronized by using the synchronized statement. public class Account { private long balance; public boolean withdraw(long amount) { // WRITE YOUR CODE HERE… if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; } else { return false; } } } Rajeev Gupta 152
  • 154. Inter thread communication  Java have elegant Interprocess communication using wait() notify() and notifyAll() methods  All these method defined final in the Object class  Can be only called from a synchronized context 154 Rajeev Gupta
  • 155. wait() and notify(), notifyAll()  wait()  Tells the calling thread to give up the monitor and go to the sleep until some other thread enter the same monitor and call notify()  notify()  Wakes up the first thread that called wait() on same object  notifyAll()  Wakes up all the thread that called wait() on same object, highest priority thread is going to run first 155 Rajeev Gupta
  • 156. Incorrect implementation of produce consumer … class Q class Producer implements Runnable { { int n; synchronized int get() Q q; { public Producer(Q q) { this.q=q; System.out.println("got:"+n); new Thread(this,"Producer").start(); return n; } } public void run() synchronized void put(int n) { { this.n=n; int i=0; while(true) System.out.println("Put:"+n); q.put(i++); } } } } 156 Rajeev Gupta
  • 157. Incorrect implementation of produce consumer … public class PandC { public static void main(String[] args) { Q q=new Q(); new Producer(q); new Consumer(q); System.out.println("ctrol C for exit"); } } 157 Rajeev Gupta
  • 158. Correction needed in Queue class… class Q { int n; boolean valueSet=false; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException ex){} System.out.println("got:"+n); valueSet=false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException ex){} this.n=n; valueSet=true; System.out.println("Put:"+n); 158 Rajeev Gupta notify();
  • 159. DAY-5 159 Rajeev Gupta
  • 160. Session-1  Session-1  Object class in Java  Collections Framework  List, Map, Set usages introduction  Usages  ArrayList, LinkedList, HashMap, TreeMap, HashSet  Comparable, Comparator interface implementation  User define key in HashMap 160 Rajeev Gupta
  • 161. Object  Object is an special class in java defined in java.lang  Every class automatically inherit this class whether we say it or not…  Why Java has provided this class? 161 Rajeev Gupta
  • 162. Method defined in Object class…  String toString()  boolean equals()  int hashCode()  clone()  void finalize()  getClass()  Method that can’t be overridden  final void notify()  final void notifyAll()  final void wait() 162 Rajeev Gupta
  • 163. toString( )  If we don’t overriding toString() method of Object class it print Object ID no by default  Override it to print some useful information…. 163 Rajeev Gupta
  • 164. toString() 164 Rajeev Gupta
  • 165. equals  What O/P do you expect in this case……  O/P would be two employees are not equals.... ???  Problem is that using == java compare object id of two object and that can never be equals, so we are getting meaningless result… 165 Rajeev Gupta
  • 166. Overriding equals()  Don’t forget DRY run….. 166 Rajeev Gupta
  • 167. hashCode()  Whenever you override equals()for an type don’t forget to override hashCode() method…  hashCode() make DS efficient  What hashCode does  HashCode divide data into buckets  Equals search data from that bucket… 167 Rajeev Gupta
  • 168. clone()  Lets consider an object that creation is very complicated, what we can do we can make an clone of that object and use that  Costly , avoid using cloning if possible, internally depends on serialization  Must make class supporting cloning by implementing an marker interface ie Cloneable 168 Rajeev Gupta
  • 169. finalize()  As you are aware ..Java don’t support destructor  Programmer is free from memory management   Memory mgt is done by an component of JVM ie called Garbage collector GC  GC runs as low priority thread..  We can override finalize() to request java “Please run this code before recycling this object”  Cleanup code can be written  Not reliable, better not to use…  Demo programm  WAP to count total number of employee object in the memory at any moment of time if an object is nullified then reduce count…. 169 Rajeev Gupta
  • 170. Java collection  Java collections can be considered aka readymade data structure, we should know how to use it….  collection  Name of topic  Collection  Base interface  Collections  Static utility class provide various useful algorith 170 Rajeev Gupta
  • 171. collection  Collection  Why it is called an framework?  Readymade Data structure in Java… 171 Rajeev Gupta
  • 172. 172 Rajeev Gupta
  • 173. ArrayList: aka growable array… 173 Rajeev Gupta
  • 174. ArrayList of user defined object 174 Rajeev Gupta
  • 175. Comparable and Comparator interface  We need to teach Java how to sort user define object  Comparable and Comparator interface help us to tell java how to sort user define object…. 175 Rajeev Gupta
  • 177. Comparator  Don’t need to change Employee class  177 Rajeev Gupta
  • 178. Useful stuff 178 Rajeev Gupta
  • 179. Useful examples… 179 Rajeev Gupta
  • 180. Useful examples… 180 Rajeev Gupta
  • 181. LinkedList : AKA Doubly Link list……….. can move back and forth....... 181 Rajeev Gupta
  • 182. Useful examples… 182 Rajeev Gupta
  • 183. fundamental diff bw ArrayList and LinkedList  ArrayLists manage arrays internally. [0][1][2][3][4][5] ....  List<Integer> arrayList = new ArrayList<Integer>();  LinkedLists consists of elements where each element has a reference to the previous and next element [0]->[1]->[2] .... <- <- 183 Rajeev Gupta
  • 184. ArrayList vs LinkedList  Java implements ArrayList as array internally  Hence good to provide starting size  i.e. List<String> s=new ArrayList<String>(20); is better then List<String> s=new ArrayList<String>(20);  Removing element from starting of arraylist is very slow?  list.remove(0);  if u remove first element, java internally copy all the element (shift by one)  Adding element at middle in ArrayList is very inefficient… 184 Rajeev Gupta
  • 185. Performance ArrayList vs LinkedList !!! 185 Rajeev Gupta
  • 186. HashMap  Key ---->Value  declaring an hashmap  HashMap<Integer, String> map = new HashMap<Integer, String>();  populating values map.put(5, "Five"); map.put(8, "Eight"); map.put(6, "Six"); map.put(4, "Four"); map.put(2, "Two");  getting value  String text = map.get(6);  System.out.println(text); 186 Rajeev Gupta
  • 187. Looping through HashMap for(Integer key: map.keySet()) { String value = map.get(key); System.out.println(key + ": " + value); } 187 Rajeev Gupta
  • 188. LinkedHashMap  aka dll  key and value are in same order in which u hv inserted.......  TreeMap  sort keys in natural order(what is natural order?)  for int  1,2,3..........  for string  "a","b".............  For user define key  Define sorting order using Comparable /Comparator  188 Rajeev Gupta
  • 189. set  Don’t allow duplicate element 189 Rajeev Gupta
  • 190. Assignment 190 Rajeev Gupta
  • 191. User define key in HashMap  If you are using user define key in hashmap don’t forget to override hashcode for that class… otherwise you may not find that content again…  Demo 191 Rajeev Gupta
  • 192. HashMap vs Hashtable  Hashtable is threadsafe, slow as compared to HashMap  Better to use HashMap  Some more intresting difference  Hashtable give runtime exception if key is “null” while HashMap don’t 192 Rajeev Gupta
  • 193. Session-2  Java 5 Language Features II  Generics  Annotations 193 Rajeev Gupta
  • 194. Generics  Before Java 1.5  List list=new ArrayList();  Can add anything in that list  Problem while retrieving  Now Java 1.5 onward  List<String> list=new ArrayList<String>(); list.add(“foo”);//ok list.add(22);// compile time error  Generics provide type safety  Generics is compile time phenomena… 194 Rajeev Gupta
  • 195. Issues with Generics  Try not to mix non Generics code and Generics code…we can have strange behaviour. 195 Rajeev Gupta
  • 196. Polymorphic behaviour 196 Rajeev Gupta
  • 197. <? extends XXXXXX> 197 Rajeev Gupta
  • 198. <? Super XXXXX> 198 Rajeev Gupta
  • 199. Generic class 199 Rajeev Gupta
  • 200. Generic method 200 Rajeev Gupta
  • 201. Annotation  @ magic !!!  Annotations in Java is all about adding meta-data facility to the Java Elements.  Like Classes, Interfaces or Enums, Annotations define a type in Java and they can be applied to several Java Elements.  Tools which will read and interpret the Annotations will implement a lot of functionalities from the meta-information obtained.  For example, they can ensure the consistency between classes, can check the validity of the paramters passed by the clients at run-time and can generate lot of base code for a project. 201 Rajeev Gupta
  • 202. Built-in Annotations in Java  There are some pre-defined annotations available in the Java Programming language. They are,  Override  Deprecated  SuppressWarnings  Demo user define annotation and its need… 202 Rajeev Gupta
  • 203. References:-  Head first java  SCJP katthy  Google  Stackoverflow.com  …..  ….. 203 Rajeev Gupta