Sunteți pe pagina 1din 55

http://docs.oracle.com/javase/tutorial/index.html http://www.learn-java-tutorial.com/JavaIntroduction.cfm#.URSpjfJgUbY http://tutorials.jenkov.com/java/index.html http://www.tutorialspoint.com/java/index.htm http://www.javatpoint.

com/ Java Basic Syntax When we consider a Java program it can be defined as a collection of objects that communicate via invoking each others methods. Let us now briefly look into what do class, object, methods and instant variables mean.

Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support. Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instant Variables - Each object has its unique set of instant variables. An object's state is created by the values assigned to these instant variables.

About Java programs, it is very important to keep in mind the following points.

Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different meaning in Java. Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class each inner words first letter should be in Upper Case. Example class MyFirstJavaClass Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void myMethodName() Program File Name - Name of the program file should exactly match the class name. When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile). Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java' public static void main(String args[]) - java program processing starts from the main() method which is a mandatory part of every java program..

Java Variables: A Java variable is a piece of memory that can contain a data value. There are two fundamental categories of variables, primitive data and references:

With primitive data, the compiler names a memory location and uses itto store the actual data - numeric values such as integers, floating point values, and the code values of single individual text characters are stored as primitives. With references, the data is accessed indirectly - the compiler selects a memory location, associates it with the variable name, and stores in it a value that is effectively the memory address of the actual data - in Java, all objects and arrays are stored using references.

In the diagram below, the boxes are areas in memory:

Variable Declaration: The basic form of a variable declaration is shown here: type identifier [ = value][, identifier [= value] ...] ; The type is one of Java's datatypes. The identifier is the name of the variable. To declare more than one variable of the specified type, use a comma-separated list. Here are several examples of variable declarations of various types. Note that some include an initialization. int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing d and f. char x = 'x'; // the variable x has the value 'x'. Here are examples of how to declare variables of all the primitive data types in Java: byte myByte;--------8 bit(1 byte) short myShort;-------16 bit char myChar;--------16 bit

int myInt;---------32 bit long myLong;--------64 bit float myFloat;-------32 bit double myDouble;------64 bit Here are examples of how to declare variables of the object types in Java: Byte myByte; Short myShort; Character myChar; Integer myInt; Long myLong; Float myFloat; Double myDouble; String myString; The following chart summarizes the default values for the above data types. Data Type byte short int long float double char boolean Default Value (for fields) 0 0 0 0L 0.0f 0.0d '\u0000' false

String (or any object) null

In Java there are four types of variables: Non-static fields Static fields Local variables Parameters Instance Variables (Non-Static Fields) Objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class Instance variables are declared in a class, but outside a method, constructor or any block. Instance variables can be declared in class level before or after use. Access modifiers can be given for instance variables. The instance variables are visible for all methods, constructors and block in the class..

Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) they should be called using the fully qualified name . ObjectReference.VariableName.

