SlideShare a Scribd company logo
1 of 123
UNIT - I
CHAPTER – 1
  java

              1
CONTENTS
1. INTRODUCTION
     1.1. history of java
2. STRUCTURE OF JAVA PROGRAM
     2.1. standard program and Applets
     2.2. packages
     2.3. importing classes and Packages
3. THE JAVA COMPILER AND VIRUTAL MACHINE
4. DOCUMENTATION COMMENTS
5. DATA TYPES



                                           2
6. METHODS
      6.1. parameters
      6.2. Overloaded Methods
 7. EXCEPTIONS
      7.1. throwing an exception
      7.2. handling exceptions
 8. ACCESS MODIFIERS
9. INHERITANCE AND METHOD OVERRIDING
      9.1. Super-classes and Subclasses
10. GENERIC METHODS
11. GARBAGE COLLECTION
12. RECURSION
      12.1. recursive function
      12.2. induction
      12.3. recursive methods
                                          3
13. TESTING AND DUBUGGING
      13.1. what is testing
      13.2. designing test data
      13.3. debugging




                                  4
1. INTRODUCTION
1.1. HISTORY OF JAVA

 1. Java programming language is usually associated
    with “ World Wide Web ”.
 2. Java predates the Web.
 3. Java began it’s life as the programming language
     “ Oak ”.
 4. Oak was developed by the “Green Project Members”
                * Patrick Naughton
               * Mike Sheridan
               * James Gosling
  5. A group formed in 1991 to create products for the
     “ Smart electronic Markets “
                                                     5
6. The existing programming language were not
   suitable for “ consumer electronics “.
7. The Chief Programmer of Sun Microsystem –
     James Gosling :
           created the software for controlling
           “ Consumer Electronic devices “.
 8. The team wanted a fundamentally new way of
    computing , based on the power of “ Networks “.
    And the S/W to run on different kinds of computers

9. Patenting issues gave a new name to Oak – Java.

10. HotJava
        - The first Java-enabled Web browser
                                                         6
ChaRaCTERISTICS Of java
    • Java is simple
    • Java is object-oriented
    • Java is distributed
    • Java is interpreted
    • Java is robust
    • Java is secure
    • Java is architecture-neutral
    • Java is portable
    • Java is high-performance
    • Java is multithreaded
    • Java is dynamic language
                                     7
• Java is simple
      Java is simple language, can be learned easily.
• Java is object-oriented
      Java provides Abstraction, Encapsulation,
  Inheritance and Polymorphism.
• Java is distributed
       Java is tuned to the Web, So java program can
  access data – across the Web as easily as they access
  data from local system.
• Java is interpreted
       Java is both Interpreted and compiled. The code
  is complied to byte code that’s “ Binary “ and “
  platform independent”.
                                                          8
• Java is robust
       Java forces the programmer to handle
  unexpected errors. This ensure that java programs are
  “Robust” (Reliable) and bug free and don’t crash.
• Java is secure

         A program traveling from internet to pc could
  possibly carry a virus. Java done strong type-checking
  on the user-machine, and changes in the program are
  tagged as errors and program will not executed. So,
  java is “secure”.
. Java is architecture-neutral
    The byte code can be executed on a variety of
  computers running on different operating systems.
                                                       9
• Java is portable

        Java program can run on any machine that has
  a java interpreter. Other people can use the programs
  written in java, even if they have different machines
  with different operating systems.
• Java is multithreaded

        perform multiple task at the same time.
• Java is dynamic language

         Maintaining different versions of an
  application is very easy in Java.

                                                      10
2. STRUCTURE Of java
•                    PROGRaM
    Types of Java Programs are:
      1. Applications (or) stand-alone program
           - they are program that don’t need a browser
             to run simultaneously.
           - need MS-DOS or UNIX prompt to execute
             the program.
      2. Applets
            - Applets are programs that execute inside
               a Web page.
            - Applets require a Java enabled browser like
                  * MS-internet Explorer
                   * Netscape Navigator
                   * Hotjava                            11
           - Applet have Graphical User Interface.
3. Servlets
      - these programs extend the functionality of
        web servers
4. Packages
       - they are collections of classes that can be
          shared by other Java programs.




                                                   12
2.1. standard program and Applets
• Every java program is a – CLASS
• Every class may contain data and METHOD members

S. No     Application              applet
1.      METHOD name is “ main” METHOD name is “ int”


2.      Syntax for Compiling     Syntax for Compiling
         javac <filename.java>   javac <filename.java>

3.      Syntax for Executing     Syntax for Executing
         java filename           Appletviewer <URL.html file>

                                                          13
2.2. packages
•   DEFINITION
      A Package is a collection of classes that can be
  shared by java program.
        Packages are used to organize classes into
  groups.
• Types of Packages

      (i). Pre-defined                (ii). User-defined
            1. java.lang
             2. java.util                      user can
             3. java.applet                  create their
             4. java.awt                    own packages
             5. java.io                   ( Refer Slide Nos from

            6. java.net                          106 to 122)
                                                               14
1. java.lang
      - provides classes and interfaces that are
        fundamental to java programming.
2. java.util
      - provides classes that support collections, data and
        calendar operations, parsing, internationalization

        and basic event processing. Also refers to all
        programs in the directory (lang/java or
     langjava).
3. java.applet
       - provides classes, necessary for basic applet
         programming.
4. java.awt (abstract window toolkit)                    15
       - provides classes for creating GUI programs.
5. java.io
    - provides classes for reading and writing data in
      the form of streams. (input stream, output stream)
      e.g: memory, file, buffer, network
6. java.net
     - provides classes that provide network
       programming.




                                                           16
2.3. importing classes and Packages
Syntax for package
• import <package_name>.*;
• import <package_name> . <class_name>;

 Example:
    import java.awt.*;
    import java.awt.Button;

import java.awt.*;
   in this syntax all the classes in awt package have to

    imported
import java.awt.Button;
   in this syntax only button class from awt package
  have to imported                                     17
3. ThE java COMPIlER aND vIRTUal
                MaChINE
• Java source code is converted into Java Byte code
  (or) J-code.
* When the program <programName> is compiled, the
   program source code is read from the file
            <programName.java>
* The compiled byte code is written in the file
            <programName.class>
* Java Virtual Machine (JVM) is a software that
   interpret and executes the byte code.
• The main task of JVM is – the loading of .class files
• JVM- has class loaders that loads the .class files, and
  executed by the execution engine.

                                                          18
• Each java applications run inside a JVM.
• JVM starts when you start a java program and
  terminates when the program ends.
• The no. of JVM starts when you start a java program
  and terminates when the program ends.

• CLASS LOADER ARCHITECTURE
  1. A JVM can have many class Loader. They provide

     security and network to java programs.
  2. The JVM has two types of class loaders.
         (a) Primordial Class Loader
         (b) Class Loader Objects
                                                        19
(a) Primordial Class Loader
        A primordial Class Loader is a part of the JVM
    implementation. It loads the java API classes when
    you execute a java program.
(b) Class Loader Objects
       An application can create many class loaders at
    runtime for loading the classes of the application.

Implementation of Class Loader

           Class Loader            Class Loader


           Java Virtual Machine Implementation
                  Primordial Class Loader         Java API



                                                          20
JAVA VIRUTAL MACHINE




                       21
• Through the Java VM, the same application is capable
  of running on multiple platforms.




                                                    22
• The Java platform has two components:
     – The Java Virtual Machine (JVM)
     – The Java Application Programming Interface (API)




                                                    23
4. DOCUMENTaTION COMMENTS
•  A comment is a message for a programmer &
   describes a class, a method, or even a statement.
   The complier ignore what you write as comments
• Comments are ignored by the compiler but are
   useful to other programmers
• Java support three styles of comments:
         1. Multiple line comments
        2. Single line comment entries
        3. The javadoc comments
1.Multiple line comments
      Anything you write between /* and */ is treated
   as a comment. The text that you type here can cover
   many lines.
             /* multiple line comments */             24
2. Single line comment entries
    anything you type after // is treated as a comment.
   The text can’t span (extend) more than a line. If you
   have multiple lines as comments, you must start
   every line with //.
             // single line comment
3. The javadoc comments
     these lines are used by the javadoc utility to create
   documentation. These comments are similar o the
   multiple line comments but start with a /** instead
   of /*
           /** this is a javadoc comment*/


                                                             25
5. DaTa TYPES
• The data that’s stored in memory can be of many
  types. For example:
    * a person’s age is stored as a numeric value & an
      address is stored as alphanumeric characteristics.
    * an address is stored as alphanumeric characters
 Data types are used to define the operations possible on
 them and the storage method.

* The data types in java are classified as:
       1. primitive (or) standard data types
        2. Abstract (or) derived data types

                                                        26
1. primitive (or) standard data types

 Data Type   Size/Format     Description Range
                        (Numbers)

   Byte         8-bit         Byte-length   -128 to +128
                              integer        If signed(-2 7 to
                                            27 -1)
                                            If unsigned(0 to
                                            255)


   Short        16-bit        Short integer -32768 to
                                            +32767(-215 to
                                            215-1)
 Int         32-bit           Integer       -231 to 231-1

                                                                 27
Data Type   Size/Format      Description        Range
                        (Numbers)

  long         64-bit          Long integer     -2 63 to 2 63-1


  float        32-bit          Single-          +/-about 10 39
                               precision
                               floating point

 double        64-bit          Double-          +/-about 10 317
                               precision
                               floating point

                   (other types)
 Char          16-bit          A single character

 Boolean       1-bit           A Boolean value (true or false)
                                                                  28
2. Abstract (or) derived data types

