SlideShare uma empresa Scribd logo
1 de 181
Core Java

   Rajeev Gupta
      MTech CS
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                                           rgupta.trainer@gmail.com
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, eclipse,javadoc                  Abstraction,
    Hello World application                          Inheritence,
    Procedural Programming                           Polymorphism,message passing
        If..else,switch, looping                 ( concepts only, implementation on day 2)
        Array

        Examples




 3                                     rgupta.trainer@gmail.com
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
    4                                          rgupta.trainer@gmail.com
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                                        rgupta.trainer@gmail.com
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                                  rgupta.trainer@gmail.com
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                                    rgupta.trainer@gmail.com
DAY-1




8           rgupta.trainer@gmail.com
Session-1
       Introduction to Java
           What is Java,Why Java?
           JDK,JRE and JVM discussion
           Installing JDK, eclipse,javadoc
       Hello World application
       Procedural Programming
           If..else,switch, looping
           Array
       Examples





    9                                  rgupta.trainer@gmail.com
What is Java?
    Java is not only an oo programming
      language



     It can be best described as


     OOPS+JVM+API


    10                         rgupta.trainer@gmail.com
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                               rgupta.trainer@gmail.com
Java Platform




12              rgupta.trainer@gmail.com
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




    13                        rgupta.trainer@gmail.com
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                                   rgupta.trainer@gmail.com
Understanding JVM




15             rgupta.trainer@gmail.com
Hello World
    Lab set-up
        Java 1.7
        Eclipse 4.2 ( eclipse juno)
        Java doc 1.7




    16                                 rgupta.trainer@gmail.com
Analysis of Hello World !!!




17                 rgupta.trainer@gmail.com
Java Program Structure

             Documentation Section


              Package Statement


               Import Statements


              Interface Statements


               Class Declarations

               Main Method Class
               {
               }


18                  rgupta.trainer@gmail.com
Java Data Type
    2 type
        Primitive data type
        Reference data type (latter)




    19                              rgupta.trainer@gmail.com
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                                  rgupta.trainer@gmail.com
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                           rgupta.trainer@gmail.com
Array
    One Dimensional array

        int x[]=new int[5]




    22                        rgupta.trainer@gmail.com
Session-2
    Object Oriented Concepts
         Object, class
    Basic principles of OO
        Encapsulation
        Abstraction
        modularity
        Inheritance/ Hierarchy
        Polymorphism, message passing




    23                           rgupta.trainer@gmail.com
So what is object orientation?




24                rgupta.trainer@gmail.com
What is an Object?




25               rgupta.trainer@gmail.com
What is an class?




26                  rgupta.trainer@gmail.com
What is the relationship bw class and
objects?




27                rgupta.trainer@gmail.com
Basic principles of OO




28                rgupta.trainer@gmail.com
What is abstraction?




29                rgupta.trainer@gmail.com
What is encapsulation?




30               rgupta.trainer@gmail.com
What is modularity?




31               rgupta.trainer@gmail.com
What is Hierarchy?




32               rgupta.trainer@gmail.com
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                                  rgupta.trainer@gmail.com
DAY-2




34           rgupta.trainer@gmail.com
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                                   rgupta.trainer@gmail.com
What can goes inside an class?




36                rgupta.trainer@gmail.com
Creating Classes and object




37                rgupta.trainer@gmail.com
Correct way?




38             rgupta.trainer@gmail.com
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                                   rgupta.trainer@gmail.com
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              rgupta.trainer@gmail.com
“this” used to resolve confusion…




41                rgupta.trainer@gmail.com
this : Constructor chaining?
    Calling one constructor
     from another ?




    42                         rgupta.trainer@gmail.com
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                                      rgupta.trainer@gmail.com
Using static data..




44                    rgupta.trainer@gmail.com
Initialization block
    We can put repeated
     constructor code in an
     Initialization block…

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




    45                         rgupta.trainer@gmail.com
Initialization block