Example: public class Employee{ // this instance variable is visible for any child class. public String name; // salary variable is visible in Employee class only. private double salary; // The name variable is assigned in the constructor. public Employee (String empName){ name = empName; } // The salary variable is assigned a value. public void setSalary(double empSal){ salary = empSal; } // This method prints the employee details. public void printEmp(){ System.out.println("name : " + name ); System.out.println("salary :" + salary); } public static void main(String args[]){ Employee empOne = new Employee("Ransika"); empOne.setSalary(1000); empOne.printEmp(); } } This would produce following result: name : Ransika salary :1000.0 Class/static variables :

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value. Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Static variables can be accessed by calling with the class name . ClassName.VariableName. Static variables have default values When declaring class variables as public static final, then variables names (constants) are all in upper case.

Example: public class Employee{ // salary variable is a private static variable private static double salary; // DEPARTMENT is a constant public static final String DEPARTMENT = "Development "; public static void main(String args[]){ salary = 1000; System.out.println(DEPARTMENT+"average salary:"+salary); } } This would produce following result: Development average salary:1000 Local variables :

Local variables are declared inside methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor or block. There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.

Example: Here age is a local variable. This is defined inside pupAge() method and its scope is limited to this method only. public class Test{ public void pupAge(){ int age = 0; age = age + 7; System.out.println("Puppy age is : " + age);

public static void main(String args[]){ Test test = new Test(); test.pupAge(); } } This would produce following result: Puppy age is: 7 Parameters A parameter is a variable that is passed to a method when the method is called. Parameters are also only accessible inside the method that declares them, although a value is assigned to them when the method is called. public void writeText(String text1, String text2) { System.out.print(text1); System.out.print(text2); } Differences between STATIC and NON-STATIC variables Static Variables Defined at Class Level Static Variables are initialized ,loaded with Class itself. A static variable is shared among all instances of a class. There is only one copy of static variable and even when the class is instantiated, the value remains the same. It can be accessed directly by the class without object. Static variables by calling with the class name. ClassName.VariableName. Non-Static Variables Defined at Instace/Object Level. Instance variable initialized when Object for that Class is instantiated. A non-static variable is specific to a single instance of that class. Every time the class is instantiated, the object has their own copy of these variables.

It cannot accessed directly without its class reference.(Object) Non Static variables by called using the Object name. ObjectReference.VariableName.

EXAMPLE: public class DifferenceBetweenStaticAndNonStatic { static int count = 0; private int count1 = 0; public DifferenceBetweenStaticAndNonStatic(){

count1 = count1+1; } public int getCount1() { return count1; } public void setCount1(int count1) { this.count1 = count1; } public static int countStaticPosition() { count = count+1; return count; /* * one can not use non static variables in static method.so if we will * return count1 it will give compilation error. return count1; */ } } public class StaticNonStaticCheck { public static void main(String[] args){ for(int i=0;i<4;i++) { DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic(); System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count); System.out.println("static count position is " +p.getCount1()); System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition()); System.out.println("next case: "); System.out.println(" "); } } Now output will be::: static count position is 0 static count position is 1 static count position is 1 next case: static count position is 1 static count position is 1 static count position is 2 next case: static count position is 2 static count position is 1 static count position is 3 next case:

What is a Static Method? In object oriented programming, static method is a method that is associated with a class. Therefore, static methods do not have the capability to operate on a particular instance of a class. Static methods can be invoked without using an object of the class that contains the static method. Following is an example of defining a static method in Java. The static has to be used when defining a static method in Java. public class MyClass { public static void MyStaticMethod() { // code of the static method } } The static method defined above could be called as follows using the name of the class it belongs to. MyClass.MyStaticMethod(); One important thing to note is that static methods can only access static members. What is a Non Static Method? A non static method or an instance method is a method that is associated with an object in a class. Therefore, non static methods are called using an object of the class in which the method is defined. A non static method can access non static members as well as static members of a class. In many object oriented languages (such as C++, C#, Java), when a non static method is called, the object that invoked the method is passed as an implicit argument (it is called the this reference). So, inside the method this keyword can be used to refer to the object that called the method. Following is an example of defining an instance method in Java. public class MyClass { public void MyInstanceMethod() { // code of the instance method } } The instance method defined above could be called as follows using an object of the class it belongs to. MyClass objMyClass = new MyClass(); objMyClass.MyInstanceMethod ();

What is the difference between Static and Non Static Method? Static methods are methods that are associated with a class, whereas non static methods are methods that are associated with objects of a class. A class needs to be instantiated first to invoke a non static method, but static methods do not have this requirement. They can be simply invoked using the name of the class that holds the static method. Another important difference is that a non static method usually possesses a reference to the object that called the method and it can be accessed using the this keyword inside the method. But this keyword cannot be used in static methods since they are not associated with a particular object. Java Classes: Java classes are a mechanism used to group data (variables) and Java code (methods) together into coherent "modules". A class typically contains:

Fields Constructors Methods

Fields are variables (data) that are local to the class, or instances (object) of that class. Constructors are methods that initialize an instance of the class. Typically a constructor sets the values of fields in the given instance. Methods are operations that the class or instances of that class can perform. For instance, a method may perform an operation on input parameters, or change the value of fields kept internally in the object etc. Defining a Class All it takes to define a class in Java is this: public class MyClass { } Objects An object is: a collection of data along with the functions to work with that data A class is an object definition, containing the data and function elements necessary to create an object. An instance of an object is one object created from the class definition (the process is known as instantiation) The data and function elements are known as members. Data members are also known as fields, properties, or attributes, and function members as methods A constructor is a function that defines the steps necessary to instantiate one object of that class

Creating Objects Each of the statements has three parts 1. Declaring a Variable to Refer to an Object Variable declarations that associate a variable name with an object type. type name; 2. Instantiation: The new keyword is a Java operator that creates the object. Type name=new type; 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object. Type name=new type(values); The this Keyword The this keyword provides a reference to the current object. It is used to resolve name conflicts. Using this with a Field Class X{ String s; Public void setS(String s){ this.s=s; } } If you have a method that receives an input parameter String s, but s is already a member variable String reference. But, we can pass the local variable's value into the field s by using the this reference to resolve s as the one that belongs to this object. Using this with a constructor Use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width;

this.height = height; } ... } This class contains a set of constructors. The no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments. Java constructors Java constructors are special methods that are called when an object is instantiated. A constructor initializes the created instance. Typically the constructor initializes the fields of the object that need initialization. Constructors can also take parameters, so fields can be initialized in the object at creation time. Every class should have at least one method: the constructor. This specifies code that must run to instantiate (usually to initialize) a new object from the class definition. [modifiers] class ClassName { [modifiers] ClassName(paramType paramName, . . . ) { [code goes here] } } The name of the constructor is the the same as the name of the class. Constructors have no return type and do not return a value. They may use the standard access keywords - usually they are public (but in some circumstances involving inheritance they are sometimes protected or private). You don't have to define a constructor for a class, but if you don't define any constructor, the Java compiler will insert a default, no-argument constructor. Thus, once the class is compiled it will always at least have a no-argument constructor. If you do define a constructor for your class, then the Java compiler does not insert the default no-argument constructor into your class.

Types:

Default Constructor:- Default Constructor is also called as Empty Constructor which has no arguments andis Automatically called when we creates the object of class but Remember name of Constructor is same as name of class. Parameterized constructors Constructors that can take arguments are termed as parameterized constructors. The number of arguments can be greater or equal to one(1) Copy constructors Copy constructors define the actions performed by the compiler when copying class objects. A copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object).

It is used to create a copy of an existing object of the same class. Even though both classes are the same, it counts as a conversion constructor. Conversion constructors Conversion constructors provide a means for a compiler to implicitly create an object belonging to one class based on an object of a different type. These constructors are usually invoked implicitly to convert arguments or operands to an appropriate type, but they may also be called explicitly. The constructors can be called explicitly or implicitly.The method of calling the constructor implicitly is also called the shorthand method. example e = example(0, 50); example e(0, 50); //explicit call //implicit call

Explicit means done by the programmer. Implicit means done by the JVM or the tool , not the Programmer. For Example: Java will provide us default constructor implicitly. Even if the programmer didn't write code for constructor, he can call default constructor. Explicit is opposite to this , ie. programmer has to write . Destructor: 1. It is a member function whose name is same as the class. But preceded by a ~ (tilde) symbol. 2. It has no return type. 3. It cannot have parameters. 4. It is implicitly called when object is no longer required. 5. It is used to release the memory and close files and database conversions. Java Access Modifiers: Java classes, fields, constructors and methods can have one of four different access modifiers: private default protected public Private If a method or variable is marked as private, then only code inside the same class can access the variable, or call the method. Code inside subclasses cannot access the variable or method, nor can code from any external class. If a class is marked as private then no external class an access the class. This doesn't really make so much sense for classes though. Therefore, the access modifier private is mostly used for fields, constructors and methods.

Here is an example of a private field: public class Clock { private long time = 0; } The member variable time inside the Clock class cannot be accessed from code outside the Clock class. But code inside the class can access the time variable. For instance: public class Clock { private long time = 0; public long getTime() { return this.time; } public void setTime(long theTime) { this.time = theTime; } } In the above example the two methods getTime() and setTime() can access the time member variable. The two methods are declared public, meaning they can be called from code anywhere in your application. Default The default access level is declared by not writing any access modifier at all. Default access levels means that code inside the class itself + code inside classes in the same package as this class, can access the class, field, constructor or method. Therefore, the default access modifier is also sometimes called a package access modifier. Subclasses cannot access methods and member variables in the superclass, if they have default accessibility declared, unless the subclass is located in the same package as the superclass. Here is an example: public class Clock { long time = 0; } public class ClockReader { Clock clock = new Clock(); public long readClock{ return clock.time; } } The ClockReader class above can read the time member variable of the Clock object, provided that ClockReader and Clock are located in the same package.

protected The protected acces modifier does the same as the default access, except subclasses can also access protected methods and member variables of the superclass. This is true even if the subclass is not located in the same package as the superclass. Here is an example: public class Clock { protected long time = 0; // time in milliseconds } public class SmartClock() extends Clock{ public long getTimeInSeconds() { return this.time / 1000; } } In the above example the subclass SmartClock has a method called getTimeInSeconds() which accesses the time variable of the superclass Clock. This is possible even if Clock and SmartClock are not located in the same package. public The public access modifier means that all code can access the class, field, constructor or method, regardless of where the accessing code is located. Here is a public field example: public class Clock { public long time = 0; } public class ClockReader { Clock clock = new Clock(); public long readClock{ return clock.time; } } The ClockReader class can access the time field in the Clock no matter what package the ClockReader is located in, because both the Clock class and the time field are declared public InstanceOf keyword: The keyword instanceOf in java programming language is a boolean operator that is used to test whether an object is of an specified type or not and returns the value accordingly. This operator is used only for object reference variables. InstanceOf operator is wriiten as: ( Object reference variable ) instanceOf (class/interface type)

Eg: String s = "XYZ"; if (s instanceof java.lang.String) returns TRUE. But, using instanceof on a null reference variable returns FALSE Eg: String s = null; if (s instanceof java.lang.String) returns FALSE In a parent child relationship the instanceof would return TRUE. Eg: if (child instanceof Parent) returns TRUE class Parent { public Parent() { } } class Child extends Parent { public Child() { super(); } } public class MainClass { public static void main(String[] a) { Child child = new Child(); if (child instanceof Parent) { System.out.println("true"); } } } Output: true Java Loop Control

There may be a sitution when we need to execute a block of code several number of times, and is often referr Java has very flexible three looping mechanisms. You can use one of the following three loops: while Loop do...while Loop for Loop As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop: A while loop is a control structure that allows you to repeat a task a certain number of times. Syntax: The syntax of a while loop is: while(Boolean_expression) { //Statements }

When executing, if the boolean_expression result is true then the actions inside the loop will be executed. Thi as long as the expression result is true.

Here key point of the while loop is that the loop might not ever run. When the expression is tested and the res loop body will be skipped and the first statement after the while loop will be executed. Example: public class MainClass { public static void main(String[] args) { int i = 0; while (i < 3) { System.out.println(i); i++; } } }

Sometimes, you use an expression that always evaluates to true (such as the boolean literal true) but relies on statement to escape from the loop. public class MainClass { public static void main(String[] args) { int k = 0; while (true) { System.out.println(k); k++; if (k > 2) { break; } } } } The do...while Loop: A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one

Syntax: The syntax of a do...while loop is: do { //Statements }while(Boolean_expression);

the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the B tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop exec process repeats until the Boolean expression is false. Example: public class MainClass { public static void main(String[] args) { int i = 0; do { System.out.println(i); i++; } while (i < 3); } } This prints the following to the console: 0 1 2

The following do-while demonstrates that at least the code in the do block will be executed once even though value of j used to test the expression j < 3 evaluates to false. public class MainClass { public static void main(String[] args) { int j = 4; do { System.out.println(j); j++; } while (j < 3); } } This prints the following on the console. 4

The for Loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a sp of times. A for loop is useful when you know how many times a task is to be repeated. Syntax: The syntax of a for loop is: for ( init ; booleanExpression ; update ) { statement (s) } 1. 2. 3. 4.

init is an initialization that will be performed before the first iteration. booleanExpression is a boolean expression which will cause the execution of statement(s) if it evalua update is a statement that will be executed after the execution of the statement block. init, expression, and update are optional.

The for statement will stop only if one of the following conditions is met: 1. booleanExpression evaluates to false 2. A break or continue statement is executed 3. A runtime error occurs. Example: public class MainClass { public static void main(String[] args) { for (int i = 0; i < 5; i++) { System.out.println(i + " "); } } } The initialization part of the for statement is optional. public class MainClass { public static void main(String[] args) { int j = 0; for (; j < 3; j++) { System.out.println(j); } // j is visible here } } The update statement is optional. public class MainClass { public static void main(String[] args) { int k = 0; for (; k < 3;) {

System.out.println(k); k++; } } } You can even omit the booleanExpression part. public class MainClass { public static void main(String[] args) { int m = 0; for (;;) { System.out.println(m); m++; if (m > 4) { break; } } } }

Enhanced for loop in Java: This is mainly used for Arrays, this is read only. Syntax: The syntax of enhanced for loop is: for(declaration : expression) { //Statements } Declaration . The newly declared block variable, which is of a type compatible with the elements of t are accessing. The variable will be available within the for block and its value would be the same as th element. Expression . This evaluate to the array you need to loop through. The expression can be an array vari call that returns an array. Example: public class Test { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names ={"James", "Larry", "Tom", "Lacy"};

for( String name : names ) { System.out.print( name ); System.out.print(","); } } } This would produce following result: 10,20,30,40,50, James,Larry,Tom,Lacy, The break keyword The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax: The syntax of a break is a single statement inside any loop: break; Example: public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { break; } System.out.print( x ); System.out.print("\n"); } } } This would produce following result: 10 20 The Labeled break Statement

