Introduction to core java

674 views

Published on

Introduction to Core Java
Introduction
1.1 Features of JAVA
1.2 JDK Environment & Tools
(javac, java, appletviewer, javadoc, jdb)
Object Oriented concepts with respect to Java
Difference between C++ & JAVA
Java Programming Fundamentals
Structure of java program, data types, variables,
Operators, Keywords, Naming conventions,
Decision making statements, Iterative statements,
Type casting, Arrays (One dimensional & Multidimensional)
String (String Arrays, String Methods, StringBuffer)
1.3 Creating classes & objects
1.4 Constructors (with all types)
1.5 Garbage collection & finalize() method.
1.6 Implementation of Inheritance
Single, Multilevel, Hierarchical, Use of super keyword, super
constructor, this keyword
1.7 Implementation of polymorphism
Method overloading, Method overriding
1.8 Nested & inner classes
1.9 Modifiers & Access control (Default, public, private, protected, private protected)
1.10 Final variables, Methods & classes
1.11 Abstract methods & classes
1.12 Interfaces
1.13 Packages
Packages concept, Creating user defined package, Java built in packages (Java.lang, java.util)
1.14 Exception Handling
Exception types, Using try catch, Multiple catch,Nested try, throw, throws, finally, user defined exceptions

Published in: Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
674
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
51
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Introduction to core java

  1. 1. Java Programming Introduction to Core Java Prof. Shailesh Gahane Assistant Professor Dr. D. Y. Patil School of MCA Charholi (Bk), Lohegaon, Pune – 412105 Mail ID: shaileshmca2007@gmail.com Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  2. 2. FEATURES OF JAVA • Simple • Secure • Portable • Object-oriented • Robust • Multithreaded • Architecture-neutral • Interpreted • High performance • Distributed • Dynamic Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  3. 3. Java was designed to be easy for the professional programmer to learn and use effectively. The object model in Java is simple and easy to extend, while primitive types, such as integers, are kept as high-performance nonobjects. The multiplatform environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of Java. Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneouslyProf. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  4. 4. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow even on the same machine. So the JAVA goal is “write once; run anywhere, any time, forever.” To a great extent, this goal was accomplished. Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network. Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  5. 5. Structure of java program class Example { // Your program begins with a call to main(). public static void main(String args[]) { System.out.println("This is a simple Java program."); } } Call this file "Example.java“ Compiling the Program C:>javac Example.java C:>java Example When the program is run, the following output is displayed: This is a simple Java program. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  6. 6. Two Control Statements The if Statement The Java if statement works much like the IF statement in any other language. Further, it is syntactically identical to the if statements in C, C++, and C#. Its simplest form is shown here: if(condition) statement; if (condition) statement1; else statement2; Here, condition is a Boolean expression. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed. example: if(num < 100) System.out.println("num is less than 100"); Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  7. 7. The for Loop for(initialization; condition; iteration) statement; Example: class ForTest { public static void main(String args[]) { int x; for(x = 0; x<10; x = x+1) System.out.println("This is x: " + x); } } This program generates the following output: This is x: 0 This is x: 1 This is x: 2 This is x: 3 This is x: 4 This is x: 5 This is x: 6 This is x: 7 This is x: 8 This is x: 9 Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  8. 8. Nested ifs if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; // this if is else a = c; // associated with this else } else a = d; Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune The if-else-if Ladder if(condition) statement; else if(condition) statement; else if(condition) statement; ... else statement;
  9. 9. switch The general form of a switch statement: switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break; ... case valueN: // statement sequence break; default: // default statement sequence } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  10. 10. EX: // A simple example of the switch. class SampleSwitch { public static void main(String args[]) { for(int i=0; i<6; i++) switch(i) { case 0: System.out.println("i is zero."); break; case 1: System.out.println("i is one."); break; case 2: System.out.println("i is two."); break; case 3: System.out.println("i is three."); break; default: System.out.println("i is greater than 3."); } } } The output produced by this program is shown here: i is zero. i is one. i is two. i is three. i is greater than 3. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  11. 11. Iteration Statements while The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true. Here is its general form: while(condition) { // body of loop } // Demonstrate the while loop. class While { public static void main(String args[]) { int n = 10; while(n > 0) { System.out.println("tick " + n); n--; } } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  12. 12. do-while it is desirable to execute the body of a loop at least once, even if the conditional expression is false. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is do { // body of loop } while (condition); // Demonstrate the do-while loop. class DoWhile { public static void main(String args[]) { int n = 10; do { System.out.println("tick " + n); n--; } while(n > 0); } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  13. 13. The Java Keywords The JAVA keywords cannot be used as names for a variable, class, or method. abstract ,continue ,for, new, switch, assert ,default, goto, package, synchronized, boolean, do, if, private, this,break, double, implements, protected, throw, byte, else, import, public, throws,case, enum, instanceof ,return, transient,catch, extends, int, short, try,char, final, interface, static, void,class, finally, long, strictfp, volatile,const, float, native, super, while. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  14. 14. Data Types in JAVA The Primitive Types Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups: • Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers. • Floating-point numbers This group includes float and double, which represent numbers with fractional precision. • Characters This group includes char, which represents symbols in a character set, like letters and numbers. • Boolean This group includes boolean, which is a special type for representing true/false values. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  15. 15. Name Width Range long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 int 32 –2,147,483,648 to 2,147,483,647 short 16 –32,768 to 32,767 byte 8 –128 to 127 Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune class Light { public static void main(String args[]) { int lightspeed; long days; long seconds; long distance; // approximate speed of light in miles per second lightspeed = 186000; days = 1000; // specify number of days here seconds = days * 24 * 60 * 60; // convert to seconds distance = lightspeed * seconds; // compute distance System.out.print("In " + days); System.out.print(" days light will travel about "); System.out.println(distance + " miles."); } } This program generates the following output: In 1000 days light will travel about 16070400000000 miles.
  16. 16. Floating-Point Types Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune Name Width in Bits Approximate Range double 64 4.9e–324 to 1.8e+308 float 32 1.4e–045 to 3.4e+038 float The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors. float hightemp, lowtemp; double Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions,
  17. 17. Characters In Java, the data type used to store characters is char. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. In Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always. // Demonstrate char data type. class CharDemo { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); } } This program displays the following output: ch1 and ch2: X Y Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  18. 18. Booleans Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if and for. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  19. 19. Variables The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. Declaring a Variable type identifier [ = value][, identifier [= value] ...] ; Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  20. 20. Type Conversion and Casting Java’s Automatic Conversions When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: • The two types are compatible. • The destination type is larger than the source type. When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required.Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  21. 21. Casting Incompatible Types To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form: (target-type) value For Example: int a; byte b; ------- ------- b = (byte) a; Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  22. 22. Arrays An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. One-Dimensional Arrays A one-dimensional array is, essentially, a list of like- typed variables. To create an array, you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is: type var-name[ ]; Ex: int month_days[]; array-var = new type[size]; month_days = new int[12]; Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  23. 23. Declaration of an Array month_days = new int[2]; month_days[0] = 31; month_days[1] = 28; OR int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  24. 24. Multidimensional Arrays In Java, multidimensional arrays are actually arrays of arrays. int twoD[][] = new int[4][5]; This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int. // Demonstrate a two-dimensional array. class TwoDArray { public static void main(String args[]) { int twoD[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<5; j++){ System.out.print(twoD[i][j] + " "); System.out.println(); } } } } This program generates the following output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  25. 25. Operators operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  26. 26. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune Operator Result + Addition – Subtraction (also unary minus) * Multiplication / Division % Modulus ++ Increment += Addition assignment –= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment – – Decrement
  27. 27. Bitwise Operators Java defines several bitwise operators that can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  28. 28. Relational Operators The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  29. 29. Boolean Logical Operators The Boolean logical operators shown here operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  30. 30. Introducing Classes A class is declared by use of the class keyword. A simplified general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  31. 31. /* A program that uses the Box class. Call this file BoxDemo.java */ class Box { double width; double height; double depth; } class BoxDemo { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // compute volume of first box vol = mybox1.width * mybox1.height * mybox1.depth; System.out.println("Volume is " + vol); // compute volume of second box vol = mybox2.width * mybox2.height * mybox2.depth; System.out.println("Volume is " + vol); } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  32. 32. Constructors Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. A Constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the Constructor is automatically called immediately after the object is created, before the new operator completes. Constructors look a little strange because they have no return type, not even void. This is because the implicit return type of a class’ constructor is the class type itself. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  33. 33. Example: class Box { double width; double height; double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  34. 34. Parameterized Constructors // This is the Parameterized Constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } The this Keyword Java defines the this keyword. this can be used inside any method to refer to the current object. this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class type is permitted. Example: // A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  35. 35. The finalize( ) Method Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non- Java resource such as a file handle or character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  36. 36. The finalize( ) method has this general form: protected void finalize( ) { // finalization code here } Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  37. 37. Overloading Methods Method overloading is one of the ways that Java supports “Polymorphism”. In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Overloaded methods must differ in the type and/or number of their parameters. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  38. 38. // Demonstrate method overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  39. 39. Overloading Constructors class Box { double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } class OverloadCons { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  40. 40. // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } } The output produced by this program is shown here: Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0 Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  41. 41. Access Specifiers (Modifiers) 1. public 2. private 3. protected 4. default (friendly) public access modifier Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  42. 42. private access modifier The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. protected access modifier Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not aProf. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  43. 43. friendly access modifier () When no access modifier is specified the class member has the friendly access bydefault . The public modifier is visible in anywhere but in case of Friendly, It can be visible in same package but not in other package. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  44. 44. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune /* This program demonstrates the difference between public and private. */ class Test { int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) { // set c's value c = i; } int getc() { // get c's value return c; } } class AccessTest { public static void main(String args[]) { Test ob = new Test(); // These are OK, a and b may be accessed directly ob.a = 10; ob.b = 20; // This is not OK and will cause an error //ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); } }
  45. 45. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune ACCESS MODIFIERS PUBLIC PROTECTED DEFAULT (FRIENDLY) PRIVATE ACCESS LOCATION SAME CLASS YES YES YES YES SUBCLASS IN SAME PACKAGE YES YES YES NO OTHER CLASSES IN SAME PACKAGE YES YES YES NO SUBCLASS IN OTHER PACKAGES YES YES NO NO NON SUBCLASSES IN OTHER PACKAGES YES NO NO NO
  46. 46. Abstract Classes and Methods Abstract Methods: These are opposite to final methods. Abstract methods must be compulsorily overridden in a sub class. Syntax of abstract method: Access_Modifier abstract datatype MethodName(parameter list); Syntax of abstract class: abstract class Class_Name { } Abstract classes are act as a super classes and these are the classes from which instances can not be created. Methods in an interface that are not declared as default or static, they are implicitly abstract, so the abstract modifier is not used with interface methods. We can not declare abstract constructor or abstract static methods.Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  47. 47. // A Simple demonstration of abstract. abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.println("This is a concrete method."); } } class B extends A { void callme() { System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { B b = new B(); b.callme(); b.callmetoo(); } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  48. 48. final variable or method If you want to prevent the members of superclass from being overridden in the subclasses then declare them as final using the keyword final as a modifier. Variable of a class can be declared as final indicating that the value of that particular variable cannot be changed. Ex: final int a =10; Local variable can not be declared as final variable. Methods can be declared final indicating that they can be overridden in subclasses. It ensures that the functionality defined in this method will never be altered in anyway. Ex: final void display () { ___________ } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  49. 49. Interfaces • Using interface, we can fully abstract a class interface from its implementation. • Using interface, we can specify what a class must do. • Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. • Once it is defined, any number of classes can implement an interface. • One class can implement any number of interfaces. • To implement an interface, a class must create the complete set of methods defined by the interface. • Each class is free to determine the details of its own implementation. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  50. 50. Defining interface access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; // ... return-type method-nameN(parameter-list); type final-varnameN = value; } Access can be public or default The methods which are declared have no bodies(abstract). They end with a semicolon after the parameter list. Each class that includes an interface must implement all of the methods. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  51. 51. • Variables can be declared inside of interface declarations. They are implicitly final and static, means they cannot be changed by the implementing class. • Variables must also be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public. interface Callback { void callback(int param); } • Once an interface has been defined, one or more classes can implement that interface. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  52. 52. • To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface access class Classname [extends superclass][implements interface [,interface...]] { // class-body } • access is either public or not used. • If a class implements more than one interface , the interfaces are separated with a comma. • Note: When you implement an interface method, it must be declared as public. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  53. 53. • Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition interface Callback { void callback1(int param); } class Client implements Callback { public void callback1(int p) { System.out.println("callback1 called with " +p); } } class TestIface { public static void main(String args[]) { Client c = new Client(); c.callback1(42); } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  54. 54. Packages • Till now all java classes were stored in same name space. • As the applications grows it becomes difficult to keep all the files in same directory, also we need to ensure that the name we choose should be unique. • To address this problem java introduces a mechanism to manage all the classes this is called Packages. • Packages are containers for classes that are used to keep the class name space separately. • It is both a naming and a visibility control mechanism.Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  55. 55. • To create a package simply include a package command as the first statement in a Java source file. • Any classes declared within that file will belong to the specified package . • The package statement defines a name space in which classes are stored. • If we omit the package statement, the class names are put into the default package, which has no name • General form of the package statement: package package_name; Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  56. 56. • Java uses file system directories to store packages. • More than one file can include the same package statement. Importing Packages • To create package hierarchy separate each package name from the one above it by use of a period. • In java all of the standard classes are stored in some named package. • If we need use some classes from different package we should import that package using import statement . Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  57. 57. • Once imported, a class can be referred to directly, using only its name. • To specify either an explicit classname or a star (*), which indicates that the Java compiler should import the entire package. Syntax: import pkg1[.pkg2].*; import pkg1.class_name; Ex: import java.awt.image; import java.awt.*; import java.util.Date; import java.io.*; Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  58. 58. Exception Handling  An Exception is an abnormal condition that occurs during the execution of a program.  Types of Errors:  Compile Time Errors  Mismatch of Brackets  Missing Semicolons  Use of undeclared variables  Run Time Errors  dividing an Integer by Zero  Trying to illegally change the state of the thread.  Exception Types:  ArithmaticException  ArrayIndexOutOfBoundsException  EOFException  NumberFormatException Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  59. 59. Exceptions  An exception is a representation of an error condition or a situation that is not the expected result of a method.  Exceptions are built into the Java language and are available to all program code.  Exceptions isolate the code that deals with the error condition from regular program logic.  Exceptions fall into two categories:  Checked Exceptions  Unchecked Exceptions  Checked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program execution  Checked exceptions must be handled in your code, orProf. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  60. 60.  Unchecked exceptions represent error conditions that are considered “fatal” to program execution.  You do not have to do anything with an unchecked exception. Your program may be terminate with an appropriate error message.  Examples:  Checked exceptions include errors such as “array index out of bounds”, “file not found” and “number format conversion”.  Unchecked exceptions include errors such as “null pointer”. Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  61. 61. Throws and Throw Whenever a program does not want to handle exception using try block, it can use the throws clause. This throws clause can handle the different types of exceptions generated by the program. throw statement is used to explicitly throw an exception. Ex: class Throw1 { public static void main(String Args[]) throws ArithmeticException { System.out.println(“ n 1. Inside main Fuction”); Int i=0,j; j=6/i; System.out.println(“ n 2. Second statement of main fuction”); } } Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune
  62. 62. Thank you !!! Prof. Shailesh T. Gahane, Dr. D Y Patil School of MCA, Pune Prof. Shailesh Gahane Assistant Professor Dr. D. Y. Patil School of MCA Charholi (Bk), Lohegaon, Pune – 412105 Mobile No: +91-9960886053

×