46                     rgupta.trainer@gmail.com
Packages
   Packages are Java’s way of grouping a number of
    related classes and/or interfaces together
    into a single unit.
   Packages act as “containers” for classes.




    47                         rgupta.trainer@gmail.com
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                                           rgupta.trainer@gmail.com
Visibility Modifiers
    For instance variable and methods
        Public
        Protected
        Default (package level)
        Private
    For classes
        Public and default




    49                             rgupta.trainer@gmail.com
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




    50                                          rgupta.trainer@gmail.com
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




51                                rgupta.trainer@gmail.com
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()

 52                            rgupta.trainer@gmail.com
Call by value
    Java support call by value
    The value changes in function is not going to reflected in
     the main.




    53                         rgupta.trainer@gmail.com
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




    54                                       rgupta.trainer@gmail.com
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




    55                                        rgupta.trainer@gmail.com
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




    56                               rgupta.trainer@gmail.com
Diamond Problem?
    Hierarchy inheritance can leds to
     poor design..

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




    57                        rgupta.trainer@gmail.com
Inheritance example
    Use extends keyword

    Use super to pass values
     to base class
     constructor.




    58                          rgupta.trainer@gmail.com
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…

    59                                       rgupta.trainer@gmail.com
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.




    60                                   rgupta.trainer@gmail.com
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.




    61                         rgupta.trainer@gmail.com
Polymorphism
    Every animal sound but
     differently…
    We want to have Pointer of
     Animal class assigned by object
     of derived class




    62                        rgupta.trainer@gmail.com
Example…




63         rgupta.trainer@gmail.com
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



    64                               rgupta.trainer@gmail.com
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 



    65                                rgupta.trainer@gmail.com
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

    66                              rgupta.trainer@gmail.com
More example…




67              rgupta.trainer@gmail.com
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….
    68                                 rgupta.trainer@gmail.com
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




    69                                     rgupta.trainer@gmail.com
Final Method
    Final Method Can’t overridden
    Class containing final method can be extended
    Killing substitutability




    70                       rgupta.trainer@gmail.com
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 ….
 71                                     rgupta.trainer@gmail.com
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…


    72                              rgupta.trainer@gmail.com
Implementing an interface…




73               rgupta.trainer@gmail.com
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();

    74                                   rgupta.trainer@gmail.com
75   rgupta.trainer@gmail.com
Type of relationship bw objects
    USE-A
    HAS-A
    IS-A (Most costly ? )



ALWAYS GO FOR LOOSE COUPLING AND HIGH
 COHESION…

But HOW?


    76                       rgupta.trainer@gmail.com
IS-A   VS                         HAS-A




77     rgupta.trainer@gmail.com
Self Reading ..will discuss latter..
    Implementation inheritance (Already done)
    Interface inheritance with composition(Google it)




    78                     rgupta.trainer@gmail.com
Just for fun!!!




79                rgupta.trainer@gmail.com
DAY-3




80           rgupta.trainer@gmail.com
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


    81                                    rgupta.trainer@gmail.com
String
    Immutable i.e. once assigned then can’t 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”);



    82                                  rgupta.trainer@gmail.com
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



    83                                                      rgupta.trainer@gmail.com
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))
             …..
             …..




    84                        rgupta.trainer@gmail.com
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?



    85                                rgupta.trainer@gmail.com
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();
     ….

    86                             rgupta.trainer@gmail.com
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();

    87                                  rgupta.trainer@gmail.com
Java 5 Language Features (I)

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




    88                     rgupta.trainer@gmail.com
Enhanced For loop

    Provide easy looping construct to loop through array and
     collections




    89                        rgupta.trainer@gmail.com
Varargs

    Java start supporting variable argument method in Java 1.5




    Discuss function overloading in case of Varargs and
     wrapper classes

    90                        rgupta.trainer@gmail.com
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

    91                                         rgupta.trainer@gmail.com
Enums
    Enum is a special type of classes.
    enum type used to put restriction on the instance values




    92                        rgupta.trainer@gmail.com
Inner classes
    A class define inside another
        Why to define it?




    93                         rgupta.trainer@gmail.com
top level inner class
    Non static inner class object can't be createed without outer class instance
    All the private data of outer class is available to inner class
    Non static inner class can't have static members




    94                                rgupta.trainer@gmail.com
