0% found this document useful (0 votes)
80 views151 pages

OOP in Java

oop

Uploaded by

liracam748
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
80 views151 pages

OOP in Java

oop

Uploaded by

liracam748
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 151
OOP in Java BCA THIRD OY} SEMESTER Mechi Multiple Campus Bhadrapur eM Teor eo 7 LCI sole} MCA, Purbanchal UniversityUn Introduction to Java [2 Hrs. Java is an object-oriented, cross platform, multi-purpose programming language produced by Sun Microsystems. It is 2 combination of features of C and C++ with some essential additional concepts. Java is well suited for both standalone and web application development and is designed to provide solutions to most of the problems faced by users of the internet era. It was originally designed for developing programs for set-top boxes and handheld devices, but later became a popular choice for creating web applications. The Java syntax is similar to C++, but is strictly an object-oriented programming language. For example, most Java programs contain classes, which are used to define objects, and methods, which are assigned to individual classes. Java is also known for being stricter than C++, meaning variables and functions must be explicitly defined, This means Java source code may produce errors or "exceptions" more easily than other languages, but it also limits other types of errors that may be caused by undefined variables or unassigned types. Unlike Windows executables (.€XE files) or Macintosh applications (. APP files), Java programs are not run directly by the operating system. Instead, Java programs are interpreted by the Java Virtual Machine, or JVM, which runs on multiple platforms. This means all Java programs are multiplatform and can run on different platforms, including Macintosh, Windows, and Unix computers. However, the JVM must be installed for Java applications or applets to run at all. Fortunately, the JVM is included as part of the Java Runtime Environment (RE. Oracle acquired Sun Microsystems in January, 2010. Therefore, Java is now maintained and distributed by Oracle. Features of Java a) Object-Oriented - Java supports the features of object-oriented programming. Its object model is simple and easy to expand. b) Platform independent - C and C++ are platform dependency languages hence the application programs written in one Operating system cannot run in any other Operating system, but in platform independence language like Java application programs written in one Operating system can able to run on any Operating system c) Simple - Java has included many features of C / C ++, which makes it easy to understand. d) Secure - Java provides a wide range of protection from viruses and malicious programs. It ensures that there will be no damage and no security will be broken. ) Portable - Java provides us the concept of portability. Running the same program with Java on different platforms is possible. f) Robust - During the development of the program, it helps us to find possible mistakes as soon as possible. g) Multithreaded - The multithreading programming feature in Java allows you to write a program that performs several different tasks simultaneously. Prepared by: Raju Poudel [MCA] 2h) Distributed - Java is designed for distributed Internet environments as it manages the TCP/IP protocol. The most striking feature of the language is that itis a platform-neutral language. Java is the first programming language that is not tied to any particular hardware or operating system. Programs developed in Java can be executed anywhere on any stream. We can call Java as a revolutionary technology because it has brought in a fundamental shift in how we develop and use programs. Nothing like this has happened to the software industry before. History of Java Java is a general-purpose, object-oriented programming language developed by Sun Microsystems of USA in 1991. Originally called Oak by James Gosling, one of the inventors of the language, Java was designed for the development of software for consumer electronic devices like TVs, VCRs and such other electronic machines. The goal had a strong impact on the development team to make the language simple, portable and highly reliable. The Java team which included Patrick Naughton discovered that the existing languages like C and C++ had limitations in terms of both reliability and portability. However, they modelled their new language Java on C and C++ but removed a number of features of Cand C++ that were considered as sources of problems and thus made Java a really simple, reliable, portable and powerful language. Java Milestones Year Development 1990 Sun Microsystems decided to develop special software that could be used to manipulate consumer clectronic devices. A team of Sun Microsystems programmers headed by James Gosling was formed to undertake this task. 1991 After exploring the possiblity of using the most popular object-oriented language C++, the team announced a new language named “Oak” 1992 The team, known as Green Project team by Sun, demonstrated the application of their new language to contro! alist of home appliances using a hand-held device with a tiny touch-sensitive screen 1993 The World Wide Web (WWW) appeared on the Internet and transformed the text-based Intemet into a graphical-nch environment. The Green Project team came up with the idea of developing Web applets (tiny peograms) using the new language that could run on all types of computers connected to Internet 1994 The team developed a Web browser called "HoUava” to locate and run applet programs on Internet. HoUlva demonstrated the power of the new language, thus making it instantly popular among the Internet users 1995 Oak was renamed “Java”, due to some legal snags. Java is just a name and is not an acronym. Many Popular companies including Netscape and Microsoft announced their support to Java. 1996 Java established itself not only as a leader for Internet programming but also as a general-purpose, object-oriented programming language. Sun releases Java Development Kit 1.0. 1997 Sun releases Java Development Kit 1.1 JDK 1.1). 1998 Sun relases the Java 2 with version 1.2 of the Software Development Kit (SDK 1.2). 1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE). 2000 J2SE with SDK 1.3 was released. 2002 12SE with SDK 1.4 was released. 2004 _J2SE with JDK 5.0 (instead of IDK 1.5) was released. This is known as J2SE 5.0. Prepared by: Raju Poudel [MCA] 2The Internet and Java’s Place in IT Earlier Java was only used to design and program small computing devices, but it was later adopted as one of the platform-independent programming languages, and now according to. Sun, 3 billion devices run Java. Java is one of the most important programming languages in today's IT industries. * JSP In Java, JSP (Java Server Pages) is used to create dynamic web pages, such as in PHP and ASP. * Applets - Applets are another type of Java programs that are implemented on Internet browsers and are always run as part of a web document. + IZEE - Java 2 Enterprise Edition is a platform-independent environment that is a set of different protocols and APIs and is used by various organizations to transfer data between each other. © JavaBeans - This is a set of reusable software components that can be easily used to create new and advanced applications. © Mobile - in addition to the above technology, Java Is widely used in mobile devices nowadays, many types of games and applications are being made in Java. Types of Java Applications and Applets a) Web Application - Java is used to create server-side web applications. Currently, Servlet, JSP, Struts, JSF, etc. technologies are used. b) Standalone Application - It is also known as the desktop application or window- based application. An application that we need to install on every machine or server such as media player, antivirus, etc. AWT and Swing are used in java for creating standalone applications. c) Enterprise Application - An application that is distributed in nature, such as banking applications, etc. It has the advantage of the high-level security, load balancing, and clustering. in Java, EJB is used for creating enterprise applications. d) Mobile Application - Java is used to create application software for mobile devices. Currently, Java ME is used for building applications for small devices, and also Java is a programming language for Google Android application development. Java Virtual Machine Java Virtual Machine, or JVM as its name suggest is a “virtual” computer that resides in the “real” computer as a software process. JVM gives Java the flexibility of platform independence. Java code is written in java file. This code contains one or more Java language attributes like Classes, Methods, Variable, Objects etc. Javac is used to compile this code and to generate .class file. Class file is also known as “byte code “. The name byte code is given may be because of the structure of the instruction set of Java program. Java byte code is an input to Java Virtual Machine. !VM read this code and interpret it and executes the program. Prepared by: Raju Poudel [MCA] 4Java Code (,java) Java class is written in Unicode characters. JAVAC i i in Java compiler convert these Se Unicode characters into Byte code. Java Byte code can only be understandable by JVM. The JVM has two primary functions: to allow Java programs to run on any device or ‘operating system (known as the "Write once, run anywhere” principle), and to manage and optimize program memory. When Java was released in 1995, all computer programs were written to a specific operatin; developer. So the VM was a ig system, and program memory was managed by the software revelation. Java Program "Source Code Viewal Machine ‘aR, Real Mache Process of converting bytecode into machine code Prepared by: Raju Poudel [MCA] 5Byte Code — not an Executable Code Java bytecode is the resulting compiled object code of a Java program. This bytecode can be run in any platform which has a Java installation in it. The Java bytecode gets processed by the Java virtual machine (JVM) instead of the processor. It is the job of the JVM to make the necessary resource calls to the processor in order to run the bytecode. The Java bytecode is not completely compiled, but rather just an intermediate code sitting in the middle because it still has to be interpreted and executed by the JVM installed on the specific platform such as Windows, Mac or Linux. Upon compile, the Java source code is converted into the .class bytecode. Procedure-Oriented vs. Object-Oriented Programming Object-Oriented Programming (OOP) is 2 high-level programming language where a program is divided into small chunks called objects using the object-oriented model, hence the name. This paradigm is based on objects and classes. © Object - An object is basically a self-contained entity that accumulates both data and procedures to manipulate the data. Objects are merely instances of classes. © Glass ~ A class, in simple terms, Is a blueprint of an object which defines all the commen properties of one or more objects that are associated with it. A class can be used to define multiple objects within a program The OOP paradigm mainly eyes on the data rather than the algorithm to create modules by dividing a program into data and functions that are bundled within the objects. The modules cannot be modified when a new object is added restricting any non-member function access to the data. Methods are the only way to assess the data Objects can communicate with each other through same member functions. This process is known as message passing. This anonymity among the objects is what makes the program secure. A programmer can create a new object from the already existing objects by taking most of its features thus making the program easy to implement and modify. Procedure-Oriented Programming (POP) follows a step-by-step approach to break down a task into a collection of variables and routines (or subroutines) through a sequence of instructions. Each step is carried out in order in a systematic manner so that a computer can understand what to do. The program is divided into small parts called functions and then it follows a series of computational steps to be carried out in order. It follows a top-down approach to actually solve 2 problem, hence the name. Procedures correspond to functions and each function has its own purpose. Dividing the program into functions is the key to procedural programming. So a number of different functions are written in order to accomplish the tasks. Prepared by: Raju Poudel [MCA] 6Difference between OOP and POP is shown below: Procedure Oriented Programming Object Oriented Programming In POP, program is divided into small parts called functions. In OOF, program is divided into parts called objects. In POP, Importance is not given to data but to functions as well as sequence of actions to be done. In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. POP follows Top Down approach. OOP follows Bottom Up approach. POP does not have any access specifier. OOP has access specifiers named Public, Private, Protected, etc. In POP, Data can move freely from function to function in the system. In OOP, objects can move and communicate with each other through member functions. To add new data and function in POP is not so easy. OOP provides an easy way to add new data and function. In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system. In OOP, data cannot move easily from function to function, it can be kept public or private so we can control the access of data. POP does not have any proper way for OOP provides Data Hiding so provides more hiding data so itis less secure. security, In POP, Overloading isnot possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET, CH.NET. Prepared by: Raju Poudel [MCA] 7Unit — 2 Tokens, Expressions and Control Structures [5 Hrs.] Primitive Data Types Primitive types are the most basic data types available within the lava language. There are 8 primitive cata types: boolean, byte, char, short, int, long, float and double. These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind. Because these data types are defined into the Java type system by default, they come with a number of operations predefined. Data types are divided into two groups: * Primitive data types - includes byte, short, int, long, float, double, boolean and char + Non-primitive(Derived) data types - such as String, Arrays and Classes Data Type | Size _| Description byte Lbyte | Stores whole numbers from -128 to 127 short Zbytes_| Stores whole numbers from -32,768 to 32,767 int Abytes_| Stores whole numbers from -2,147,483,648 to 2,147,483,647 long Bbytes [Stores whole numbers from -9,223,372,036,854,775,808 to 9,223.372,036,854,775,808 float bytes | Stores fractional numbers from 3.4e-038 to 3.4e+038, Sufficient for storing 6 to 7 decimal digits double | Sbytes | Stores fractional numbers from 1.7e-308 to 1.7e+038. Sufficient for storing 15 decimal digits boolean | 1byte _| Stores true or false values char 2bytes | Stores a single character/letter User Defined Data Types User defined data types are those that user / programmer classes, interfaces. For example: imself defines. For example, MyClass obj Here obj is a variable of data type MyClass and we call them reference variables as they can be used to store the reference to the object of that class. Declaration of Variables and Assignment In Java, variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler. Declaration does three things: 1. It tells the compiler what the variable name is. 2. It specifies what type of data the variable will hold. 3. The place of declaration (in the program) decides the scope of the variable. A variable can be used to store a value of any data type. That is, the name has nothing to do with the type. Java allows any properly formed variable to have any declared data type. The general form of declaration of a variable is: type variable!, variable2,..... variable Prepared by: Raju Poudel [MCA] 8A simple method of giving value to a variable is through the assignment statement as follows variableName = value; For Example: abe = 100; xyz = 10.2; It is also possible to assign a value to a variable at the time of its declaration. This takes the form: type vartableName = value: | Examples: int finalValue = 100 char yes ° i double total = 75.36 Type Conversion and Casting Conversion of one data type to another data type is called type casting. If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a Jong variable. However, not all types are compatible, and thus, not all type conversions are implicitly allowed. For instance, there is no automatic conversion defined from double to byte. Fortunately, it is still possible to obtain a conversion between incompatible types. To do so, you must use a cast, which performs an explicit conversion between incompatible types 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 mi * 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. For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other. As mentioned earlier, Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char. Casting Incompatible Types Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign an int value toa byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it wil fitinto the target type. Prepared by: Raju Poudel [MCA] 9To 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 Here, target-type specifies the desired type to convert the specified value to. For example, the following fragment casts an int to a byte. If the integer’s value is larger than the range of, a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range. int a; byte b; I]. b= (byte) 0; The following program demonstrates some type conversions that require casts: // Demonstrate casts class Conversion { b= (byte) i; System.out.printin("i and bt +44" "+ BI; System.out .print1n(*\aConver: i= (int) a; System.out.printin("d and it yds" t+ on of double to System.out .print1n(*\nConversion of double to byte."); b= (byte) dy System.out.printin("d and bt + ds" "4 b); ) , This program generates the following output: Conversion of int to byte. i and b 257 1 Conversion of double to int @ and i 323.142 323 conversion of double to byte 4 and b 323.142 67 Let’s look at each conversion. When the value 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256 (the range of a byte), which is 1 in this case. When the d is converted to an int, its fractional component is lost. When d is converted to a byte, its fractional component is lost, and the value is reduced modulo 256, which in this case is 67. Prepared by: Raju Poudel [MCA] 10Garbage Collection Java garbage collection is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory. In C/C++, programmer is responsible for both creation and destruction of objects. Usually programmer neglects destruction of useless objects. Due to this negligence, at certain point, for creation of new objects, sufficient memory may not be available and entire program will terminate abnormally causing OutOfMemoryErrors. But in Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects. Main objective of Garbage Collector is to free heap memory by destroying unreachable objects. Generally, an object becomes eligible for garbage collection in Java on following cases: 1. All references to that object explicitly set to null e.g. object = null 2. The object is created inside a block and reference goes out scope once control exit: that block, 3. Parent object set to null if an object holds the reference to another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection. Operators in Java ‘An operator, in Java, is a special symbols performing specific operations on one, two or three operands and then returning a result. Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators. Assume integer variable A holds 10 and variable B holds 20, then ~ Operator Description Example + (Addition) ‘Adds values on either side of the operator. A+ B will give 30 ~ (Subtraction) Subiracts right-hand operand from left-hand operand. A- B will give -10 * (Multiplication) | Multiplies values on either side of the operator. A* Bwill give 200 7 (Division) Divides left-hand operand by right-hand operand B/ A will give 2 % (Modulus) Divides left-hand operand by right-hand operand and | 6% A will returns remainder. give 0 ++ (Increment) increases the value of operand by 1. B++ gives 21 ~ (Decrement) Decreases the value of operand by 1. B- gives 19 Prepared by: Raju Poudel [MCA] 1Relational Operators There are following relational operators supported by Java language. ‘Assume variable A holds 10 and variable B holds 20, then — Operator Description Example (equal to) _| Checks if the values of two operands are equal or not, | (A == 8) is yes then condition becomes true. not true. not equal to) | Checks if the values of two operands are equal or not, if| (A = B) is values are not equal then condition becomes true. true. > (greater than) | Checks if the value of left operand is greater than the | (A > B) is value of right operand, if yes then condition becomes true. | not true. = (less than) Checks if the value of left operand is less than the value of [(A = B) is or equal to) to the value of right operand, if yes then concition | not true. becomes true. > (right shift) Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. ‘A >> 2 will give 15 which is 1111 >>> (uero fill shift) right | Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. ‘A >>>2 will give 15 which is 0000 1111 Logical Operators The following table lists the logical operators. ‘Assume Boolean Variables A holds true and variable B holds false, then — Operator Description Example && (logical and) Called Logical AND operator. if both the operands | (A && B) is false are non-zero, then the condition becomes true. TT (logical or) Called Logical OR Operator. If any of the two | (A]| 6)istrue operands are non-zero, then the condition becomes true. 1 (logical not) Called Logical NOT Operator. Use to reverses the | (A && B)is true logical state of its operand. If a condition is true then Logical NOT operator will make false. Assignment Operators Following are the assignment operators supported by Java language — Operator _| Description Example = ‘Simple assignment operator. Assigns values from right side operands | C= A+B will to left side operand. assign value of A+B into c = ‘Add AND assignment operator. it adds right operand to the left|C += A is operand and assign the result to left operand. equivalent toC=C+A = Subtract AND assignment operator. It subtracts right operand fromthe |C -= A is left operand and assign the result to left operand. equivalent toC=C-A Propared by: Raju Poudel [MCA] 33Multiply AND assignment operator. It multiplies right operand with the |C *= A is left operand and assign the result to left operand. equivalent toC=C*A 7: Divide AND assignment operator. It divides left operand with the right |C /= A is operand and assign the result to left operand. equivalent toC=C/A Modulus AND assignment operator. It takes modulus using two Ais operands and assign the result to left operand. equivalent toC=C%A >= Right shift AND assignment operator. C >= 2 is same as C = Co>2 Bitwise AND assignment operator. Cc & 2 is same as C = Ca2 bitwise exclusive OR and assignment operator. C= 21s same as C = cr2 = bitwise inclusive OR and assignment operator. c i= 2 is same as C = c\2 Conditional Operator (? Conditional operator is also known as the ternary operator. This operator consists of three ‘operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as — variable x = (expression) ? value if true : value if false Following is an example — public class Test { public static void main(String args[]) { int a, bs 1) ? 20: 30; System.out.println( "Value of bis : "+ b): Output b= (a == 10) ? 20: 30; System.out.println( "Value of bis : "4b ): Velue of b is : 30 Velue of b is : 20 Prepared by: Raju Poudel [MCA] 14Control Statements A programming language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Java’s program control statements can be put into the following categories: selection, iteration, and jump. - Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. - Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). - Jump statements allow your program to execute in a nonlinear fashion. Java’s Selection Statements Java supports two selection statements: if and switch. These statements allow you to control the flow of your program's execution based upon conditions known only during run time. The if statement is Java's conditional branch statement. It can be used to route program ‘execution through two different paths. Here is the general form of the if statement: if (condition) statement1; else statement2; The if works like this: If the condition is true, then statementi is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed. For example, consider the following: ifla 100) c = 4; // this it else a= cy 7/ associated with this else eis 4 to i£(4 == 10) q // this else rege Asthe comments indicate, the final else is not associated with if(}100) because itis the closest if within the same block. Prepared by: Raju Poudel [MCA] 15The if-else-if Ladder ‘A common programming construct that is based upon a sequence of nested ifs is the if-else- if ladder. It looks like this: if(condition) statement; else if(condition) statement; else if(condition) statement; else statement; Here is a program that uses an if-else-if ladder to determine which season a particular month is in. // Demonstrate if-else-if statements clase IfElee ( Public static void main(string argell) ( int month = 4; // April if (month 32 || month swinter*; 2 || month else if (month {| month == 4 || month season = "Spring™ else if (month || month == 7 || month else if (month I] mos 20 || month == 13) ‘season = "Autumn"; else ‘eason = "Bogus Month'; Systen.out.printin(*April is in the * + season + * ) Here isthe output produced by the program: April is in the Spring, switch The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements. Here is, the general form of a switch statement: Prepared by: Raju Poudel [MCA] 16‘switch (expression) { ‘case valet: // statement sequence break; ‘case vulue2: // statement sequence break; ‘case nalueN: // statement sequence break; default: // default statement sequence : Here isa simple example that uses a switch statement: // ® simple example of the switch. class Sampleswiten public static void main(String arge(]) ( for(int i=0; i Output: ‘Sum of two numbers=: class Box{ double width,height,depth,vol; //data members void getvolune() { | //method widt! height=20; depth=11.5; } double calculate() | //nethos vol-width*height*depth; return vol + class Volume { public static void main(string[] args) { Box objenew Box(); //creating instance of a class Sox ‘obj.getvolume(); _//calling menber function using object double ressobj.colculate(); //calling System.out.printIn("Volune of 2 box is “#res)3 r + Output: Volume of a box is 2300.0 Prepared by: Raju Poudel [MCA] 25Method That Takes Parameters Passing by value ‘Actual parameter expressions that are passed to a method are evaluated and a value is derived. Then this value is stored in a location and then It becomes the formal parameter to the invoked method. This mechanism is called pass by value and Java uses it. class Box{ double vol; //data menbers void getvolune(double width, double height, double depth) { //method volawidth*height*depth; + void display() { __//method ‘System.out.printIn("Volume of a box is "+vel); + + class Volune { public static void main(String{] args) { Box obj=new Box(); //creating instance of a class Box ‘obj -getvolume(10,20,11.5); //calling menber function using ebject obj.display(); //calling + Output: Volume of a box is 2300.0 Another Example class tox{ double width HIRE depth,vol; //data menbers void getdata(double w, double h, double 4) { //method widthew height=h; depthed: + double calculate() { — //method vol=widthsheight*depth; + return vol; class Volume { public static void mein(string{] o-gs) { Box objenew Box(); //creating instance of a class Box obj.getdata(10,20,11.5); //calling member function using object double reseobj.calculate(); — //calling System.out.println("Volune of a box is "#res); Output: Volume of a box is 2300. Prepared by: Raju Poudel [MCA] 26Passing by Reference We know that in C, we can pass arguments by reference using pointers, and same can be done in C+ using references. Java is pass by value and it is not possible to pass primitives by reference in Java. Also integer class is immutable in java and java objects are references that are passed by value. So an integer object points to the exact same object as in the caller and but no changes can be made to the object which gets reflected in the caller function. Constructors A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method: = Aconstructor doesn’t have a return type. + The name of the constructor must be the same as the name of the class. * Unlike methods, constructors are not considered members of a class. + Aconstructor is called automatically when a new instance of an objectis created. All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used. Following is the syntax of a constructor ~ class Classtione { Classtane() { } > Default Constructor The default constructor is a constructor that is automatically generated in the absence of explicit constructors (ie. no user defined constructor). The automatically provided constructor is called sometimes a nullary constructor. Constructor with no Arguments class BOX{ double 1,b,h,vol; Box(){ 1-105 bss i 235 y void calculate() { vol=1"b"h; Systen.out.println("Volume of a box is "+vol): public class Constructor { public static void main(String[] arg=) { Box obj=new Box()5 obj.calculate(); + + Outpu' Volume of a box is 165.0 Prepared by: Raju Poudel [MCA] 27Parameterized Constructor The constructor which has parameters or arguments is known as parameterized constructor. In this type of constructor, we should supply/pass arguments while defining object of a class. The values of arguments are assigned to data members of the class. class B0x{ double 1,b,h,vols Box(double x, double y, double 2){ Lexs + void calculate() { vol=1*b*h; System.out.printIn("Volume of a box is *+vol); + + public class Constructor { public static void main(String[] args) { Box objenew Box(10,5,3-3)3 obj.-calculate(); + y Output: Volume of a box is 165.0 The this Keyword Keyword this is a reference variable in Java that refers to the current object. The various usages of ‘THIS’ keyword in Java are as follows: * It can be used to refer instance variable of current class + Itcan be used to invoke or initiate current class constructor + It'can be passed as an argument in the method call + It can be passed as argumentin the constructor call + Itcan be used to return the current dass instance Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines this keyword. this can be used inside any method to refer to the current object. That is, 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. // ® redundant use of this. Box (double w, double h, double d) { this.width = w; this.height = h Prepared by: Raju Poudel [MCA] 28/Tlava code for using ‘this’ keyword to //eefer current class instance variables class Test { int a; int b; // Parameterized constructor Test(int a, int b) { this. = a5 this.b = b5 } void display() { //Displaying value of variables a and b System.out.printin("a =" +a+" b=" +b); 3 public static void main(String[] args) { Test object = new Test(1@, 20); object.display(); Output: a=10 b=20 Propared by: Raju Poudel [MCA] 29Four Main Features of Object Oriented Programming: 1. Abstraction 2. Encapsulation 3. Polymorphism 4, Inheritance Abstraction Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information ‘on what the object does instead of how it does it. In Java, abstraction is achieved using Abstract classes and interfaces. Abstract Class ‘A class which contains the abstract keyword in its declaration is known as abstract class. * Abstract classes may or may not contain abstract methods, i.e., methods without body (public void get();) + But, if a class has at least one abstract method, then the class must be declared abstract. + Ifaclass is declared abstract, it cannot be instantiated (We cannot create object). * To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it. + If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. abstract class Box{ int 1,b,h,vol5 void getdata() { 1-105 void calculate() { bth ut.println(“Volume of a box is “+vol); public class Abstraction extends Box { public static void main(String[] args) { Abstraction obj-new Abstraction(); obj.getdata(); obj-ealeulate(); Output: Volume of a box is 100 Prepared by: Raju Poudel [MCA] 20Encapsulation Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, itis also known as data hiding. To achieve encapsulation in Java- * Declare the variables of a class as private. * Provide public setter and getter methods to modify and view the variables values. Benefits of Encapsulation + The fields of a class can be made read-only or write-only. + Aclass can have total control over what is stored in its fields. class Test{ private String name; private int age; public String getname() { return name; ¥ public int getage() { return ages + public void setnane(String nm)|if names + public void setage(int ag) { age=2gs } + public class Encapsulation { public static void main(String args) { Test objenew Test( obj -setname("Raaju Poudel”); obj. setage (27; System.out-printLn("Name: "“+obj-getname()); System.out.printLn("Age: “+obj.getage()); Output: Name: Raaju Poudel Age: 27 Here, we cannot access private data members name and age directly. So we have created public getter and setter methods to access private data members. Prepared by: Raju Poudel [MCA] anPolymorphism Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding. Polymorphism in Java ‘Compile Time Runtime (Method Overloading)| (Method Overiding) Method Overloading Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists. In order to overload a method, the argument lists of the methods must differ in either of these: a) Number of parameters. add(int, int) add(int, int, int) b) Data type of parameters. add(int, int) add(int, float) ¢) Sequence of Data type of parameters. add(int, float) add{float, int) Prepared by: Raju Poudel [MCA] 22Example of method overloading: class Overload { void demo (int a) { system.out.println ("a: " + a); } void demo (int a, int b) { System.out.println ("a and b: "+a + "," +b); ? double demo(double a) { System.out.printIn("double a: " + a); return a + Class MethodOverloading { public static void main (string args []) t Overload 0bj double result; Obj .demo(10); Obj .demo(10, 20); bj -demo(5.5 System.out.print1n("0/P : new Overload()s result + result); Output: a: 10 a and b: 10,20 double a: 5.5 O/P : 30.25 Here the method demo() is overioaded 3 times: first method has 1 int parameter, second method has 2 int parameters and third one is having double parameter. Which method is to be called is determined by the arguments we pass while calling methods. This happens at compile time so this type of polymorphism is known as compile time polymorphism. Prepared by: Raju Poudel [MCA] 33Method Overriding Declaring @ method in sub class which is already present in parent class is known as method overriding. Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. In this cese the method in parent class is called overridden method and the method in child class is called overriding method Let's take a simple example to understand this. We have two classes: A child class Boy and a parent class Human. The Boy class extends Human class. Both the classes have a common method void eat (). Boy class Is giving its own Implementation to the eat () method or in other words it is overriding the eat () method. class Hunan{ //overridden method public void eat() { Systen.out.print1n("Human is eating”); Hy class Boy extends Human{ //overriding method public void eat(){ systen.out.print1n("Boy is eating"); + public static void main( string args{]) { Boy obj = new Boy(); This will ca: obj.eat(); the child class version of eat() Output: Boy is eating Rules of method overriding in Java 1. Argument list: The argument list of overriding method (method of child class) must match the Overridden method (the method of parent class). The data types of the arguments and their sequence should exactly match. 2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of parent class method is public then the overriding method (child class method) cannot have private, protected and default Access modifier, because all of these three access modifiers are more restrictive than public. Prepared by: Raju Poudel [MCA] 34Another Example: AnimaLjava public class Animal{ public void sound(){ Systen.out.printIn(“Animal is making a sound"); Horse.java class Horse extends Aninal{ @override public void sound(){ System.out.println("Neigh’ + public static void main(String args[]){ Aninal obj = new Horse(); obj.sound(); Output: Neigh Recursion Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to Java programming, recursion is the attribute that allows a method to call itself. ‘A method that calls itself is said to be recursive. The classic example of recursion Is the computation of the factorial of @ number. The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 x 2 x 3, or 6. Here is how a factorial can be computed by use of a recursive method: Prepared by: Raju Poudel [MCA] as// ® simple example of recursion clase Factorial { // this is a recursive method int fact(int n) ( int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } class Recursion { public static void main(String args{J) { Factorial f = new Factorial (); system.out.printin(*"Factorial of 3 is * + £.fact(3)); System.out .printIn("Factorial of 4 is " + £.fact (4); System.out.print1n(*"Factorial of 5 is * + £.fact (5)); } The output from this program is shown here: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120 Introducing Nested and Inner Classes It is possible to define a class within another class; such classes are known as nesied classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B does not exist independently of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. A nested class that is declared directly within its enclosing class scope is a member of its enclosing class. It is also possible to declare a nested class that is local to a block. There are two types of nested classes: static and non-static. A static nested class is one that has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. The following program illustrates how to define and use an inner class. The class named Outer has one instance variable named outer_x, one instance method named test{ ), and defines one inner class called Inner. Prepared by: Raju Poudel [MCA] 36// Demonstrate an inner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner display (); } // this is an inner class class Inner { void display() { System. out .printIn(*display: outer_x = " + outer_x); } } } clase InnerClaseDemo { public static void main(String args{]) { Outer outer = new Outer(); outer.test(); } } Output from this application is shown here: display: outer_x = 100 In the program, an inner class named Inner is defined within the scope of class Outer. Therefore, any code in class Inner can directly access the variable outer_x. An instance method named display( ) is defined inside Inner. This method displays outer_x on the standard output stream. The main( ) method of InnerClassDemo creates an instance of class Outer and invokes its test{ ) method. That method creates an instance of class Inner and the display( ) method is called. Access Control ‘As you know, encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. For example, allowing access to data only through a well- defined set of methods, you can prevent the misuse of that data. Java’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved. Prepared by: Raju Poudel [MCA] a7Unit — 4 Inheritance & Packaging [3 Hrs. Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features (fields and methods) of another class. The process by which one class acquires the properties (dato members) and functionalities(methods) of another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also Inheritance represents the IS-A relationship which is also known as aparent- child relationship. inheritance is used in java for the following: © For Method Overriding (so runtime polymorphism can be achieved). © For Code Reusability. Terms used in Inheritance Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. © Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. © Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. Itis also called a base class or a parent class. © Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. The syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields + The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited Is called a parent or superclass, and the new class is called child or subclass. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. Prepared by: Raju Poudel [MCA] a8Single Inheritance [crea | public class A ) public class B extends A { ca Multi Level inheritances = public class A{ d Clase 8 public class B extends A (. } public class Cextends 8 { } Multiple Inheritance public class A... public class B extends A (. public class C extends A {..ncnnnnnm) public class A ( ) public class B (. } public class Cextends A,B ( 11 Java does not support mutiple inheritance gle Inheritance Single Inheritance refers to @ child and parent class relationship where a class extends the another class. class Animal{ void eat(){ ‘System.out.printin("eating..."); 3 + class Dog extends Animal{ void bark(){ System.out.printin("barking..."); 3 + class TestInheritance{ public static void main(String args(]){ Dog d.bark(); dveat(); jew Dog(); Prepared by: Raju Poudel [MCA] 29eating. 2. Multilevel Inheritance Multilevel inheritance refers to a child and parent class relationship where a class extends the child class. For exemple, class C extends class B and class B extends class A. class Animal{ void eat(){ System.out.printin(“eating 3 + class Dog extends Animal{ void bark(){ System,out.printin("barking...” oa + class BabyDog extends Doot void weep(){ System.out.printin("weeping. 3 + class Testinheritance2{ public static void main(String args[1) { // declare constant fields // declare methods that abstract // by default. To deciare an interface, use interface keyword. It is used to provide total abstraction. That means all the methods in interface are declared with empty body and are public and all fields are public, static and final by default. A class that implement interface must implement all the methods declared in the interface. To implement interface use implements keyword. Why do we use interface? + Itisused to achieve total abstraction. * Since java does not support multiple inheritance in case of cass, but by using interface it can achieve multiple inheritance. // & simple interface interface Player final int id = 10; int move(); Prepared by: Raju Poudel [MCA] a2Example of Interface // Java program to demonstrate working of // interface. import java.io.*; J/ & simple interface interface inl { // public, static and final final int a = 10; // public and abstract void display(); 3 J] A class that implements interface. class testClass implements ind { // Implementing the capabilities of I) interface. public void display() { System. out. printin(“Geek"); } // Driver Code public static void main (String[] args) { testClass t = new testClass(); t.display(); System. out .printin(a); 3 + Output: Geek 10 Prepared by: Raju Poudel [MCA]Use of Interface to achieve multiple inheritance Let us say we have two interfaces A & B and two classes C & D. Then we can achieve multiple inheritance using interfaces as follows: interface A{ } interface B{ } class C{ } class D extends C implements A,B { } Example Program interface interfacel{ void display1(); t interface interface2f] void display2(); W class A{ void display3() { System.out.print1n("I am inside class"); } } class B extends A implements interface1, interface2{ public void display1() { System.out.println("I am inside interfacei"); + public void display2() { System.out.print1n("I am inside interface2"); + } public class Multilevel { public static void main(String[] args) { B obj=new B(); obj-display1(); obj.display2(); obj. display3();| } } Output I am inside interfacel I am inside interface2 I am inside class Prepared by: Raju Poudel [MCA] a4Another Example interface interfacel{ int o=20,b=10; void add(); + class Ax{| int diff; void subtract (int x,int y) { diff=x-y; System.out.print1n("Subtraction= "+diff); ) q class Bx extends Ax implements interfacel{ int sum; public void add() { sum=a+b; System. out. print1n("Addition= "+sum) 5 + public class Multilevel { public static void main(String[] args) { Bx obj=new Bx()5 obj.add(); obj.subtract(50, f1);| Prepared by: Raju Poudel [MCA] 4sDynamic Method Dispatch Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. Here is an example that illustrates dynamic method dispatch: // Dynamic Method Dispatch class A { void callme() { System.out .printIn("Inside A's callme method"); } 4 class B extends A { // override calime() void callme() { System.out .printin("Inside B's callme method") ; } ' class C extends A { // override calime() void callme() { System.out.printin("Inside C's callme method") ; } } class Dispatch { public static void main(String args{}) { Aa = new A(); // object of type A Bb = new B(); // object of type B Cc = new C(); // object of type C Ar; // obtain a reference of type A r =a; // x refers to an A object r.callme(); // calls A's version of callme x= b; // x refers to a B object r.callme(); // calls B's version of callme r=; // x refers to a C object r.callme(); // calls C's version of callme } } The output from the program is shown here: Inside A’s callme method Inside B’s callme method Inside C’s callme method Prepared by: Raju Poudel [MCA] 46This program creates one superclass called A and two subclasses of it, called B and C. Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of type A,B, and C are declared. Also, a reference of type A, called r, is declared. The program then in turn assigns a reference to each type of object to r and uses that reference to invoke callme{ ). As the output shows, the version of callme( ) executed is determined by the type of object being referred to at the time of the call. Had it been determined by the type of the reference variable, r, you would see three calls to A’s callme( ) method. Super Keyword The super keyword in java is @ reference variable that is used to refer parent class objects. The keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the following contexts: 1, Use of super with variables: This scenario occurs when a derived class and base class has same data members. In that case there is a possibility of ambiguity for the JVM. We can understand it more clearly using this code snippet: /* Base class vehicle */ class Vehicle { + int maxSpeed - 120; /* sub class Car extending vehicle */ class Car extends Vehicle { int maxSpeed = 180; void display() { /* print naxSpeed of base class (vehicle) */ System.out.printIn( "Maximum Speed: " + super.maxSpeed) ; } } /* Driver program to test */ class Test { public static void main(String[] args) { Car small = new Car()5 small.display(); Output: Maximum Speed: 120 Prepared by: Raju Poudel [MCA] a7In the above example, both base class and subclass have a member maxSpeed. We could access maxSpeed of base class in subclass using super keyword. 2. Use of super with methods: This is used when we want to call parent class method. So whenever a parent and child class have same named methods then to resolve ambiguity we use super keyword. This code snippet helps to understand the said usage of super keyword. /* Base class Person */ class Person { void message() System.out.println(“This is person class"); } /* Subclass Student */ class Student extends Person { void message() { System.out.printin("This is student class" + J] Note that display() is only in Student class void display() J/ will invoke or call current class message() method message(s 1/ will invoke or call parent class message() method super.message(); + } /* Driver program to test class Test t public static void main(String args[]) { Student s = new Student()5 I/ calling displey() of Student s.display(); + t Output This is student class This is person class In the above example, we have seen that if we only call method message () then, the current class message () is invoked but with the use of super keyword, message () of superclass could also be invoked. Prepared by: Raju Poudel [MCA] 483. Use of super with constructors: super keyword can also be used to access the parent class constructor. One more important thing is that, ‘super’ can call both parametric as well as non-parametric constructors depending upon the situation. Following is the code snippet to explain the above concept: /* superclass Person */ class Person t Person() { System. out.printIn("Person class Constructor } } /* subclass Student extending the Person class */ class Student extends Person t Student() { // invoke or call parent class constructor super()5 System.out.printIn("Student class Constructor"); } + /* Driver program to test*/ class Test { public static void main(String[] args) { Student s = new Student(); t } Output: Person class Constructor Student class Constructor In the above example we have called the superclass constructor using keyword ‘super’ via subclass constructor. Prepared by: Raju Poudel [MCA] 49Abstract and Final Classes Abstract class has been discussed already in Unit-3 (Abstraction). The keyword final has three uses. First, it can be used to create the equivalent of anamed constant. The other two uses of final apply to inheritance. Using final to Prevent Overriding While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring, To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final: class A { final void meth() { System.out .printin(*This is a ) ) 1 method.) ; class B extends a { void meth() { // ERROR! Can’ System. out .print1n(*Tilegal!*) ; } } Because meth () is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time error will result. Using final to Prevent Inheritance Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as, final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. Here is an example of a final class: final W ) ase A { // The following class class B extends A { / Wi ) 2 {2legal ROR! Can't subclass A As the comments imply, itis illegal for B to inherit A Since A is declared as final. Prepared by: Raju Poudel [MCA] 50The Object Class There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array. Object defines the following methods, which means that they are available in every object Method Jobject clone( ) boolean equais(Object object) void finalize ) Class getClass( ) int hashCode( ) void notify( ) [void nouityAlK ) String toString( ) [void wait) void wait(long milliseconds) |void waitiiong milisecones, int nanoseconds) Purpose Creates new object that is the same as the object being cloned. Determines whether one object is equal to another. Called before an unused object is recycled. Obtains the class of an object at run time. Returns the hash code associated with the invoking object. Resumes execution of a thread waiting on the invoking abject. Resumes execution of all threads waiting on the invoking object. Returns a string that describes the object. ‘Waits on another thread of execution, The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override the others. However, notice two methods now: equals( ) and toString( ). The equals( ) method compares the contents of two objects. It returns true if the objects are equivalent, and false otherwise. Package A Java package Is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision. The package keyword is used to create 2 package in java. //save as Simple.java package mypack; public class Simple Output :Helle ‘Subpackage in java Package inside the package Is called the subpackage. package java.util. Scanner; class Simplet public static void main(String args[]){ ‘Scanner scan=new Scanner(System. ‘System.out.printin("Enter a number"); int a = scan.nextint(); ‘System.out.printin(“Inputted number is: “+a); +} Prepared by: Raju Poudel [MCA] 52Unit — 5 Handling Error/Exceptions [2 Hr: ‘An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e. atrun time, that disrupts the normal flow of the program's instructions. Error vs Exception Error: An Error indicates serious problem that a reasonable application should not try to catch. Exception: Exception indicates conditions that a reasonable application might try to catch. ‘An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled ‘An exception can occur for many different reasons. Following are some scenarios where an exception occurs. + Auser has entered an invalid data. + file that needs to be opened cannot be found. + Anetwork 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. Based on these, we have three categories of Exceptions. You need to understand them to know how exception handling works in Java. * Checked exceptions - A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored; the programmer should take care of (handle) these exceptions. * Unchecked exceptions - An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. «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. Prepared by: Raju Poudel [MCA] 53Hierarchy of Java Exception classes The java.lang, Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below: Prepared by: Raju Poudel [MCA] saJava Exception Keywords There are 5 keywords which are used in handling exceptions in Java. Keyword |Description try The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. catch The “catch” block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. finally ‘The “finally” block Is used to execute the Important code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws | The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies thet there may occur an exception in the method. It is always used with method signature. Java Exception Handling Example Let's see an example of Java Exception Handling where we using a try-catch statement to handle the exception. public class JavaExceptionExample{ void main(String args[]) + Output: Exception in thread main java.lang.A rest of the co hmeticException:/ by zero Prepared by: Raju Poudel [MCA] 55Common Scenarios of Java Exceptions There are given some scenarios where unchecked exceptions may occur. They are as follows 1) A scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException int a=50/0;//Arithmeticexception 2) A scenario where NullPointertxception occurs If we have a null value in any variable, performing any operation on the variable throws a NuliPointerException String s=null; System. out.printin(s.length());//NullPointerException 3) A scenario where NumberFormat€xception occurs The wrong formatting of any value may occur NumberFormatException. Suppose | have a string variable that has characters, converting this variable into digit will occur NumberFormatException. String "5 int i=Integer.parseint(s);//NumberFormatéxception ‘abc’ 4) A scenario where ArrayindexOutOfBoundsException occurs If you are inserting any value in the wrong index, it would result in ArrayindexOutOfBoundsException as shown below: int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException Java finally block Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block. public class TestFinallyBlock2{ public static void main(String args[]){ try{ int data=25/0; ‘System.out.printin(data);, > catch(ArithmeticException e){ System.out.printin(e); 3 finally{ ‘System.out. printin("finally block is always executed"); Prepared by: Raju Poudel [MCA] 56+ ‘System.out.printin(“rest of the code..."); Exception in thread main java.lang.Arithmeticaxception:/ by zero finally block is always executed rest of the code... Java Multi-catch block A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block. At a time only one exception occurs and at a time only one catch block is executed. All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception. public class MultiplecatchBiock1 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; + catch(Arithmeticexception e) Output: ArraylndexOutofBounds Exception occurs rest of the code Java Nested try block The try block within a try block is known as nested try block in java. Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Syntay try { statement 1; statement 2; try { statement 1 statement 2; } Prepared by: Raju Poudel [MCA] 58catch(Exception e) } } catch(Exception e) { } Example: class Excep6{ public static void main(String args[]) System out printin(“other statement); }eatch(Exception e){ System.out.printin("handeled"); + System.out.printin("normal flow.."); + + Prepared by: Raju Poudel [MCA] 59Java throw keyword The Java throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. The syntax of java throw keyword is given below. throw new lOException("sorry device error); Example: In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. public class TestThrow1{ static void validate(int age){ if(age s2, it returns positive number si

You might also like