Download as pdf
Download as pdf
You are on page 1of 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 1 RMK 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 2 RMK 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 3 RMK 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 4 RMK 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 5 RMK 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 6 RMK 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 7 RMK 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 <0) { Iishow error }else account_balance = account_balance + a + } Suppose a hacker managed to gain access to the code of our bank account, Now, he tries to deposit amount -100 into our account by two ways. Let us see the first method or approach, Approach I: He tries to deposit an invalid amount (say -100) into our bank account by manipulating the code. Science and Engineering 8 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Usually, a variable in a class are set as "private" as shown below. It can only be accessed with the methods defined in the class. No other class or object can access them. Ifa data member is private, it means it can only be accessed within the same class. No outside class can access private data member or variable of other class. So in our case hacker cannot deposit amount -100 to our account. Approach 2: Hacker's first approach failed to deposit the amount, Next, he tries to do deposit an amount -100 by using "deposit" method. But method implementation has a check for negative values. So the second approach also fails. Department of Computer Science and Engineering 9 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Thus, we never expose our data to an external party. Which makes our application The entire code can be thought of a capsule, and we can only communicate through the messages. Hence the name encapsulation. ) and thrpws Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.4 Inher nce Inheritance is an important concept of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features (data and methods) of another class. The aim of inheritance is to provide the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class. Important terminology: Super Class: The class whose features are inherited is known as super class (or a base class or a parent class). Sub Class: The class that inherits the other class is known as sub class (or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. Reusability : Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, wwe can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. The keyword used for inheritance is extends. Syntax class derived-class extends base-class Jimethods and fields } Example: In this example, we have a base class Teacher and a sub class PhysicsTeacher. Since class PhysicsTeacher extends the designation and college properties and work() method from Department of Computer Science and Engineering " RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. base class, we need not to declare these properties and method in sub class. Here we have collegeName, designation and work) method which are common to all the teachers so we have declared them in the base class, this way the child classes like MathTeacher, MusicTeacher and PhysicsTeacher do not need to write this code and can be used directly from base class. class Teacher { String designation = String collegeName void does(){ System.out.printin("Teaching"); a } "Teacher"; "XYZ College"; public class PhysicsTeacher extends Teacher{ String mainSubject = "Physics"; public static void main(String args{)){ PhysicsTeacher obj = new PhysicsTeacher! System.out.printIn(obj.collegeName); System. out.p: System.out. printin(obj.mainSubject); ‘obj.does(); Output: Beginnersbook Teacher Physi Teaching Based on the above example we can say that Physics Teacher 1S-A Teacher. This means that a child class has IS-A relationship with the parent class. This inheritance is known as IS-A. relationship between child and parent class 1.4.1 Types of inheritance in Java ‘There are five types of Inheritance in OOP concept. However Java support only four types. Department of Computer Science and Engineering n RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1, Single Inheritance 2. Multilevel Inheritance 3. Hierarchical Inheritance 4. Hybrid Inheritance 5, Multiple Inheritances 1. Single Inheritance: refers to a child and parent class relationship where a class extends another class. Single hence Example: ‘TestInheritance,java class Animal{ void eat(){ System. out.printin("eating.. 2 } class Dog extends Animal{ void bark(){ System. out.printin("barking... - 2 class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); Department of Computer Science and Engineering 2B RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. barking... eating... 2. Mull the child class. For example class C extends class B and class B extends class A. level inheritance: refers to a child and parent class relationship where a class extends Example ‘TestInheritance2,java class Animal{ void eat(){ ‘System.out.printin(“eating. ; + class Dog extends Animal{ void bark(){ System.out.printin("barking..."); ; x class BabyDog extends Dog{ void weep(){ System.out.printin("weeping ; 3 class Testinheritance2{ public static void main(String args{])¢ BabyDog d=new BabyDo9(); d.weep(); Department of Computer Science and Engineering 4 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. d.bark(); dveat(); Bo Output: weeping barking eating 3. ierarchical inheritance: refers to a child and parent class relationship where more than one classes extends the same class. For example, classes B, C & D extends the same class A. A PJ Ce) Hierarchical nbertance Example ‘TestInheritance3 java class Animal< void eat(){ ‘System.out.printin(“eating. ; y class Dog extends Animal{ void bark(0{ System.out.printin("barking.. } y class Cat extends Animal void meow(){ System.out.printin("meowing , ; class Testinheritance3{ Department of Computer Science and Engineering 15 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public static void main(String args{]){ Cat c=new Cat(); c.meow(); ceat(); Me.bark();//C.T.Error 3 2 Output: meowing... eating.. 4. Multiple Inheritance: refers to the concept of one class extending more than one classes, ‘which means a child class has two parent classes. For example class C extends both classes Aand B. Java doesn’t support multiple inheritance € ute nertance Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and we call it from child class object, there will be ambiguity to call method of A or B class. Since compile time errors are better than runtime errors, java renders compile time error if we inherit 2 classes. So whether we have same method or different, there will be compile time error now. class A void msg()¢ System.out.printin("Hello"); , , Department of Computer Science and Engineering 16 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. class 8( void msg()¢ System.out.printin("Welcome"); > 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 7 RMK 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 18 RMK 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 20 RMK 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 2 RMK 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 2 RMK 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 23 RMK 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 24 RMK 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 25 RMK 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 26 RMK 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 a7 RMK 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 28 RMK 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 30 RMK 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 31 RMK 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 32 RMK 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 33 RMK 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 4 RMK 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 35 RMK 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 36 RMK 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 37 RMK 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() {<—— Se // function body 1. While Java is executing the program code, it encounters myMethod(); in the code. 2. The execution then branches to the myFunetion() method, and executes code inside the body of the method. 3. After the codes execu inside the method body is completed, the program returns to the original state and executes the next statement. Department of Computer Science and Engineering 38 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. L.11 Access Specifiers Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods in Java.These Specifiers determine whether a field or method in a class, can be used or invoked by another method in another class or sub-class. Access Specifiers can be used to restrict access. Access Specifiers are an integral part of object-oriented programming. L.1L.1 Types Of Aces Specifiers : In java we have four Access Specifiers and they are listed below. 1. public (Visible to the world) 2. private (Visible to the class only) 3. protected (Visible to the package and all subclasses) 4, default (no specifier- Visible to the package) Example protectedclass Test {} public classMain ( public static voidmain (String args[]) { ) 1.11.2 Static keyword in java Department of Computer Science and Engineering 39 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. static is a non-access modifier in Java which is applicable for the following: 1. blocks 2 les 3. methods 4. nested classes To create a static member(block,variable,method,nested class), precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. For example, in below java program, we are accessing static method m1() without creating any object of Test class. // Java progzan to demonstrate that a static member can be accesséd béforé //instantiating a class clase Test JI static method ie void ma () ‘ Syetem.out.printla ("fom mi"); ) public static voidmain(String(] args) // calling ml without creating any object “of class Test mi); Advantage of static variable: It makes our program memory efficient (ie it saves memory). Note: main method is static, since it must be accessible for an application to run, before any instantiation takes place. 1.12 Comments in Java In a program, comments take part in making the program become more human readable by placing the detail of code involved and proper use of comments makes maintenance easier and finding bugs easily. Comments are ignored by the compiler while compiling a code. In Java there are three types of comments: Single — line comments. 2. Multi —line comments, 3. Documentation comments. 1. Single-line Comments Department of Computer Science and Engineering 40 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ‘A beginner level programmer uses mostly single-line comments for describing the code functionality lis the most easiest typed ‘comments. Syntax: {comments ner Text inthis ine only is considered as comment ) Example: //0ava program to show single Line conments class public static void main(String args() i // Single Line coment here Systen.out.printin ("Single line comment above") ? 2. Multi-tine Comments To describe a full method in a code or a complex snippet single line comments can be tedious to write, since we have to give ‘/” at every line. So to overcome this multi line comments ean be used. Syntax: Comment starts continues continues, Commnent ends*/ Example: //3ava program ¢6 show mlti line conments class Sconnent, ( public staticvoidmain (String args{1) ( system.6ut.printin ("Multi line comments below"); yaCorment line 1 Corment line 2 Conment line 3*/ ) ' 1.13 Data types in Java Java has two categories of data: © Primitive data (e.g., number, character) Department of Computer Science and Engineering 41 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ‘© Non Primitive data or Object data (programmer created types) 1.13.1 Primitive data Primitive data are only single values; they have no special capabilities. There are 8 primitive data types 1. boolean 2 byte 3. short 4. int 5. long 6. float 7. double 8 char Data Type Primitive Noe-Pririnive ae Su [— String Boolean Numeric [— Array ee ete Character Integral ao, Intezer Floating-point LT # * boolean char byte short int long float. double 1. boolean boolean data type represents only one bit of information either true or false . Values of type boolean are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code. // & Java program to demonstrate boolean data type class GeeksforGeeks ( public static void main(String args(]) Department of Computer Science and Engineering 2 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. boolean ~ true Lf (b == true) System.out printin ("Hi Geek" 2. byte The byte data type is an 8-bit signed two's complement integer:The byte data type is useful for saving memory in large arrays. © Size: &-bit © Value: -128 to 127 // Java program to demonstrate byte data type in Java class Testbyte H public static voidmain(string args{1) ( bytea - 126; W/ byte is 8 bit value System. out .printin (a); System.out .printin (a); J/ te overflows here because // byte can hold values from “128 to 127 System.out .printin(a) + // Looping back within the range System. out.printin(a) 126 227 128 “27 3. short The short data type is a 16-bit signed two's complement integer. Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually matters. Department of Computer Science and Engineering 4B RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Size: 16 bit ‘Value: -32,768 to 32,767 (inclusive) 4. int It is a 32-bit signed two's complement integer. Size: 32 bit Value: -231 t0 231-1 Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer, which has value in range (0, 232-1]. Use the Integer class to use int data type as an unsigned integer. 5. long: The long data type is a 64-bit two's complement integer. Size: 64 bit Value: -263 to 263-1 Floating point Numbers : float and double 6. float The float data type is a single-precision 32-bit. Use a float (instead of double) if we need to save memory in large arrays of floating point numbers. Size: 32 bits Suffix : F/f Example: 9.8f 7. double The double data type is a double-precision 64-bit, For decimal values, this data type is generally the default choice. 8. char ‘The char data type is a single 16-bit Unicode character. A char is a single character. Value: *\u0000" (or 0) to “fi? 65535 Hf sava program to demonstrate sStchar mitive data types in Java public static voldmain (string args(]) // declaring chara chara = 'G'; J/ Integer data type is generally 7/ used for numeric values Department of Computer Science and Engineering “4 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. int in89; byte and short if memory is a con: 45 J/ this will give error as number is a larger than byte range 7/ byte bl = 7888885955; short s = 56; J/ his will give error as number is larger than short V7 short 81 = 8787878787 range’ // by default fraction value is double in java double d = 4.355453532; W/ for float use '£" as suffix float £ = 4.7333434£; systen.oi System. System. intin("char: "+ a); printIn("integer: "+ i); intln("byte: "+ b); system intin("short: "+ s)7 System-out.printIn("float: "+ £)% System.out .print1n ("double:/* + @)? Output: char: G integer: 89 byte: 4 short: 56 float: 4.733436 double: 4.355453532 1.13.2 Non Primitive Data Types Non-primitive data types are created by programmer. It is also called as "Reference Variables' or ‘Object reference’ because it refers a memory location where data is stored. On the other hand, primitive data types stores value. String It is class in java provided with several methods used to store group of characters. Department of Computer Science and Engineering 45 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. For example, abed, indial23 ete. String is not a primitive data type because it has methods and only class can have methods Primitive data types cannot have methods. So, String is a class which is non-pri 'String’ is used to represent string class. Example: String s="World” ive type. ‘Objects and Array Objects and Array are non-primitive data types because it refers to the memory location 1.14 Java Identifiers In programming languages, identifiers are used for identification purpose. In Java an identifier can be a class name, method name, variable name or a label. For example public class Test { public static void main(Stringl] args) t int a = 20; » » In the above java code, we have 5 identifiers namely = Department of Computer Science and Engineering 46 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Test : class name. main : method name. String : predefined class name. args : variable name. a: variable name, Rules for defining Java Identifiers There are certain rules for defining a valid java identifiers. These rules must be followed, otherwise we get compile-time error. The only allowed characters for identifiers are all alphanumeric characters({A-Z],[a-2],[0-9]) ‘* Identifiers should not start with digits([0-9]), For example “123students” is a not a valid java identifier. Java identifiers are ease-sens There is no limit on the length of the identifier but it is advisable to use an optimum. length of 4 ~ 15 letters only. © Reserved Words can’t be used as an identifier. For example “int while = 20:” is an invalid statement as while is a reserved word. Variables in Java A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. +A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. ‘© In Java, all the variables must be declared before they can be used. Department of Computer Science and Engineering 47 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. How to declare variables? We can declare variables in java as follows: int age =20;4— value datatype —_vatiabl 20 Rereried Memorrforvarable RAM datatype: Type of data that can be stored in this variable, variable_name: Name given to the variable. value: It is the initial value stored in the variable. Examples: float simpleinterest; //Declaring float variable int time = 10, speed = 20; //Declaring and Initializing integer variable char var = 'h'; // Declaring and Initializing character variable ‘Types of variables There are three types of variables in Java: © Local Variables ‘© Instance Variables * Static Variables 1.15.1 Local Variables: A variable defined within a block or method or constructor is called local variable. ‘© These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function, ‘©The scope of these variables exists only within the block in which the variable is declared. ie. we can access these variable only within that block. Department of Computer Science and Engineering 48 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Sample Program 1: public class StudentDetails { public void Studentage () { //lecal variable age int age age = age + 5; System-out.print1n("Student age is : "+ age); } public static voidmain (String args[1) fl StudentDetails obj = new StudentDetails(); obj .Studentage () ; Output: Student age is : 5 In the above program the variable age is local variable to the function StudentAge(). If we use the variable age outside StudentAge() function, the compiler will produce an error as shown in below program. Sample Program 2: public class Student Detais ( public void Studentage () { //local variable age intage = 0: age ¥ 53 ) public static void main(String args{]} { Y/using local variable age outside it's scope System.out.printin ("Student age is : "+ age); Department of Computer Science and Engineering 49 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. error: cannot find symbol “+ age): 1.15.2. Instance Variables: ‘* Instance variables are non-static variables and are declared in a class outside any method, constructor or block. © As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed, © Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used. Sample Program: Department of Computer Science and Engineering 50 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. import java.io.*; class Marks { //These variables are instance variables //These variables are in a class and are not inside any function int engMarks; int mathstarks; int phyMarks; ) class MarksDemo public static voidmain(String args{]) {1 //£irst object Marks objl = newMarks(); objl.engMarks = 50; objl.mathsMarks = 80; objl.phyMarks = 90; /{second object Marks obj2 = newMarks(); obj2.engMarks = 8 obj2.mathsMarks = 60; obj2.phyMarks = 85; //displaying marks for first object System-out.printIn("Marks for first object:"); system.out .print1n(obj1.engMarks); system. out -printin(obj1.mathsMarks) ; System. out -print1n(obj1.phyMarks); /{displayifig marks*for second object System.out-printin("Marks for second object System, out print 1n(obj2.engMarks) ; System-out-print1n(obj2.mathsMarks) ; System. out+print1n(obj2.phyMarks); Output: Marks for first object: 50 80 90 Marks for second object: Department of Computer Science and Engineering a1 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 60 85 ‘AS we can see in the above program the variables, engMarks , mathsMarks , phyMarksare instance variables. In case we have multiple objects as in the above program, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of instance variable. 1.15.3 Static Variables: Static variables are also known as Class variables. ‘© These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block, © Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create. ‘© Static variables are created at start of program execution and destroyed automatically when execution ends, © To access static variables, we need not to create any object of that class, we can simply access the variable as: class_name.variable_ name; Sample Program: import java.io. class Emp ( // static variable salary public static double salary: public static String name = "Harsh"; ) public class EmpDemo { public statievoidmain(String args{]) { J/aceessing static variable without object Emp.salary = 1000; System.out.printIn(Emp.name + "'s average salary:"+ Emp.salary); output Harsh’s average salary:1000.0 Department of Computer Science and Engineering 2 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1.16 Operators Operator in java is a symbol that is used to perform operations. For example: +, ,*, / te Operators in Java g. bore aa e 4 Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. Some of the types are- 5. 6 7 Arithmetic Operators, Unary Operators Assignment Operators Relational Operators Logical Operators ‘Ternary Operators Bitwise Operators Shift Operators Department of Computer Science and Engineering 3 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1. Arithmetic Operators in Java Java Arithmetic operators are used for simple math operations, they are © Addition (+) © Subtraction (-) © Multiplication (* © Division (/) * Modulo (%) Example public class operators public static void main(Stting[], args) ( int a= 20, b= 10, ¢ String x = "Thank", y // + and ~ operator System.out.printin("a 4 b System.out .println ("a -\b // + operator if used with strings // concatenatés theigiven strings. System.out.printIn("x + y = "#x + y)i 11 * and { operator System.out ’printin("a * b = "+(a * b) System.out.printIn("a / b= "t(a / b) // modulo operator gives remainder on dividing first operand with second System.out.printin("a $b = "+(a 3 b)); // 4£ denominator is 0 in division then Arithmetic exception is thrown. Uncommenting below line would throw an exception // System.out.printin (a/c); } } Output atb 30 Department of Computer Science and Engineering 34 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. a-b = 10 xty = ThankYou atb = 200 a/b = 2 atb = 0 2. Unary Operator The Java unary operators require only one operand, Unary operators are used to perform various operations ie + incrementing/decrementing a value by one + negating an expression : inverting the value of a boolean Example 1: ++ and ~ class OperatorExample{ public static void main(String argstl) int x=10; System.out.printin(x++); //10/()), System.out.printin(++x); //12 System.out.printIn(x--); //12 (LY) System.out .printIn(--x); //10 Example 2: ++ and — class OperatorExample( public static void main(String args[])( int a=10; int b=10 System.out.printin(a++ + +a) ;//10+12=22 System. out.printin(b++ + b++);//10+11=21 } Department of Computer Science and Engineering 35 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Example: ~ and ! class OperatorExample( public static void main(String args{]){ int a=10; int b=-10; boolean c=tru boolean d-false; System.out.printIn(~a);//11 (minus of total positive value //whic h starts from 0) System.out .printIn(~b);//9 (positive of total ‘minus, positive / /starts from 0) System.out.printIn(!c) ;//false (opposit® of“boolean value) System.out.printIn(!d) ;//true } b Output: “ll 9 false true 3. Assignment Operators Assignment operators are used to assigning values to the left operand. (Operator Name [Description (To add the right and left operator and then assigning the result to the left operator ‘To subtract the two operands on left and right and then assign the value to the left operand ae [To multiply the two operands on left and right and then assign the value to fi the left operand [To divide the two operands on left and right and then assign the value to the left operand. = [To raise the value of left operand to the power of right operator Department of Computer Science and Engineering 56 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Po= [To apply modulo operator General format is variable = value; Example 1: class OperatorExample( public static void main(String args[])( int a=10; (a=10+4) (b=20-4) System.out.printin(a); system. out.print1n(b) ; } } Output: 14 16 Example 2: class OperatorExample( public static void main(String[] args) ( int a=10; at=3;//1043 System. out .printIn (a) ; a=4;//13-4 System.out .printIn(a) ; a*=2;//942 System. out.print1A(a) ; a/=2;//18/2 System.out.printin(a); n Output: 1 9 18 Example 3: class OperatorExample{ public static void main(String args[]) ( short, ;//a=atb internally so fine Department of Computer Science and Engineering 37 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. a-atb;//Compile time error because 10+10=20 now int System.out.printIn (a); n Output: Compile tine error After type cast: class OperatorExample{ public static void main(String args{1){ short a=10; short b=10; short) (a+b) ;//20 which is int now converted to short System.out.printin(a}; n Output: 20 4. Relational Operators : These operators are used to check for equality and comparison, They return Boolean (true or false) result after the comparison and are extensively used in looping statements as well as conditional if else statements. General format is, variable relation_operator value [Operator Name [Description == (equals to) ex. x=y [True if x equals y, otherwise false (not equal to) ex. [True if x is not equal to y, otherwise false < (less than) ex. xy [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 58 RMK 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 38 RMK 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 > 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 a RMK 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 68 RMK 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 Engineering RMK 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 65 RMK 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 66 RMK 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 or RMK 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 7 RMK 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 B RMK 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 < arr.length; i++) system.out.printin("Element at index "+ i + Department of Computer Science and Engineering » ' Output: Element Elenent Element Elenent Element 2. Multi Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also known as Jagged Arrays. A multidimensional array is at at at at at RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. wa arelilyy index 0 : 10 index 1 : 20 index 2: 30 index 3: 40 index 4: 50 created by appending one set of square brackets ({]) per dimension, Examples: 1{] intarray = new int [10] [20]; //a 2D ateay or matrix int (}(J() intArray = new int {10} (20) [10);,//a Sbearray Example class Testarray3{ public static void main(String args[1)( //declaring and initiabizing 2D array int are{](1=((1/2, 3h) (2,405), (4.4/5) 44 //printing 2D array for(int i=071<3;i++) { for (int System, out print (arr[i] [j1+" ) 3S375+4){ System-out .printin(); 123 245 445 Passing Arrays to Methods Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Like variables, we can also pass arrays to methods. For example, below program pass array to method sum for calculating sum of array's values, // Java program to demonstrate // passing of array to method ( W/ Driver method public static voldmain (string args{1} ( int arr{] = 13, 1, 2, 5, aly // passing array to method ml sum (arr); public static void sum(int(] arr) ‘ WY ger! int sum ng sum of array values for (inti = 07 i < arr.lengthy i+) eunt=are [117 System.out.printin ("sum of array values + sum); ) , Output : sum of array values : 15 Returning Arrays from Methods ‘As usual, a method can also return an array. For example, below program returns an array from method m1 // Jawa progran to dendnstrate // return of arfay from method class Test 1/ Déiver method Publiastatic ( id main(String args[]) Ant are() = m0; for (int i = 07 i < arr.length; i++) System.out print (arr[il+" "); ) public static int(] ml () W/ returning array return new int(](1,2,3}; Department of Computer Science and Engineering 81 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. , Output: 123 1.19 Java Package A java package is a group of similar types of classes, interfaces and sub-packages. Package in {java can be categorized in two form, built-in package and user-defined package. ‘There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc, Here, we will have the detailed leaming of creating and using user-defined packages. Advantage of Java Package These are the reasons why we should use packages in Java: ‘© Reusability: While developing a project in java, we often feel that there are few things that we are writing again and again in our code. Using packages, we can create such things in form of classes inside a package and whenever we need to perform that same task, just import that package and use the class. ‘© Better Organization: Again, in large java projects where we have several hundreds of classes, itis always required to group the similar types of classes in a meaningful package ame so that we can organize our project better and when we need something we can quickly locate it and use it, which improves the efficiency. ‘+ Name Confliets: We can define two classes with the same name in different packages so to avoid name collision, we can use packages Types of packages in Java As mentioned in the beginning of this guide that we have two types of packages in java. User defined package ‘The package we create is called user-defined package. Built-in package ‘The already defined package like java.io.", java.lang.* ete are known as built-in packages. 1. Built-in Packages ‘These packages consist of a large number of classes which are a part of Java APLSome of the commonly used built-in packages are: 1) java.tang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported Department of Computer Science and Engineering 82 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 2) javacio: Contains classed for supporting input / output operations. 3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations. 4) javaaapplet: Contains classes for creating Applets 5) java.awt: Contain classes for implementing the components for graphical user terfaces (like button , :menus etc). 6) java.net: Contain classes for supporting networking operations. 2. User defined package Example The package keyword is used to create a package in java. //save as Simple. java package mypack; public class Simple( public static void main(String args[}){ System.out.printin ("Welcome to package"); ) } How to access package from another package’ There are three ways to access the package from outside the package. 1. import package.*; 2. import package.classname; 3. fully qualified name. 1) Using packagename.* Ifwe use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package. Example of package that import the packagename.* //save by A.java Department of Computer Science and Engineering 83 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. package pack; public class A{ public void msq() (System.out .print1n ("Hello") } //save by B.java package mypack; import pack. *; class B{ public static void main(String args{])( A obj = new A()7 obj-msg() } } Output: Hello Using packagename.elassname If we import package.classname then only declared class of this package will be accessible. Example of package by import package.classname //save by A.java package pack? public class A{ public void msg() (System.outyprintin ("Hello") +) } //save by B.java package mypack; class Bi public static yOid main(String args[])( pack.A obj = new pack.A();//using fully qualified name obj ..msg (1; 1.20 JavaDoc Comments Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. One of the nice things about Java is javadoc. The javadoc utility lets us to put our comments right next to our code, inside our " java” source files. Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML format from Java source code, which requires documentation in a predefined format. Java language supports three types of comments ~ SeNo. Comment & Description : P* text *7 ‘The compiler ignores everything from /* to */. 2 Ihtext ‘The compiler ignores everything from / to the end of the line. 3 /** documentation */ This is a documentation comment and in general its called doc comment. The JDK javadoc tool uses doc comments when preparing automatically generated documentation. We can include required HTML tags inside the description part. For instance, the following example makes use of .... 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 85 RMK 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 86 RMK 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 87 RMK 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 Engineering RMK 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()< System.out.printin(color);//prints color of Dog class ‘System.out.printin(super.color);//prints color of Animal class } } class TestSuper1{ public static void main(String args[]){ Dog d=new Dog(); d.printColor(); } Output black whice In the above example, Animal and Dog both classes have a common property color. If we print color property, it will print the color of current class by default. To access the parent property, we need to use super keyword. 2) super can be used to invoke parent class method The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden, Example class Animal{ void eat(){ System.out.printin("eating..."); + o Department of Computer Science and Enginee RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. class Dog extends Animalt void eat(){ ‘System.out.printin("eating bread..."); void bark(){ System.out.printin("barking ? void work(){ super.eat(); bark(); , , class TestSuper2{ public static void main(String args(]){ Dog d=new Dog); d.work(); + Output eating... barking In the above example Animal and Dog both class 18 have eat() method if we call eat() method from Dog class, it will call the eat() method of Dog class by default because priority is given to local. To call the parent class method, we need to use super keyword. 3) super is used to invoke parent class constructor, ‘The super keyword can also be used to invoke the parent class constructor. Example class Animal{ Animal() System.out.printin("animal is created"); } z class Dog extends Animal{ Dog(){ Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. super(); ‘System.out.printin("dog is created"); } } class TestSuper3{ public static void main(String args[]){ Dog d=new Dos(); } 3 Output dog is created Note: super() is added in each class constructor automatically by compiler if there is no super() or this(). class Bike class Bike( Bike()t ; compiler } Bike java } Bike.class As we know well that default constructor is provided by compiler automatically if there is no constructor. But, it also adds super() as the first statement. Another example of super keyword where super() is provided by the compiler implicitly. class Animal{ Animal(){System.out.printin(“animal is created");} > class Dog extends Animal{ Dog(){ ‘System.out.printin("dog is created"); + + class TestSupera{ public static v main(String args[]){ Department of Computer Science and Engineering RMK 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 Engineering RMK 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(])< Department of Computer Science and Enginee! RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. obj.run(); y }iend of class output :Compile Time Error Final Method If you make any method as final, you cannot override it. Example class Bike{ final void run(){ System.out.printin("running"); ba class Honda extends Bike{ void run(){ System.out.printin("running safely with 100kmph"); + public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } ¥ outpu :Compile Time Err! Final Class If we make any class as final, we cannot extend it. Example final class Bike{} class Honda extends Bike{ void run(){ System.out.printin("running safely with 100kmph"); Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Public static void main(String args[]){ Honda honda= new Honda(); honda.run(); i + output :Compile Time Error Using final to Prevent Inheritance a Class Sometimes we will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations final class A { Was } // The following class is illegal. class B extends A { // ERROR! Can't subclass A “ } As the comments imply, itis illegal for B to inherit A since A is declared as final However final method can be inherited but you cannot override it, Example class Bike{ final void run(){ System.out.printin("running..."); } ¥ class Honda extends Bike{ Public static void main(String args{]){ new Honda().run(); + 3 output: running... abstract class vs final class Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. PROPERTY ABSTRACT CLASS | FINAL CLASS Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Should be subclassed to override the Can never be SUBCLASSING functionality of subclassed as final abstract methods does not permit Abstract class Final class methods METHOD methods functionality | cannot be altered and ALTERATIONS can be altered in should be used as it is subclass by other classes Cannot be INSTANTIATION instantiated Can be instantiated Overriding concept OVERRIDING For later use, all the | does not arise as final CONCEPT abstract methods class cannot be should be overridden _| inherited INHERITANCE Can be inherited Cannot be inherited ABSTRACT Can contain abstract} Cannot contain METHODS methods abstract methods ‘A few methods can be ae implemented anda __| All methods should IMPLEMENTATION few cannot have implementation Cannot create IMMUTABLE immutable objects __| Immutable objects can (CHANGELESS OBJECTS | (infact, no objects can | be created (eg. String be created) class) Itisan incomplete _| It is a complete class class (for this reason _| (in the sense, all NATURE only, designers do not | methods have allow to create complete functionality objects) or meaning) Extra functionality to | No extra functionality ADDING EXTRA the methods canbe | can be added and FUNCTIONALITY added in subclass should be used as it is Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 2.1.8 Interfaces We discussed abstract class which is used for achieving partial abstraction. Unlike abstract class an interface is used for full abstraction. Using the keyword interface, we can fully abstract a class’ interface from its implementation. That is, using interface, we can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. Onee it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces. To implement an interface, a class: must create the complete set of methods defined by the interface. However, each class is free to determine the details of its own implementation. By providing the interface keyword, Jaya allows you to fully utilize the “one interface, multiple methods” aspect of polymorphism. Syntax public interface NameOfinterface { // Any number of final, static fields // Any number of abstract method declarations } Here is an simple example of an interface definition. It declares an interface that contains one ‘method called calback( ) that takes a single integer parameter. interface Callback { void callback (int param); } Interfaces have the following properties «An interface is implicitly abstract. We do not need to use the abstract keyword while declaring an interface. + Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. + Methods in an interface are implicitly public. Once an interface has been defined, one or more classes can implement that interface. When a class implements an interface, we can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A cla uses the i plements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration, Department of Computer Science and Enginee RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Understanding relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface. class interface interface * extends | implements extends class class interface Implementing Interfaces Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements is: class classname [extends superclass] [implements interface L,interface...}] { // ¢lass-body: ) Example Interface Bank{ float rateOfinterest(); + class SBI implements Bank{ public float rateOfinterest(){ return 9.15f; } Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. class 10B implements Bank< public float rateOfinterest(){ return 9.7f; 3 + class Testinterface{ public static void main(String{] args){ Bank b=new SBI); ‘System.out.printin("Rate of Interest: "+b.rateOfinterest()); } + Output Rate of Interest: 9.15 Multiple Interfaces If a clas implements multiple interfaces, or an interface extends multiple interfaces i.e known as multiple inheritance. interface interface interface interface * * a ae class Interface Multiple Inheritance in Java Example interface Printable{ void print(); + interface Showable{ void show(); + class A implements Printable, Showable{ public void print(){ ‘System.out.printin("Hello"); _) public void show(){ Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. System.out.printin("Welcome"); } public static void main(String args[]){ A obj = new A(); ‘obj.print(); ‘obj.show(); Note: Multiple inheritance is not supported through class in java but it is naccihle hw intarfare Example interface Printable{ void print(); } interface Showable{ void print(); + class Testinterface implements Printable, Showable{ public void print(){ System.out.printin("Hello"); + public static void main(String args[]){ TestInterface obj = new Testlnterface(); obj.print(); > ¥ Output Hello Nested Interfaces Department of Computer Science and Engineering RMK 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 < 0 ? false : true; y } class NestedIFDemo [ public static void main(string args{]) \{ // use a nested interface reference A.NestedIF nif = new‘B(); if (nif isNotNegative (10) ) system.out.printin("10 is not negative"); if (nif. isNotNegative(-12)) System.out, printin( is won't be displayed"); Extending Interfaces (Interface inheritance) Acclass implements interface but one interface extends another interface. Example interface Printable{ Inherits Printable void print(); tense 2 interface Showable extends Printable{ void show(); } class Testinterface implements Showable{ public void print(){ System.out.printin("Hello"); 3 Department of Computer Science and Enginee! RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public void show(){ ‘System.out.printin("Welcome"); + public static void main(String args[]){ Testinterface obj = new Testinterface(); obj.print(); 0bj.show(); } } Output Hello Welcome Variables in Interfaces We can declare variables in Java interfaces. By default, these are public, final and static, That is they are available at all places of the program, we cannot change these values. Only one instance of these variables is created, it means all classes which implement this interface have only one copy of these variables in the memory. Example: i This is a simple Java program about Interface. Call this file interfaceVariables.java W interface x { int max = 10; + class Example implements X { public void getMax(){ System. out. printin(max); } } class InterfaceVariables { public static void main(String args{]){ Uncommenting this will generate Example ob = new Example(); compile error. Because By ob.getMax(); default, these are public, final Hlob.max = 20; and static. + : Output Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 10 Difference between Abstract classes and Interfaces Abstract class Interface Abstract class is a class which contain ‘one or more abstract methods, which has to be implemented by its sub classes. Interface is a Java Object containing method declaration but no implementation. The classes which implement the Interfaces must provide the method definition for all the methods. Abstract class is a Class prefix with an abstract keyword followed by Class definition, Interface is @ pure abstract class which starts with interface keyword, Abstract class can also contain concrete methods. Whereas, Interface contains all abstract methods and final variable declarations. Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented. 2.1.9 Object Cloning Object cloning refers to the creation of exact copy of an object. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object. The eloneQ method of Object object. is used to clone an To use java object clone method, we have to implement the marker interface java.lang-Cloneable so that it won't throw CloneNotSupportedException at runtime, Also Object clone is a protected method, so we will have to override it to use with other classes. Department of Computer Science and Enginee RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Advantage The clone() method saves the extra processing task for creating the exact copy ofan object. If we perform it by using the new keyword, it will take a lot of processing time to be performed that is why we use object cloning. In Java, there is no operator to create copy of an object. Example of creating an object using assignment operator // Java program to demonstrate that assignment // operator only creates a new reference to same // object import java.io. *s // B test class whose objects are cloned class Test t int x, yF Test 0) // Driver Class class Main i public static voidmain(string!] args) c Test obl = new Test (); System.outiprintin\obl.x + " "+ obl.y); 4f Creating 2 new reference variable ob? // pointing to same address as obl Test Ob2a= ob1; Yi\Ahy Change made in ob2 will be reflected {in ob: ob2.x 00; System.out.print1n(obl.x+" "tobl.y); System.out.print1n(ob2.x+" "+ob2.y); output 1020 Department of Computer Science and Enginee! RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 100 20 100 20 Creating a copy using clone) method // ® Java program to demonstrate shallow copy // using clone() import java.util.Arraybists // An object reference of this class is // contained by Test? class Test ( int x, yz } // Contains a reference of Test and implements 7/ clone with shallow copy. class Test2 implements Cloneable t int as int b Test c = newTest(); public Object clone() throws CloneNotSupportedException ( return superselone() + , , // Driver class public class Main ( public static voidmain(String args[]) throws CloneNotSupportedException ( Test2 th = new Test2(); tla = 10; ehab™= 20; tl.c.x = 30; tl.c.y = 407 Test2 t2 = (Test2)tl.clone(); // Creating a copy of object tl and passing 7 it to t2 t2.a = 100; // Change in primitive type of t2 will not // be reflected in tl field Department of Computer Science and Enginee! RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. t2.c.x = 300; // Change in object type field will be // reflected in both t2 and t1(shallow copy) System.out.printin(tl.a +" "+ ti.b +" "+ tle +" "+ tl.c.y); System.out.printin(t2.a +" "+ t2.b¢" "+ tlc +" "+ t2c.y)s , } Output 10 20 300 40 1100 20 300 40, Creating a copy using clone() method The class whose object’s copy is to be made must have a public clone method in it or in one ofits parent class. Every class that implements clone() should call super.clone() to obtain the cloned object reference. The class must also implement javaclang.Cloneable interface whose object clone we want to create otherwise it will throw CloneNotSupportedException when clone method is called on that class’s object. // & Java program to demonstrat // using clone() import java.util.ArrayList; shallow copy // An object reference of this class is // contained by, Test2 class Test, r int xa vy; ) // Contains a reference of Test and implements // clone with shallow copy. ss Test2 implements Cloneable inta; int b, Test new Test (); public Object clone() throws CloneNotSupportedException ( Department of Computer Science and Enginee! RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. return super.clone(); ) // Driver class public class Main { public static voidmain (String args{]) throws CloneNotSupportedException ( Test2 tl = newTest2(); tl.a = 10; t1.b = 20; tl.c.x = 30; x tl.c.y = 40; Test2 t2 = (Test2)t1.clone(); // Creating a copy of object «tl, and\passing // it to t2 t2.a = 100; // Change in primitive type oB\t2) will not // be reflected intl Field t2.c.x = 300; // Change in object typé\field will be // reflected in both t2 and ti(shallow copy) System.out.printin(tl.a + ttle" "4 tl.ex +" "4+ tl.c.y); Systemvoub.printla(t2.a + + t2.b+" "4 c.x “+ t2.c.yi ) output, 10 20 300.40 1100 20 300 40, In the above example, t1.clone returns the shallow copy of the object t1. To ob a deep copy of the object certain modifications have to be made in clone method after obtaining the copy. Shallow Cloning ‘This is default implementation in java, In overridden clone method, if you are not cloning all the object types (not primitives), then you are making a shallow copy. Department of Computer Science and Enginee! RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. All above examples are of shallow copy only, because we have not cloned the Department object on Employee class’s clone method. Deep cloning Itis the desired behavior in most the cases. We want a clone which is independent of original and making changes in clone should not affect original. 2.1.10 Inner Classes It is possible to define a class within another class; such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class. ‘Thus, if class B is defined within class A, then B does not exist independently of A. A non- static class that is ereated inside a class but outside a method is called member inner class There are two types of nested classes: static and non-static. ‘The most important It has aK type of nested class is the inner class. An inner class is a non-static nested cla 88 to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Nested classes Inner classes Static Nested classes Method local Anonymous Inner classes. Inner classes Inner classes The following program illustrates how to define and use an inner class. The class named Outer has one instance variable named outer_x, one instance method named test( ), and defines one inner class called Inner. // Demonstrate an inner class. ss Outer { int outer_x void test () Inner inner = new Inner(); inner. display (); t 100; Department of Computer Science and Enginee! RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. // this is an inner class class Inner { void display() { System. out.printin("displa’ } outer_x = " + outer_x); } class InnerClassDemo { public static void main(String args(]) [{ Outer outer = new Outer (); outer. test (); y } Output display: outer_x = 100 In the program, an inner class named Inner is defined within the scope of class Outer. Therefore, any code in class Jnner can directly access the variable outer_x. An instance method named display( ) is defined inside Inner, This method displays outer_x on the standard output stream, The main() method of InnerClassDemo creates an instance of class Outer and invokes its test) method. That method creates an instance of class Inner and the display() method is called, It is important to realize that an instance of Inner can be created only within the scope of class Outer. The Java compiler generates an error message if any code outside of class Outer attempts to instantiate class Inner. Note : An inner class has access to all of the members of its enclosing class, but the reverse is not true. There are basically three advantages of inner classes in java. They are as follows: 1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. 2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only. 3) Code Optimization: It requires less code to write. ‘There are three types of Inner classes 1. Member inner class Department of Computer Science and Enginee! RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 2. Anonymous inner class 3. Local inner class ‘Type Description Member Inner Class A class created within class and outside method. Anonymous Inner Class A class created for implementing interface or extending class. Its name is decided by the java compiler. Local Inner Class A class created within method. Static Nested Class A static class created within class. Nested Interface An interface created within class or interface. 2.1.11 ArrayList Class The ArrayList class extends AbstractList and implements the List interface. ArrayList is a generic class that has this declaration: class ArrayList 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 Enginee RMK 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 Engineering RMK 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 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 Engineering RMK 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 <= 3; i++) { System. out printin(Thread.currentThread().getStackTrace()Li. getMethodName()); + } } Output method name : function2 function main Example : Returns the line number of a program // Java code illustrating getLineNumber() method. import java.lang.*; import java.io.*; Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. import java.util public class StackTraceElementDemo t public static void main(String(] arg) i systen.out.printin("line number: * for(int i = 0; i<2; i++) system. out .print1n (Thread.currentThread() .getStackTrace() [1]. Output line number: 1556 10 3.8 Input /Output Basies One of Java’s most important packages is : io. The fo package supports Java’s basic VO (input/output) system, including file VO. 3.8.1 /O Basics In the example programs not much use of HO has been made. In fact, aside from print() and rintIn( ), none of the I/O methods have been used significantly. The reason is, most real applications of Java are not text-based, console programs. Rather, they are graphically oriented programs that rely upon Java's Abstract Window Toolkit (AWT) or Swing for interaction with the user. Also, Java’s support for console VO is limited. Text-based console I/O is just not very important to Java programming. 3.8.2 Streams Java programs perform V/O through streams. A stream that either produces or consumes information, A stream is linked to a physical device by the Java VO system. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Java implements streams within class hierarchies defined in the java.io package. 3.8.2.1 The Byte Stream Classes Byte streams arc defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has several concrete Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. subclasses that handle the differences between various devices, such as disk fil , network connections, and even memory buffers. To use the stream classes, we must import java.io. ‘Two of the most important abstract classes InputStream and OutputStream define are read() and write(), which, respectively, read and write bytes of data 3.8.2.2 The Character Stream Classes Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer, These abstract classes handle Unicode character streams. The abstract classes Reader and Writer define several key methods, two of the most important methods are read( ) and write( ), which read and write characters of data, respectively, 3.9 Reading and Writing Console 3.9.1 Reading Console Input The preferred method of reading console input is to use a character-oriented stream, which makes our program easier to internationalize and maintain. There are three different ways for reading input from the user in the command line environment(console), 1.Using Buffered Reader Class 2. Using Scanner Class 3. Using Console Class 1.Using Buffered Reader Class In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object, BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here: BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created, Reader is an abstract class. One of its concrete subclasses. is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to Spstem.in, use the following constructor: Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. InputStreamReader(InputStream inputSiream) Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader (new InputStreamReader (System. in)); After this statement executes, br is a character-based stream that is linked to the console through System.in. // Jawa program to demonstrate BufferedReader import java. io.BufferedReader; import java.io. IOException; import java.io. InputStreamReader; public Class Test i public static voidmain(string[] args) throws Tozxception fi //enter data using BufferReader BufferedReader reader= new BufferedReader (new InputStreamReader (System, in)) ; // Reading data using FeadLine String name = reader.readLine(); // Printing/the read“line System.out.println (name) ; , Input Computer Output Computer 2. Using Seanner Class This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it is, also can be used to read input from the user in the command line. Advantages: © Convenient methods for parsing primitives (nextIntQ, nextPloat(), ...) from the tokenized input. * Regular expressions can be used to find tokens, Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Drawback: ‘* The reading methods are not synchronized Example // Java program to demonstrate working of Scanner in Java //import java-util.Scanner; class Get InputFromUser ( public static voidmain(String args{]) fi // Using Scanner for Getting Input from User Scanner in = new Scanner (System. in); String s = in.nextLine(); System.out.printin("You entered string: "+s)¥ inta = in-nextint (); System.out.println("You entered integer: \"+a); float = in.nextFloat (); System.out.printin ("You entered™£loat: "+b); b Input Computer 12 14.3 Output You entered string: Computer You entered integer: 12 You entered float: 14.3 3. Using Console Class It is a preferred way for reading user’s input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()). Advantages: ‘© Reading password without echoing the entered characters. ‘© Reading methods are synchronized. ‘© Format string syntax can be used. Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Drawback: © Does not work in non-interactive environment (such as in an IDE). Example //Java program to demonstrate working of System.console(). Note that //this program does not work on IDEs as System.console() may require //console public cla: i ple public static voidmain(String!] args) cl // Using Console to input data from user String name = System.console().readLine(); system. out.print1n (name) } 3.9.2 Writing Console Output Console output is most easily accomplished with print() and printin() methods. ‘These methods are defined by the class PrintStream which is the type of object referenced by ‘System.in, Even though System.out is a byte stream, using it for a simple program output is, still acceptable, Because the PrintStream is an output stream derived from the OutputStream, it also implements the low-level method write(. Thus, write) can be used to write to the console. ‘The simplest form of write() defined by the PrintStream is shown below void write(int byteval) This method writes the byte specified by Ayteval. Although byreval is declared as an integer, only the low-order eight bits are written. Following is a short example that uses write() to output the character 'X' followed by a newline to the screen: /* Java Program Example - Java Write Console Output * This program writes the character X followed by newline * This pro demonstrates System.out.write() */ class WriteConsoleoutput public static void main(String args{]) int yz yates System. out .weite(y) System.out.write("\n'); Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Output x You will not often use write() to perform console output (although doing so might be useful in some situations) because print() and printIn( are substantially easier to use. 3.9.10 The PrintWriter Class Although using System.out to write to the console is acceptable, its use is probably best for the debugging purposes or for sample programs. For real-world programs, the recommended method of writing to the console when using Java is through the PrintWriter stream. The PrintWriter is one of the character-based classes. Using a character-based class for the console output makes internationalizing your program easier. The PrintWriter defines several constructors. The one we will use is shown below = PrintWriter (OutputStream outputStream, boolean flushingOn) Here, ourputStream is an object of type OutputStream, and flushingOn controls whether Java flushes the output stream every time a println() method (among others) is called. IfflushingOn is true, flushing automatically takes place. If false, flushing is not automati ‘The PrintWriter supports the print() and printInQ methods. Thus, you can use these ‘methods in the same way as you used them with System.out, If an argument is not a simple type, the PrintWriter methods call the object's toString( method and then display the result. To write to the console by using the PrintWriter, specify System.out for the output stream and automatic flushing. For example, the following line of code creates a Print Writer that is connected to console output: PrintWriter pw - new PrintWriter(System.out, true); Example cr Class Writer */ * Java Program Example - Java Prin * This program demonstrate the Printi import java.io.*; class PrintWriterDemo Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public static void main(String args(1) ntWriter prnwrt = new PrintWriter(System.out, true); prnwrt.printin("This is a string"); int i= -7 prnwrt-printin (i); double d = 4.5e-7; prnwrt -printin(d) ; 3.9.10 The PrintWriter Class Although using System.out to write to the console is acceptable, its use is probably best for the debugging purposes or for sample programs. For real-world programs, the recommended method of writing to the console when using Java is through the PrintWriter stream. The PrintWriter is one of the character-based classes. Using a character-based class for the console output makes intemationalizing your program easier. The PrintWriter defines several constructors. The one we will use is shown below : PrintWriter (OutputStream outputStream, boolean flushingOn) Here, ourputStream isan object of type OutputStream, and flushingOn controls whether Java flushes the output stream every time a println() method (among others) is called. If flushingOn is true, flushing automatically takes place. If false, flushing is not automatic. The PrintWriter supports the print() and printInQ) methods. Thus, you can use these methods in the same way as you used them with System.out. If an argument is not a simple type, the PrintWriter methods call the object's toString() method and then display the result. To write to the console by using the PrintWriter, specify System.out for the output stream and automatic flushing. For example, the following line of code creates a PrintWriter that is connected to console output: Printwriter pw - new Printwriter(System.out, true); Example Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. * gava Program Example - Java PrintWriter Class * This program demonstrate the Printiiriter */ import java.io.*; class PrintWriterDemo public static void main(String args[]) ntWriter prnwrt = new PrintWriter(System.out, true); prnwrt.printin("This is a string"); int i= -7; prnwrt .printin (i); double d = 4.5e-7; prnwrt .printin(d); Output This is a string “1 4.5E-7 3.10 Reading and Writing Files Java provides a number of classes and methods that allow you to read from and write to the files. The purpose of this chapter is to introduce the basic techniques that read from and write to a file, Although bytes reams are used, these techniques can be adapted to character- based streams. Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to the files. To open a file, you simply create an object of one of these class , specifying the name of file as an argument to the constructor. Although both the classes support additional constructors, the following are the forms that we will be using: FileInputStream(String fileName) throws FileNotFoundException) eOutputStream(String fileName) th FileNotFoundExcept Here, fileName specifies the name of the file that you want to open. When you create an input stream, ifthe file does not exist, then FileNotFoundException is thrown. For output streams, if the file can't be opened or created, _ then FileNotFoundException is Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. thrown, FileNotFoundException is a subclass of IOException. When an output file is, opened, any pre-existing file by the same name is destroyed. When you are done with a file, you must close it. this is done by calling the elose() method, which is implemented by both FileInputStream and FileOutputStream. It is shown below : void close() throws IOException Closing a file releases the system resources allocated to the file, allowing them to be used by another file, Failure to close a file can result in "memory leaks” because of unused resources remaining allocated. Before moving on, itis important to point out that there are two basic approaches that you can use to close a file when you are done with it. The first is the traditional approach, in which the close() method is called explicitly when the file is no longer needed. defined within To read from a file, you can use a version of the read() method that the FileInputStream. The one that we will use is shown below int read() throws IOException Each time that it is called, it reads a single byte from the file and returns the byte as an integer value. The read(returns -1 when the end of the file is encountered. It can throw an IOException. The following program uses read() method to input and display the contents of a file that contains ASCII text. The name of the file is specified as a command-line argument. /* Java Program Example - Java Read and Write File pro: ad() to input and display the * file's content. * Display a text file. * To use this program, specify the name of the * file that you want to see. * For example, to see a file called DEMO.TXT, * use the following command Line * java FileOperationDemo DEMO. TXT import java.io.*; ileOperationDemo Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. public static void main(String args[}) { int i; FileInputStream fin; /* first, confirm that a filename has been * specified (args.length != 1) System.out.println("Usage : FileOpe: return; onDemo filename /* now attempt to open the file */ try fin = new FileInputstream(args(0]) ; catch (FileNotFoundixception e) System.out.printin ("Cannot Open the File..!!"); return; /* at this point, the file is open and can be read * The following reads characters until EOF is encountered */ try { do A i = fin-read(); if(i I= -1) System.out.print ((char) i); fwhile(i != -1); } catch (IOException e) { System.out.print1n ("Error in Reading File..!! } /* now close the file */ try ( fin.close(); } cate (LoException e) Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. { System.out.print1n("Error in Closing the File..!! ) In this program, notice the try/eatch blocks that handle the 1/O errors that might occur. Each V/O operation is monitored for exceptions, and if an exception occurs, it is handled. Be aware that in simple programs or example code, it is common to see /O exceptions simply thrown out of the main), as was done in the earlier console I/O examples. Also, in some real-world code, it can be helpful to let an exception propagate to a alling routine to let the caller know that an /O operation failed. Although the preceding example closes the file stream afier the file is read, there is a variation that is often useful. The variation is to call the elose() method within a finally block. In this approach, all of the methods that a ss the file are contained within a try block, and finally block is used to close the file, This way, no matter how the try block terminates, the file is closed. Assuming the preceding example, below is how the try block that reads the file can be recoded. Department of Computer Science and Engineering RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. UNIT -IV 4, MULTITHREADING AND GENERIC PROGRAMMING. Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently, Each part of such a program is called a shread, and each thread define a separate path of execution. Thus, multithreading is a specialized form of multitasking. However, there are two distinet types of multitasking: (processbased and (ii) thread-based. It is important to understand the difference between the two. A process is, in essence, a program that is executing. Thus, process-based multitasking is the feature that allows the computer to run two or more programs concurrently. For example, process-based multitasking enables us to run the Java compiler at the same time that we are using a text editor. In processbased multitasking, a program is the smallest unit of code that ean be dispatched by the scheduler. In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a single program ean perform two or more tasks simultaneously. For instance, a text editor can format text at the same time that itis printing, as long as these two actions are being performed by two separate threads. and. thread-based multitasking handles the details. Multitasking threads require less overhead than multitasking Thus, process-based multitasking deals with the “big picture, processes. 4.1 Difference Between Multithreading and Multitasking Multithreading vs Multitasking Multithreading is to execute multiple Multitasking is to run multiple processes threads in a process concurrently. ‘on a computer concurrently. Execution In Multithreading, the CPU switches In Multitasking, the CPU switches between multiple threads in the same between multiple processes to complete process, the execution. Resource Sharing In Multithreading, resources are shared In Multitasking, resources are shared among multiple threads in a process. among multiple processes. ‘Complexity Multithreading is light-weight and easy | — Multitasking is heavy-weight and harder to create to create 4.1.1 Multitasking Department of Computer Science and Engineering 153 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Multitasking is when a single CPU performs several tasks (program, process, task, threads) at the same time, To perform multitasking, the CPU switches among theses tasks very frequently so that user can interact with each program simnltancously In a multitasking operating system, several users can share the system simultaneously. As we saw the CPU rapidly switches among the tasks, soa litte time is needed to switch from one user to the next user. This puts an impression on a user that entire computer system is dedicated to him, ve mae tii + Multitasking 4.1.2 Multithreading Multithreading is different from multitasking ina sense that multitasking allows multiple tasks at the same time, whereas, the Multithreading allows multiple threads of a single task (program, process) to be processed by CPU at the same time. A thread is a basic execution unit which has its own program counter, set of the register, stack but it shares the code, data, and file of the process to which it belongs. A process can have multiple threads simultaneously, and the CPU switches among these threads so frequently making an impression on the user that all threads are running, simultaneously and this is called multithreading. a Key Differences Between Multitasking and Multithreading 1. The basic difference between multitasking and multithreading is that in multitasking, the system allows executing multiple programs and tasks at the same time, whereas, in multithreading, the system executes multiple threads of the same or different processes at the same time, 2. In multitasking CPU has to switeh between multiple programs so that it appears that multiple programs are running simultaneously. On other hands, in multithreading CPU has to switch between multiple threads to make it appear I that all threads are running simultaneously. 14 3. Multitasking allocates separate memory and resources for each process/program whereas, in multithreading threads belonging to the same nnrocess shares the cama memary and resaurees as that of the nracese RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 4.2 Thread Life Cycle Threads exist in several states. A thread cé soon as it gets CPU time, A running thread can be suspended, which temporarily suspends its be running. It can be ready to run as activity. A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed. san sleep done, 0 ' ‘omplet oc a, a) my —— [Non-Runnable (oe) eae a meeicg >) — 7c, econ, wt eos fetes, spend, wa oe Temata a, Thread Priori Department of Computer Science and Engineering 155 RMK 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 156 RMK 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 157 RMK 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 158 RMK 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 159 RMK 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 160 RMK 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(])< ‘TestMultiPriority1 m1=new TestMultiPriority1(); ‘TestMultiPriority1 m2=new TestMultiPriority1(); mL.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); mL.start(); m2.start(); » Department of Computer Science and Engineering 161 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ¥ Output Qutput:running thread name is:Thread-0 inning thread priority is:10 nning thread name is:Thread-1 isAlive() and join() The isAlive( ) method returns true if the thread upon whic! returns false otherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use to. wait fora thread to finish is called join( ) is called is still running. It 4.5 Synchronization When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this tion. is achieved is called synchroni: This is implemented using a concept called monitors, Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. 4.5.1 Using Synchronized Methods Java programming language provides a very handy way of creating threads and synchronizing their t Syntax synchronized (object) ( by using synchronized blocks. J/statement to be synchronized The following example program has three simple classes. The first one, Callme, has a single method named eall( ). The eall( ) method takes a String parameter called msg. This ‘method tries to print the msg string inside of square brackets. The interesting thing to notice is that after call( ) prints the opening bracket and the msg string, it calls Thread .sleep(1000), which pauses the current thread for one second, The constructor of the next class, Caller, takes a reference to an instance of the Callme class and a String, which are stored in target and msg, respectively. The constructor also creates a new thread that will call this object's Department of Computer Science and Engineering 162 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. run() method. The thread is started i ‘mediately. The run( ) method of Caller calls the eall( ) method on the target instance of Callime, passing in the msg string. Finally, the Syneh class starts by creating a single instance of Calle, and three instances of Caller, each with a unique message string. The same instance of Callme is passed to each Caller. Example // This program is not synchronized. class Callme { void call(Sstring msg) { system try { -out-print("(" + msg); Thread.sleep (1000); } catch(Interruptedzxception e) { System. } out.printin ("Interrupted") ; System.out.printin("]"); } } class Caller implements Runnable { String calime ‘Thread public msg; target; e Caller(Callme targ,\String s) { target = targ: msg = 08; t 4 } public = new Thread (this); start (); void run() { target seal (msg) ; z } class Synch { public static void main(String args(]) { Callme target = new Callme(); Caller obl = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronizea"); Caller ob3 = new Caller(target, "Worla"); / wait for threads to end try { ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch nterruptedException e) { Department of Computer Science and Engineering 163 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. System.out.println ("Interrupted") ; . } Output Hello [Synchronized [World] 1 1 As we can see, by calling sleep( ), the eall( ) method allows execution to switch to another thread. To fix the preceding program, we must serialize access to eall(). That is, we must restrict its access to only one thread at a time. To do this, we simply need to precede call( )’s definition with the keyword synchronized, as shown here: class Callme { synchronized void call(Sstring msg) { This prevents other threads from entering call(.) while another thread is using it. After synchronized has been added to call( ), the output of the program is as follows: [Hello] [synchronized] [World] Any time that we havea method, or group of methods, that manipulates the internal state of an object ina multithreaded situation, we should use the synchronized keyword to guard the state from race conditions. 4.8.2 The synchronized Statement While creating synchronized methods within classes that we create an easy and effective means of achieving synchronization, it will not work in all cases. Imagine that we want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by us, but by a third party, and we do not have access to the source code. Thus, we can’t add synchronized to the appropriate methods within the class. Fortunately, the solution to this problem is, simply put calls to the methods defined by this class inside a synchronized block. ‘This is the general form of the synchronized statement: synchronized(object) { // statements to be synchronized Department of Computer Science and Engineering 164 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. ) Here is an alternative version of the preceding example, using a synchronized block within the run() method: // This program uses a synchronized block. class Callme { void call (string msg) { System.out.print("[" + msg); try { Thread.sleep(1000) ; } catch (InterruptedException e) { System.out.printin ("Interrupted") ; } System.out.print1n("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = 5; t = new Thread (this); testaxe(); } // synchronize cal18 to call() publie void run() synchronized(target) { // synchronized block target veal (msg) ; , } class Synch { public static void main(String args[]) { Callme target = new Callme(); Caller obl = new Caller(target, "Hello"); Caller ob2 = new Caller(target, “Synchronized") ; Caller ob3 = new Caller(target, "Worla"); // wait for threads to end try { obl.t.join(); ob2.t.join() + ob3.t.join(); Department of Computer Science and Engineering 165 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. } catch(InterruptedException e) { System.out.printin ("Interrupted") ; a Here, the eall( ) method is not modified by synchronized. Instead, the synchronized statement is used inside Caller’s run() method. This causes the same correct output as the preceding example, because each thread waits for the prior one to finish before proceeding. 466 Inter-thread Communication The preceding examples unconditionally blocked other threads from asynchronous access to certain methods. This use of the implicit monitors in Java objects is powerful, but wwe can achieve a more subtle level of control through interprocess communication. Java includes an elegant interprocess communication mechanism. via the wait( ), notify( ), and notifyAl( ) methods. These methods are implemented as final methods in Object, so all classes have them, All three methods can be called only from within a synchronized context. © wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ) © notify() wakes up a thread that called wait( ) on the same object. ‘© notifyAlI() wakes up all the threads that called wait( ) on the same object. One of the threads will be granted access. ‘These methods are declared within Object, as shown here: final void wait( ) throws InterruptedException final void notify( ) final void notifyAN() Difference between wait() and sleep() wait() sleep( called from synchronised block no such requirement monitor is released monitor is not released gets awake when notify() or notifyAll | does not get awake when notify() or method is called. notifyAIIQ) method is called not a static method static method Department of Computer Science and Engineering 166 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. is generaly used on condition sleep() method is simply used to put your thread on sleep Example // An implementation of a producer and consumer. class Q { int ny boolean valueSet = false; synchronized int get() { while (!valueset) try { wait; } catch (InterruptedException e) { System. out .print1n ("InterruptedException caught") ; } system. out.printin ("Got valueSet false; notify (); return nj +n)y ) synchronized void put (int n) ( while (valueSet) try { wait; } catch(InterruptedException e) { system. out.printin("InterruptedException caught") ; this.n =n; valueSet \= true} System.outprintin("Put: " +n); notity (7 } ‘ class Producer implements Runnable { Q Producer (Q q) { this.q = q? new Thread(this, "Producer").start(); public void run() { int i = 0; while (true) { q.put (i++) 7 } Department of Computer Science and Engineering 167 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 1 class Consumer implements Runnable { og onsumer (Q q) { this.q = ai new Thread(this, "Consumer").start (); } public void run() { while(true) { g.get 0; } ) class PCFixed { public static void main(String args{]) { Qq = new Q0); new Producer (q); new Consumer (q) 7 em.out.println ("Press ‘Contro Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies you that some data is ready. When this happens, execution inside get( ) resumes. After the data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more data in the queue. Inside put( ), wait() suspends execution until the Consumer has. removed the item from the queue. When execution resumes, the next item of data is put in the queue, and notify() is called. This tells the Consumer that it should now remove it Output vue Pew EE 4.7 Daemon Thread in Java Daemon thread in java is a service provider thread that provides services to the user xy of user threads ic. when all the user threads dies, JVM thread. Its life depend on the met terminates this thread automatically. Department of Computer Science and Engineering 168 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. © It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads. * Its life depends on user threads, © Itis.a low priority thread. 4.7.1 Methods for Java Daemon thread by Thread class Method Description public void setDaemon(boolean status) jis used to mark the current thread as daemon thread or user thread. public boolean isDaemon() is used to check that current is daemon, Example public class TestDaemonThread1 extends Thread} public void run(){ if (Thread. current Thread () .isDaéton()) (//checking for //daemon thread System.out.print1n("daemom.thread work") ; b else( System.out.println("usef thread work"); public static void main(String[] args) { ‘TestDaemonThréadl ti=new ‘TestDaemonthread! ();//creating //thread TestDaemonThread1 t2-new TestDaemonThread] (); TestbaémonThread1 t3-new TestDaemonThreadl (); tlsetDaemon(true);//now tl is daemon thread ti.start();//starting threads t2.start()7 t3.start()7 » Output daemon thread work user thread work user thread work Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw MegalThreadStateException. \69 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. 4.7.2 ThreadGroup in Java Java provides a convenient way to group multiple threads in a single object. In such way, we can suspend, resume or interrupt group of threads by a single method call. There are only two constructors of ThreadGroup class. No. | Constructor Description 1 | ThreadGroup(String name) creates a thread group with given ) name. 2] ThreadGroup(ThreadGroup parent, |_ creates a thread group with given ) | String name) parent group and name. A list of important methods are given below. No. | Method Description 1 | intactiveCount() returns no, of threads running in current group. ) 2 | intactiveGroupCount() | returns ano. of active group in this thread group. ) 3| void destroy() destroys this thread group and all its sub groups. ) 4 | String getName() retums the name of this group. ) 5 | ThreadGroup returns the parent of this group. ) | getParent() 6 | void interrupt() interrupts all threads of this group. ) 7 | void list prints information of this group to standard ) console Department of Computer Science and Engineering 170 RMK College of Engineering and Technology RSM Nagar, Puduvoyal-601 206. Example public class ThreadGroupDemo implements Runnable{ public void run() { System. out.print1n (Thread.currentThread() .getName()); , public static void main(String[] args) { Thread Th: roupDemo runnable = new ThreadGroupDemo (); adGroup tgl = new ThreadGroup ("Parent ThreadGroup' Thread tl = new Thread(tgl, runnable,"one"); tlestart (0; Thread t2 = new Thread(tgl, runnable,"two"); t2.start(); Thread t3 new Thread(tgl, runnable,"three"); +3.start() System.out.println("Thread Group Name: "“+tgl.getName()); tgl.list(); } b Output two three Thread 6 pup Name: Parent ThreadGroup Java. lang. ThreadGroup[name=Parent ThreadGroup, maxpri=10] Thread[one, 5, Parent ThreadGroup] Thread|[two, 5, Parent ThreadGroup] Thread|three, 5, Parent ThreadGroup] 4.8 Generies Generics means parameterized types. Using generics, it is possible to create a single class, that works with different types of data. A class, interface, or method that operates on a parameterized type is called generic, as in generic class or generic method. Generic Programming refers to writing code that will work for many types of data. Syntax for creating an object of a generic type Class_nane reference name = new Class_name (); oR Department of Computer Science and Engineering 171 RMK 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 172 RMK 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 (< and >) that precedes the method's return type (< E > 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 173 RMK 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 < E > 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 174 RMK 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 175 RMK 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