Method local inner class
    Class define inside an method
    Can not access local data define inside method
    Declare local data static to access it




    95                                        rgupta.trainer@gmail.com
Anonymous Inner class
    A way to implement polymorphism
    “On the fly”




    96                     rgupta.trainer@gmail.com
Session-2

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


    assertions




    97                            rgupta.trainer@gmail.com
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…

    98                              rgupta.trainer@gmail.com
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

    99                                  rgupta.trainer@gmail.com
Exception Hierarchy




100              rgupta.trainer@gmail.com
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.

    101                      rgupta.trainer@gmail.com
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


    102                         rgupta.trainer@gmail.com
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



    103                       rgupta.trainer@gmail.com
    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.


    104                                           rgupta.trainer@gmail.com
Preconditions




105             rgupta.trainer@gmail.com
Post condition




106              rgupta.trainer@gmail.com
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




107                                            rgupta.trainer@gmail.com
DAY-4




108           rgupta.trainer@gmail.com
Session-1
    Char and byte oriented streams
    BufferedReader and BufferedWriter
    File handling
    Object Serialization
           [ObjectInputStream / ObjectOutputStream]




    109                     rgupta.trainer@gmail.com
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


    110                                rgupta.trainer@gmail.com
111   rgupta.trainer@gmail.com
Some important classes form java.io




112               rgupta.trainer@gmail.com
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)



    113                                  rgupta.trainer@gmail.com
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”)));




    114                               rgupta.trainer@gmail.com
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




    115                                                   rgupta.trainer@gmail.com
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…




    116                      rgupta.trainer@gmail.com
What actually happens during
Serialization
    The state of the object from heap is sucked and written
     along with some meta data in an file….




    117                       rgupta.trainer@gmail.com
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 !!!




    118                       rgupta.trainer@gmail.com
Hello world Example…




119             rgupta.trainer@gmail.com
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




    120                               rgupta.trainer@gmail.com
What is threads? LWP




121             rgupta.trainer@gmail.com
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


    122                          rgupta.trainer@gmail.com
Creating threads in
Java?
    Implements Runnable interface
    Extending Thread class……..

    Job and Worker analogy…




    123                      rgupta.trainer@gmail.com
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()




    124                                rgupta.trainer@gmail.com
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….


    125                                       rgupta.trainer@gmail.com
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




    126                              rgupta.trainer@gmail.com
Creating Threads
    By extending Thread class




    Implementing the Runnable interface




    127                          rgupta.trainer@gmail.com
Understanding join( )




128               rgupta.trainer@gmail.com
Checking thread priorities




 129                         rgupta.trainer@gmail.com
Understanding thread synchronization




130              rgupta.trainer@gmail.com
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.

                              rgupta.trainer@gmail.com   131
Using thread synchronization




132           rgupta.trainer@gmail.com
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




    133                       rgupta.trainer@gmail.com
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


    134                             rgupta.trainer@gmail.com
Incorrect implementation of produce
consumer …




135              rgupta.trainer@gmail.com
Correct implementation of produce
consumer …




136              rgupta.trainer@gmail.com
DAY-5




137           rgupta.trainer@gmail.com
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




    138                                  rgupta.trainer@gmail.com
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?

    139                        rgupta.trainer@gmail.com
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()


    140                            rgupta.trainer@gmail.com
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….




    141                        rgupta.trainer@gmail.com
toString()




142          rgupta.trainer@gmail.com
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…
    143                       rgupta.trainer@gmail.com
Overriding equals()
    Don’t forget DRY run…..




    144                        rgupta.trainer@gmail.com
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…




    145                            rgupta.trainer@gmail.com
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




    146                                rgupta.trainer@gmail.com
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….


    147                                                                    rgupta.trainer@gmail.com
Java collection
    Java collections can be considered a kind of readymade
     data structure, we should only need to know how to use
     them and how they work….



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

    148                                rgupta.trainer@gmail.com
collection
    Collection
         Why it is called an framework?
         Readymade Data structure in Java…




    149                                       rgupta.trainer@gmail.com
150   rgupta.trainer@gmail.com
ArrayList: aka growable array…




