Your SlideShare is downloading. ×
0
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Java
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Java

496

Published on

This presentation is useful to the beginners in JAVA.

This presentation is useful to the beginners in JAVA.

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
496
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. UNIT - ICHAPTER – 1 java 1
  • 2. CONTENTS1. INTRODUCTION 1.1. history of java2. STRUCTURE OF JAVA PROGRAM 2.1. standard program and Applets 2.2. packages 2.3. importing classes and Packages3. THE JAVA COMPILER AND VIRUTAL MACHINE4. DOCUMENTATION COMMENTS5. 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 MODIFIERS9. INHERITANCE AND METHOD OVERRIDING 9.1. Super-classes and Subclasses10. GENERIC METHODS11. GARBAGE COLLECTION12. 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. INTRODUCTION1.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 computers9. 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 servers4. 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 membersS. No Application applet1. 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, network6. java.net - provides classes that provide network programming. 16
  • 17. 2.3. importing classes and PackagesSyntax 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 importedimport 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
  • 21. JAVA VIRUTAL MACHINE 21
  • 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 comments1.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 comment3. 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 - examplepublic 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-2public 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 exceptions1. ArithmeticException Exception2. NullPointerException Exception3. 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. Default1. 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 VisibilityDefault 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 ConfirmedTicketSyntax: 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 chairpublic 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 chairpublic class wheelchair extends chair{ //overriding adjustHeight() methodpublic 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 Interface1. Import the interface2. 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 interfaceImport 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)=12012.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 DUBUGGING13.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 0Example: 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 sortpackage 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 sortpackage 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 sortpackage 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 Programimport 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

×