1. The break statement can be followed by a label. 2. The presence of a label will transfer control to the start of the code identified by the label. 3. For example, consider this code. public class MainClass {

public static void main(String[] args) { OuterLoop: for (int i = 2;; i++) { for (int j = 2; j < i; j++) { if (i % j == 0) { continue OuterLoop; } } System.out.println(i); if (i == 37) { break OuterLoop; } } } } The continue Keyword: The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: The syntax of a continue is a single statement inside any loop: continue; Example: public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { continue; } System.out.print( x ); System.out.print("\n"); } } } This would produce following result: 10 20

40 50 Exception: An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions: Checked exceptions: A compiler for the Java programming language checks, at compile time, that a program contains handlers for checked exceptions. A checked exception is an exception that is typically a user error or a problem that cannot be foreseen(guess) by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Java defines several exception classes inside the standard package java.lang. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available. Java defines several other types of exceptions that relate to its various class libraries. Following is the list of Java Unchecked RuntimeException. Exception ArithmeticException ArrayStoreException ClassCastException Description Arithmetic error, such as divide-by-zero. Assignment to an array element of an incompatible type. Invalid cast.

ArrayIndexOutOfBoundsException Array index is out-of-bounds.

IllegalArgumentException IllegalMonitorStateException IllegalStateException IllegalThreadStateException IndexOutOfBoundsException NegativeArraySizeException NullPointerException NumberFormatException SecurityException StringIndexOutOfBounds UnsupportedOperationException