151              rgupta.trainer@gmail.com
ArrayList of user defined object




152                rgupta.trainer@gmail.com
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….




    153                      rgupta.trainer@gmail.com
Implementing Comparable




154             rgupta.trainer@gmail.com
Comparator
    Don’t need to change Employee class 




    155                     rgupta.trainer@gmail.com
Useful stuff




156            rgupta.trainer@gmail.com
Useful examples…




157                rgupta.trainer@gmail.com
Useful examples…




158                rgupta.trainer@gmail.com
LinkedList : AKA Doubly Link list………..
can move back and forth.......




 159                        rgupta.trainer@gmail.com
Useful examples…




160                rgupta.trainer@gmail.com
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] ....
                   <- <-




    161                       rgupta.trainer@gmail.com
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>();
    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…



    162                                   rgupta.trainer@gmail.com
Performance ArrayList vs LinkedList !!!




163               rgupta.trainer@gmail.com
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);

    164                                 rgupta.trainer@gmail.com
Looping through HashMap
for(Integer key: map.keySet())
   {
           String value = map.get(key);


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




 165                                        rgupta.trainer@gmail.com
   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
 166                                rgupta.trainer@gmail.com
set
    Don’t allow duplicate element




    167                      rgupta.trainer@gmail.com
Assignment




168          rgupta.trainer@gmail.com
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




    169                        rgupta.trainer@gmail.com
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




    170                              rgupta.trainer@gmail.com
Session-2

    Java 5 Language Features II
         Generics
         Annotations




    171                       rgupta.trainer@gmail.com
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…
    172                                       rgupta.trainer@gmail.com
Issues with Generics
    Try not to mix non Generics code and Generics code…we
     can have strange behaviour.




    173                     rgupta.trainer@gmail.com
Polymorphic behaviour




174              rgupta.trainer@gmail.com
<? extends XXXXXX>




175            rgupta.trainer@gmail.com
<? Super XXXXX>




176               rgupta.trainer@gmail.com
Generic class




177             rgupta.trainer@gmail.com
Generic method




178              rgupta.trainer@gmail.com
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.


    179                                 rgupta.trainer@gmail.com
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…




    180                       rgupta.trainer@gmail.com
References:-
    Head first java
    SCJP katthy
    Google
         Stackoverflow.com
         …..
         …..




    181                       rgupta.trainer@gmail.com

Mais conteúdo relacionado

Mais procurados

Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming languagemasud33bd
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVAHome
 
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 session02
Java session02Java session02
Java session02Niit Care
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 
8 most expected java interview questions
8 most expected java interview questions8 most expected java interview questions
8 most expected java interview questionsPoonam Kherde
 
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
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
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
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: IntroductionAnton Keks
 

Mais procurados (18)

Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming language
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVA
 
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
 
1
11
1
 
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 session02
Java session02Java session02
Java session02
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
8 most expected java interview questions
8 most expected java interview questions8 most expected java interview questions
8 most expected java interview questions
 
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
 
Introducing Java 7
Introducing Java 7Introducing Java 7
Introducing Java 7
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
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
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
 

Semelhante a Core Java Guide for Beginners

Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuffRajiv Gupta
 
Java 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaJava 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaManjula Kollipara
 
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
 
Scotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloScotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloJulian Arocena
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)Shaharyar khan
 
Course schedule of oop, Course schedule of java, object oriented programming,...
Course schedule of oop, Course schedule of java, object oriented programming,...Course schedule of oop, Course schedule of java, object oriented programming,...
Course schedule of oop, Course schedule of java, object oriented programming,...Kuntal Bhowmick
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & RailsPeter Lind
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoopSeo Gyansha
 
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
 
Course schedule of java, object oriented programming
Course schedule of java, object oriented programmingCourse schedule of java, object oriented programming
Course schedule of java, object oriented programmingKuntal Bhowmick
 

Semelhante a Core Java Guide for Beginners (20)

Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuff
 
Java J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus ChecklistJava J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus Checklist
 
Javamschn3
Javamschn3Javamschn3
Javamschn3
 