• Abstract data types are based on primitive data types
  and have more functionality than primitive data
  types.
• Example
     “String” is an abstract data type that can store
  letters, digits and other characters like /,(), : , ; , $ , #

 * “String ”provides methods for concatenating two
  strings, searching for one string within another, and
  extracting a portion of a string. The primitive data
  types don’t have these features.


                                                              29
6. METhODS
                 1. parameters
• A method is a body of code that’s used for performing
  a set of tasks. The behavior of an object is determined
  by the program.
• Declaring Methods:

   syntax:
  [<access_specifier>] [<modifiers>] <return_type>
  <method_name> ([argument_list])
    {
       //statements
    }
                                                        30
• Example:
    public static int abc (int a, int b, int c)
      {
          return a+b*c+b/c;
         }
Where:
   abc - name of the method
   int - return type of the method is ‘int’
   (int a, int b, int c) – formal paramenters of the
                           method abc, each is of integer
                           type.


                                                            31
• If the method is invoked by the statement
                 Z = abc (2,x,y)
  then 2,x,y are the ‘actual parameter’.

* when the method ‘abc’ is invoked the
           a - is assigned to 2
           b - is assigned to x
           c - is assigned to y
* In java all method parameters are ‘value parameters’.
* At run time the value of each ‘actual parameter’ is
  copied into the corresponding format parameter before
  the method is executed.
                                                     32
2. Overloaded methods
• Overloading is a technique in which more than one
   method having the same name can be present in a
   program. The compiler resolves the method to be
   invoked using the signature of the method.
• Function signature
        1. The name of the method
        2. The number of arguments it takes
        3. The data type of the arguments
        4. The order of the arguments
 - when we call a method, the compiler uses the signature
   of the method to resolve the method to be invoked.
 - A class can’t have two methods having the same
   signature.
                                                       33
- this is because the compiler will not know which
   method to invoke if more than one method has the same
   signature.
Example:
   java supports method overloading and hence, the
   methods can be declared as follows:
       * public void add(int a, int b); // add two integers
       * public void add(float a, float b); // add two floats
       * public void add(float a, int b); // adds a float and
                                              an integer
* In the following example the ‘calculator’ class, the
   methods have the same name but different
   parameters and the signatures of the methods are
   different.                                                 34
class calculator
  {
  public int add(int a, int b)
   {
      System.out.println("int and int");
      return a + b;
    }

 public float add(float a, float b)
  {
     System.out.println("float and float");
     return a + b;
   }
                                              35
public float add(float a, int b)
  {
     System.out.println("float and int");
     return a + b;
   }
public static void main(String args[])
  {
    calculator c = new calculator();
    System.out.println(c.add(1,10))
    System.out.println(c.add(1.6f,10.5f));
   }
}                                            36
37
class calculator
  {
  public int add(int a, int b)
   {
      System.out.println("int and int");
      return a + b;
    }

 public float add(float a, float b)
  {
     System.out.println("float and float");
     return a + b;
   }
                                              38
public float add(float a, int b)
  {
     System.out.println("float and int");
     return a + b;
   }
public static void main(String args[])
  {
    calculator c = new calculator();
    System.out.println(c.add(1,10))
    System.out.println(c.add(1.6f,10.5f));
    System.out.println(c.add(10.5f,2));
   }
}
                                             39
40
7. EXCEPTIONS
• An exception is defined as an ‘abnormal’ event that
  occurs during program execution and disturb the
  normal flow of instructions.
• Error-handling becomes necessary, when developing
  applications and need to take care of unexpected
  situations.
• The unexpected situations that may occur during
  program execution are:
      * Running out of memory
      * Resource allocation errors
      * Inability to find files
      * Problems in network connectivity

                                                        41
Exception-Handling Techniques
• When an unexpected error occurs in a method, java
  creates an object of the types ‘ Exception’.
• After creating the Exception object, java sends it to
  the program, by an action called “throwing an
  exception”.
• The Exception object contains information about the

   - type of error
   - status of the program when the exception occurred
* Key words in Excepting:
                    try
                    catch
                    throw
                    throws                           42
• Try Block
   syntax:
      try
        {
           //statements that may cause an exception
         }
* If an exception occurs within the try block, the
  appropriate exception-handler that’s associated
  with the try block handles the exception.
* A try block must have at least one catch block
  that follows it immediately.



                                                  43
• catch Block
   syntax:
        try
         {
            //statements that may cause an exception
          }
       catch(……)
          {
              // error handling routines
            }
• The catch statement take the object of the exception
  class that refers to the exception caught.
• Once the exception is caught, the statements within
  the catch block are executed.
• The scope of the catch block is based on the statement
                                                       44
  in the preceding try block.
Exception handling mechanism
• In java, exception-handling facility handles abnormal
  & unexpected situation in a structured manner.
• When an exception occurs, the java runtime system
  searches for an exception-handler (try-catch-block).
• If a handler is not found in the current method, the
  handler is searched for in the ‘calling method’.
• The searches goes on till the runtime system finds an
  appropriate exception-handler.
• EXAMPLE:
  // derivedclass.java
  class baseclass
     {
       public int divide(int num1, int num2)
       {                                               45
return num1 / num2;
 }
}
public class derivedclass extends baseclass
{
   public int divide(int a, int b)
   {
        return super.divide(a,b);
    }
  public static void main(String args[])
  {
     int result = 0;
     derivedclass d1 = new derivedclass();
                                              46
try
     {
           result = d1.divide(100, 0);
        }
        catch(ArithmeticException e)
          {
            System.out.println(“Error…division by zero”);
            }
           System.out.println(“The result is: “ + result”);
    }
}


                                                         47
48
Multiple catch block - example

public class trycatch
{
  public static void main(String args[])
  {
     int num1, num2, result = 0;
     num1 = 100;
     num2 = 0;
     try
        {
            result = num1/num2;

        }


                                             49
catch(ArithmeticException e)
        {
           System.out.println("Error---division by zero");
         }
     catch(ArrayIndexOutOfBoundsException e)
        {
          System.out.println("Error----out of bounds");
          }
      catch(Exception e)
        {
           System.out.println("some other error");
          }
         System.out.println("The result is: " + result);
      }

}
                                                             50
51
EXAMPLE-2

public class trycatch
{
  public static void main(String args[])
  {
     int num1, num2, result = 0;
     num1 = 100;
     num2 = 4;
     try
        {
            result = num1/num2;

        }
                                           52
catch(ArithmeticException e)
        {
           System.out.println("Error---division by zero");
         }
     catch(ArrayIndexOutOfBoundsException e)
        {
          System.out.println("Error----out of bounds");
          }
      catch(Exception e)
        {
           System.out.println("some other error");
          }
         System.out.println("The result is: " + result);
      }

}
                                                             53
54
throw statement
• When a user enters a wrong login-ID (or) password,
  the throw statement is used to throw an exception.
• The throw statement takes a single statement, which
  is an object of the ‘Exception class’.
• Syntax
          throw Throwableinstance;
* Example
          throw ThrowObject;
• The compiler gives an error if the object ‘ThrowObject”
  doesn’t belong to a valid ‘Exception class’.
• The ‘throw statement is commonly used in
  ‘programmer-defined’ exceptions.
                                                       55
throws statement
• Throws statement is used to specify that ‘ an exception
  has to be handled by the calling method. It’s used for an
  exception that a method is capable of raising, but not
  handling.
• Syntax
 [<access_specifier>][<modifier>]<return_type>
  <method_name> (<arg_list>) [throws <exception_list>]
• Example
  public void acceptpassword() throws IllegalAccessException
  {
     System.out.println(“ intruder !!”);
     throw new IllegalAccessException;
 }

                                                         56
Finally Block
• The finally block is used when it’s necessary to
  process certain statements no matter, whether an
  exception is raised or not.
• Example
    try
       {
        openFile();
        writeFile(); // may cause an exception
        }
   catch(……..)
    {
          // process the exception
     }
   Finally
     {       closeFile();
                                                     57
   }
Common exceptions

1. ArithmeticException Exception

2. NullPointerException Exception

3. ArrayIndexOutofBoundsException Exception




                                              58
8. ACCESS MODIFIERS
•  An access specifier determines which features of a
   class (the class itself, the data members, and the
   method) may be used by the other classes.
• Java supports three specifiers (or) Access Modifiers
                1. public
                2. private
                3. Protected
                4. Default
1. Public access specifier
   A class, data member (or) method that has a public
   access specifier can be accessed by any object. An
   inner class can’t have a public access specifier.
                                                         59
• Syntax
    <access_specifier> <return_type> <method>
   ([argment list])
    { ----------
      }
  Example:
      public class employee
       {
         string empname;
         string empadd;
          public void displaydetails( )
          {
             // place the code for displaying employee
   details
           }
}                                                        60
2. Private access specifier
• Only object of the same class can access a variable or
  a method that has a private access specifier. The
  variables and method of the inner classes can be
  declared as private.
• Example:
   private int privateVariable;

3. Protected access specifier
   variable, methods, and inner classes that are declared
   protected accessible to the subclasses of the class in
   which they are declared.
Example:
     protected int protectedVariable
                                                           61
4.Default access
  A class, a variable or a method that doesn’t have an
  access specifier as private, public, protected is said to
  have default access. These classes, variables or
  methods are accessible to all the classes of a package.
  Example:
   consider following set of classes y and z inherit from
  class x. class z belongs to the package p1 and classes
  x and y belong to the package p2.

               Package p1

                 Class X               Package p2

                                        Class Z
                 Class Y
                                                          62