Illegal argument used to invoke a method. Illegal monitor operation, such as waiting on an unlocked thread. Environment or application is in incorrect state. Requested operation not compatible with current thread state. Some type of index is out-of-bounds. Array created with a negative size. Invalid use of a null reference. Invalid conversion of a string to a numeric format. Attempt to violate security. Attempt to index outside the bounds of a string. An unsupported operation was encountered. Description Class not found. Attempt to clone an object that does not implement the Cloneable interface. Access to a class is denied. Attempt to create an object of an abstract class or interface. One thread has been interrupted by another thread. A requested field does not exist. A requested method does not exist.

Following is the list of Java Checked Exceptions Defined in java.lang. Exception

ClassNotFoundException CloneNotSupportedException IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException

Exceptions Methods: Following is the list of important medthods available in the Throwable class. SN 1 Methods with Description public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. public String toString() Returns the name of the class concatenated with the result of getMessage() public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. public StackTraceElement [] getStackTrace()

2 3

4 5

Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. 6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Some of the common exceptions you may encounter in the exam are: 1. ArrayIndexOutOfBoundsException - Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array). 2. ClassCastException - Thrown when attempting to cast a reference variable to a type that fails the IS-A test. 3. IllegalArgumentException - Thrown when a method receives an argument formatted differently than the method expects. 4. IllegalStateException - Thrown when the state of the environment doesnt match the operation being attempted, e.g., using a Scanner thats been closed. 5. NullPointerException - Thrown when attempting to access an object with a reference variable whose current value is null. 6. NumberFormatException - Thrown when a method that converts a String to a number receives a String that it cannot convert. 7. AssertionError - Thrown when a statements boolean test returns false. 8. ExceptionInInitializerError - Thrown when attempting to initialize a static variable or an initialization block. 9. StackOverflowError - Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.) 10. NoClassDefFoundError - Thrown when the JVM cant find a class it needs, because of a command-line error, a classpath issue, or a missing .class file. Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. The try block will execute a sensitive code which can throw exceptions. try is where you put unsafe code The catch block will be used whenever an exception (of the type caught) is thrown in the try block. catch is where you put the code you want to run if something very bad happens. The catch block will handle the Exception Syntax: try { //Protected code }catch(ExceptionName e1) { //Catch block

} A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Example: The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. // File Name : ExcepTest.java import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } This would produce following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches

ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch (ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } } Nested Try-Catch Blocks In Java we can have nested try and catch blocks. It means that, a try statement can be inside the block of another try. If an inner try statement does not have a matching catch statement for a particular exception, the control is transferred to the next try statement?s catch handlers that are expected for a matching catch statement. This continues until one of the catch statements succeeds, or until all of the nested try statements are done in. If no one catch statements match, then the Java run-time system will handle the exception. The syntax of nested try-catch blocks is given below: try { try { // ... } catch (Exception1 e) { //statements to handle the exception } } catch (Exception 2 e2) { //statements to handle the exception }

Lets have an example that uses the nested try-catch blocks import java.io.*; public class NestedTry{ public static void main (String args[])throws IOException { int num=2,res=0; try{ FileInputStream fis=null; fis = new FileInputStream (new File (args[0])); try{ res=num/0; System.out.println("The result is"+res); } catch(ArithmeticException e){ System.out.println("divided by Zero"); } } catch (FileNotFoundException e){ System.out.println("File not found!"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Array index is Out of bound! Argument required"); } catch(Exception e){ System.out.println("Error.."+e); } } } Output of the program: C:\Roseindia\>javac NestedTry.java C:\Roseindia\>java NestedTry Array index is Out of bound! Argument required An example of nested try statements.

class NestTry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a;

System.out.println("a = " + a); try { if (a == 1) a = a / (a - a); // division by zero if (a == 2) { int c[] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch (ArithmeticException e) { System.out.println("Divide by 0: " + e); } } } Try statements can be implicitly nested via calls to methods

class MethNestTry { static void nesttry(int a) { try { if (a == 1) a = a / (a - a); if (a == 2) { int c[] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); nesttry(a); } catch (ArithmeticException e) { System.out.println("Divide by 0: " + e);

} } } The throws/throw Keywords: If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. throws will pass the error to his caller. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. The following method declares that it throws a RemoteException: import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition } A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException: import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition } class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch (NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } }

public static void main(String args[]) { try { demoproc(); } catch (NullPointerException e) { System.out.println("Recaught: " + e); } } } class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } THROW user defined exception. we want throw manually actually used to throw Exception in Java code, it is surrounded by the try catch block throw transfers control to caller, throw keyword can be used in switch case in Java but throw keyword can be used inside method or static initializer block provided sufficient exception handling Example; THROWS JVM handles the exceptions

used in method signature to declare Exception possibly thrown by any method used when you are not using the try catch statement in your code throws is suggest for information and compiler checking throws keyword cannot be used.

throws keyword cannot be used anywhere exception method signature

public void shutdown() throws IOException{ throw new IOException("Unable to shutdown"); } static{ try { throw new Exception("Not able to initialized"); } catch (Exception ex) { Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex); } } 4) throw keyword can also be used to break a switch statement without using break keyword as shown in below example: int number = 5; switch(number){ case 1: throw new RuntimeException("Exception number 1"); case 2: throw new RuntimeException("Exception number 2"); } The finally Keyword The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes.

} Example: public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } } This would produce following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Note the following: A catch clause cannot exist without a try statement. It is not compulsory to have finally clauses whenever a try/catch block is present. The try block cannot be present without either catch clause or finally clause. Any code cannot be present in between the try, catch, finally blocks. Declaring you own Exception: Creating your own exception is known as custom exception or user defined exception. You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes: All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below: class MyException extends Exception{ } You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example: // File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException. // File Name CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs);

} } public double getBalance() { return balance; } public int getNumber() { return number; } } The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount. // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } } } Compile all the above three files and run BankDemo, this would produce following result: Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13)