Java 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kolliparaJava 7 Dolphin manjula kollipara
Java 7 Dolphin manjula kollipara
 
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
 
Jvm fundamentals
Jvm fundamentalsJvm fundamentals
Jvm fundamentals
 
Scotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao PabloScotas - Oracle Open World Sao Pablo
Scotas - Oracle Open World Sao Pablo
 
Complete java
Complete javaComplete java
Complete java
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
Course schedule of oop, Course schedule of java, object oriented programming,...
Course schedule of oop, Course schedule of java, object oriented programming,...Course schedule of oop, Course schedule of java, object oriented programming,...
Course schedule of oop, Course schedule of java, object oriented programming,...
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & Rails
 
Java se7 features
Java se7 featuresJava se7 features
Java se7 features
 
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
 
Java solution
Java solutionJava solution
Java solution
 
JAVA Training in Bangalore
JAVA Training in BangaloreJAVA Training in Bangalore
JAVA Training in Bangalore
 
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
 
Course schedule of java, object oriented programming
Course schedule of java, object oriented programmingCourse schedule of java, object oriented programming
Course schedule of java, object oriented programming
 

Mais 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
 

Mais de Rajiv Gupta (17)

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
 
Struts2
Struts2Struts2
Struts2
 
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

Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 

Último (20)

Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 