* A method accesme() has been declared in class X. The
  following table shows the accessibility of the method
  accessme() from class Y and Z.

 Access specifier     Class X          Class Y
 accessme() is      Accessible as Y is Accessible as z is
 declared as        a subclass         a subclass (even
 protected                             if it’s in another
                                       class)
 accessme() is    Accessible as it is Not accessible as
 declared without in the same         it is not in the
 an access        package             same pckage
 speicifer

                                                        63
Access Specifier   Member Visibility
Default            Member is visible only to
                   classes in the same
                   package.
Private            Member is visible only
                   within the class C.
Protected          Member is visible to all
                   classes in the same
                   package and to
                   subclasses of c in other
                   packages.
Public             Member is visible to all
                   classes in all packages.
                                               64
MODIFIERS
• Modifiers determine how the data members and
  methods are used in other classes and objects.
• The modifiers in java:
              1. static
              2. final
              3. abstract
              4. native
              5. transient
              6. synchronized
              7. volatile


                                                   65
9. INHERITANCE AND METHOD
           OVERRIDING
• Inheritance is a situation in which a class derives a
  set of attributes and related behavior from a parent
  class.
• 9.1. super classes and subclasses:
   * super class:
  super class is a class from which another class
  inherits properties. It share its properties with its
  child classes.
  * sub class:
    sub class is a class that inherits attributes and
  methods from a super class.
                                                          66
• Super class some times referred to as the ‘base class’
  and the subclass is referred to as the ‘derived class’.
• Subclass don’t inherit the constructs of the super
  class.
• Example:
  let us take the example of ‘air tickets’- it can be of two
  types. Confirmed and request ticket. both the
  tickets have a lot of common attributes. For
  example
   flight_number, date, time and destination.
  confirmed ticket would have a ‘seat number’, while
  a request ticket would have a ‘status’.


                                                          67
• Example:
                       Ticket



     RequestTicket                  ConfirmedTicket


Syntax:

  public class <subclass name> extends <superclass
  name>

  public class confirmedTicket extends Ticket



                                                      68
Final keyword
• The final modifier doesn’t allow a class to be
  inherited. A method declared anal can’t be overridden
  by a subclass.
• Final- keyword can prevent people from extending a
  class by using the ‘final’ modifier as follow:
      example:
           final class password
             {
                    --------
                  }



                                                      69
OVERRIDING METHODS
• In overridding, a subcalss method overrrides the
  definition of a super class method, if the method
  defined in the subcalss has the same signature of a
  method in the super class.
• Example:
    let us consider the class ‘wheelchair’ is derived
  from the ‘chair class’. Both the classes have a
  method called ‘adjustHeight()’. Wheelchair is
  adjusted differently form the way other chairs are
  adjusted. Therefore, the wheelchair class overrides
  superclass method ‘adjustHeight()’.



                                                        70
// declaring base class chair (saved as wheelchair.java)
class chair
{
   public void adjustHeight()
   {
          System.out.println(“adjusting chair height”);
     }
}
//deriving wheelchair class from chair
public class wheelchair extends chair
{
  public static void main (String args[])
{      wheelchair w
       w = new wheelchair();
       w.adjustHeight();
}
}                                                          71
72
// declaring base class chair (saved as wheelchair.java)
class chair
{
   public void adjustHeight()
   {
          System.out.println(“adjusting chair height”);
     }
}
//deriving wheelchair class from chair
public class wheelchair extends chair
{
 //overriding adjustHeight() method
public void adjustHeight()
{ System.out.println(“adjust wheelchair height”);
  }                                                  73
public static void main (String args[])
{    wheelchair w
     w = new wheelchair();
     w.adjustHeight();
}
}




                                          74
75
10. GENERIC METHODS
* The following two programs differ only in the data
  types of the formal parameters & the return value.

Program-1:
Public static int abs(int a, int b, int c)
   {
      return a+b*c+b/c;
     }
Program-2:
  Public static float abc(float a, float b, float c)
     {
        return a+b*c+b/c;
       }
                                                       76
• Write a new version of the code for every data type of
  the formal parameters & return value – we can write
  a ‘generic code that’s independent of this data type.
• It’s not possible to write generic methods to work
  with actual parameters of any of java primitive data
  types.
• Generic methods can be written to work with actual
  parameters of the type object (or) any subclass of
  object.
• Example:
  generic methods will work with the wrapper classes
  of java, because these wrapper classes are
  subclasses of ‘object’.


                                                       77
wrapper classes
• A wrapper class extends the functionality of the
  primitive data types. It allows an object to be created
  from a primitive data type.
• Variables that are declared using ‘primitive data types’
  aren’t objects.
• To make primitive types to behave like objects, theses
  wrapper classes also provide methods for converting
  strings to various data types.
• Example:
  represent a set of primitive data types like ‘int’, it can
  be done in at least two way:
    1) create an array of actual size:
             int x[] = {10,20,30};
                                                          78
2) the other way is to use a wrapper class:
    Integer x[] = {new integer(10), new Integer(20),
                     new Integer(30)};
• In terms of speed & memory space, the first statement
  is more efficient for representing a set of values.
• The wrapper classes in java.lang are:
   s.no.   Primitive data types   Wrapper classes
   1.      byte                   Byte
   2.      char                   Char
   3.      int                    Int
   4.      long                   Long
   5.      float                  Float
   6       double                 Double
   7.      boolean                Boolean
   8.      short                  Short              79
INTERFACE
• An interface contains constant values and method
  declarations. The difference between a class and
  interface is that the methods in an interface are only
  declared and not implemented.
• Interfaces are used to define a ‘behavior protocol’
  (standard behavior) that can be implemented by any
  class anywhere the class hierarch.
• Syntax:
  An interface is declared like a class, but the keyword
  ‘class’ is replace by the keyword ‘interface’. The
  declaration of an ‘interface’ is shown below:
   public interface interfaceName // interface declaration
    {
        // interface body

     }                                                   80
• Example:
   public interface color
    {
       final int white = 0;
       final int black = 1;
      final int red = 2;
    }
• Example:
  consider the devices TV & VDU, both of them require
  a common functionality as far as brightness control is
  concerned. This functionality can be provided by
  implementing an interface called “Brightnesscontrol”
  which is applicable for both the devices.
                                                       81
// interface definition of Brightnesscontrol
  public interface BrightnessControl
  {
        void increaseBrightness();
        void decreaseBrightness();
    }
 // TV class implementing the interface
  public class TV implements Brightnesscontrol
  {
      void increaseBrightness()
       {
           // implementation code
        }
                                                 82
void decreaseBrightness()
      {
          // implementation code
      }
  }

//VDU class implementing the interface
  public class VDU implements BrightnessControl
   {
      void increaseBrightness()
       {
           // implementation code
        }
                                                  83
Void increaseBrightness()
     {
        // implementation code
      }
}




                                 84
Steps for implementing an Interface

1. Import the interface
2. Declare the class and use the implement keywords
   followed by the name of the interface.
3. Ensure that the class implements every method that

   has been declared in the interface.
4. Save the file with the .java extension.
5. Compile the applet or application created.




                                                    85
Example program
 // implementinterface.java
 // example of an interface
Import java.lang.*;
{
    public String displayText(); //   no implementation of method

    }

public class implementinterface implements inter
{
   implementinterface inter = new implementinterface();
   String str = inter.displayText();
   System.out.println(str);
 }                                                   86
public String displayText()
  {
     return “ Good Morning”;
   }
}

Out put:

     Good Morning




                               87
11. GARBAGE COLLECTION
• When a program stops referencing an object the object
  is not required any more and becomes garbage.
  Garbage collection is a process that automatically
  frees the memory of objects that are no more in use.
• Garbage collector must do two things:
    1. Detect garbage objects
    2. De-allocate the memory of garbage objects and
       make it available to the program.
• There are different garbage collection algorithms (or)
    there are different approaches used for detecting
    garbage objects are as follows:

 * Reference-counting garbage collectors – keep a
   count of the references for each live object.
                                                      88
*Tracing collectors (or) mar-and-sweep algorithm
     - the mark phase marks all the referenced objects.
       The sweep phase collects the memory of
       unreferenced objects.
  * Compacting collectors
     - reduce fragmentation of memory by moving all the
       free space to one side during action.

 * Adaptive algorithm
     - monitors the situation and uses the garbage
  techniques that best suits the situation.

The finalize( ) method
  - before freeing the memory associated with an object,
  the garbage runs the ‘finalize() method’.            89
• Finalize method is declared in any class. The finalize()
  method is declared as follows:

     protected void finalize() throws Throwbale
      {
             super. finalize( );
        }
* Garbage collector is called manually using the
  ‘system.gc ( ) method.’




                                                        90
12. RECURSION
• Recursive method invokes itself. There are two types
  of recursions
        (i) Direct recursion
             - the code for method ‘ f ‘ contains a statement that
                invokes ‘ f ’.
         (ii) Indirect recursion
               - method ‘ f ‘ invokes a method ‘ g’ , which invokes a
                method ‘h’. and so on, until method ‘ f ‘ is again
                invoked.
12.1.Recursive Functions
    The factorial function is defined as follow:
            f(n) = 1                n<=1
                     nf(n-1)        n>1

   This definition states that f(n) = 1 whenever n is less than or
  equal to 1.
                                                                     91
• When ‘ n ‘ is less than 1, f(n) is defined recursively
• Example
    f (n) = nf(n-1); f(3) = 3*f(3-1) = 3*f(2) = 3*2 = 6