Common Exceptions: In java it is possible to define two catergories of Exceptions and Errors. JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, Programmatic exceptions . These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException. In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod(). public class CatchThrow { private static void throwsMethod() throws NumberFormatException { String intNumber = "5A"; Integer.parseInt(intNumber); } private static void catchMethod() { try { throwsMethod(); } catch (NumberFormatException e) { System.out.println("Convertion Error"); } } public static void main(String[] args) { catchMethod(); } } OOPS Concepts Abstraction : Hiding unnecessary things and showing the essential information, access specifiers like public,private etc are used to provide different level in abstraction. Example: Suppose take a car: In that we will have breaks and stering and etc... Here when we are changing the gear box to up or bottom then gears will work but we don't know how they are managing internally and we don't no how it is working. As a driver we don't need to know how it is working internally when we are changing every time. That is the reason they will hide the wires and cables internally and they will show up only gear box to us. Advantages: 1) Code will be clean and for managing it will be very easy Encapsulation : Taking data and object in a single unity is called Encapsulation. A class is example for Encapsulation. Wrapping up of data and methods into a single unit. Example: In our class we need to make all our varables and methods keeping together. Advantage: Maintance will be good

Inheritance : Acquiring the properties from super class to subclass. Example: Suppose take two java classes Class A contains 2 variables and ClassB Extends Class A that means here ClassB can access the classA variables without declaring it. If we do this then the memory will be less and reusable. Advantages: 1)Reusability of code polymorphism : if single mthod performs different task is called polymorphism. It means many forms. 2 types: 1) Compile time polymorphism 2) Run time polymorphism Method overloading is an example for Compile time polymorphism and Method overriding is an example for Run time polymorphism Abstract Class Abstraction is a process of hiding the implementation details and showing only functionality to the user. In other words, it shows only important things to the user and hides the internal details There are 2 ways to achieve abstraction 1. Abstract class 2. Interface A class declared as abstract is known as abstract class. It needs to be instantiated that means it cannot create new instance or object of an abstract class. The purpose of an abstract class is to function as a base for subclasses. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own. An abstract class can have data member, abstract method, method body, constructor and even main() method. Abstract class with all methods as in abstract, it is known as Fully abstract class An abstract class may have static fields and static methods. You can use these static members with a class referencefor example, AbstractClass.staticMethod()as you would with any other class. Declaring a method as abstract has two results: The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well. Any child class must either override the abstract method or declare itself abstract. Declaration: Abstract class abstract class<class name> { ----------} Abstract Method abstract return type <method name>(); //no braces {} EXAMPLE abstract class Bike {