Core Java Guide for Beginners

  • 1. Core Java Rajeev Gupta MTech CS
  • 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 rgupta.trainer@gmail.com
  • 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, eclipse,javadoc  Abstraction,  Hello World application  Inheritence,  Procedural Programming  Polymorphism,message passing  If..else,switch, looping ( concepts only, implementation on day 2)  Array  Examples 3 rgupta.trainer@gmail.com
  • 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 4 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 8. DAY-1 8 rgupta.trainer@gmail.com
  • 9. Session-1  Introduction to Java  What is Java,Why Java?  JDK,JRE and JVM discussion  Installing JDK, eclipse,javadoc  Hello World application  Procedural Programming  If..else,switch, looping  Array  Examples  9 rgupta.trainer@gmail.com
  • 10. What is Java?  Java is not only an oo programming language It can be best described as OOPS+JVM+API 10 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 12. Java Platform 12 rgupta.trainer@gmail.com
  • 13. 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 13 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 15. Understanding JVM 15 rgupta.trainer@gmail.com
  • 16. Hello World  Lab set-up  Java 1.7  Eclipse 4.2 ( eclipse juno)  Java doc 1.7 16 rgupta.trainer@gmail.com
  • 17. Analysis of Hello World !!! 17 rgupta.trainer@gmail.com
  • 18. Java Program Structure Documentation Section Package Statement Import Statements Interface Statements Class Declarations Main Method Class { } 18 rgupta.trainer@gmail.com
  • 19. Java Data Type  2 type  Primitive data type  Reference data type (latter) 19 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 22. Array  One Dimensional array  int x[]=new int[5] 22 rgupta.trainer@gmail.com
  • 23. Session-2  Object Oriented Concepts  Object, class  Basic principles of OO  Encapsulation  Abstraction  modularity  Inheritance/ Hierarchy  Polymorphism, message passing 23 rgupta.trainer@gmail.com
  • 24. So what is object orientation? 24 rgupta.trainer@gmail.com
  • 25. What is an Object? 25 rgupta.trainer@gmail.com
  • 26. What is an class? 26 rgupta.trainer@gmail.com
  • 27. What is the relationship bw class and objects? 27 rgupta.trainer@gmail.com
  • 28. Basic principles of OO 28 rgupta.trainer@gmail.com
  • 29. What is abstraction? 29 rgupta.trainer@gmail.com
  • 30. What is encapsulation? 30 rgupta.trainer@gmail.com
  • 31. What is modularity? 31 rgupta.trainer@gmail.com
  • 32. What is Hierarchy? 32 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 34. DAY-2 34 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 36. What can goes inside an class? 36 rgupta.trainer@gmail.com
  • 37. Creating Classes and object 37 rgupta.trainer@gmail.com
  • 38. Correct way? 38 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 41. “this” used to resolve confusion… 41 rgupta.trainer@gmail.com
  • 42. this : Constructor chaining?  Calling one constructor from another ? 42 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 44. Using static data.. 44 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 46. Initialization block 46 rgupta.trainer@gmail.com
  • 47. Packages  Packages are Java’s way of grouping a number of related classes and/or interfaces together into a single unit.  Packages act as “containers” for classes. 47 rgupta.trainer@gmail.com
  • 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 rgupta.trainer@gmail.com
  • 49. Visibility Modifiers  For instance variable and methods  Public  Protected  Default (package level)  Private  For classes  Public and default 49 rgupta.trainer@gmail.com
  • 50. 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 50 rgupta.trainer@gmail.com
  • 51. 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 51 rgupta.trainer@gmail.com
  • 52. 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() 52 rgupta.trainer@gmail.com
  • 53. Call by value  Java support call by value  The value changes in function is not going to reflected in the main. 53 rgupta.trainer@gmail.com
  • 54. 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 54 rgupta.trainer@gmail.com
  • 55. 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 55 rgupta.trainer@gmail.com
  • 56. 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 56 rgupta.trainer@gmail.com
  • 57. Diamond Problem?  Hierarchy inheritance can leds to poor design.. Java don’t support it directly… ( Possible using interface ) 57 rgupta.trainer@gmail.com
  • 58. Inheritance example  Use extends keyword  Use super to pass values to base class constructor. 58 rgupta.trainer@gmail.com
  • 59. 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… 59 rgupta.trainer@gmail.com
  • 60. 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. 60 rgupta.trainer@gmail.com
  • 61. 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. 61 rgupta.trainer@gmail.com
  • 62. Polymorphism  Every animal sound but differently…  We want to have Pointer of Animal class assigned by object of derived class 62 rgupta.trainer@gmail.com
  • 63. Example… 63 rgupta.trainer@gmail.com
  • 64. 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 64 rgupta.trainer@gmail.com
  • 65. 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  65 rgupta.trainer@gmail.com
  • 66. 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 66 rgupta.trainer@gmail.com
  • 67. More example… 67 rgupta.trainer@gmail.com
  • 68. 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…. 68 rgupta.trainer@gmail.com
  • 69. 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 69 rgupta.trainer@gmail.com
  • 70. Final Method  Final Method Can’t overridden  Class containing final method can be extended  Killing substitutability 70 rgupta.trainer@gmail.com
  • 71. 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 …. 71 rgupta.trainer@gmail.com
  • 72. 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… 72 rgupta.trainer@gmail.com
  • 73. Implementing an interface… 73 rgupta.trainer@gmail.com
  • 74. 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(); 74 rgupta.trainer@gmail.com
  • 75. 75 rgupta.trainer@gmail.com
  • 76. Type of relationship bw objects  USE-A  HAS-A  IS-A (Most costly ? ) ALWAYS GO FOR LOOSE COUPLING AND HIGH COHESION… But HOW? 76 rgupta.trainer@gmail.com
  • 77. IS-A VS HAS-A 77 rgupta.trainer@gmail.com
  • 78. Self Reading ..will discuss latter..  Implementation inheritance (Already done)  Interface inheritance with composition(Google it) 78 rgupta.trainer@gmail.com
  • 79. Just for fun!!! 79 rgupta.trainer@gmail.com
  • 80. DAY-3 80 rgupta.trainer@gmail.com
  • 81. 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 81 rgupta.trainer@gmail.com
  • 82. String  Immutable i.e. once assigned then can’t 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”); 82 rgupta.trainer@gmail.com
  • 83. 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 83 rgupta.trainer@gmail.com
  • 84. 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)) ….. ….. 84 rgupta.trainer@gmail.com
  • 85. 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? 85 rgupta.trainer@gmail.com
  • 86. 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(); …. 86 rgupta.trainer@gmail.com
  • 87. 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(); 87 rgupta.trainer@gmail.com
  • 88. Java 5 Language Features (I)  AutoBoxing and Unboxing  Enhanced For loop  Varargs  Static Import  Enums 88 rgupta.trainer@gmail.com
  • 89. Enhanced For loop  Provide easy looping construct to loop through array and collections 89 rgupta.trainer@gmail.com
  • 90. Varargs  Java start supporting variable argument method in Java 1.5  Discuss function overloading in case of Varargs and wrapper classes 90 rgupta.trainer@gmail.com
  • 91. 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 91 rgupta.trainer@gmail.com
  • 92. Enums  Enum is a special type of classes.  enum type used to put restriction on the instance values 92 rgupta.trainer@gmail.com
  • 93. Inner classes  A class define inside another  Why to define it? 93 rgupta.trainer@gmail.com
  • 94. top level inner class  Non static inner class object can't be createed without outer class instance  All the private data of outer class is available to inner class  Non static inner class can't have static members 94 rgupta.trainer@gmail.com
  • 95. Method local inner class  Class define inside an method  Can not access local data define inside method  Declare local data static to access it 95 rgupta.trainer@gmail.com
  • 96. Anonymous Inner class  A way to implement polymorphism  “On the fly” 96 rgupta.trainer@gmail.com
  • 97. Session-2  Exception handling  Try, catch, throw, throws, finally  Checked and Unchecked exception  User defined exceptions  assertions 97 rgupta.trainer@gmail.com
  • 98. 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… 98 rgupta.trainer@gmail.com
  • 99. 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 99 rgupta.trainer@gmail.com
  • 100. Exception Hierarchy 100 rgupta.trainer@gmail.com
  • 101. 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. 101 rgupta.trainer@gmail.com
  • 102. 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 102 rgupta.trainer@gmail.com
  • 103. 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 103 rgupta.trainer@gmail.com
  • 104. 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. 104 rgupta.trainer@gmail.com
  • 105. Preconditions 105 rgupta.trainer@gmail.com
  • 106. Post condition 106 rgupta.trainer@gmail.com
  • 107. 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 107 rgupta.trainer@gmail.com
  • 108. DAY-4 108 rgupta.trainer@gmail.com
  • 109. Session-1  Char and byte oriented streams  BufferedReader and BufferedWriter  File handling  Object Serialization [ObjectInputStream / ObjectOutputStream] 109 rgupta.trainer@gmail.com
  • 110. 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 110 rgupta.trainer@gmail.com
  • 111. 111 rgupta.trainer@gmail.com
  • 112. Some important classes form java.io 112 rgupta.trainer@gmail.com
  • 113. 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) 113 rgupta.trainer@gmail.com
  • 114. 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”))); 114 rgupta.trainer@gmail.com
  • 115. 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 115 rgupta.trainer@gmail.com
  • 116. 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… 116 rgupta.trainer@gmail.com
  • 117. What actually happens during Serialization  The state of the object from heap is sucked and written along with some meta data in an file…. 117 rgupta.trainer@gmail.com
  • 118. 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 !!! 118 rgupta.trainer@gmail.com
  • 119. Hello world Example… 119 rgupta.trainer@gmail.com
  • 120. 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 120 rgupta.trainer@gmail.com
  • 121. What is threads? LWP 121 rgupta.trainer@gmail.com
  • 122. 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 122 rgupta.trainer@gmail.com
  • 123. Creating threads in Java?  Implements Runnable interface  Extending Thread class……..  Job and Worker analogy… 123 rgupta.trainer@gmail.com
  • 124. 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() 124 rgupta.trainer@gmail.com
  • 125. 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…. 125 rgupta.trainer@gmail.com
  • 126. 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 126 rgupta.trainer@gmail.com
  • 127. Creating Threads  By extending Thread class  Implementing the Runnable interface 127 rgupta.trainer@gmail.com
  • 128. Understanding join( ) 128 rgupta.trainer@gmail.com
  • 129. Checking thread priorities 129 rgupta.trainer@gmail.com
  • 130. Understanding thread synchronization 130 rgupta.trainer@gmail.com
  • 131. 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. rgupta.trainer@gmail.com 131
  • 132. Using thread synchronization 132 rgupta.trainer@gmail.com
  • 133. 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 133 rgupta.trainer@gmail.com
  • 134. 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 134 rgupta.trainer@gmail.com
  • 135. Incorrect implementation of produce consumer … 135 rgupta.trainer@gmail.com
  • 136. Correct implementation of produce consumer … 136 rgupta.trainer@gmail.com
  • 137. DAY-5 137 rgupta.trainer@gmail.com
  • 138. 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 138 rgupta.trainer@gmail.com
  • 139. 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? 139 rgupta.trainer@gmail.com
  • 140. 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() 140 rgupta.trainer@gmail.com
  • 141. 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…. 141 rgupta.trainer@gmail.com
  • 142. toString() 142 rgupta.trainer@gmail.com
  • 143. 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… 143 rgupta.trainer@gmail.com
  • 144. Overriding equals()  Don’t forget DRY run….. 144 rgupta.trainer@gmail.com
  • 145. 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… 145 rgupta.trainer@gmail.com
  • 146. 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 146 rgupta.trainer@gmail.com
  • 147. 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…. 147 rgupta.trainer@gmail.com
  • 148. Java collection  Java collections can be considered a kind of readymade data structure, we should only need to know how to use them and how they work….  collection  Name of topic  Collection  Base interface  Collections  Static utility class provide various useful algorith 148 rgupta.trainer@gmail.com
  • 149. collection  Collection  Why it is called an framework?  Readymade Data structure in Java… 149 rgupta.trainer@gmail.com
  • 150. 150 rgupta.trainer@gmail.com
  • 151. ArrayList: aka growable array… 151 rgupta.trainer@gmail.com
  • 152. ArrayList of user defined object 152 rgupta.trainer@gmail.com
  • 153. 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…. 153 rgupta.trainer@gmail.com
  • 154. Implementing Comparable 154 rgupta.trainer@gmail.com
  • 155. Comparator  Don’t need to change Employee class  155 rgupta.trainer@gmail.com
  • 156. Useful stuff 156 rgupta.trainer@gmail.com
  • 157. Useful examples… 157 rgupta.trainer@gmail.com
  • 158. Useful examples… 158 rgupta.trainer@gmail.com
  • 159. LinkedList : AKA Doubly Link list……….. can move back and forth....... 159 rgupta.trainer@gmail.com
  • 160. Useful examples… 160 rgupta.trainer@gmail.com
  • 161. 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] .... <- <- 161 rgupta.trainer@gmail.com
  • 162. 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>();  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… 162 rgupta.trainer@gmail.com
  • 163. Performance ArrayList vs LinkedList !!! 163 rgupta.trainer@gmail.com
  • 164. 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); 164 rgupta.trainer@gmail.com
  • 165. Looping through HashMap for(Integer key: map.keySet()) { String value = map.get(key); System.out.println(key + ": " + value); } 165 rgupta.trainer@gmail.com
  • 166. 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  166 rgupta.trainer@gmail.com
  • 167. set  Don’t allow duplicate element 167 rgupta.trainer@gmail.com
  • 168. Assignment 168 rgupta.trainer@gmail.com
  • 169. 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 169 rgupta.trainer@gmail.com
  • 170. 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 170 rgupta.trainer@gmail.com
  • 171. Session-2  Java 5 Language Features II  Generics  Annotations 171 rgupta.trainer@gmail.com
  • 172. 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… 172 rgupta.trainer@gmail.com
  • 173. Issues with Generics  Try not to mix non Generics code and Generics code…we can have strange behaviour. 173 rgupta.trainer@gmail.com
  • 174. Polymorphic behaviour 174 rgupta.trainer@gmail.com
  • 175. <? extends XXXXXX> 175 rgupta.trainer@gmail.com
  • 176. <? Super XXXXX> 176 rgupta.trainer@gmail.com
  • 177. Generic class 177 rgupta.trainer@gmail.com
  • 178. Generic method 178 rgupta.trainer@gmail.com
  • 179. 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. 179 rgupta.trainer@gmail.com
  • 180. 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… 180 rgupta.trainer@gmail.com
  • 181. References:-  Head first java  SCJP katthy  Google  Stackoverflow.com  …..  ….. 181 rgupta.trainer@gmail.com