• For a recursive definition of f(n), the f must meet the following
  requirements:

       * The definition must include a base component in which f(n)
  is
        defined directly, (i.e. non-recursively) for one or more values
        of n.
              e.g. from the above equation the base is
                   f(n) = 1 for n<=1

       * In the recursive component all occurrence of ‘f’ on the right
         side should have a parameter smaller than ‘n’, so that
         repeated application of the recursive component transforms
         all occurrences of ‘f’ on the right side.
                                                                      92
•    repeated application of the recursive components transforms
     f(n-1) to f(n-2), f(n-3)……. and finally f(1).
     (e.g)
         repeated application of the recursive component gives the
    following:

             f(5)=5f(4)=20f(3)=60f(2)=120f(1)=120
                      i.e. f(5)=120

12.2.Induction
• In a proof by induction, the validity of claim is established as
   follow:     n

               ∑ i=n(n+1)/2, n>=0
                i=0

• This method has three components to make a proof
         1. induction base
         2. induction hypothesis
                                                                     93
         3.induction step
• 12.3.Recursive Methods

   a proper recursive method must include a base component.

Public static int factorial(int n)
{
      if ( n < = 1)
           return 1;
     else
        return n * factorial (n-1);
}




                                                              94
13. TESTING AND DUBUGGING
13.1. what is testing
  Correctness is the most important attributes of a
  program.
* program Testing:
       providing mathematical proof of correctness for a
       small program is difficult.
• Test data:
     - compare the program behavior with the expected
       behavior.
     - if these two behaviors are different program
       having problem.


                                                           95
- if these two behaviors are same also, we couldn’t
      conclude that the program is correct, if the
      behavior isn’t same on other input data.

• Test data: (Definition)
   Execute the program on the target computer using
   input data is called “Test Data”.

• Test Set:
   The subset of the input data space that’s actually
   used for testing is called the “Test set”.

Example: (Quadratic Roots)
  A Quadratic function (or) quadratic in x is a function

  that has a form
                    ax2 + bx + c                          96
where
    a, b, c - real numbers and a = 0

 examples for quadratic            not a quadratic
      functions                      functions
  3x2-2x+4
  -9x2-7x                                 5x+3
  3.5x2+4
  5.8x2+3.2x+5

 The roots of a quadratic function are the values of ‘x’
 at which the function value is 0.

                                                           97
• Example:

  (1) f(x) = x2-5x+6
      if x = 2
      f(2) = 22 -(5*2)+6
           = 4 -(5*2)+6
           = 4-10+6
           = -6+6
          = 0


 (2) f(x) = x2-5x+6
      if x = 3
      f(2) = 32 -(5*2)+6
           = 9 -(5*3)+6
           = 9-15+6
           = -6+6
           = 0

                           98
• Every quadratic has exactly two roots, and these roots
  are given by the following formula:
              -b + b2 – 4ac
             ____________________
                      2a
   if the function
      f(x) = x2-5x+6 and a=1, b=-5, c=6 then

          = -(-5) + -52 – 4*1*6
            ___________________
                      2*1
          =5+1            5–1
              2       ;    2
           f(x) = (3,2)                                99
Designing Test data
• Objectives of Testing
             expose the presence of error
• Correctness of the programs depends on – if the
  designed data fails to expose errors.
• Example:
       Quadratic Roots
    - behavior of any test data may be verified in one of
      two ways:
      first:
         find out the roots of the test quadratic
           (e.g) before slide
               (a, b, c) = (1, -5, 6)
                                                        100
second:
     - substitute the roots(answers(3,2)) produced by
       the program into the quadratic function.

       -and verify the function value is 0

Example:

          f(x) = x2-5x+6

(i)   If f(3) = 32-5*3+6       (ii) if f(2) = 22-5*2+6
              = 9 – 5*3+6                    = 4-5*2+6
              = 9-15+6                       = 4-10+6
              = -6 + 6                       = -6+6
              = 0                            =    0
                                                         101
Data Testing Techniques
• There are two categories in data testing techniques
              (i) Black Box Method
              (ii) White Box Method
 (i) Black Box Method
      while developing test data, consider only program’s

     function, not the actual code.
       * the most popular black box methods are
                I/O partitioning
                cause-effect graphing
       * In I/O partitioning the input and output data
         are partition into classes.
       * Data in different classes cause the program
         to exhibit qualitatively different behaviors.
       * Data in same class cause qualitatively similar102
         behaviors.
• Example:
   The quadratic roots has three different qualitatively
   behaviors:
       1. the roots are complex
       2. the roots are real and distinct
       3. the roots are real and the same.
  Each behaviors has different kinds of behaviors.

(ii) White Box Method
     while developing test data, consider only program’s
     actual code.
 * Statement coverage:
     the weakest condition we can place on a test set, will
     execute the program statement at least once.
                                                         103
• Decision coverage
    the test set cause each condition in the program to
  take on both true and false values.
• Clause coverage
   strengthen the decision coverage criterion to require
  each clause of each condition to take on both true and
  false values. The strengthen criterion is called “ clause
  coverage”.
   clause
     it is defined as Boolean expression that contains no
  Boolean operator (i.e., &&, ||, ! ).
             (e.g) x > y, x + y < y * z


                                                         104
Debugging
• The process of determining and correcting the
  difference between the desired and observed behaviors
  is called “ debugging”.
• Suggestions for debugging:
    1. Try to determine an error by logical reasoning.
    2. Errors should be corrected first by determining
       their cause and then redesigning your solutions as

      necessary.
   3. After corrected an error, the correction doesn’t
      result an errors.
   4. When testing and debugging a multi-method
      program, begin with a single method that’s
      independent.This method is typically i/p & o/p
      method. Then introduce additional methods one at
      at a time. This is called as “ incremental testing &
                                                         105
USER DEFINED PACKAGE
      PROGRAM




                       106
Design and develop a Package in Java which contains
  following Sorting techniques
                  a) Bubble Sort
                  b) Selection Sort

                 c) Shell Sort




                                                  107
Steps in creating “ User Defined Program”
Step -1 : Create a folder name of your User defined package in the path, where

        the java is installed
 Example:
           ►Create a Folder Name “BUBBLE”
           ► Click the Folder (BUBBLE) and save your java file name
               (bubblesort.java)
           ► Click the Folder (SELECTION) and save your java file name
               (selectionsort.java)
           ►Create a Folder Name “SHELLSORT”
           ► Click the Folder (SHELLSORT) and save your java file name
               (shellsort.java)