abstract void run(); public void show(){ System.out.println("SHOW"); } } public class Honda extends Bike{ void run(){ System.out.println("Run"); } } public static void main(String[] args) { Bike b=new Honda(); b.run(); b.show(); } } Rules of abstract class: Abstract classes cannot be instantiated, but they can be subclassed. In abstract classes methods can be either abstract or non abstract. A method can either be final or abstract. If a method is abstract then its class must be declared abstract An Abstract method has no body (implementation) and ends with a semicolon If a class is abstract, we may call its constructor only via super in a class that extends it, not via the new operator. That is, we cannot explicitly construct an object using an abstract class, but we can use it to help construct an object from a subclass. We can treat an abstract class as a superclass and extend it; its subclasses can override some or all of its inherited abstract methods. If through this overriding a subclass contains no more abstract methods, that class is concrete (and we can construct objects directly from it). If it still abstract, it too can be used as a superclass ... (until eventually a subclass of a subclass ... is concrete). Interface It is a blueprint of a class. It has a static constants and abstract methods. The interface is a mechanism to achieve abstraction in java. It is used to achieve fully abstraction and multiple inheritance in java. An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Why use interface? There are three reasons to use interface: It is used to achieve fully abstraction.

Support the functionality of multiple inheritances. It can be used to achieve loose coupling. [one object interacts with another object, that is a coupling.]

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. An interface is similar to a class in the following ways:

An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The bytecode of an interface appears in a .class file. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including:


You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces.

Declaring Interface:

[modifiers] interface InterfaceName { // declaring methods [public abstract] returnType methodName1(arguments); // defining constants [public static final] type fieldName = value; } EXAMPLE: Interface Printable { Void Print (); } Class A implements Printable { Public void print(){ System.out.println (Hello); } public static void main(String[] args) { A obj =new A (); Obj.print (); } } Interfaces have the following properties:

An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public.

When overriding methods defined in interfaces there are several rules to be followed:

Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. An implementation class itself can be abstract and if so interface methods need not be implemented.

When implementation interfaces there are several rules:


A class can implement more than one interface at a time. A class can extend only one class, but implement many interface.

An interface can extend another interface, similarly to the way that a class can extend another class.

One interface extends another interface: Interface Printable { Void Print (); } Interface Showable extends Printable { Void show (); } Class A implements Showable { Public void print(){ System.out.println (Hello); } Public void show(){ System.out.println (Welcome); } public static void main (String[] args) { A obj =new A (); Obj.print (); } } Multiple Interface A class cannot extend two classes but it can implement two interfaces. Interface Printable { Void Print (); } Interface Showable { Void show (); } Class A implements Printable, Showable { Public void print(){ System.out.println (Hello); } Public void show(){ System.out.println (Welcome); } public static void main (String[] args) { A obj =new A ();

Obj.print (); } } Multiple inheritance is not supported in case of class but it is supported in case of interface why? To reduce the complexity and simplify the language multiple inheritance is not supported in java. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class. Interface Printable { Void print (); } Interface Showable { Void print (); } Class A implements Printable, Showable { Public void print(){ System.out.println (Hello); } public static void main (String[] args) { A obj =new A (); Obj.print (); } } The printable and showable interface have same methods but its implementation is provided by class A, so there is no ambiguity. Tagging Interfaces: An interface that have no member is known as tagged interface or marker interface. Example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation. The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as: package java.util; public interface EventListener{} An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces:

Creates a common parent: As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario. Adds a data type to a class: This situation is where the term tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism. Difference between abstract class and interface Abstract Class 1.It is a class 2.inherit the implementation of other (nonabstract) methods (can implement methods) 3.A Java abstract class should be extended using extends keyword 4.An abstract class can have method body(non abstract class) 5.An abstract class can have instance methods 6.Can have constructor 7.Can have static methods 8.Can extends only one abstract class 9. May contain non-final variables. 10. Members like public, private, protected. 11. Abstract classes should have subclasses else that will be useless. 12. Abstract scope is upto derived class. Interface It is not a class, is a interface an interface cannot provide any method implementations. Java interface should be implemented using keyword implements keyword Interface have only abstract methods Interface cannot have instance methods Cannot have constructor Cannot have static methods. Can implements multiple interface Variables declared in interface is by default final Members are public by default Interfaces must have implementations by other classes else that will be useless Interface scope is upto any level of its inheritance chain. Interface is absolutely abstract and cannot be instantiated; Java interfaces are slow as it requires extra indirection.

13. Java abstract class cannot be instantiated, but can be invoked if a main () exists. 14. Abstract classes are fast.

When to use abstract class and interface in Java Here are some guidelines on when to use an abstract class and interface in Java:

1. An abstract class is good if you think you will plan on using inheritance since it provides a common base class implementation to derived classes. 2. An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must be public. 3. If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface, then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle. 4. Interfaces are a good choice when you think that the API will not change for a while. 5. Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces. Choose Interface. Because the same feature can have different implementations in different Objects. And can also support for multiple Inheritance through Interfaces. If you go for Abstract Classes it should have some common functionality and common features in that class ofcourse it is also having abstract classes as well as Concrete Classes. We have to extend the available feature in our class. But here the Interfaces we can implement our own features in our class. Whenever a good programmer choose for Interfaces. One Ex..In Threads Concept: Everybody choose to create Thread by using Runnable interface not extends the Class Thread Because of Object Oriented Design Pattern it is safe to using Interfaces. class MyClass implements Runnable{ public static void main(String[] args){ Runnable r=new MyClass(); Thread t=new Thread(r); t.start (); ----write here the run method----} } When to use an Interface: it asks you to start everything from scratch. You need to provide implementation of all the methods. So, you should use it to define the contract, which youre unsure of how the different vendors/producers will implement. So, you can say that Interfaces can be used to enforce certain standards. When to use an Abstract Class: it is used mostly when youve partial implementation ready with you, but not the complete. So, you may declare the incomplete methods as abstract and //here we are using the // interface to create a thread

leave it to the clients to implement it the way they actually want. Not all the details can be concrete at the base class level or different clients may like to implement the method differently. When to use both: if you want to implement multiple inheritance where you have the luxury of providing partial implementation as well. Youll then put all that code in an abstract class (this can be a concrete class as well but here we assume that the class is also only partially implemented and hence an abstract class), extend that class, and implement as may interfaces as you want

Encapsulation It is the process of wrapping code and data together into a single unit. It is also referred to as data hiding. It is the techniques of making the fields in a class private and providing access to the fields via public methods. If a field is declared as private, it cannot be accessed by anyone outside the class thereby hiding the fields within the class. Example: /* File name : EncapTest.java */ public class EncapTest{ private String name; private String idNum; private int age; public int getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; } public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; } public void setIdNum( String newId){ idNum = newId; } }

