0% found this document useful (0 votes)
487 views179 pages

Oops Notes

Oops notes

Uploaded by

Selva612
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)
487 views179 pages

Oops Notes

Oops notes

Uploaded by

Selva612
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/ 179
RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. UNIT- INTRODUCTION TO OOP AND JAVA FUNDAMENTALS. 1, Object Oriented Programming (OOP) Object-oriented programming (OOP) is a programming language model organized around objects rather than "aetions" and data rather than “logic”. Historically, a program, has been viewed as a logical procedure that takes input data, processes it, and produces output data, Object Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: © Object Class Abstraction Encapsulation Inheritance Polymorphism Four major OOPS concepts are 1. Abstraction 2. Polymorphism 3. Inheritance 4, Encapsulation Structure of a Java Program Example: “Hello World” Java Program public class Main { public static void main(String[] args) { System.out.printin("Hello, World!"); } t The first line defines a class called Main, ol lass Main { In Java, every line of code that can actually run needs to be inside a class. This line declares a class named Main, which is public, that means that any other class can access it. ‘ide a file with the same Notice that when we declare a public class, we must declare it i name (Main.java), otherwise well get an error when compiling, Department of Computer Science and Engineering 1RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. The next line is: This is the entry point of the Java program. The main method has to have this exact signature in order to be able to run our program. © BEAR sain means that anyone can access it . means that we can run this method without creating an instance of FEBEM. (We do not need to create object for static methods to run. They can run itself) © (BBG means that this method doesn't return any value, © HEB is the name of the method. The arguments we get inside the method are the arguments that we will get when running the program with parameters. I's an array of strings. Tn Wis a pre-defined class that Java provides us and it holds some useful methods and variables. His static variable within System that repre s the output of our program (stdout). . is a method of out that can be used to print a line. 1.1 Classes and objects Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities, L.L.1 Class A class is a user defined blueprint or prototype a program from which objects are created. It represents the set of properties or methods that are common to all objects of one type. Example 2: public class Cat { int age; String color; void barking() { Department of Computer Science and Engineering 2RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. } void hungry() { F void sleeping() { + Aclass can be public or has default access. The name should begin with an initial letter (capitalized by convention). 2 The class body surrounded by braces, { } : The sub functions a may have in their body. Aclass can contain any number of variables. A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods. In general, class is a collection of methods (Functions) and attributes (Variables). 1.1.2 Objects It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java program creates many objects, which interact by invoking methods. An object consists of : State: Itis represented by attributes of an object. It also reflects the properties of an object. Behavior It is represented by methods of an object. It also reflects the response of an object with other objects. Identity It gives a unique name to an object and enables one object to interact with other objects. Example of an object : Cat, its state is - name, color, and the behavior is - barking, wagging the tail, running ete. Example = Public class Point { int x; int ys } This class defined a point with x and y values (variables). Department of Computer Science and Engineering 3RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. In order to create an instance of this class, we need to use the keyword [ISM Point p = new Point(); In general, object is an instance of a class. 1.2 Abstraction Abstraction is one of the major concepts behind object-oriented. programming (OOP). Abstraction is a process of hiding the implementation details from the user. Only the functionality will be provided to the user. In Java, abstraction is achieved using abstract classes and interfaces. Data Abstraction is the property of displaying only the essential details to the user. The trivial or the non-essentials units are not displayed to the user. Example : A car is viewed as a car rather than its individual components. Abstract Class Aclass which contains the abstract keyword in its declaration is known as abstract class, Example: abstract class Bike{} Abstract method Abstract classes may or may not contain abstract methods, i.e., methods without body (public void get; ) But, if class has at least one abstract method, then the class must be declared abstract. Ifa class is declared abstract, it cannot be instantiated. A method that is declared as abstract and does not have implementation is known as abstract method. Example: abstract void printStatus();//no body and abstract Example of abstract class that has abstract method: In this example, Bike the abstract class that contains only one abstract method run. Its implementation is provided by the Honda class. // Abstract class declaration Department of Computer Science and Engineering 4RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. abstract class Bike{ abstract void run(); > 1 Class Hondad inherits the characteristics of the abstract class class Honda extends Bike{ void run() ‘ System.out.printin("running safely..’ // Main class which invokes the class Honda public static void main(String args{]){ Bike obj = new Honda(); obj.run(); 2 i Understanding the real scenario of abstract class with an example: Example L: File: TestAbstraction| java abstract class Shape{ abstract void draw(); > /Iin real scenario, implementation is provided by others i.e. unknown by the end user class Rectangle extends Shape( void draw() a System.out.printin("drawing rectangle"); . ? class Circle1 extends Shape{ void draw() 4 System.out.printin("drawing circle"); > } Department of Computer Science and Engineering 5RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. //in real scenario, method is called by programmer or user class TestAbstraction1{ public static void main(String args{]) { Shape s=new Circle1();//In real scenario, object is provided through method e.g. /igetShape() method s.draw(); @rawing circle In the above example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know about the implementation class (ie. hidden to the end user) and object of the implementation class is provided by the factory method. (4 factory method is the method that returns the instance of the class.) In this example, if’ we create the instance of Rectangle class, draw() method of Rectangle class will be invoked. Example 2: abstract class Bank{ abstract int getRateOfinterest(); > class SBI extends Bank( int getRateOfinterest() £ return 7; y + class 10B extends Bank{ int getRateOfinterest() £ return 8; + > Department of Computer Science and Engineering 6RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. class TestBank{ public static void main(String args{]){ Bank b; b=new SBI(); ‘System.out. printin("Rate of Interest is: "+b.getRateOflnterest()+" %" b=new 108(); ‘System.out. printin("Rate of Interest is: "-+b.getRateOfinterest()+" %"); + Output Rate of Interest is: 74 Rate of Interest is: 3% 1.3 Encapsulation Encapsulation in java is a process of wrapping code and data together into a single unit, for example capsule i.e, mixed of several medicines. We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and ger the data in it. By providing only setter or getter method, we can make the class read-only or write-only. It provides the control over the data. Example : [iStudent.java public class Student ate String name; Public String getName(){ return name; + Public void setName(String name){ this.name=name 2 Department of Computer Science and Engineering 7RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ? Test.java class Test( public static void main(String[] args){ Student s=new Student(); s.setName("vijay"); ‘System.out.printin(s.getName()); y i Output: vijay Example 2: To understand what is encapsulation in detail consider the following bank account class with deposit and show balance methods: class Account { private int account_number; private int account_balance; public void show Data() { Iicode to show data + public void deposit(int a) { if(a y class c extends A,8{//suppose if it were Public Static ve C obj=new C(); obj.msg();//Now which msg() method would be invoked? > 2 ~+= Execute and see the output of this program main(String args[}){ 5. Hybrid inheritance: It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces. Cae Ges Department of Computer Science and Engineering 7RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.5 Polymorphism Polymorphism in java is a concept by which we ean perform a single action by different ways. For example, we have a smartphone for communication. The communication mode we choose could be anything. It can be a call, a text message, a picture message, mail, etc. So, the goal Polymorphism. S common that is communication, but their approach is different. This is called Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means ‘many and "morphs" means forms. So polymorphism means many forms. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways. For example, lets say we have a class Animal that has a method sound(). Since this is a generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a generic message. public class Animal{ public void sound(){ ‘System.out.printin("Animal is making a sound"); + } Now lets say we two subclasses of Animal class: Horse and Cat that extends (see Inheritance) Animal class. We can provide the implementation to the same method like this: Department of Computer Science and Engineering 18RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public class Horse extends Animal{ ” @override public void sound(){ System. out:printin("Neigh"); } , and public class Cat extends Animal{ @override public void sound(){ System.out.printin(*Meow"); > + Note : The @Override means that the method is overriding the parent class (in this case createSolver ). When a method is marked with the @Override annotation, the compiler will perform a check to ensure that the method does indeed override or implement a method in ‘super class or super interface. ‘As we can sce that although we had the common action for all subclasses sound() but there were different ways to do the same action. This is a perfect example of polymorphism (feature that allows us to perform a single action in different ways). It would not make any sense to just call the generic sound() method as each Animal has a different sound. Thus we can say that the action this method performs is based on the type of object. Polymorphism is divided into two, they are: * Static or Compile time polymorphism (achieved by method overloading) * Dynamic or Runtime polymorphism (achieved by method overriding) Static polymorphism in Java is achieved by method overloading and Dynamic polymorphism in Java is achieved by method overriding Department of Computer Science and Engineering 1»RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.5.1 Static or Compile time Polymorphism Example: Method Overloading on the other hand is a compile time polymorphism example. class Overload void demo (int a) { System.out-printin ("a: " +a); } Void demo (int a, int b) { System.out.printin ("a and b: "+ a+ "," + b); double demo(double a) { System.out.printin("double a: " + a); return ata; + class MethodOverloading public static void main (String args [}) { Overload Obj = new Overload(); double result; Obj .demo(10); Obj .demoi10, 20); result = Obj demo(5.5); System.out.printin("O/P : " + result); + } Here the method demo() is overloaded 3 times: first method has 1 int parameter, second method 35 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 runtime so this type of polymorphism is known as compile time polymorphism, Output: a:10 aand b: 10,20 double a: 5.5 OP 30.25 Department of Computer Science and Engineering 20RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.5.2 Dyna or Runtime Polymorphism: Example: mal.java public class Animal{ public void sound(){ ‘System.out.printin("Animal is making a sound"); class Horse extends Animal{ ‘@Override public void sound) { System.out.printin("Neigh" + public static void main(String args[]){ Animal obj = new Horse(); obj.sound(); Catjava public class Cat extends Animal{ @Override public void sound(){ System.out.printin("Meow"); } ublic static void main(String args{]){ Animal obj = new Cat(); obj. sound(); Department of Computer Science and Engineering 2RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.5.3 Rules for Method Overriding ‘© The method signature i.e. method name, parameter list and return type have to match exactly, * The overridden method can widen the accessibility but not narrow it, ie. if it is private in the base class, the child class can make it public but not vice versa. Doctor 3) Overrides the treatPatient() Method 2) Adds anew ‘Method Incision() ‘Surgeon Difference between Static & Dynamic Polymorphism (Difference between Overloading and Overriding) ‘Static Polymorphism I Dynamic Polymorphism It relates to method overloading. [it relates to method overriding. Errors, if any, are resolved at compile time. [In case a reference variable is calling an Since the code is not executed during Joverridden method, the method to be invoked i lcompilation, hence the name static [determined by the object, our reference variabl lis pointing to. This is can be only determined at Ex: [runtime when code in under execution, hence ithe name dynamic. }void sum (int a , it b); void sum (float a, double b): Department of Computer Science and Engineering 2RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. int sum (int a, int b); i/compiler gives error. Ex: I/reference of parent pointing to child object Doctor obj = new Surgeon(); I/ method of child called jobj.treatPatient(); Method overloading is in the same class, hwhere more than one method have the same name but different signatures. Ex: Jvoid sum (int a , int b); Jvoid sum (int a , int b, int c); Jvoid sum (float a, double b); [Method overriding is when one of the methods in the super class is redefined in the sub-class. In this case, the signature of the method remains the same. Ex: iclass X{ public int sum0{ iI some code } lclass Y extends X{ public int sum(){ /Joverridden method fJsignature is same y b Important points * Polymorphism is the ability to create a variable, a function, or an object that has more than one form. * In java, polymorphism is divided into two parts : method overloading and method overriding, © Another term operator overloading is also there, e.g. “+” operator can be used to add vo integers as well as concat two sub-strings. We cannot have our own custom defined operator overloading in java. Department of Computer Science and Engineering 23RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.6 Characteristics of Java Simple: ‘© Java is Easy to write and more readable and eye catching, ‘* Java has a concise, cohesive set of features that makes it easy to leam and use, © Most of the concepts are drew from C+ thus making Java learning simpler. Secure : * Java program cannot harm other system thus making it secure. ‘* Java provides a secure means of creating Intemet applications. ‘© Java provides secure way to access web applications. Platform Independent: ‘* java is platform independent Department of Computer Science and Engineering 24RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ‘* Java is platform independent because itis different from other languages like C, C+ etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in which a program runs. ‘© Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA), Portable: ‘© Java programs can execute in any environment for which there is a Java run-time system.(IVM ~ Java Virtual Machine) ‘© Java programs can be run on any platform (Linux, Window,Mac) ‘© Java programs can be transferred over world wide web (e.g applets) Object-oriented : ‘© Java programming is object-oriented programming language. ‘+ Like C++ java provides most of the object oriented features. ‘+ Javaiis pure OOP. Language. (while C++ is semi object oriented) Robust : ‘* Java encourages error-free programming by being strictly typed and performing run- time checks. Multithreaded : ‘© Java provides integrated support for multithreaded programming. Architecture-neutral : ‘© Java is not tied to a specific machine or operating system architecture ‘* Machine Independent i.e Java is independent of hardware . Interprete ‘* Java supports cross-platform code through the use of Java bytecode, © Bytecode can be interpreted on any platform by JVM High performance : © Bytecodes are highly optimized. ‘© JVMcan executed them much faster Distributed : ‘© Java was designed with the distributed environment. ‘© Java can be transmit,run over internet. Dynamic : Department of Computer Science and Engineering 25RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ‘© Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time, Java Runtime Environment (JRE) The Java Runtime Environment (JRE) is a set of software tools for development of Java applications. It combines the Java Virtual Machine (JVM), platform core classes and supporting, libraries, JRE is part of the Java Development Kit (JDK) was developed by Sun Microsystems. Java Source File A Java source file is a plain text file containing Java source code and having java extension. The -java extension means that the file is the Java source file. Java source code file contains source code for a class, interface, enumeration, or annotation type. There are some rules associated to Java source file. The following rules to be followed while writing Java source code. ‘© There can be only one public class per source code fil. ‘© Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules. Java comment can be inserted anywhere in a program code where a white space can also be ‘© If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Student { } must be in a source code file named Student.java.(ce the file name and the class name must be same) ‘© If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present. ‘© If there are import statements, they must go between the package statement (if there is fone) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements , the class declaration must be the first line in the source code file. Department of Computer Science and Engineering 26RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ‘© import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports * A fille can have more than one non~publie class ‘© Files with non~publie classes can have a name that does not match any of the classes in the file Java Source File Structure ‘A Java source file can have the following elements that, if present, must be specified in the following order: + Anoptional package declaration to specify a package name. * Zero or more import declarations. * Any number of top-level type declarations. Class, enum, and interface declarations are collectively known as type declarations. * In Java, at the most one public class declaration per source file can be defined. Ifa public class is defined, the file name must match this public class. Example // Filename: Newdpp java // PART 1; (OPTIONAL) package declaration package com.conpany.. project. fragi lePackage; // PART 2: (ZERO OR MORE) inport declarations inport java.io.s; ‘import java.util.«; // PART 3: (ZERO OR MORE) top-level class and interface declarations public class NewApp { } class AClass { } interface I0ne { } class BClass { } interface ITwo { } Wise // end of File Example Program: package javatutorial; Department of Computer Science and Engineering a7RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. * My first Java HelloWorld class prints the Hello World message. public class HelloWorld { public static void main(String[] args) { System.out printIn("Hello World : I am learning java @ fSjava.com"); } t 1.7.2 Compile and Run Java Program Sample Java Program public class FirstlavaProgram { public static void main(Stringl] args){ ‘System. out.printin("This is my first program in java"); Ji/End of main WIEnd of FirstjavaProgram Class How to compile and run the above program Step 1: Open a text editor, like Notepad on windows. Write the program in the text editor. Step 2: Save the file as FirstJavaProgram,java, We should always name the file same as the public classname. In our program, the public class name is FirstJavaProgram, that’s why our file name should be FirstJavaProgram,jaya. Step 3: In this step, we will compile the program. For this, open command prompt (emd) on Windows. To compile the program, type the following command and hit enter. javac FirstjavaProgram.java Department of Computer Science and Engineering 28RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Step 4: After compilation the java file gets translated into the .class file(byte code). Now we can run the program. To run the program, type the following command and hit enter: java FirstjavaProgram Closer look to the First Java Program Now that we have understood how to run a java program, let have a closer look at the program we have written above, public class FirstlavaProgram { This is the first line of our java program. Every java application must have at least one class definition that consists of class keyword followed by class name. When we say keyword, it means that it should not be changed, we should use it as it is. However the class name can be anything, We have made the class public by using publie access modifier, we will cover access modifier in separate post, all we need to know now that a java fi can have only one public class and the file name should be same as public class name. ‘an have any number of classes but it Public static void main(String[] args) { This is the next line in the program, lets break it down to understand it: public: This makes the main method public that means that we can call the method from outside the class static: We do not need to create object for static methods to run, They can run itself. void: It does not return anything, main: It is the method name. This is the entry point method from which the JVM can run our progran (String[] args): Used for command line arguments that are passed as strings. System.out.printin("This is my first program in java"); This method prints the contents inside the double quotes into the console and inserts a newline after. 1.8 Fundamental Programming Structure in Java Department of Computer Science and Engineering 2»RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Java program consists of different sections. Some of them are mandatory but some are optional. The optional section can be excluded from the program depending upon the requirements of the programmer. * Documentation Section © Package Statement Import statements Interface Section Class Section Documentation Seetion: It includes the comments to tell the program's purpose. It improves the readability of the program, Single line (or end-of line) comment It starts with a double slash symbol (/) and terminates at the end of the current line. The compiler ignores everything from // to the end of the line. For example: 1 Calculate sum of two numbers Muttitine Comment = Java programmer can use C/C++ comment style that begins with delimiter /* and ends with */. All the text written between the delimiter is, ignored by the compiler. This style of comments can be used on part of a line, a whole line or more commonly to define multi-line comment. For example. /rcalculate sum of two numbers */ Comments cannot be nested, In other words, we cannot comment a line that already includes traditional comment, For example, (*x=y / initial value */ +25 */ is wrong. Package Statement = It includes statement that provides a package declaration For example: Suppose we write the following package declaration as the first statement in the source code file. package employee; This statement declares that all classes and interfaces defined in this source file are part, of the employee package. Only one package declaration can appear in the source file Import statements = It includes statements used for referring classes and interfaces that are declared in other packages. For example: Department of Computer Science and Engineering 30RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Import java.util.Date; /* imports only the Date class in java.util package */ java applet package import javaapplet.*;—_// importsall the classes i tis similar to a class but only includes constants, method declaration, + It describes information about user defines classes present in the program, Every Java program consists of at least one class definition. This class definition declares the main method. It is from where the execution of program actually starts. Main method zExecution of a java application starts from “main” method. In other ‘words, its an entry point for the class or program that starts in Java Run- time. Interface Section Class Section 1.9 Defining classes in Java ‘Acclass is the basic building block of an object-oriented language such as Java. The class is a template that describes the data and the behavior associated with instances of that class. When we instantiate a class we create an object that looks and feels like other instances of the same class. The data associated with a class or object is stored in variables; the behavior associated with a class or object is implemented with methods. Methods are similar to the functions or procedures in procedural languages such as C. In the Java language, the simplest form of a class definition is Department of Computer Science and Engineering 31RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. class Name { } ‘The keyword class begins the class definition for a class named Name. The variables and methods of the class are embraced by the curly brackets that begin and end the class definition block. The "Hello World” application has no variables and has a single method named main, In general, class declarations can include these components, in order: 1. Modifiers such as public, private, and a number of others 2. The class name, with the i ial letter capitalized by convention. 3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 4, Acomma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 5. The class body, surrounded by braces, {}. Example public class Cat { int age; String color; void barking() { } Objects An object is a software module that has state and behavior. An object's state is contained in its member variables and its behavior is implemented through its methods. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. 1.9 Constructors In Java, constructor is a block of codes similar to method. It is called automatically when an instance of object is created and memory is allocated for the object. Department of Computer Science and Engineering 32RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. It isa special type of method which is used to initialize the object. Constructor, © Itis called constructor because it constructs the values at the time of object creation. © Itis not necessary to write a constructor for a class. # Its because java compiler creates a default constructor if our class doesn't have any. 1.9.1 Rules for creating java constructor There are basically two rules defined for the constructor. © Constructor name must be same as its class name ‘© Constructor must have no explicit return type Example public class MyClass{ [This is the constructor MyClass(){ + Note:the constructor name matches with the class name and it doesn 't have a return type. When we create the object of MyClass MyClass obj = new MyClass() ‘The new keyword here creates the object of class MyClass and invokes the constructor to initialize this newly created object. 1.9.2. A simple constructor program in java Here we have created an object off of class Hello and then we displayed the instance variable name of the object. As we can see that the output is Hello how are you? which is what Department of Computer Science and Engineering 33RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. wwe have passed to the name during initialization in constructor. This shows that when we created the object ofthe constructor got invoked. In this example we have used this keyword, which refers to the current object, object ofj in this example. public class Hello { i ‘Keyword this is a reference variable in String name; s consettcton ‘Java that refers to the current object. Hello(){ It can be used to refer instance this.name = "Hello how are you?"; variable of current class M7 * Itcan be used to invoke or initiate current public static void main(String{] args) err Itcan be passed as an argument in Hello obj = new Hello(); © the method call System.out.printin(obj.name); } It can be passed as argument in the } constructor call + Itcan be used to return the current class Output cae Hello how are you? public class MyClass{ // Constructor MyClass System.out.println(" Hello how are you? "); } public static void main(String args[]){ MyClass obj = new MyClass(); New keyword creates the object of MyClass } & invokes the constructor to init } created object 1.9.3 Types of java constructors Department of Computer Science and Engineering 4RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. There are three types of constructors in java: 1. Default constructor 2. No-arg constructor 3. Parameterized constructor Types of Constructor Default No-arg Parameterized 1. Default constructor If we do not implement any constructor in our class, Java compiler inserts a default constructor {nto our code automatically. This constructor is known as default constructor. We cannot find it in our source code (the java file) as it would be inserted into the code during compilation and exists in .elass file. This process is shown in the diagram below: public class MyClass public class MyClass ‘ { myclass¢ pensacmsmncmenna| — |" ; sycenetismn cna, | >(Conrn)-> Potente dma we) : : a ‘MyClass obj = new MyClass) > ) MyClassjava 2 My Classcta If we implement any constructor then we no longer receive a default constructor from Java compiler. 2. No-arg constructor: Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body of the constructor is empty. Example: no-arg constructor class Demo public Demo() { System.out.printin("This is a no argument constructor"); Department of Computer Science and Engineering 35RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public static void main(String aras[l) { new Demo(); * } Output: This is a no argument constructor 3. Parameterized constructor Constructor with arguments (or we can say parameters) is known as Parameterized constructor, Example: parameterized constructor In this example we have a parameterized constructor with two parameters id and name. While creating the objects obj/ and obj2 we have passed two arguments so that this constructor gets, invoked after creation of obj! and obj2. public class Employee { int empld; String empName; Iiparameterized constructor with two parameters Employee(int id, String name){ this.empid = id; this.empName name; + void info(){ System.out.printin("Id: "+empld+" Name: “+empNam¢ iy public static void main(String args{]){ Employee obj = new Employee(10245,"Chaitanya"); Employee obj2 = new Employee(92232,"Ragu"); obj1.info();, obj2.info(); t } Output: (0245 Name: Chaitanya Id: 92232 Name: Ragu Difference between Constructor and Methods Constructors Methods ‘A constructor doesn’t have a return type. ‘A method may or may not have a return type. Department of Computer Science and Engineering 36RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Constructor always have same name as class name. Constructors are called imp | of the class is created. Constructors are not considered members of a class Methods may have any name. tly when object | ethods need to be called explicitly Methods are considered members of a class 1.10 Methods in Java ‘A method is a collection of statements that perform some specific task and return result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In general, method declarations has six components = © Modifier-: Defines access type of the method i.e. from where it can be accessed in our application. In Java, there 4 type of the access specifiers. public: accessible in all class in our application. ‘protected: accessible within the class in which itis defined and in its subclass(es) + private: accessible only within the class in which itis defined. default (declared/defined without using any modifier) : accessible within same class and package within which its class is defined. * The return type : The data type of the value returned by the the method or void if does not return a value. © Method Name : the rules for field names apply to method names as well, but the convention isa little different. © Parameter list ; Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, we must use empty parentheses () * Exception list : The exceptions we expect by the method can throw, we can specify these exception(s) © Method body’: it is enclosed between braces. The code we need to be executed to perform wer intended operations. Department of Computer Science and Engineering 37RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. return-type een ae parameter-list modifier

y) return x; [| ———+ body of the method else How to call a Jaya Method? Now we defined a method, we need to use it. For that, we have to call the method. Here's how: myMethod(); This statement calls the myMethod() method that was declared earlier. class Main { public static void main(string[] args) { myFunction() 5 , e private static void myFunction() {y [True if x is greater than y, otherwise false (greater than or equal to) €x.x>=y [True if x is greater than or equal to y, otherwise false less than or equal fo) ex. x= [True if x is less than or equal to y, otherwise false Example // Java peogzam to illustrate // relational operators public class operators publi®static voidmain(string[] args) ( ar(] int br boolean condition = trues //various conditional operators System.out-printin("a == b :"+ (a Dds Department of Computer Science and Engineering 58RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. System.out.printin("a b (a> dpe System.out.printin("a >= b i" + (a >= b)); System-out-printin("a != b:"+ (a != b)); // exays cannot be compared with Z/ relational operators because objects 7/ store references not the value System.out.printin("x == yi "+ (ar ve System.out .printIn("condition~=true :"+ (condition ~~ true); 5. Logical Operators : These operators are used to perform “logical AND” and “logical OR” operation, i.e. the function ilar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, ic. it has short-circuiting effect. Used extensively to test. for several conditions for making a decision. Conditional operators are- + && Logical AND : returns true when both conditions are true. al Logical OR : returns true if at least one condition is true. // Java program to illustrate // logical operators public class operators { public static voidmain(string[] args) { string x String y Sher"; Locked"; Scanner s = new Scanner (System. in); System-out print ("Enter usernam String uvid next ()¢ Department of Computer Science and Engineering 38RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. System.out.print ("Enter password:"); String upwd = s.next (); // Check if user-name and password match or not. if ((uuid.equals(x) 6% upwd.equals(y)) | (uuid-equals(y) && upwd.equals(x))) { System-out.println("Welcome user. } else ( System.out.printin("Wrong uid or password"); } ) Output : Enter username: Sher Enter password: Locked Welcome user 6. Ternary operator : Temary operator is a shorthand version of if-else statement, It has three operands and hence the name ternary. General format is- condition ? if true : if false Example minval = (a >> Unsigned Right shift operator: shifts the bits of the number to the right and fills O on voids left as a result. The leftmost bit is set to 0. // sbitt operators public class operators public static void main(String[] args) U/ left shift operator 77 0000 0101> 2.0000 0001 (1) J) similar to 5/(2*2) System.out .printin(a>>2 = "+ (a >> 2)); // unsigned eight shift operator System.out.printla("b>>>2 = "+ (b >>> 2)); b>>>2 = 1073741821 Operator Precedence Operator precedence determines the grouping of terms in an expression, This affects how an expression is evaluated. Precedence and associative rules are used when dealing with hybrid equations involving more than one type of operator. In such cases, these rules determine which part of equation to consider first as there can be many different valuations for the same equation. Department of Computer Science and Engineering aRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206, Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator Example X=7+3* 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7 Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. Category Operator Asso Postfix >() [] . (dot operator) Left toright Unary ee Right to left Multiplicative 7 Left to right Additive St Left to right Shift So Left to right Relational SS Left to right Equality Left to right Bitwise AND Left to right Bitwise XOR Left to right Bitwise OR Left to right Logical AND Left to right Logical OR Left to right Conditional Right to left ‘Assignment Right to left 1.17 Control Flow Statements When we write a program, we type statements into a file. Without control flow statements, the interpreter executes these statements in the order they appear in the file from left to right, top to bottom. We can use control flow statements in the programs to conditionally execute statements, to repeatedly execute a block of statements, and to otherwise change the normal, sequential flow of control. The Java programming language provides several control flow statements, which are listed in the following table. Department of Computer Science and Engineering 68RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206, Statement Type Keyword decision making if-else, switch-case while, do-while , for Looping exception handling try-catch-finally, throw branching break, continue, labels, 117.1 Decision Making Statements, Decision making statement statements is also called selection statement, That is depending on the condition block need to be executed or not while is decided by condition. If the condition is "true" statement block will be executed, if condition is “false” then statement block will not be executed. In java there are three types of decision making statement. at © ifelse © switeh it{ con If condition condition is false Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. iffthen Statement if-then is the most basic statement of the decision making statement. It tells to program to execute a certain part of code only if a particular condition or testis true, Statement (5) ‘© Constructing the body if always optional, that is recommended to create the body when we are having multiple statements. ‘© Fora single statement, itis not required to specify the body. © Ifthe body is not specified, then automatically condition parts will be terminated with next semicolon ;. + Itis a keyword, by using this keyword we can ereate an alternative block for "if" part. ‘+ Using else is always optional i.e, itis recommended to use when we are having alternate block of condition. ‘+ When we are working with if else among those two block at any given point of time only ‘one block will be executed ‘+ When if condition is false, then else part will be executed, if partis executed, then automatically else part will be ignored. if-else statement In general, it can be used to execute one block of statement among two blocks, in Java language if and else are the keyword in Java. Syntax {e(conaition) statement (8) st tement (s) Statement (9) Department of Computer Science and Engineering 65RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206, In the above syntax whenever the condition is true all the if block statement are executed remaining statement of the program by neglecting else block statement. If the condition is false else block statement remaining statement of the program are executed by neglecting if block statements. A Java program to find the addition of two numbers if first number is greater than the second. number otherwise find the subtraction of two numbers. Example import java.util.*; clase Nan ( public static void main(String args|]) a-10,b=20, 7 System.out.printIn ("Enter any two num"); 5£ (a>) cxa-b; System. out .printin ("Result: 3. Switch Statement A switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and string. Syntax switch (expres ion/variable) i case value: Jiscaxenents 7] any number of case statements br@ak: \//optional @efaule: //optional /Iecatenents Rules for apply switch statement With switch statement use only byte, short, int, char data type. We can use any number of case statements within a switch. The value for a case must be same as the variable in a switch. Limitations of switch statement Logical operators cannot be used with a switch statement. For instance Department of Computer Science and Engineering 66RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Example case k>~2i is not allowed Switch case variables can have only int and char data type. So float data type is not allowed, For instance in the switch syntax given below: break; In this ch can be integer or char and cannot be float or any other data type. 1.17.2 Looping statement These are the statements execute one or more statement repeatedly a several number of times. In Java programming language there are three types of loops are available, that is, while, for and do-while. Advantage with looping statement ‘+ Length on the developer is reducing. ‘+ Burden on the developer is reducing. ‘+ Burden of memory space is reduced time consuming process to execute the program is, reduced. Difference between conditional and looping statement Conditional statement executes only once in the program were as looping statement executes repeatedly several numbers of time. 1, While loop ‘+ When we are working with while loop always pre-checking process will be occurred. ‘+ Pre-checking process means before the evolution of statement block condition parts will be executed, Department of Computer Science and Engineering orRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ‘+ While loop will be repeated in clockwise direction, Syntax while (condition) G ment (3) rement / decrements (++ or D Example class whilepeno q public static void main(String args (J) int 1-0; while (i= 5) { } System.outipfintIn ("Password “An implicit return is hei ) publié static void main(string{] args) ( ‘display2assword ("basketball") displayPassword ("cat"); baeketball Password: cat Baseword too short! Department of Computer Science and Engineering 7RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.18 Array a collection of similar type of elements that have contiguous memory location. Java array is an object that contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array. Array in java is index based, first element of the array is stored at 0 index. Element Fist index (at index 8) [o] 1 2 9 4 6 @ 7\e 9 —intcos BEER ED iim | + vray engin e 10 There are two types of array. Single Dimensional Array © Multi jensional Ar 1. Single Dimensional Array Declaring Array Variables To use an array in a program, we must declare a variable to reference the array, and we must specify the type of array the variable can reference. Here is the syntax for declaring an array variable ~ Syntax datatype (} arrayRefvar; // preferred way. GataTypevarrayRefVar{]; // correct but not preferred way. Example Govble{] mybist: // preferred way. Govble mybist{]s // works but not preferred vay. Creating (Instating) Arrays We can create an array by using the new operator with the following syntax ~ Department of Computer Science and Engineering BRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Syntax arrayRefvar = new datatype [arraySize]: The above statement does two things — + Itcreates an array using new dataType[arraySize]. ‘+ Itassigns the reference of the newly created array to the variable arrayRefVar. Example Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList ~ double[] mybist = new double[10]; Following picture represents array myList. Here, myList holds ten double values and the are from 0 to 9. Processing Arrays ‘When processing array elements, we often use either for Joop or foreach loop because all of the elements in an array are of the same type and the size of the array is known, // Java program to illustrate creating af atray // of integers, puts some values in the array, // and prints cach value to standard output. clase GEG ( public static voldmain’ (String{] args) // declares an Array of integers. int() arry // allocating menory for § integers arr = new int (517 // Anitiavize the first elements of the array arr(0} = 10; /yGnitialize the second elements of the array arz[i] = 20; // accessing the elements of the specified array for (inti = 0; 1 .... for heading and

has been used for creating paragraph break. Example pe *

Hello, World!

* The HelloWorld program implements an application that * simply displays "Hello World!" to the standard output. *

* Giving proper comments in your program makes it more * user friendly and it is assumed as a high quality code. * @author Author_Name * @version 1.0 *@since 2018-03-31 g public class HelloWorld { public static void main(String{] args) { /* Prints Hello, World! on standard output. Department of Computer Science and Engineering 85RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. System.out printin("Hello World!"); + + 1.20.1 The javadoe Tags The javadoc tool recognizes the following tags should no longer be used. Tag Description Syntax @author Adds the author of a class. @author name-text Displays text in code font without {@eode} interpreting the text as HTML markup or {@code text} nested javadoc tags. Represents the relative path to the generated {@docRoot} | document's root directory from any generated | {@docRoot} page, @deprecatea | Adds @ comment indicating that this APL @deprecated deprecatedtext @exception Adds a Throws subheading to the generated documentation, with the classname and description text. @exception class-name description {@inheritDoc 3 Inherits a comment from the nearestinheritable class or implementable interface. Inherits a comment from the immediate surperclass Inserts an in-line link with the visible text label that points to the documentation for the {@link description to the "Parameters" section. {@linky specified package, cass, or member name of | P&tkege.classi#member label} areferenced class. Identical to {@link}, except the link’s label is | {@linkplain {@linkplain} | displayed in plain text than code font. package.classi#member label} Adds a parameter with the specified a @param parameter-name followed by the specified param pal description Department of Computer Science and Engineering 86RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Adds a "Returns" section with the description @return ae @retum description Adds a "See Also" heading with a link or text | Ce entry that points to reference. selene @seriat Used in the doc comment for a default @serial field-description | serializable field. include | exclude @serialData Documents the data written by the writeObject( ) or writeExtemal( ) methods. @serialData data- description Documents an ObjectStreamField @serialField field-name QserialField | component. field-type field-description ‘Adds a "Since" heading with the specified @since since-text to the generated documentation, | @since release Pe The @throws and @exception tags are @throws class-name synonyms. description When (@value} is used inthe oe comment | vay {@value} | of astatc fied, it displays the value ofthat] T@valwe | oe package class#ield} ‘Adds a "Version" subheading with the ified version-text to the generated d @version —_| SHecifird versionvtext io the generated docs | @version version-text when the -version option is used. © End of Unit — 1 *** Department of Computer Science and Engineering 87RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. UNIT — I - INHERITANCE AND INTERFACES 2.1 Inheritance An important part of OPPs(Object Oriented programming system) is Inheritance. The process by which one class acquires the properties(data members) and functionatities(methods) of another class is called inheritance. The keyword used inherit the propertied of a class is extends. The idea behind inheritance in java is that we can create new classes that are built upon existing classes. When we inherit from an existing class, we can reuse methods and fields of parent class, and we can add new methods and fields also. Syntax class subClass extends superClass { /imethods and fields + Tert ology Super Class (Parent Class) : The class whose features are inherited is known as super class(or a base class or a parent class). ‘Sub Class (Child Class): The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subelass can add its own fields and methods in addition to the superclass fields and methods Reusability : Inheritance supports the concept of “reusability”, ie. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. Example: In below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class which extends Bicycle class and class Test is a driver class to run program. //Java program to illustrate the concept of inheritance // base class class Bicycle i // the Bicycle class has two fields Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public int gear, public int speeds // the Bicycle class has one constructor public Bicycle(int gear, int speed) { this.gear = gear; this. speed = speed; , // the Bicycle class has three methods public void applyBrake (int decrement) fl speed -= decrement; , public void speedup (int increment) cl speed ++ increment; , // toString() method to print info.of Bicycle public String toString() cl return("No of gears are."+gear +"\n" + "speed of bicycle) isu"+speed) + } // derived class class NcuntainBike extends Bicycle ( // the HountainBike Subclass adds one more field publi¢int seatHeight; /{ the\MountainBike subclass has one constructor publicMountainBike(int gear, int speed, int startHeight) cl /} invoking base-class (Bicycle) constructor super (cear, speed); seatHeight = startHeights , // the MountainBike subclass adds one more method public void setHeight (int newValue) cl seatHeight = newValue; , // overriding toString() method of Bicycle to print more info Goverride Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public String toString () ‘ return (super.toString()+"\nseat height is "+seatHeight); , I // driver class public class Test ( public static voidmain(string args{]) ( MountainBike mb = newMountainBike(3, 100, 25); System. out .print1n (mb. toString ()); b Output: No of gears are 3 speed of bicycle is 100 Seat height is 25 In above program, when an object of MountainBike class is created, a copy of the all methods and fields of the superclass acquire memory in this object. That is why, by using the object of the subclass ‘we can also access the members of a superclass. Iustrative image of the prograr int gear int speed copy of Bicycle methods and applyBrake()| fields in MountainBike object speedUp() toString() objects of MountainBike class int seatHeight setHeight() toString() ‘The super keyword ‘The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used. ‘+ It is used to differentiate the members of superclass from the members of subclass, if they have same names. + It is used to invoke the superclass constructor from subclass.RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Important faets about inheritance in Java Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (s gle inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object class, Superclass can only be one: A superclass can have any number of subclasses, But a subclass can have only one superclass. This is because Java does not support multiple inheritance with classes Although with interfaces, multiple inheritance is supported by java. Inheriting Constructo A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass, A subelass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for ack ing its private fields, these can also be used by the subclass. Role of Subclass In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new ‘members: ‘+ The inherited fields can be used directly, just like any other fields. ‘* Wecan declare new fields in the subclass that are not in the superclass ‘© The inherited methods can be used directly as they are. We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (as in example above, toString() method is overridden), ‘*) Weccan write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it © We can declare new methods in the subclass that are not in the superclass. © We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 2.1.1 Types of Inheritance 884 (Please refer UNIT Notes for detailed explanation and examples) Single Inheritance public lass A ¢ Class A z } public lass B extends A { Class 8 } ‘Maiti Level taheritance public class A ( ) public class B extends A {.... public dass C extends B {econo} iorarchical inheritance public dass A ) puble dass B extends A... } [tase c | | puttecass Coxtands A (ob ‘Maltiple Inheritance public dass A ) public class B , Se public class C extends A,8 { 11 Java does not support mutiple Inheritance 2.1.2 Super Class The super keyword in java is a reference variable which is used to refer immediate parent class object. Whenever we create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. Usage of java super Keyword 1. super can be used to refer émmediate parent class instance variable. 2. super can be used to invoke immediate parent class method. 3. super() can be used to invoke immediate parent class constructor 1) super is used to refer immediate parent class instance variable.. Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. Example class Animal{ String color="white"; + class Dog extends Animal{ String color="black" void printColor() class Dog extends Animal{ Dog(){ ‘System.out.printin("dog is created"); + + class TestSupera{ public static v main(String args[]){ Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Dog oo yew Dog); Output animal ie created dog is created 2.1.3 Protected Member The private members of a class cannot be directly accessed outside the class. Only methods of that class can access the private members directly. However, sometimes it may be necessary for a subclass to access a private member of a superclass. If we make a private member public, then anyone can access that member. So, if'a member of a superclass needs to be (directly) accessed in a subclass and yet still prevent its direct access outside the class, you must declare that member protected. Following table deseribes the difference Modifier Class Subclass World public Y Y Y protected ¥ Y N private ¥ N. N Following program illustrates how the methods of a subclass can directly access a protected ‘member of the superclass. For example, le’s imagine a series of classes to describe two kinds of shapes: rectangles and triangles. These two shapes have certain common properties height and a width (or base). This could be represented in the world of classes with a class Shapes from which we would derive the two other ones : Rectangle and Triangle Example Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public class shape { protected double height; // To hold height. protected double width; //To hold width or base * The setValue method sets the data * in the height and width field public void setValues(double height, double width: this.height = height; this.width = width; Rectan; ye * This class Rectangle calculates * the area of rectangle * public class Rectangle extend# Shape t yee * The method retufns the area * of rectangle. */ public double getarea () ( return height * width; //accessing protected members } Triangle.java ye * this class Triangle calculates * the area of triangle y public class Triangle extends Shape { yee * The method returns the area * of triangle. */ public double getarea() ci Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. return height * width / 2; //accessing protected members ‘Testprogram,java Jan * This program demonstrates the Rectangle and * ‘riangle class, which inherits from the Shape class. “/ public class TestProgram ( public static void main(String[] args) fl {/Create object of Rectangle. Rectangle rectangle = new Rectangle(); {/Create object of Triangle Triangle triangle = new Triangle(); (Set values in rectangle object rectangle.setValues (5,4); //Set values dn trianlge object triangle.setValues (5,10); // Display the/area Of rectangle. System.out.printin ("Area of rectangle : " + rectangle.getArea()) 7 //-pisplay the’area of triangle. System.out.print1n("Area of triangle : " + triangle.getArea()); Output : Area of rectangle : 20.0 Area of triangle : 25.0 2.1.4 Constructors in sub classes Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. In Java, constructor of base class with no argument (default constructor) gets automatically called in derived class constructor. For example, output of following program is: Example Main. java Base() System.out.println ("Base Class Constructor Called "); } class Derived extends Base ( Derived() System. out.printin ("Derived Class Constructor Called ") } publicclass Main { public static voidmain(String[] args) { Derived d = new Derived(): t output Base Class Constructor Called Derived Class Constructor Called But, if we want to call parameterized contructor of base ela , then we can call it using ss constructor call must be the first line in derived class super(). The point to note is base constructor. For example, in the following program, super(_x) is first line derived class constructor. Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. // filename: Main. java class Base { int x: Base(int_x) { } class Derived extends Base { int yz Derived(int x, int_y) { uper (_x)7 Wi void Display() { System.out.println("* = "+x", y = } publicclass Main { public static void main(String[] args)\ { Derived d = new Derived(10, 20); d.Display(); } Run on IDE Output: x= 10,y=20 The rules is: sub class constructor has to invoke super class instructor, either explicitly by programmer or implicitly by compiler. For either way, the invoked super constructor has to be defined. 2.1.5 The Object Class Every class in Java is directly or indirectly derived from the Object class. All other classes are subelasses of Object. The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java. 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. Note : The Object class, in the java.lang package, sits at the top of the class hierarchy tree Method Purpose Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ‘Creates a new object that is the same as the object being cloned. ‘Determines whether one object is equal to Object clone( ) boolean equals(Object object) another. void finalize ) Called before an unused object is recycled. Class getClass( ) 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 object. Resumes execution of all threads waiting on the invoking object. int hashCode( ) void notify) void notifyA() String toString() Returns a string that describes the object. void wait() void wait(long milliseconds) void wait(long milliseconds, int nanoseconds) Waits on another thread of execution, ‘The methods getClass( ), notify( ), notifyAII( ), and wait( ) are declared as final, You may override the others. 2.1.6 Abstract Classes There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes we will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. General form: abstract type name (parameter-list); To declare a class abstract, we simply use the abstract keyword in front of the elass keyword at the beginning of the class declaration. Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Here is a simple example of a class with an abstract method, followed by a class which implements that method: // ® Simple demonstration of abstract. abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.printin("This is a concrete method." } } class B extends A { void calime() { System.out.printin("B's implementation of callme."); } } class AbstractDemo { public static void main(string args(]) { Bb = new B( b.callme( b.callmetoo() + y , Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class. One other point: class A implements a concrete ‘method called eallmetoo( ). Although abstract elasses cannot be used to instantiate objects, they can be used to create object references, because Java’s approach to run-time polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subel 38 object. Using an abstract class, we can improve the Figure class example. Since there is no ‘meaningful concept of area for an undefined two-dimensional figure, the following program declares area( ) as abstract inside Figure. This, of course, means that all classes derived from Figure must override area( ). // Using abstract methods and classes. abstract class Figure [ double dim; double din2; Figure(double a, double b) { dim = a; dim? = b; ) // area is now an abstract method abstract double area(); Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. , class Rectangle extends Figure { Rectangle (double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.printin ("Inside Area for Rectangle."); return dim] * dim2; } } class Triangle extends Figure { Triangle (double a, double b) { super (a, b); } // override area for right triangle double area) { System.out.printin ("Inside Area for Triangle. return diml * dim2 / 2; } } class Abstractareas { public static void main(String args (J) // Figure £ = new Figure(10, 10)%// illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created figref = system.out .printin ("Area ia." + figref.area()); figref = t; system.out.p } } ntin ("area is “ + figref.area()); As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since it is now abstraet, And, all subclasses of Figure class must override area() Although it is not possible to create an object of type Figure, we can create a reference variable of type Figure. The variable figref is declared as a reference to Figure class, which ‘means that it can be used to refer to an object of any class derived from Figure class. 2.1.7 Final Methods and Classes Inheritance is one of the highly useful features in Java, But at times, it may be desired that a class should not be extendable by other classes to prevent misusing by others. For such purpose, we have the final keyword. A class declared as final cannot be extended while a Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. method declared as final cannot be overridden in its subclasses. Though a final class cannot be extended, it can extend other classes. /n simpler words, a final class can be a sub class but not a super class. Normally, Java resolves calls to methods dynamically, at run time. This is called fate binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding. Syntax final public class A //code } The final keyword can be placed either before or after the access specifier. The following deck jon of class A is equivalent to the above. public final class A //code , final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a © variable, © amethod © aclass. Final Variable: If we make any variable as final, we cannot change the value of final variable (It will be constant). Example of final variable ‘There is a final variable speedlimit, we are going to change the value of this variable, but it can't be changed because final variable once assigned a value can never be changed class Bike{ al int speediimit=90; //final variable void run(){ speedlimit=400; + public static void main(String args(]) ¥ Output Hello Nested Interfaces Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. An interface can be declared a member of a class or another interface. Such an interface is called a member interface or a nested interface. Example // & nested interface example. // This class contains a member interface. class A { // this is a nested interface public inte: ice NestedIF { boolean isNotNegative(int x); } } // B implements the nested interface. class B implements A.NestedIF { public boolean isNotNegative(int x) { return x Here, E speci Declaration the type of objects that the list will hold. public class ArrayList extends AbstractList implements List, RandomAcc ess, Cloneable, Serializable Department of Computer Science and EngineeRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Iterable (eee extends Collection acne) extends List Ly implements AbstractList * extends ArrayList ArrayList has the constructors shown here: ArrayList() ArrayList(Collection ¢) ArrayList(int capacity) © The first constructor builds an empty array list. © The second constructor builds an array list that is initialized with the elements of the collection ¢. ‘© The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list. Example // Demonstrate ArrayList. import. java.util.*; class ArrayListDemo { public static void main(string args{]) { // Create an array list. Arraybist al = new ArrayList(); System.out.printin("Initial size of al: " + al.size()); // Add elements to the array list. al.add("c") ; al.add ("A") ; al.add("E") ; al.add ("B") ; al.add("D") ; al.add("F") ; Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. al.add(1, "A2"); system.out..printin(" al.size()); // Display the array list. System.out.print1n("Contents of al: " + al); // Remove elements from the array list. al.remove ("F"); al.remove (2); ize of al after additions: " + System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } } ‘The output: Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, Fl Size of al after deletions: 5 Contents of al: [C, A2, E, B, DJ Notice that al starts out empty and grows as elements are added to it. When elements are removed, its size is reduced. Obtaining an Array from an ArrayList When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list. You can do this by calling toArray( ), which is defined by Collection. // Convert an ArrayList into an array. import java.util.*; class ArrayListToarray { public Static void:main(string args{]) ( // Cteate an array list. ArrayList al = new ArrayList(); // Add elements to the array list. al.ada(1) ; al.ada(2); al.add(3); al.add(4); system. out.printin(" // Get the array. Integer ia[] = new Integer[al.size()]; ia = al.toArray(ia); int sum = 0; // Sum the array. for(int i : ia) sum += 4; ontents of al: "+ al); Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. System.out.printin("Sum is: " + sum); } t The output from the program is shown here: Contents of al: [1, 2, 3, 4] sum is: 10 2.1.12 Strings A string is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String. Somewhat unexpectedly, when you create a String object, you are creating a string that cannot be changed. That is, once a String object has been created, you cannot change the characters that comprise that string. ‘The String Constructors The String class supports several constructors. To create an empty String, you call the default constructor. Example String s = new string(); This will create an instance of String with no characters in it. ‘The String class provides a Variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here: String(char chars{/}) Example char chars(} =“{ 'al, ‘bt, 'e'}; String s\= new.string(chars) ; ‘This constructor initializes s with the string “abe”. We can specify a subrange of a character array as an initializer using the following constructor: String(char chars[ ], int startIndex, int numChars) Here, startindex specifies the index at which the subrange begins, and mumChars specifies the number of characters to use. Example: char chars[] = { 'a', "bt, ‘ct, ‘dt, tet, tft; String s = new String(chars, 2, 3); This initializes s with the characters ede. Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. You can construct a String object that contains the same character sequence as another String object using this constructor: String(String strdbj) Example // Construct one String from another class Makestring { public static void main(String args{]) ( char cf] = ('d", tat, tv, ‘ath; String s1 = new String(c); string s2 = new String(s1); system.out.printin(s1); system.out .printin(s2); } } output: Java Java As we can see, s1 and s2 contain the same string, String Length The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method: int length() ‘The following fragment prints “3”, since there are three characters in the string s: char chars[] = {1a",'b'yto'}; String s = new String(chars) ; systen.out.printin(s.length()); Special String Operations Java has added special support for several string operations within the syntax of the language. String Literals The earlier examples showed how to explicitly create a String instance from an array of characters by using the new operator. However, there is an easier way to do this using a string literal. For each string literal in our program, Java automatically constructs a String object. Thus, we can use a str g literal to initialize a String object. For example, the following code fragment creates two equivalent strings char chars[] = ('a',*b',tc'}; String 61 = new String(chars); String s2 = "abe"; //use string literal It calls the length( ) method on the string “abe”. As expected, it prints system.out-print1n("abe".length()) ; Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. String Coneatenation In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result Example //0sing concatenation to prevent long lines. class Concat { public static void main(String args(]) ¢ String longStr = "This could have been " + "a very long line that would have * + “wrapped around. But string concatenation " + “prevents this. system.out.print1n(longstr) ; } ) String Concatenation with other data types Example | String age = "9"; String s = "He is " + age + "Years old. "7 system.out .printin(s); Output He is 9 years old. Example 2: String s = "fou + 2M 2; System.outprint1n(s); output fourt,22 Character Extraction ‘The String class provides a number of ways in which characters can be extracted from a String object. charAt() To extract a single character from a String, we can refer directly to an individual character via the charAt() method. The general form: char charAt (int where) Here, where is the index of the character that you want to obtain, The value of where must be nonnegative and specify a location within the string. charAf() retums the character at the specified location. For example, char ch; Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ch = "abo" charat (1) ; assigns the value “b” to ch, getChars() If we need to extract more than one character at a time, you can use the getChars( ) method. The seeneral form: void getChars(int sourceStart, int sourceEnd, char target{ 1, int targetStart) Here, soureeStart specifies the index of the beginning of the substring, and soureeEnd specifies an index that is one past (additional) the end of the desired substring. Thus, the substring. contains the characters from soureeStart through soureeEnd-I. The array that will receive the characters is specified by target. The index within target at which the substring will be copied i passed in targetStart, Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring, class getCharsDemo { public static void main(String args(])/ String s = "This is a demo of the getChars\method. int start = 10; int end = 14; char buf[] = new char[end - start); s.getChars(start, end, buf, 0); system.out.println (buf) ; ) } Output demo There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is called getBytes(), and it uses the default character-to-byte conversions provided by the platform. Here is its simplest form: bytef\) getBytes( ) String Operations Following are the list of operati supported by String class No. | Method Description returns char value for the 1 | char charAt (int index’ particular index Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. No. | Method Description 2 | imt length returns string length Static String format (String See returns formatted string 4 | Static String format (Locale 1, | returns formatted string with String format, Object... aras) —_| given locale ee 5 | String substring lint beainindex) | ums substring for given begin index g | Stuing_substring (int beainindex, | retums substring for given begin int_endIndex index and end index returms true or false after 7 | boolean contains (CharSequence s} | matching the sequence of char value static String join (CharSequence 8 | delimiter, CharSequence... returns a joined string elements) static String join (CharSequence 9 |delimiter, Iterable extends returns a joined string, Chars: > el s | | poolean equals (Object another Se eee ots 0 with object 11 | boolean istmpty checks if string is empty 1 , | Stzing_concat (string stx concatinates specified string 1 | String replace (char old, char replaces all occurrences of 3 | new: specified char value 1 | String replace (CharSequence old, | replaces all occurrences of 4 | CharSequence new! specified CharSequence Department of Computer Science and Enginee!RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ‘No. | Method Description 1 | static string compares another string, It 5 IsTgnox: xing another) | doesn’t check case. ' |seringt) split (string regex Seas 6 matching regex 1 |String(] split(string regex, int | — retums splitted string 7 | Limits matching regex and limit L 3 String intern returns interned string Mayor dae returns specified char value 9 index 2 |int indexof (int ch, int che specified charvalue a index starting with given aes index 2 lint indexo£ (String substring returns specified substring I index 2 |int indexof (String substring eae Grea SST index starting with given 2 |int fromtndex: index 216 3 | Stina_tolowerCase retums string in lowercase. a a oe coe Fetus string in lowerease 4 using specified locale. 2 5 |St#ina touppercase returns string in uppercase. 2 oe if ee returns string in upperease 6 using specified locale. 2 | ering trim removes beginning and 7 ending spaces of this string. Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. No. | Method Description 2 | static string valueOf (int value orn eee care 8 string, Itis overloaded. Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. UNIT — TD EXCEPTION HANDLING AND I 3.1 Exceptions Java exception is an object that desi nal (that is, error) condition that has occurred in a piece of code, When an exceptional condition arises, an object representing, that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Here is how they work. ‘+ Program statements that we want to monitor for exceptions are contained within a try block * [fan exception occurs within the try block, itis thrown, © Our code can eatch this exception (using catch) and handle it in some rational manner. ‘System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. © Any exception that is thrown out of a method must be specified as such by a throws, clause. © Any code that absolutely must be executed after a try block completes is put in a finally block. General form try { // block of cod@ to monitor for errors ) catch (ExceptionTypel/exob) { // exception handler for ExceptionTypel ) catch (ExceptionType2 exob) ( //exeeption handler for ExceptionType2 ) “ finally { // block of code to be executed ) © try block ends Exception is an event that interrupts the normal flow of execution. It is a disruption during the execution of the Java program Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 3.2 Exception Hierarchy All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. cnet eek ees Preece og etc 3.2.1 Uncaught Exceptions Let us see what happens if we don’t handle exceptions. Following small program includes an expression that intentionally causes a divide-by-zero error: class Exc0 { public static void main(String args[]} { int 4 = 0; int a= 42)4 ds // divided by zero t ; When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of the program to stop. In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run time system. The default handler displays a string describing the exception and terminates the program. Here is the exception generated when this example is executed: java.lang.ArithmeticException: / by zero at ExcO.main (Exc. java:4) Department of Computer S nce and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 3.3 Using try and catch Although the default exception handler provided by the Java run-time system is useful for debugging, we will usually want to handle an exception our self and provides two benefits. First, it allows us to fix the error. Second, it prevents the program from automatically terminating, To guard against and handle a run-time error, simply enclose the code that we want to monitor inside a fry block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch, class Exc2 { public static void main(String args(]) ¢ int d, a; try { // monitor a block of code. a= 0; a= 42/4; System.out.printIn("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error system.out.print1n ("Division by Zero."); ) system.out.printin ("After catch statement.) ; } This program generates the following output: Division by zero. After catch statement. Notice that the call to printing) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution never “returns” to the try block from a catch, Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism. Atty and its catch statement form a unit. The scope of the catch clause is restricted to those statements specified by the immediately preceding try statement. A catch statement cannot catch an exception thrown by another try statement, 3.3.1 Multiple catch Clauses In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, we can specify two or more catch clauses, each catching a different type of exception, When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/eatch block. Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. The following example traps two different exception types: // Demonstrate multiple catch statements class Multicatch [ public static void main(string args{J) { try { int a = args.length; System.out.printin("a = " + a); int b= 42 / a; int cf] = {135 [42] = 99; } catch (Arithmeticexception e) { System.out.printin ("Divide by 0: " + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.printin ("Array index oob: * + e)\y } system.out.print1n ("After try/catch blocks. } } This program will cause a division-by-zero exception if it is started with no command line arguments, since a will equal zero, It will survive the division if you provide a command-line argument, setting a to something larger than zero. But it will cause an ArraylndexOutOfBoundsException, since the int array c has a length of 1, yet the program attempts to assign a value to ¢[42]. Here is the output generated by running it both ways: >java Multiatch 0 Divide by. 0: java.langsArithmeticException: / by zero After try/eatch blocks :\>java Multi¢atch Testarg et Array index cob: java.lang.arrayIndexoutofsoundsexception: 42 After try/catch blocks. 3.3.2 Nested try Statements The ty statement can be nested. That is, a fry statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is, unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception. Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Here is an example that uses nested try statements: // ¥n example of nested try statements. class NestTzy { public static void main(String args(]) { try { int a = args.length; /* L£ no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b= 42 / a; System.out-printin("a = " + a); try { // nested try block /* T£ one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if (a } a = a/(a-a); // division by zero /* TL two command-line argé\are/used, then generate an out-of -bounds exception. */ if(as=2) { int cll = 1125 [42] = 99; // ganerate an out-of-bounds exception } } catch (arrayrndexoutofBoundsexception e) { system.out-printin("Array index out-of-bounds: " + e); } } catch (Arithmetickxception e) { system,out.printIn("Divide by 0: " +e); } + } As we can see, this program nests one try block within another. The program works as follows. When you execute the program with no command-line arguments, a divide-by-zero exception is generated by the outer try block. Execution of the program with one command- line argument generates a divide-by-zero exception from within the nested try block. Since the inner block does not catch this exception, it is passed on to the outer try block, where it is handled. If you execute the program with two command-line arguments, an array boundary exception is generated from within the inner try block. Here are sample runs that illustrate each case: Output: Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. C:\>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero >java NestTry One a=1 Divide by 0: java.lang.ArithmeticException: / by zero c:\>Java NestTry One Two az2 Array index out-of -bounds: java. lang. ArrayIndexOutOfBoundsException:42 3.4 throw So far, we have only been catching exceptions that are thrown by the Java. run-time system. However, it is possible for our program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: throw ThrowableInstanct Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on, If'no matching catch is found, then the default exception handler halts the program and prints the stack trace Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler. // Demonstrate throw class ThrowDemo { static void demoproc() { try throw new NullPointerException ("demo") ; } catch (Nul1PointerException e) { System.out.printin("Caught inside demoproc. throw e; // rethrow the exception } i public static void main(String args(]) { try { demoproc() + } catch (NullPointerzxception e) { Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. system.out.println("Recaught: "+ e); J Jd This program gets two chances to deal with the same error. First, main() sets up an exception context and then calls demoproc( ). The demoproc( ) method then sets up another exceptionhandling context and immediately throws a new instance of NullPointerException, which is caught on the next line, The exception is then rethrown. Here is the resulting output: Caught inside demoproc. Recaught: java.lang.NullPointerException: demo 3.4.1 throws If a method is capable of causing an exception that it does not handle, it must specify t behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a ‘method can throw must be declared in the throws elause. If they are not, a compile-time error will result. General form: type method-name(paramet. ( 1/ body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw. list) thfows exception-list Example // This program contains an error and will not compile. class ‘ThrowsDeno static void throwone() System:out.printin ("Inside throwOne.") ; throw.new. IllegalaccessException ("demo") ; } public static void main(string args(]) { throwOne() ; i ‘To make this example compile, we need to make two changes. First, we need to declare that throwOne( ) throws IlegalAccessException. Second, main( ) must define a ty/catch statement that catches this exception. ‘The corrected example is shown here: Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. // This is now correct. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.print1n("Inside throwOne.") ; throw new IllegalAccessException ("demo") ; i public static void main(String args{]) { try ( throwone() ; } catch (IllegalaccessException e) { System.out.printin ("Caught " + e}; i } } Output inside throwone caught java.lang.TllegalAccessException: demo 3.4.2 finally finally creates a block of code that will be executed after a try/eateh block has completed and before the code following the try/catch block, The finally block will execute whether or not an exception is thrown, If an exception is thrown, the finally block will execute even if no catch statement matches the exception. This can be useful for closing file handles and freeing, up any other resources that might have been allocated at the beginning of a method. The finally clause is optional. However, cach try statement requires at least one catch or a finally clause. General form: ty { [Statements that may cause an exception } catch { {Handling exception } finally { [Statements to be executed } Example public class MyFinallyBlock { public static voidmain(Stringf] a) ( yee * Exception will occur here, after catch block + the contol will goto finally block. try( Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. int i = 10/0; ) catch (Exception ex) { Systen.out .printIn("Inside Ist catch Block"); finally ( systen.out printIn ("Inside 1st finally block"); je * In this case exception won't, after executing * the contol will goto finally block. */ try( int i = 10/10; catch (Exception ex) { System.out.print1n ("Inside 2nd catch Block"); finally ( System.out.printin ("Inside 2nd finally block"); ry block , } Output Inside 1st catch Block Inside 1st finally block Inside 2nd finally block The finally block always executes immediately after try-catch block exits. The finally block is executed incase even if an unexpected exception occurs. The main usage of finally block is to do clean up job. Keeping cleanup code in a finally block is always a good practice, even when no exceptions are occured. + The runtime system always executes the code within the finally block regardless of ‘what happens in the try block. So itis the ideal place to keep cleanup code. 3.5 Java’s Bi in Exceptions Inside the standard package java.lang, Java defines several exception classes. The most general of these exceptions are subclasses of the standard type RuntimeException. These exceptions need not be included in any method’s throws list. In Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. Unchecked RuntimeException. SrNo. Exception & Description ArithmeticException Arithmetic error, such as divide-by-zero. Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Sr.No. Exception & Description ArrayIndexOutOfBoundsException Array index is out-of-bounds. : ArrayStoreException . Assignment to an array element of an incompatible type. 7 ClassCastExeeption Invalid cast. 5 MlegalArgumentException legal argument used to invoke a method. é MlegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread. : MlegalStateE xeeption Environment or application is in incorrect state. 7 IlegalThreadStateExeeption Requested operation not compatible with the current thread state. IndexOutOfBoundsException Some type of index is out-of-bounds. Array created with a negative size. ‘NullPointerException Invalid use of a null reference. a NumberFormatException Invalid conversion of a string to a numeric format 3 SecurityException Attempt to violate security. 14 StringIndexOutOfBounds Attempt to index outside the bounds of a string. UnsupportedOperationExeeption Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Sr.No. Exception & Description An unsupported operation was encountered. Checked Exceptions SrNo. Exception & Description 1 ClassNotFoundException Class not found. ; CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. : MlegalAccessException : Access to a class is denied. 4 Attempt to create an object of an abstract class or interface : InterruptedExce} (One thread has been interrupted by another thread. : NoSuchFieldException A requested field does not exist. _ NoSuchMethodException A requested method does not exist. 3.6 Creating Own Exceptions Although Java’s built-in exceptions handle most common errors, we will probably ‘want to create your own exception types to handle specific situations. This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable) that allows us to use them as exceptions. The Exception class does not define any methods of its ‘own instead, it inherit those methods provided by Throwable. Example // ® Class that represents use-defined expception Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. yException extends Exception public MyException(String s) fl // Call constructor of parent Exception super (s) ; // ® Class that uses above MyException public class Main fl // Deiver Program public static void main(String args{]) c try ( // Throw an object of user defined e: throw new MyException ("My Exception"); catch (MyBxception ex) System.out.printlm("caught™) ; // Print the message from MyException object System. out.printin (ex, getMessage()); , , Output Caught My Exception In the above code, constructor of MyException requires a string as its argument. The string is passed to parent class Exception’s constructor using super(). The constructor of Exception class can also be called without a parameter and call to super is not mandatory. 3.7 Stack Trace Elements The Stack TraceElement class describes a single stack frame, which is an individual clement of a stack trace when an exception occurs. Each stack frame represents an execution ‘point, which includes such things as the name of the class, the name of the method, the name of the file, and the source-code line number. An array of StackTraceElements is returned by the getStackTrace() method of the Throwable class. StackTraceElement has one constructor: Department of Computer Science and EngineeringRMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. StackTraceElement(String className, String methName, string fileName, int line) Here, the name of the class is specified by className, the name of the method is, specified in methName, the name of the file is specified by fileName, and the line number is passed in line. Example: The following example shows the usage of java lang. StackTraceElement.getMethodName() method, import java.lang.*; public class StackTraceElementDemo { public static void main(String[] args) { function (); + public static void function1() { new StackTraceElementDemo().function2(); } public void function2() { int i; System.out.printin("method name : " J/ print stack trace for(i = 1;i ) — 7c, econ, wt eos fetes, spend, wa oe Temata a, Thread Priori Department of Computer Science and Engineering 155RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Java assigns to each thread a priority that determines how that thread should be treated with respect to the others. Thread priorities are integers that specify the relative priority of one thread to another. Instead, a thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. The rules that determine when a context switch takes place are simple: © A thread can voluntarily relinquish control. This, done by explicitly yielding, sleeping, or blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given the CPU. * A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply pre-empted by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking. 4.3 Creating a Thread In the most general sense, we create a thread by instantiating an object of type Thread. Java defines two ways in which this ean be accomplished: * Wecan implement the Runnable interface. * Wecan extend the Thread class, itself. 4.3.1 Implementing Runnable The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. We can construct a thread on any object that implements Runnable, To implement Runnable, a class need only implement a single method called run(), which is declared like this: public void run() Inside run( ), we will define the code that constitutes the new thread, run( ) establishes: the entry poi returns. for another, concurrent thread of execution. This thread will end when run( ) General form Thread(Runnable threadOb, String threadName) After the new thread is created, it will not start running until you call its start() method, which is declared within Thread, In essence, start( ) executes a call to run(). The start( ) method is as below void start() Department of Computer Science and Engineering 156RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Example // Create a second thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.printin("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i> 0; i--) { system.out.printin("Child Thread: " + i); ‘Thread. sleep (500) + } } catch (Interruptedexception e) { System.out.printin ("Child interrupted."); } System.out.printin ("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { forpim, ig= SWi > 0; i--) [ System. out.printin(" Thread.sleep (1000) ; } } catch (InterruptedException e) { Systemvout.println("Main thread interrupted."); y System.out.printin("Main thread exiting."); I Inside NewThread’s constructor, a new Thread object is created by the following statement: t = new Thread(this, "Demo Thread"); Passing this as the first argument indicates that you want the new thread to call the run ) method on this object. Next, start( ) is called, which starts the thread of execution beginning at the run() method. This causes the child thread’s for loop to begin. After calling Department of Computer Science and Engineering 157RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. start( ), NewThread’s constructor returns to main( ). When the main thread resumes, it enters its for loop. Both threads continue running, sharing the CPU, until their loops finish. Output Child threa: hread[Demo Thread, 5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 child ad: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: Main thread exiting As mentioned earlier, in a multithreaded program, often the main thread must be the last thread to finish running. The preceding, program ensures that the main thread finishes last, because the main thread sleeps for 1,000 milliseconds between iterations, but the child thread sleeps for only 500 milliseconds. This causes the child thread to terminate earlier than the main thread. 4.3.2 Extending Thread Class The second way to create a thread is to create a new class that extends Thread, and then (0 create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread. It must also call start() to begin execution of the new thread. Example (preceding program rewritten to extend Thread class) // Create a second thread by extending Thread class NewThread extends Thread ( NewThread() { // Create a new, second thread super ("Demo Thread") ; System.out.printin("Child thread: start(); // Start the thread y // This is the entry point for the second thread. + this); Department of Computer Science and Engineering 158RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep (500) ; } } catch (InterruptedException e) { system.out.println ("Child interrupted.") ; : System.out.println("Exiting child thread. } } class ExtendThread { public static void main(String args{]) { new NewThread(); // create a new thread try { for(int i = 5; i > System.out .printin(" Thread.sleep (1000); } } catch (InterruptedExceptiom e) { System.out.printin("Main thread interrupted."); inet jain Threa@: " + i); } System.out.printin("Main thread exiting."); } ) This program generates the same output as the preceding example. As we ean see, the child thread is created by instantiating an object of NewThread, which is derived from Thread. Notice the call to super() inside NewThread. This invokes the following form of the Thread constructor: public Thread(String rhreadName) 4.3.3 Creating Multiple Threads So far, We have been using only two threads: the main thread and one child thread However, our program can spawn as many threads as it needs. For example, the following program creates three child threads // Create multiple threads. class New?hread implements Runnable { String name; // name of thread Thread t; NewThread (String threadname) { name = threadname; t = new Thread(this, name); Department of Computer Science and Engineering 159RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. System.out.printin("New thread: " + t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.printin(name + ": "+ i); Thread. sleep (1000) ; } } catch (InterruptedException e) { System.out.printin(name + “Interrupted") ; } System.out.printin(name + " exiting."); y class MultiThreadDemo { public static void main(String args{]) { new NewThread("One"); // start threads new NewThread ("Two") ; new NewThread ("Three") 7 try { // wait for other threads to end Thread. sleep (10000) ; } catch (Interruptedzxception e) { System.out.printin("Main thread Interrupted"); } System.out.printin("Main thread exiting } } Output New thread: Thread [One,5,main] New thread: Thread (Two,5,main) New thread: Thread (Three, 5,main] One: 5 Two: 5 ‘Three: 5 Department of Computer Science and Engineering 160RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Two: 2 one: 1 Three: 1 Two: 1 One exiting. Two exiting. Three exiting. Main thread exiting. As we can see, once started, all three child threads share the CPU. Notice the call to sleep(10000) in main( ). This causes the main thread to sleep for ten seconds and ensures that, it will finish last. 4.4 Thread Priority In a Multi threading environment, thread scheduler assigns processor to a thread based on priority of thread. Whenever we create a thread in Java, always has some priority assigned to it, Priority can ier be given by JVM while creating the thread or it can be given by programmer explicitly. Accepted value of priority fora thread is in range of I to 10. There are 3 static variables defined in Thread class for priority. ‘© publie statie int MIN_ PRIORITY ‘* public static int NORM_PRIORITY ‘© publie static int MAX. PRIORITY Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN PRIORITY is 1 and the value of MAX_PRIORITY is 10 Example class TestMultiPriority1 extends Thread{ public void run(){ ‘System.out.printin("running thread name is:"+Thread.currentThread().getName()); ‘System.out.printin("running thread priority is:"+Thread.currentThread().getPriority()); + public static void main(String aras(]) reference name = new Class_name (); oR Department of Computer Science and Engineering 171RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Class_name reference name = new Class_name(); This is also known as Diamond Notation of creating an object of Generic type. Example class Gen // brackets indicates that the class is of //generic type T ob; //an object of type T is declared Gen(T 0) //constructor ob = oF public T getOb() return ob; lass Test { public static void main (String{]\args) //instance of IntegeYstype Gen Class. Gen dob»= new Gen(100); int x = iob.getob(); System.out .printAn (x)\; Gen sob =\new Gen("Hello"); //instance of String type Gen Class. String str = sob.getOb(); System.out.printin (str); ) Output 100 Hello 4.8.1 Generic Classes A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section. As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters, Example Department of Computer Science and Engineering 172RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public class Box { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box integerBox = new Box(); Box stringBox = new Box(); integerBox.add(new Integer(10 stringBox.add(new String("Hello World"); System.out.printf("Integer Value :%d\n\n", integerBox.get()); System.out.printf("String Value :%s\n", stringBox.get()); Output Integer Value :10 String Value :Hello World 4.8.2 Generic Methods We can write a single generic method declaration that ean be called with arguments of different types, Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods ©All generic method declarations have a type parameter section delimited by angle brackets () that precedes the method's return type ( in the next example). © Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name. ‘© The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments, ‘A generic method's body is declared like that of any other method. Department of Computer Science and Engineering 173RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Example Following example illustrates how we can print an array of different type using a single Generic method public class GenericMethodTest { // generic method printArray public static void printArray( E{] inputArray ) { II Display array elements for(E element : inputArray) { System.out.printf("g%s ", element); } System. out.printin(); + public static void main(String args{]) { 1 Create arrays of Integer, Double and Character Integer{] intArray = { 1, 2,3, 4,5}; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4}; Character{] charArray = { 'H', 'E', 'L','L', 'O' }; System.out.printin("Array integerArray contains:"); printArray(intArray); // pass an Integer array System.out.printin("\nArray doubleArray contains:"); printArray(doubleArray); // pass a Double array System.out.printin("\nArray characterArray contains:"); printArray(charArray); // pass a Character array + + Output Array integerArray contains: 12345 Array doubleArray contains: Department of Computer Science and Engineering 174RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.12.23.34.4 Array characterArray contains: HELLO 4.8.3 Bounded Type Parameters ‘There may be times when we will want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only ‘want to accept instances of Number or its subclasses. This is what bounded type parameters. To declare a bounded type parameter, list the type parameter’s name, followed by the extends keyword, followed by its upper bound Example Following example illustrates how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). This example is Generic method to return the largest of three Comparable objects public class MaximumTest { // determines the largest of three Comparable objects public static > T maximum(T x, Ty, Tz) { Tmax =x; // assume x is initially the largest if(y.compareTo(max) > 0) { max = y; //y is the largest so far i if(z.compareTo(max) > 0) { max =z; //zis the largest now + return max; // returns the largest object i public static void main(String aras{]) { System.out.printf("Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 )); System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); ‘System.out.printf("Max of %s, %s and %s is %s\n","pear", Department of Computer Science and Engineering 175RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. "apple", "orange", maximum("pear", "apple", “orange")); Output Max of 3, 4 and 5is 5 Max of 6.6,8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear 4.9 Restrictions and Limitations In Java generics, the following restrictions exists Cannot Instantiate Generic Types with Primitive Types Cannot Create Instances of Type Parameters Cannot Declare Static Fields Whose Types are Type Parameters Cannot Use Casts or instanceof With Parameterized Types Cannot Create Arrays of Parameterized Types Cannot Create, Catch, or Throw Objects of Parameterized Types Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type Department of Computer Science and Engineering 176

You might also like