Step-2: Creation of Main Program
    Example:
              ►save the main program (sort.java) in the bin path
              (e.g: C:Program FilesJavajdk1.5.0bin>
                                                                           108
// package for bubble sort
package BUBBLE;
import java.io.*;
public class bubblesort
{
int a[]=new int[10];
int n,t;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
public void bdisplay()
{ try
              {
         System.out.println("n--->BUBBLE SORT<----n");
         System.out.println("Enter N values to sort..");
         n=Integer.parseInt(br.readLine());
         System.out.println("Enter" + n + "Value one by one..");
         for(int i=1; i<=n; i++)
                                                                   109
{
    a[i] = Integer.parseInt(br.readLine());

    }
    System.out.println("n Before Sortingn");
    for(int i=1; i<=n; i++)

    {
     System.out.println(a[i]+ " ");
       }
     for(int i=1; i<=n; i++)
      {

    for(int j=1; j<=n; j++)

     {
         if(a[j]>a[j+1])
         a[j]=(a[j]+a[j+1])-(a[j+1]=a[j]);
         }
     }

                                                 110
System.out.println("n After Sortingn");
      for(int i=2; i<=n+1; i++)
        {
           System.out.println(a[i] + " ");

            }
        }
            catch(Exception e)
              {
                 System.out.println("Cause Error..");
                }
             }
        }




                                                        111
// package for Selection sort
package SELECTION;
import java.io.*;
public class selectionsort
{
int a[]=new int[10];
int n,t;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
public void sdisplay()
{     try
         {
         System.out.println("n--->SELECTION SORT<----n");
         System.out.println("Enter N values to sort..");
         n=Integer.parseInt(br.readLine());
         System.out.println("Enter" + n + "Value one by one..");
         for(int i=1; i<=n; i++)
                                                                   112
{ a[i] = Integer.parseInt(br.readLine());
         }
         System.out.println("n Before Sortingn");
         for(int i=1; i<=n; i++)
                  {
          System.out.println(a[i]+ " ");
            }
          for(int i=1; i<=n; i++)
            {
               int min,loc;
               min=a[i];
               loc=i;
               for(int j=i+1; j<=n+1; j++)
{       if(min>a[j])
                   {
                      min=a[j];
                      loc=j;
                    }                                 113
a[i]=(a[i]+a[loc])-(a[loc]=a[i]);
                }
           }
          System.out.println("n After Sortingn");
          for(int i=2; i<=n+1; i++)
            {
              System.out.println(a[i] + " ");
              }
         }
     catch(Exception e)
       {
          System.out.println("Cause Error..");
           }
        }
     }




                                                      114
// package for shell sort
package SHELLSORT;
import java.io.*;
public class shellsort
{
int a[]=new int[10];
int n,t,incr,j;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
public void shdisplay()
{
   try
       {
         System.out.println("n--->SHELL SORT<----n");
         System.out.println("Enter N values to sort..");
         n=Integer.parseInt(br.readLine());
         System.out.println("Enter" + n + "Value one by one..");

                                                                   115
System.out.println("n Before Sortingn");
      for(int i=1; i<=n; i++)
      {
       System.out.println(a[i]+ " ");
        }
          incr=n/2;
           while(incr>0)
            {
               for(int i=1;i<n+1;i++)
                 {
                    j=i;
                    t=a[i];
                    while((j>incr) && (a[j-incr]>t))
                     {
                          a[j]=a[j-incr];
                          j=j-incr;
                      }
                     a[j]=t;
}                                                      116
if(incr/3!=0)
     incr=incr/3;
     else if(incr==1)
     incr=0;
     else
     incr=1;
  }
   System.out.println("n After Sortingn");
   for(int i=1; i<=n; i++)
     {
       System.out.println(a[i] + " ");
       }
       }
   catch(Exception e)
{
 System.out.println("Cause Error..");
}}}

                                               117
//Main Program
import BUBBLE.*;
import SELECTION.*;
import SHELLSORT.*;

class sort
{
   public static void main(String[] args)
    {
        bubblesort bs = new bubblesort();
        bs.bdisplay();
         selectionsort ss = new selectionsort();
         ss.sdisplay();
         shellsort sh = new shellsort();
         sh.shdisplay();
      }
}
                                                   118
OUTPUT




         119
120
121
122
THANKS FOR WATHING MY -
           PPT

      PRESENTED BY
       KAVITHA.C.R

     ASST. PROFESSOR
          SLNCS


                          123

More Related Content

What's hot

Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technologysshhzap
 
Introduction to java by priti sajja
Introduction to java by priti sajjaIntroduction to java by priti sajja
Introduction to java by priti sajjaPriti Srinivas Sajja
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javajayc8586
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Mr. Akaash
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
Intoduction to java
Intoduction to javaIntoduction to java
Intoduction to javajalinder123
 
Java basic-tutorial for beginners
Java basic-tutorial for beginners Java basic-tutorial for beginners
Java basic-tutorial for beginners Muzammil Ali
 
Introduction to java programming tutorial
Introduction to java programming   tutorialIntroduction to java programming   tutorial
Introduction to java programming tutorialjackschitze
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkMohit Belwal
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programmingElizabeth Thomas
 

What's hot (19)

Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Inside JVM
Inside JVMInside JVM
Inside JVM
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
Introduction to java by priti sajja
Introduction to java by priti sajjaIntroduction to java by priti sajja
Introduction to java by priti sajja
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
 
Introducing Java 7
Introducing Java 7Introducing Java 7
Introducing Java 7
 
Intoduction to java
Intoduction to javaIntoduction to java
Intoduction to java
 
Java basic-tutorial for beginners
Java basic-tutorial for beginners Java basic-tutorial for beginners
Java basic-tutorial for beginners
 
Introduction to java programming tutorial
Introduction to java programming   tutorialIntroduction to java programming   tutorial
Introduction to java programming tutorial
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Lec 3 01_aug13
Lec 3 01_aug13Lec 3 01_aug13
Lec 3 01_aug13
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 

Viewers also liked

L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variablesteach4uin
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple InheritanceDamian T. Gordon
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with javaHawkman Academy
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 

Viewers also liked (12)

Presentation
PresentationPresentation
Presentation
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
Java notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esectionJava notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esection
 
Java Datatypes
Java DatatypesJava Datatypes
Java Datatypes
 
Java features
Java featuresJava features
Java features
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
 

Similar to Java (20)

OOP with Java
OOP with JavaOOP with Java
OOP with Java
 
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
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
 
j-chap1-Basics.ppt
j-chap1-Basics.pptj-chap1-Basics.ppt
j-chap1-Basics.ppt
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.ppt
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.ppt
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
Java
JavaJava
Java
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDF
 
Java introduction
Java introductionJava introduction
Java introduction
 
1 java introduction
1 java introduction1 java introduction
1 java introduction
 
1 java intro
1 java intro1 java intro
1 java intro
 
Java Tutorial to Learn Java Programming
Java Tutorial to Learn Java ProgrammingJava Tutorial to Learn Java Programming
Java Tutorial to Learn Java Programming
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Java@intro to java
Java@intro to javaJava@intro to java
Java@intro to java
 

Recently uploaded

DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 

Recently uploaded (20)

DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 

Java

  • 1. UNIT - I CHAPTER – 1 java 1
  • 2. CONTENTS 1. INTRODUCTION 1.1. history of java 2. STRUCTURE OF JAVA PROGRAM 2.1. standard program and Applets 2.2. packages 2.3. importing classes and Packages 3. THE JAVA COMPILER AND VIRUTAL MACHINE 4. DOCUMENTATION COMMENTS 5. DATA TYPES 2
  • 3. 6. METHODS 6.1. parameters 6.2. Overloaded Methods 7. EXCEPTIONS 7.1. throwing an exception 7.2. handling exceptions 8. ACCESS MODIFIERS 9. INHERITANCE AND METHOD OVERRIDING 9.1. Super-classes and Subclasses 10. GENERIC METHODS 11. GARBAGE COLLECTION 12. RECURSION 12.1. recursive function 12.2. induction 12.3. recursive methods 3
  • 4. 13. TESTING AND DUBUGGING 13.1. what is testing 13.2. designing test data 13.3. debugging 4
  • 5. 1. INTRODUCTION 1.1. HISTORY OF JAVA 1. Java programming language is usually associated with “ World Wide Web ”. 2. Java predates the Web. 3. Java began it’s life as the programming language “ Oak ”. 4. Oak was developed by the “Green Project Members” * Patrick Naughton * Mike Sheridan * James Gosling 5. A group formed in 1991 to create products for the “ Smart electronic Markets “ 5
  • 6. 6. The existing programming language were not suitable for “ consumer electronics “. 7. The Chief Programmer of Sun Microsystem – James Gosling : created the software for controlling “ Consumer Electronic devices “. 8. The team wanted a fundamentally new way of computing , based on the power of “ Networks “. And the S/W to run on different kinds of computers 9. Patenting issues gave a new name to Oak – Java. 10. HotJava - The first Java-enabled Web browser 6
  • 7. ChaRaCTERISTICS Of java • Java is simple • Java is object-oriented • Java is distributed • Java is interpreted • Java is robust • Java is secure • Java is architecture-neutral • Java is portable • Java is high-performance • Java is multithreaded • Java is dynamic language 7
  • 8. • Java is simple Java is simple language, can be learned easily. • Java is object-oriented Java provides Abstraction, Encapsulation, Inheritance and Polymorphism. • Java is distributed Java is tuned to the Web, So java program can access data – across the Web as easily as they access data from local system. • Java is interpreted Java is both Interpreted and compiled. The code is complied to byte code that’s “ Binary “ and “ platform independent”. 8
  • 9. • Java is robust Java forces the programmer to handle unexpected errors. This ensure that java programs are “Robust” (Reliable) and bug free and don’t crash. • Java is secure A program traveling from internet to pc could possibly carry a virus. Java done strong type-checking on the user-machine, and changes in the program are tagged as errors and program will not executed. So, java is “secure”. . Java is architecture-neutral The byte code can be executed on a variety of computers running on different operating systems. 9
  • 10. • Java is portable Java program can run on any machine that has a java interpreter. Other people can use the programs written in java, even if they have different machines with different operating systems. • Java is multithreaded perform multiple task at the same time. • Java is dynamic language Maintaining different versions of an application is very easy in Java. 10
  • 11. 2. STRUCTURE Of java • PROGRaM Types of Java Programs are: 1. Applications (or) stand-alone program - they are program that don’t need a browser to run simultaneously. - need MS-DOS or UNIX prompt to execute the program. 2. Applets - Applets are programs that execute inside a Web page. - Applets require a Java enabled browser like * MS-internet Explorer * Netscape Navigator * Hotjava 11 - Applet have Graphical User Interface.
  • 12. 3. Servlets - these programs extend the functionality of web servers 4. Packages - they are collections of classes that can be shared by other Java programs. 12
  • 13. 2.1. standard program and Applets • Every java program is a – CLASS • Every class may contain data and METHOD members S. No Application applet 1. METHOD name is “ main” METHOD name is “ int” 2. Syntax for Compiling Syntax for Compiling javac <filename.java> javac <filename.java> 3. Syntax for Executing Syntax for Executing java filename Appletviewer <URL.html file> 13
  • 14. 2.2. packages • DEFINITION A Package is a collection of classes that can be shared by java program. Packages are used to organize classes into groups. • Types of Packages (i). Pre-defined (ii). User-defined 1. java.lang 2. java.util user can 3. java.applet create their 4. java.awt own packages 5. java.io ( Refer Slide Nos from 6. java.net 106 to 122) 14
  • 15. 1. java.lang - provides classes and interfaces that are fundamental to java programming. 2. java.util - provides classes that support collections, data and calendar operations, parsing, internationalization and basic event processing. Also refers to all programs in the directory (lang/java or langjava). 3. java.applet - provides classes, necessary for basic applet programming. 4. java.awt (abstract window toolkit) 15 - provides classes for creating GUI programs.
  • 16. 5. java.io - provides classes for reading and writing data in the form of streams. (input stream, output stream) e.g: memory, file, buffer, network 6. java.net - provides classes that provide network programming. 16
  • 17. 2.3. importing classes and Packages Syntax for package • import <package_name>.*; • import <package_name> . <class_name>; Example: import java.awt.*; import java.awt.Button; import java.awt.*; in this syntax all the classes in awt package have to imported import java.awt.Button; in this syntax only button class from awt package have to imported 17
  • 18. 3. ThE java COMPIlER aND vIRTUal MaChINE • Java source code is converted into Java Byte code (or) J-code. * When the program <programName> is compiled, the program source code is read from the file <programName.java> * The compiled byte code is written in the file <programName.class> * Java Virtual Machine (JVM) is a software that interpret and executes the byte code. • The main task of JVM is – the loading of .class files • JVM- has class loaders that loads the .class files, and executed by the execution engine. 18
  • 19. • Each java applications run inside a JVM. • JVM starts when you start a java program and terminates when the program ends. • The no. of JVM starts when you start a java program and terminates when the program ends. • CLASS LOADER ARCHITECTURE 1. A JVM can have many class Loader. They provide security and network to java programs. 2. The JVM has two types of class loaders. (a) Primordial Class Loader (b) Class Loader Objects 19
  • 20. (a) Primordial Class Loader A primordial Class Loader is a part of the JVM implementation. It loads the java API classes when you execute a java program. (b) Class Loader Objects An application can create many class loaders at runtime for loading the classes of the application. Implementation of Class Loader Class Loader Class Loader Java Virtual Machine Implementation Primordial Class Loader Java API 20
  • 22. • Through the Java VM, the same application is capable of running on multiple platforms. 22
  • 23. • The Java platform has two components: – The Java Virtual Machine (JVM) – The Java Application Programming Interface (API) 23
  • 24. 4. DOCUMENTaTION COMMENTS • A comment is a message for a programmer & describes a class, a method, or even a statement. The complier ignore what you write as comments • Comments are ignored by the compiler but are useful to other programmers • Java support three styles of comments: 1. Multiple line comments 2. Single line comment entries 3. The javadoc comments 1.Multiple line comments Anything you write between /* and */ is treated as a comment. The text that you type here can cover many lines. /* multiple line comments */ 24
  • 25. 2. Single line comment entries anything you type after // is treated as a comment. The text can’t span (extend) more than a line. If you have multiple lines as comments, you must start every line with //. // single line comment 3. The javadoc comments these lines are used by the javadoc utility to create documentation. These comments are similar o the multiple line comments but start with a /** instead of /* /** this is a javadoc comment*/ 25
  • 26. 5. DaTa TYPES • The data that’s stored in memory can be of many types. For example: * a person’s age is stored as a numeric value & an address is stored as alphanumeric characteristics. * an address is stored as alphanumeric characters Data types are used to define the operations possible on them and the storage method. * The data types in java are classified as: 1. primitive (or) standard data types 2. Abstract (or) derived data types 26
  • 27. 1. primitive (or) standard data types Data Type Size/Format Description Range (Numbers) Byte 8-bit Byte-length -128 to +128 integer If signed(-2 7 to 27 -1) If unsigned(0 to 255) Short 16-bit Short integer -32768 to +32767(-215 to 215-1) Int 32-bit Integer -231 to 231-1 27
  • 28. Data Type Size/Format Description Range (Numbers) long 64-bit Long integer -2 63 to 2 63-1 float 32-bit Single- +/-about 10 39 precision floating point double 64-bit Double- +/-about 10 317 precision floating point (other types) Char 16-bit A single character Boolean 1-bit A Boolean value (true or false) 28
  • 29. 2. Abstract (or) derived data types • Abstract data types are based on primitive data types and have more functionality than primitive data types. • Example “String” is an abstract data type that can store letters, digits and other characters like /,(), : , ; , $ , # * “String ”provides methods for concatenating two strings, searching for one string within another, and extracting a portion of a string. The primitive data types don’t have these features. 29
  • 30. 6. METhODS 1. parameters • A method is a body of code that’s used for performing a set of tasks. The behavior of an object is determined by the program. • Declaring Methods: syntax: [<access_specifier>] [<modifiers>] <return_type> <method_name> ([argument_list]) { //statements } 30
  • 31. • Example: public static int abc (int a, int b, int c) { return a+b*c+b/c; } Where: abc - name of the method int - return type of the method is ‘int’ (int a, int b, int c) – formal paramenters of the method abc, each is of integer type. 31
  • 32. • If the method is invoked by the statement Z = abc (2,x,y) then 2,x,y are the ‘actual parameter’. * when the method ‘abc’ is invoked the a - is assigned to 2 b - is assigned to x c - is assigned to y * In java all method parameters are ‘value parameters’. * At run time the value of each ‘actual parameter’ is copied into the corresponding format parameter before the method is executed. 32
  • 33. 2. Overloaded methods • Overloading is a technique in which more than one method having the same name can be present in a program. The compiler resolves the method to be invoked using the signature of the method. • Function signature 1. The name of the method 2. The number of arguments it takes 3. The data type of the arguments 4. The order of the arguments - when we call a method, the compiler uses the signature of the method to resolve the method to be invoked. - A class can’t have two methods having the same signature. 33
  • 34. - this is because the compiler will not know which method to invoke if more than one method has the same signature. Example: java supports method overloading and hence, the methods can be declared as follows: * public void add(int a, int b); // add two integers * public void add(float a, float b); // add two floats * public void add(float a, int b); // adds a float and an integer * In the following example the ‘calculator’ class, the methods have the same name but different parameters and the signatures of the methods are different. 34
  • 35. class calculator { public int add(int a, int b) { System.out.println("int and int"); return a + b; } public float add(float a, float b) { System.out.println("float and float"); return a + b; } 35
  • 36. public float add(float a, int b) { System.out.println("float and int"); return a + b; } public static void main(String args[]) { calculator c = new calculator(); System.out.println(c.add(1,10)) System.out.println(c.add(1.6f,10.5f)); } } 36
  • 37. 37
  • 38. class calculator { public int add(int a, int b) { System.out.println("int and int"); return a + b; } public float add(float a, float b) { System.out.println("float and float"); return a + b; } 38
  • 39. public float add(float a, int b) { System.out.println("float and int"); return a + b; } public static void main(String args[]) { calculator c = new calculator(); System.out.println(c.add(1,10)) System.out.println(c.add(1.6f,10.5f)); System.out.println(c.add(10.5f,2)); } } 39
  • 40. 40
  • 41. 7. EXCEPTIONS • An exception is defined as an ‘abnormal’ event that occurs during program execution and disturb the normal flow of instructions. • Error-handling becomes necessary, when developing applications and need to take care of unexpected situations. • The unexpected situations that may occur during program execution are: * Running out of memory * Resource allocation errors * Inability to find files * Problems in network connectivity 41
  • 42. Exception-Handling Techniques • When an unexpected error occurs in a method, java creates an object of the types ‘ Exception’. • After creating the Exception object, java sends it to the program, by an action called “throwing an exception”. • The Exception object contains information about the - type of error - status of the program when the exception occurred * Key words in Excepting: try catch throw throws 42
  • 43. • Try Block syntax: try { //statements that may cause an exception } * If an exception occurs within the try block, the appropriate exception-handler that’s associated with the try block handles the exception. * A try block must have at least one catch block that follows it immediately. 43
  • 44. • catch Block syntax: try { //statements that may cause an exception } catch(……) { // error handling routines } • The catch statement take the object of the exception class that refers to the exception caught. • Once the exception is caught, the statements within the catch block are executed. • The scope of the catch block is based on the statement 44 in the preceding try block.
  • 45. Exception handling mechanism • In java, exception-handling facility handles abnormal & unexpected situation in a structured manner. • When an exception occurs, the java runtime system searches for an exception-handler (try-catch-block). • If a handler is not found in the current method, the handler is searched for in the ‘calling method’. • The searches goes on till the runtime system finds an appropriate exception-handler. • EXAMPLE: // derivedclass.java class baseclass { public int divide(int num1, int num2) { 45
  • 46. return num1 / num2; } } public class derivedclass extends baseclass { public int divide(int a, int b) { return super.divide(a,b); } public static void main(String args[]) { int result = 0; derivedclass d1 = new derivedclass(); 46
  • 47. try { result = d1.divide(100, 0); } catch(ArithmeticException e) { System.out.println(“Error…division by zero”); } System.out.println(“The result is: “ + result”); } } 47
  • 48. 48
  • 49. Multiple catch block - example public class trycatch { public static void main(String args[]) { int num1, num2, result = 0; num1 = 100; num2 = 0; try { result = num1/num2; } 49
  • 50. catch(ArithmeticException e) { System.out.println("Error---division by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Error----out of bounds"); } catch(Exception e) { System.out.println("some other error"); } System.out.println("The result is: " + result); } } 50
  • 51. 51
  • 52. EXAMPLE-2 public class trycatch { public static void main(String args[]) { int num1, num2, result = 0; num1 = 100; num2 = 4; try { result = num1/num2; } 52
  • 53. catch(ArithmeticException e) { System.out.println("Error---division by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Error----out of bounds"); } catch(Exception e) { System.out.println("some other error"); } System.out.println("The result is: " + result); } } 53
  • 54. 54
  • 55. throw statement • When a user enters a wrong login-ID (or) password, the throw statement is used to throw an exception. • The throw statement takes a single statement, which is an object of the ‘Exception class’. • Syntax throw Throwableinstance; * Example throw ThrowObject; • The compiler gives an error if the object ‘ThrowObject” doesn’t belong to a valid ‘Exception class’. • The ‘throw statement is commonly used in ‘programmer-defined’ exceptions. 55
  • 56. throws statement • Throws statement is used to specify that ‘ an exception has to be handled by the calling method. It’s used for an exception that a method is capable of raising, but not handling. • Syntax [<access_specifier>][<modifier>]<return_type> <method_name> (<arg_list>) [throws <exception_list>] • Example public void acceptpassword() throws IllegalAccessException { System.out.println(“ intruder !!”); throw new IllegalAccessException; } 56
  • 57. Finally Block • The finally block is used when it’s necessary to process certain statements no matter, whether an exception is raised or not. • Example try { openFile(); writeFile(); // may cause an exception } catch(……..) { // process the exception } Finally { closeFile(); 57 }
  • 58. Common exceptions 1. ArithmeticException Exception 2. NullPointerException Exception 3. ArrayIndexOutofBoundsException Exception 58
  • 59. 8. ACCESS MODIFIERS • An access specifier determines which features of a class (the class itself, the data members, and the method) may be used by the other classes. • Java supports three specifiers (or) Access Modifiers 1. public 2. private 3. Protected 4. Default 1. Public access specifier A class, data member (or) method that has a public access specifier can be accessed by any object. An inner class can’t have a public access specifier. 59
  • 60. • Syntax <access_specifier> <return_type> <method> ([argment list]) { ---------- } Example: public class employee { string empname; string empadd; public void displaydetails( ) { // place the code for displaying employee details } } 60
  • 61. 2. Private access specifier • Only object of the same class can access a variable or a method that has a private access specifier. The variables and method of the inner classes can be declared as private. • Example: private int privateVariable; 3. Protected access specifier variable, methods, and inner classes that are declared protected accessible to the subclasses of the class in which they are declared. Example: protected int protectedVariable 61
  • 62. 4.Default access A class, a variable or a method that doesn’t have an access specifier as private, public, protected is said to have default access. These classes, variables or methods are accessible to all the classes of a package. Example: consider following set of classes y and z inherit from class x. class z belongs to the package p1 and classes x and y belong to the package p2. Package p1 Class X Package p2 Class Z Class Y 62
  • 63. * A method accesme() has been declared in class X. The following table shows the accessibility of the method accessme() from class Y and Z. Access specifier Class X Class Y accessme() is Accessible as Y is Accessible as z is declared as a subclass a subclass (even protected if it’s in another class) accessme() is Accessible as it is Not accessible as declared without in the same it is not in the an access package same pckage speicifer 63
  • 64. Access Specifier Member Visibility Default Member is visible only to classes in the same package. Private Member is visible only within the class C. Protected Member is visible to all classes in the same package and to subclasses of c in other packages. Public Member is visible to all classes in all packages. 64
  • 65. MODIFIERS • Modifiers determine how the data members and methods are used in other classes and objects. • The modifiers in java: 1. static 2. final 3. abstract 4. native 5. transient 6. synchronized 7. volatile 65
  • 66. 9. INHERITANCE AND METHOD OVERRIDING • Inheritance is a situation in which a class derives a set of attributes and related behavior from a parent class. • 9.1. super classes and subclasses: * super class: super class is a class from which another class inherits properties. It share its properties with its child classes. * sub class: sub class is a class that inherits attributes and methods from a super class. 66
  • 67. • Super class some times referred to as the ‘base class’ and the subclass is referred to as the ‘derived class’. • Subclass don’t inherit the constructs of the super class. • Example: let us take the example of ‘air tickets’- it can be of two types. Confirmed and request ticket. both the tickets have a lot of common attributes. For example flight_number, date, time and destination. confirmed ticket would have a ‘seat number’, while a request ticket would have a ‘status’. 67
  • 68. • Example: Ticket RequestTicket ConfirmedTicket Syntax: public class <subclass name> extends <superclass name> public class confirmedTicket extends Ticket 68
  • 69. Final keyword • The final modifier doesn’t allow a class to be inherited. A method declared anal can’t be overridden by a subclass. • Final- keyword can prevent people from extending a class by using the ‘final’ modifier as follow: example: final class password { -------- } 69
  • 70. OVERRIDING METHODS • In overridding, a subcalss method overrrides the definition of a super class method, if the method defined in the subcalss has the same signature of a method in the super class. • Example: let us consider the class ‘wheelchair’ is derived from the ‘chair class’. Both the classes have a method called ‘adjustHeight()’. Wheelchair is adjusted differently form the way other chairs are adjusted. Therefore, the wheelchair class overrides superclass method ‘adjustHeight()’. 70
  • 71. // declaring base class chair (saved as wheelchair.java) class chair { public void adjustHeight() { System.out.println(“adjusting chair height”); } } //deriving wheelchair class from chair public class wheelchair extends chair { public static void main (String args[]) { wheelchair w w = new wheelchair(); w.adjustHeight(); } } 71
  • 72. 72
  • 73. // declaring base class chair (saved as wheelchair.java) class chair { public void adjustHeight() { System.out.println(“adjusting chair height”); } } //deriving wheelchair class from chair public class wheelchair extends chair { //overriding adjustHeight() method public void adjustHeight() { System.out.println(“adjust wheelchair height”); } 73
  • 74. public static void main (String args[]) { wheelchair w w = new wheelchair(); w.adjustHeight(); } } 74
  • 75. 75
  • 76. 10. GENERIC METHODS * The following two programs differ only in the data types of the formal parameters & the return value. Program-1: Public static int abs(int a, int b, int c) { return a+b*c+b/c; } Program-2: Public static float abc(float a, float b, float c) { return a+b*c+b/c; } 76
  • 77. • Write a new version of the code for every data type of the formal parameters & return value – we can write a ‘generic code that’s independent of this data type. • It’s not possible to write generic methods to work with actual parameters of any of java primitive data types. • Generic methods can be written to work with actual parameters of the type object (or) any subclass of object. • Example: generic methods will work with the wrapper classes of java, because these wrapper classes are subclasses of ‘object’. 77
  • 78. wrapper classes • A wrapper class extends the functionality of the primitive data types. It allows an object to be created from a primitive data type. • Variables that are declared using ‘primitive data types’ aren’t objects. • To make primitive types to behave like objects, theses wrapper classes also provide methods for converting strings to various data types. • Example: represent a set of primitive data types like ‘int’, it can be done in at least two way: 1) create an array of actual size: int x[] = {10,20,30}; 78
  • 79. 2) the other way is to use a wrapper class: Integer x[] = {new integer(10), new Integer(20), new Integer(30)}; • In terms of speed & memory space, the first statement is more efficient for representing a set of values. • The wrapper classes in java.lang are: s.no. Primitive data types Wrapper classes 1. byte Byte 2. char Char 3. int Int 4. long Long 5. float Float 6 double Double 7. boolean Boolean 8. short Short 79
  • 80. INTERFACE • An interface contains constant values and method declarations. The difference between a class and interface is that the methods in an interface are only declared and not implemented. • Interfaces are used to define a ‘behavior protocol’ (standard behavior) that can be implemented by any class anywhere the class hierarch. • Syntax: An interface is declared like a class, but the keyword ‘class’ is replace by the keyword ‘interface’. The declaration of an ‘interface’ is shown below: public interface interfaceName // interface declaration { // interface body } 80
  • 81. • Example: public interface color { final int white = 0; final int black = 1; final int red = 2; } • Example: consider the devices TV & VDU, both of them require a common functionality as far as brightness control is concerned. This functionality can be provided by implementing an interface called “Brightnesscontrol” which is applicable for both the devices. 81
  • 82. // interface definition of Brightnesscontrol public interface BrightnessControl { void increaseBrightness(); void decreaseBrightness(); } // TV class implementing the interface public class TV implements Brightnesscontrol { void increaseBrightness() { // implementation code } 82
  • 83. void decreaseBrightness() { // implementation code } } //VDU class implementing the interface public class VDU implements BrightnessControl { void increaseBrightness() { // implementation code } 83
  • 84. Void increaseBrightness() { // implementation code } } 84
  • 85. Steps for implementing an Interface 1. Import the interface 2. Declare the class and use the implement keywords followed by the name of the interface. 3. Ensure that the class implements every method that has been declared in the interface. 4. Save the file with the .java extension. 5. Compile the applet or application created. 85
  • 86. Example program // implementinterface.java // example of an interface Import java.lang.*; { public String displayText(); // no implementation of method } public class implementinterface implements inter { implementinterface inter = new implementinterface(); String str = inter.displayText(); System.out.println(str); } 86
  • 87. public String displayText() { return “ Good Morning”; } } Out put: Good Morning 87
  • 88. 11. GARBAGE COLLECTION • When a program stops referencing an object the object is not required any more and becomes garbage. Garbage collection is a process that automatically frees the memory of objects that are no more in use. • Garbage collector must do two things: 1. Detect garbage objects 2. De-allocate the memory of garbage objects and make it available to the program. • There are different garbage collection algorithms (or) there are different approaches used for detecting garbage objects are as follows: * Reference-counting garbage collectors – keep a count of the references for each live object. 88
  • 89. *Tracing collectors (or) mar-and-sweep algorithm - the mark phase marks all the referenced objects. The sweep phase collects the memory of unreferenced objects. * Compacting collectors - reduce fragmentation of memory by moving all the free space to one side during action. * Adaptive algorithm - monitors the situation and uses the garbage techniques that best suits the situation. The finalize( ) method - before freeing the memory associated with an object, the garbage runs the ‘finalize() method’. 89
  • 90. • Finalize method is declared in any class. The finalize() method is declared as follows: protected void finalize() throws Throwbale { super. finalize( ); } * Garbage collector is called manually using the ‘system.gc ( ) method.’ 90
  • 91. 12. RECURSION • Recursive method invokes itself. There are two types of recursions (i) Direct recursion - the code for method ‘ f ‘ contains a statement that invokes ‘ f ’. (ii) Indirect recursion - method ‘ f ‘ invokes a method ‘ g’ , which invokes a method ‘h’. and so on, until method ‘ f ‘ is again invoked. 12.1.Recursive Functions The factorial function is defined as follow: f(n) = 1 n<=1 nf(n-1) n>1 This definition states that f(n) = 1 whenever n is less than or equal to 1. 91
  • 92. • When ‘ n ‘ is less than 1, f(n) is defined recursively • Example f (n) = nf(n-1); f(3) = 3*f(3-1) = 3*f(2) = 3*2 = 6 • For a recursive definition of f(n), the f must meet the following requirements: * The definition must include a base component in which f(n) is defined directly, (i.e. non-recursively) for one or more values of n. e.g. from the above equation the base is f(n) = 1 for n<=1 * In the recursive component all occurrence of ‘f’ on the right side should have a parameter smaller than ‘n’, so that repeated application of the recursive component transforms all occurrences of ‘f’ on the right side. 92
  • 93. repeated application of the recursive components transforms f(n-1) to f(n-2), f(n-3)……. and finally f(1). (e.g) repeated application of the recursive component gives the following: f(5)=5f(4)=20f(3)=60f(2)=120f(1)=120 i.e. f(5)=120 12.2.Induction • In a proof by induction, the validity of claim is established as follow: n ∑ i=n(n+1)/2, n>=0 i=0 • This method has three components to make a proof 1. induction base 2. induction hypothesis 93 3.induction step
  • 94. • 12.3.Recursive Methods a proper recursive method must include a base component. Public static int factorial(int n) { if ( n < = 1) return 1; else return n * factorial (n-1); } 94
  • 95. 13. TESTING AND DUBUGGING 13.1. what is testing Correctness is the most important attributes of a program. * program Testing: providing mathematical proof of correctness for a small program is difficult. • Test data: - compare the program behavior with the expected behavior. - if these two behaviors are different program having problem. 95
  • 96. - if these two behaviors are same also, we couldn’t conclude that the program is correct, if the behavior isn’t same on other input data. • Test data: (Definition) Execute the program on the target computer using input data is called “Test Data”. • Test Set: The subset of the input data space that’s actually used for testing is called the “Test set”. Example: (Quadratic Roots) A Quadratic function (or) quadratic in x is a function that has a form ax2 + bx + c 96
  • 97. where a, b, c - real numbers and a = 0 examples for quadratic not a quadratic functions functions 3x2-2x+4 -9x2-7x 5x+3 3.5x2+4 5.8x2+3.2x+5 The roots of a quadratic function are the values of ‘x’ at which the function value is 0. 97
  • 98. • Example: (1) f(x) = x2-5x+6 if x = 2 f(2) = 22 -(5*2)+6 = 4 -(5*2)+6 = 4-10+6 = -6+6 = 0 (2) f(x) = x2-5x+6 if x = 3 f(2) = 32 -(5*2)+6 = 9 -(5*3)+6 = 9-15+6 = -6+6 = 0 98
  • 99. • Every quadratic has exactly two roots, and these roots are given by the following formula: -b + b2 – 4ac ____________________ 2a if the function f(x) = x2-5x+6 and a=1, b=-5, c=6 then = -(-5) + -52 – 4*1*6 ___________________ 2*1 =5+1 5–1 2 ; 2 f(x) = (3,2) 99
  • 100. Designing Test data • Objectives of Testing expose the presence of error • Correctness of the programs depends on – if the designed data fails to expose errors. • Example: Quadratic Roots - behavior of any test data may be verified in one of two ways: first: find out the roots of the test quadratic (e.g) before slide (a, b, c) = (1, -5, 6) 100
  • 101. second: - substitute the roots(answers(3,2)) produced by the program into the quadratic function. -and verify the function value is 0 Example: f(x) = x2-5x+6 (i) If f(3) = 32-5*3+6 (ii) if f(2) = 22-5*2+6 = 9 – 5*3+6 = 4-5*2+6 = 9-15+6 = 4-10+6 = -6 + 6 = -6+6 = 0 = 0 101
  • 102. Data Testing Techniques • There are two categories in data testing techniques (i) Black Box Method (ii) White Box Method (i) Black Box Method while developing test data, consider only program’s function, not the actual code. * the most popular black box methods are I/O partitioning cause-effect graphing * In I/O partitioning the input and output data are partition into classes. * Data in different classes cause the program to exhibit qualitatively different behaviors. * Data in same class cause qualitatively similar102 behaviors.
  • 103. • Example: The quadratic roots has three different qualitatively behaviors: 1. the roots are complex 2. the roots are real and distinct 3. the roots are real and the same. Each behaviors has different kinds of behaviors. (ii) White Box Method while developing test data, consider only program’s actual code. * Statement coverage: the weakest condition we can place on a test set, will execute the program statement at least once. 103
  • 104. • Decision coverage the test set cause each condition in the program to take on both true and false values. • Clause coverage strengthen the decision coverage criterion to require each clause of each condition to take on both true and false values. The strengthen criterion is called “ clause coverage”. clause it is defined as Boolean expression that contains no Boolean operator (i.e., &&, ||, ! ). (e.g) x > y, x + y < y * z 104
  • 105. Debugging • The process of determining and correcting the difference between the desired and observed behaviors is called “ debugging”. • Suggestions for debugging: 1. Try to determine an error by logical reasoning. 2. Errors should be corrected first by determining their cause and then redesigning your solutions as necessary. 3. After corrected an error, the correction doesn’t result an errors. 4. When testing and debugging a multi-method program, begin with a single method that’s independent.This method is typically i/p & o/p method. Then introduce additional methods one at at a time. This is called as “ incremental testing & 105
  • 106. USER DEFINED PACKAGE PROGRAM 106
  • 107. Design and develop a Package in Java which contains following Sorting techniques a) Bubble Sort b) Selection Sort c) Shell Sort 107
  • 108. Steps in creating “ User Defined Program” Step -1 : Create a folder name of your User defined package in the path, where the java is installed Example: ►Create a Folder Name “BUBBLE” ► Click the Folder (BUBBLE) and save your java file name (bubblesort.java) ► Click the Folder (SELECTION) and save your java file name (selectionsort.java) ►Create a Folder Name “SHELLSORT” ► Click the Folder (SHELLSORT) and save your java file name (shellsort.java) Step-2: Creation of Main Program Example: ►save the main program (sort.java) in the bin path (e.g: C:Program FilesJavajdk1.5.0bin> 108
  • 109. // package for bubble sort package BUBBLE; import java.io.*; public class bubblesort { int a[]=new int[10]; int n,t; InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); public void bdisplay() { try { System.out.println("n--->BUBBLE SORT<----n"); System.out.println("Enter N values to sort.."); n=Integer.parseInt(br.readLine()); System.out.println("Enter" + n + "Value one by one.."); for(int i=1; i<=n; i++) 109
  • 110. { a[i] = Integer.parseInt(br.readLine()); } System.out.println("n Before Sortingn"); for(int i=1; i<=n; i++) { System.out.println(a[i]+ " "); } for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { if(a[j]>a[j+1]) a[j]=(a[j]+a[j+1])-(a[j+1]=a[j]); } } 110
  • 111. System.out.println("n After Sortingn"); for(int i=2; i<=n+1; i++) { System.out.println(a[i] + " "); } } catch(Exception e) { System.out.println("Cause Error.."); } } } 111
  • 112. // package for Selection sort package SELECTION; import java.io.*; public class selectionsort { int a[]=new int[10]; int n,t; InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); public void sdisplay() { try { System.out.println("n--->SELECTION SORT<----n"); System.out.println("Enter N values to sort.."); n=Integer.parseInt(br.readLine()); System.out.println("Enter" + n + "Value one by one.."); for(int i=1; i<=n; i++) 112
  • 113. { a[i] = Integer.parseInt(br.readLine()); } System.out.println("n Before Sortingn"); for(int i=1; i<=n; i++) { System.out.println(a[i]+ " "); } for(int i=1; i<=n; i++) { int min,loc; min=a[i]; loc=i; for(int j=i+1; j<=n+1; j++) { if(min>a[j]) { min=a[j]; loc=j; } 113
  • 114. a[i]=(a[i]+a[loc])-(a[loc]=a[i]); } } System.out.println("n After Sortingn"); for(int i=2; i<=n+1; i++) { System.out.println(a[i] + " "); } } catch(Exception e) { System.out.println("Cause Error.."); } } } 114
  • 115. // package for shell sort package SHELLSORT; import java.io.*; public class shellsort { int a[]=new int[10]; int n,t,incr,j; InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); public void shdisplay() { try { System.out.println("n--->SHELL SORT<----n"); System.out.println("Enter N values to sort.."); n=Integer.parseInt(br.readLine()); System.out.println("Enter" + n + "Value one by one.."); 115
  • 116. System.out.println("n Before Sortingn"); for(int i=1; i<=n; i++) { System.out.println(a[i]+ " "); } incr=n/2; while(incr>0) { for(int i=1;i<n+1;i++) { j=i; t=a[i]; while((j>incr) && (a[j-incr]>t)) { a[j]=a[j-incr]; j=j-incr; } a[j]=t; } 116
  • 117. if(incr/3!=0) incr=incr/3; else if(incr==1) incr=0; else incr=1; } System.out.println("n After Sortingn"); for(int i=1; i<=n; i++) { System.out.println(a[i] + " "); } } catch(Exception e) { System.out.println("Cause Error.."); }}} 117
  • 118. //Main Program import BUBBLE.*; import SELECTION.*; import SHELLSORT.*; class sort { public static void main(String[] args) { bubblesort bs = new bubblesort(); bs.bdisplay(); selectionsort ss = new selectionsort(); ss.sdisplay(); shellsort sh = new shellsort(); sh.shdisplay(); } } 118
  • 119. OUTPUT 119
  • 120. 120
  • 121. 121
  • 122. 122
  • 123. THANKS FOR WATHING MY - PPT PRESENTED BY KAVITHA.C.R ASST. PROFESSOR SLNCS 123