The public methods are the access points to this class's fields from the outside java world. Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters. The variables of the EncapTest class can be access as below:: /* File name : RunEncap.java */ public class RunEncap{ public static void main(String args[]){ EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.print("Name : " + encap.getName()+" Age : "+ encap.getAge()); } } This would produce following result: Name : James Age : 20 Benefits of Encapsulation: The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code. Difference between abstraction and encapsulation Abstraction Abstraction hides the implementation details Encapsulation Encapsulation hides the data

Abstraction is implemented in Java using interface and abstract class

Encapsulation is implemented using private, package-private and protected access modifier. The user of your code doesn't depend on parts of your program that are likely to change. When you change your program, they don't have to change their code

When you change your code that implements an abstraction, the user of the abstraction doesn't have to change their code. As long as the abstraction doesn't change, the users won't have to change their code. When you write code that uses an abstraction, you can write code once that will be reusable against any new code that implements that abstraction. You can write less code to do more. Abstraction is when you simplify a

You are more in control of exactly how your code and state changes over the lifetime of your program. You must handle fewer scenarios, and will have fewer unexpected problems to fix Encapsulation is when you can use diferents

complicate proccess with a few statement. for example: o.solveEquation(2,3,5)

tool from a single object in your program. for example: Obj o=new Obj(); o.sum(); o.divide() and everything inside the same object.

Design principles "programming for interface Design principles "encapsulate whatever than implementation" is based on abstraction changes" is based upon Encapsulation.

Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object In fact, any object that satisfies more than one IS-A relationship is polymorphic in nature. Example: Let us look at an example. public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{} Now the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example: A Deer IS-A Animal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object When we apply the reference variable facts to a Deer object reference, the following declarations are legal: Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d; All the reference variables d,a,v,o refer to the same Deer object in the heap. Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding). Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.

Static Polymorphism: In Java, static polymorphism is achieved through method overloading. Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters. At compile time, Java knows which method to invoke by checking the method signatures. So, this is called compile time polymorphism or static binding. The concept will be clear from the following example: class DemoOverload{ public int add(int x, int y){ //method 1 return x+y; } public int add(int x, int y, int z){ //method 2 return x+y+z; } public int add(double x, int y){ //method 3 return (int)x+y; } public int add(int x, double y){ //method 4 return x+(int)y; } } class Test{ public static void main(String[] args){ DemoOverload demo=new DemoOverload(); System.out.println(demo.add(2,3)); //method 1 called System.out.println(demo.add(2,3,4)); //method 2 called System.out.println(demo.add(2,3.4)); //method 4 called System.out.println(demo.add(2.5,3)); //method 3 called } } In the above example, there are four versions of add methods. The first method takes two parameters while the second one takes three. For the third and fourth methods there is a change of order of parameters. The compiler looks at the method signature and decides which method to invoke for a particular method call at compile time. Dynamic Polymorphism: Suppose a sub class overrides a particular method of the super class. Lets say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called. Have a look at the following example. class Vehicle{

public void move(){ System.out.println(Vehicles can move!!); } } class MotorBike extends Vehicle{ public void move(){ System.out.println(MotorBike can move and accelerate too!!); } } class Test{ public static void main(String[] args){ Vehicle vh=new MotorBike(); vh.move(); // prints MotorBike can move and accelerate too!! vh=new Vehicle(); vh.move(); // prints Vehicles can move!! } } It should be noted that in the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference. In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called. As the method to call is determined at runtime, this is called dynamic binding or late binding. Runtime Polymorphism with data members: Method is overridden not the data members, so runtime polymorphism cant achieved by data members. class Bike{ int speed=90; } class Honda extends Bike{ int speed=150; public static void main(String[] args){ Bike obj=new Honda(); System.out.println(obj.speed); } } In the example both the classes have the same data member speed, we are accessing the data members by the reference variable of parent class which refers to the subclass object. Since

we are accessing the datamember which is not overridden, hence it will access the datamember of parent class always. Method Overloading If a class have multiple methods by same name but different parameters is known as method overloading. Adv: Increase readability of the program. Different ways to overload the method: 1. By changing number of arguments. 2. By changing the data type

How to NOT overload methods:


Its important to understand that method overloading is NOT something you can accomplish by doing these 2 things:
1. 2. Changing the return type of the method Changing the name of the method parameters, but not changing the parameter types.

Confused? Well, here are some very helpful examples of where overloading would be both valid and invalid:

Examples of Method Overloading in Java both valid and invalid:


//compiler error - can't overload based on the //type returned //(one method returns int, the other returns a float): int changeDate(int Year) ; float changeDate (int Year); //compiler error - can't overload by changing just //the name of the parameter (from Month to Year): int changeDate(int Month) ; float changeDate(int Year); //valid case of overloading, since there is an //extra parameter in the first method: int changeDate(int Year, int Month) ; int changeDate(int Year); //also a valid case of overloading, since the //parameters are of different types: int changeDate(float Year) ; int changeDate(int Year);

Method Overloading is not possible by changing the return type of the methods because there may occur ambiguity. class Calculation{

int sum(int a,int b){ System.out.println(a+b); } double sum(int a,int b){ System.out.println(a+b); } public static void main(String[] args){ Calculation c=new Calculation(); Int result=c.sum(20,20); } } Here how can java determine which sum() should be called. So the output will be compile time error. Can we overload main() method? Yes by method overloading we can overload main() method. class simple{ public static void main(int a){ System.out.println(a); } public static void main(String[] args){ System.out.println(main() mtd invoked); Main(10); } } The output will be Main() mtd invoked. 10 Method Overloading occur during compile time can overload method in same class Can overload static, final or private method in Java. Overloaded methods are bonded using static binding and Type of reference variable is used overload a method you need to change its method signature Overloaded method are fast

Method Overriding Occur during runtime. Can only override method in sub class. cannot override static, final and private method in Java Overridden method is bonded using dynamic bonding based upon actual Object. Remain same slow

Static Binding and Dynamic Binding: Binding: Collecting a method call to a method body is called binding. It can be of 2 types: Static binding(early binding) Dynamic binding(late binding) About type: 1. Variable have a type: Ex: int data=30; Here data variable is a type of int. 2. References have a type: class Dog{ public static void main(String args[]){ Dog d1; //Here d1 is a type of Dog } } 3. Object have a type: An object is an instance of particular java class, but it is also an instance of its superclass. class Animal{} class Dog{ public static void main(String args[]){ Dog d1=new Dog(); } } Here d1 is an instance of Dog class but also an insatnce of Animal. Static binding: When type of the object is determined at compiled time(by the compiler), it is known as static binding.If there is any private,final or static method in a class it is static binding. class Dog{ private void eat(){ System.out.println("dog is eating"); } public static void main(String args[]){ Dog d1=new Dog(); d1.eat(); } }

Dynamic binding: When type of object is deteremined at runtime it is known as dynamic binding. class Animal{ void eat(){ System.out.println("animal is eating"); } } class Dog extends Animal{ void eat(){ System.out.println("dog is eating"); } public static void main(String args[]){ Aniaml a=new Dog(); a.eat(); } } Output: dog is eating. In this example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So the compiler doesn't know its type, only its base type. Inheritance Inheritance is the mechanism in which one object acquires all the properties and behaviours of parent object. It represents the IS-A relationship. Why use inheritance? For method overriding For coed reusability

Syntax: class <Subclass_name> extends <Superclass_name> { //methods and fields } public class Animal{} public class Mammal extends Animal{} public class Reptile extends Animal{} public class Dog extends Mammal{} Now based on the above example, In Object Oriented terms following are true: Animal is the superclass of Mammal class. Animal is the superclass of Reptile class. Mammal and Reptile are sub classes of Animal class. Dog is the subclass of both Mammal and Animal classes.

Now if we consider the IS-A relationship we can say: Mammal IS-A Animal Reptile IS-A Animal Dog IS-A Mammal Hence : Dog IS-A Animal as well In single inheritance, one class extends one class only. In multilevel inheritance, the ladder of single inheritance increases. In multiple inheritance, one class directly extends more than one class and in hierarchical inheritance one class is extended by more than one class. Let us go in detail programmatically. Multilevel Inheritance In multilevel, one-to-one ladder increases. Multiple classes are involved in inheritance, but one class extends only one. The lowermost subclass can make use of all its super classes' members. Multilevel inheritance is an indirect way of implementing multiple inheritance. Following program explains. class Aves{ public void nature() { System.out.println("Generally, Aves fly"); } } class Bird extends Aves{ public void eat() { System.out.println("Eats to live"); } } public class Parrot extends Bird{ public void food() { System.out.println("Parrot eats seeds and fruits"); } public static void main(String args[]) { Parrot p1 = new Parrot(); p1.food(); // calling its own p1.eat(); // calling super class Bird method p1.nature(); // calling super class Aves method } } Parrot eats seeds and fruits Eata to live Generally Aves fly

Now, Parrot has two super classes Bird and Aves; but extended one-to-one. Parrot can make use of the methods of Bird and Aves. Bird can make use of the methods of Aves, but Parrot as a super class cannot access subclass members. Following figure gives a schematic representation of the multilevel hierarchy with the classes involved in the program.

Hierarchical Inheritance In hierarchical type of inheritance, one class is extended by many subclasses. It is one-tomany relationship. A realtime example is available at dynamic binding. class Aves{ public void fly() { System.out.println("Generally, aves fly"); } } class Parrot extends Aves{ public void eat() { System.out.println("Parrot eats fruits and seeds"); } } class Vulture extends Aves{ public void vision() { System.out.println("Vulture can see from high altitudes"); } } public class FlyingCreatures{ public static void main(String args[]) { // all the following code is composition for FlyingCreatures Parrot p1 = new Parrot(); p1.eat(); // calling its own member p1.fly(); // calling super class member by inheritance Vulture v1 = new Vulture(); v1.vision(); // calling its own member v1.fly(); // calling super class member by inheritance }}

Parrot eats seeds and fruits Generally Aves fly Vulture can see from high altitudes Generally Aves fly In the above code, Aves class is extended by two classes Parrot and Vulture. Both classes can make use of the methods of Aves. Even though the Parrot and Vulture are subclasses of the same class Aves, but still they cannot make use of each other members. Parrot and Vulture are known as "siblings". Siblings are disjoint and they cannot make use of other members as between them no inheritance is involved (like two sons of a father; one son's property cannot be shared by other but both can share the property of father). Following is the schematic representation of the classes involved.

Disadvantages of Inheritance 1. Both classes (super and subclasses) are tightly-coupled. 2. As they are tightly coupled (binded each other strongly with extends keyword), they cannot work independently of each other. 3. Changing the code in super class method also affects the subclass functionality. 4. If super class method is deleted, the code may not work as subclass may call the super class method with super keyword. Now subclass method behaves independently.

S-ar putea să vă placă și