Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified...

87
Prof. R.B.Diwate Assistant Professor, Deptt. Of IT & MCA www.rahuldiwate.com

Transcript of Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified...

Page 1: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Prof. R.B.DiwateAssistant Professor, Deptt. Of IT & MCA

www.rahuldiwate.com

Page 2: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Java Characteristic Simple. ... Secure. ... Architecture-neutral. ... Portable. ... Robust. ... Multithreaded.

Page 3: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Cpp vs Java

Page 4: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 5: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 6: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 7: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Java Methods, Constructors Following are the difference between constructor and method. Constructor is used to initialize an object whereas method is

used to exhibits functionality of an object. Constructors are invoked implicitly whereas methods are

invoked explicitly. Constructor does not return any value where the method

may/may not return a value. In case constructor is not present, a default constructor is

provided by java compiler. In the case of a method, nodefault method is provided.

Constructor should be of the same name as that of class.Method name should not be of the same name as that of class.

Page 8: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Static variable Syntax static keyword followed by data type, followed by variable

name. static data_type variable_name;

static variables are shared among all the instances of the class,they are useful when we need to do memory management. Insome cases we want to have a common value for all theinstances like global variable then it is much better to declarethem static as this can save memory (because only single copyis created for static variables).

Page 9: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 10: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Static Method vs Instance Method Static Method Static methods are the methods in Java that can be called without creating an object

of class. They are referenced by the class name itself or reference to the Object ofthat class.

public static void Demo(String name){// code to be executed....} // Must have static modifier in their declaration.// Return type can be int, float, String or user defined data type. Instance Method Instance method are methods which require an object of its class to be created before

it can be called. To invoke a instance method, we have to create an Object of theclass in within which it defined.

public void Demo(String name){// code to be executed....} // Return type can be int, float String or user defined data type.

Page 11: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Static Variable can be accessed directly in a static method

Page 12: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Java Methodspublic class MyClass

{

static void myMethod()

{

// code to be executed

}

}

myMethod() is the name of the method

static means that the method belongs to the MyClass class and not an object ofthe MyClass class.

void means that this method does not have a return value.

Page 13: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Information hiding: access modifiers, A Java access modifier specifies which classes can access

a given class and its fields, constructors and methods.Access modifiers can be specified separately for a class,its constructors, fields and methods. Java access modifiersare also sometimes referred to in daily speech as Javaaccess specifiers, but the correct name is Java accessmodifiers. Classes, fields, constructors and methods canhave one of four different Java access modifiers:

private default (package) protected public

Page 14: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 15: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

private Access Modifier If a method or variable is marked as private (has the private access

modifier assigned to it), then only code inside the same class can accessthe variable, or call the method.

Code inside subclasses cannot access the variable or method, nor cancode from any external class.

Classes cannot be marked with the private access modifier. Marking aclass with the private access modifier would mean that no other classcould access it, which means that you could not really use the class atall. Therefore the private access modifier is not allowed for classes.

public class Clock { private long time = 0; } The member variable time has been marked as private. That means, that

the member variable time inside the Clock class cannot be accessed fromcode outside the Clock class.

Page 16: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Accessing private Fields via Accessor Methods Fields are often declared private to control the access to them from the outside

world. In some cases the fields are truly private, meaning they are only usedinternally in the class. In other cases the fields can be accessed via accessormethods (e.g. getters and setters).

In the above example the two methods getTime() and setTime() can access the timemember variable. The two methods are declared public, meaning they can becalled from code anywhere in your application.

Page 17: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

private Constructors If a constructor in a class is assigned the private Java access modifier, that means that

the constructor cannot be called from anywhere outside the class. A privateconstructor can still get called from other constructors, or from static methods in thesame class.

This version of the Clock class contains a private constructor and a publicconstructor. The private constructor is called from the public constructor (thestatement this();). The private constructor is also called from the static methodnewClock().

Page 18: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

default (package) Access Modifier The default Java access modifier is declared by not writing any access modifier at

all. The default access modifier means that code inside the class itself as well ascode inside classes in the same package as this class, can access the class, field,constructor or method which the default access modifier is assigned to.

Therefore, the default access modifier is also sometimes referred to as the packageaccess modifier. Subclasses cannot access methods and member variables (fields) inthe superclass, if they these methods and fields are marked with the default accessmodifier, unless the subclass is located in the same package as the superclass.

The time field in the Clock class has no access modifier, which means that it isimplicitly assigned the default / package access modifier. Therefore, theClockReader class can read the time member variable of the Clock object, providedthat ClockReader and Clock are located in the same Java package.

Page 19: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

protected Access Modifier The protected access modifier provides the same access as the default access

modifier, with the addition that subclasses can access protected methods andmember variables (fields) of the superclass. This is true even if the subclassis not located in the same package as the superclass.

In the above example the subclass SmartClock has a method calledgetTimeInSeconds() which accesses the time variable of the superclassClock. This is possible even if Clock and SmartClock are not located in thesame package, because the time field is marked with the protected Javaaccess modifier.

Page 20: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

public Access Modifier The Java access modifier public means that all code can access the class, field,

constructor or method, regardless of where the accessing code is located. Theaccessing code can be in a different class and different package.

The time field in the Clock class is marked with the public Java access modifier.Therefore, the ClockReader class can access the time field in the Clock nomatter what package the ClockReader is located in.

Page 21: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Static keyword: class variables and instance variables, Class variables − Class variables also known as static variables are

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

Instance variables − Instance variables are declared in a class, but outside amethod. When space is allocated for an object in the heap, a slot for eachinstance variable value is created. Instance variables hold values that mustbe referenced by more than one method, constructor or block, or essentialparts of an object's state that must be present throughout the class.

Local variables − Local variables are declared in methods, constructors, orblocks. Local variables are created when the method, constructor or block isentered and the variable will be destroyed once it exits the method,constructor, or block.

Page 22: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example

Page 23: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Arrays An array is a group of like-typed variables that are referred to by a common name. Arrays

in Java work differently than they do in C/C++. Following are some important pointabout Java arrays.

In Java all arrays are dynamically allocated. Since arrays are objects in Java, we can find their length using member length. This is

different from C/C++ where we find length using sizeof. A Java array variable can also be declared like other variables with [] after the data type. The variables in the array are ordered and each have an index beginning from 0. Java array can be also be used as a static field, a local variable or a method parameter. The size of an array must be specified by an int value and not long or short. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable.

Page 24: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Array Example public class MyClass { public static void main(String[] args) { String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]); } }

Page 25: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Strings String is basically an object that represents sequence of char values. An

array of characters works same as Java string. For example:

Java String class provides a lot of methods to perform operations on stringsuch as compare(), concat(), equals(), split(), length(), replace(),compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable andCharSequence interfaces.

Page 26: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Inheritance: Types of inheritance, Constructors in Derived Classes Inheritance in Java is a mechanism in which one object acquires all the

properties and behaviors of a parent object. It is an important part of OOPs(Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that arebuilt upon existing classes. When you inherit from an existing class, you canreuse methods and fields of the parent class. Moreover, you can add newmethods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

Page 27: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Terms used in Inheritance Class: A class is a group of objects which have common properties. It is a

template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It

is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass

inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which

facilitates you to reuse the fields and methods of the existing class when youcreate a new class. You can use the same fields and methods already definedin the previous class.

Page 28: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

The syntax of Java Inheritance The extends keyword indicates that you are making a new class that

derives from an existing class. The meaning of "extends" is to increase thefunctionality.

In the terminology of Java, a class which is inherited is called a parent orsuperclass, and the new class is called child or subclass.

Page 29: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example

Page 30: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

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 the same method and youcall it from child class object, there will be ambiguity to call the method ofA or B class.

Since compile-time errors are better than runtime errors, Java renderscompile-time error if you inherit 2 classes. So whether you have samemethod or different, there will be compile time error.

Page 31: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example

Page 32: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 33: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 34: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 35: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Constructors in Derived Classes, In Java, constructor of base class with no argument gets

automatically called in derived class constructor. For example,output of following program is:

Base Class Constructor Called Derived Class Constructor Called

Page 36: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

But, if we want to call parameterized constructor of base class, then we can call itusing super(). The point to note is base class constructor call must be the firstline in derived class constructor.

Keyword extern is used to declaring a global variable or function in another file to provide the reference of variable or function

Page 37: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 38: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Overriding & Hiding Fields & Methods We have two classes: A child class Boy and a parent class

Human. The Boy class extends Human class. Both the classeshave a common method void eat(). Boy class is giving its ownimplementation to the eat() method or in other words it isoverriding the eat() method.

The purpose of Method Overriding is clear here. Child classwants to give its own implementation so that when it calls thismethod, it prints Boy is eating instead of Human is eating.

Page 39: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example

Page 40: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Hiding Fields & Methods Java, if you are not careful you can possibly hide both methods

and variables of the superclass. A field or variable is said to hide all fields with the same name

in superclasses. Similarly, a static method with the same namein a superclass can hide the method of the subclass.

Page 41: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Method Hiding Method hiding is closely related to method overriding and

sometimes programmer hides the method trying to override it.The concept of overriding allows you to write code whichbehaves differently depending upon an object at runtime.

Static method with the same name in a superclass can hide themethod from subrclass because a static method cannot beoverridden in Java.

Page 42: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 43: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

This example, we assume that p.sleep() will callthe sleep() method from Parent class and c.sleep() will call thesleep() method from child class, just like it happens inoverriding but because sleep() is a static method, instead ofoverriding we have hidden the sleep() method.

Since static method are resolved at compile-time, bothare p.sleep() and c.sleep() are resolved to sleep() method ofParent class because the type of p and c variable is Parent. Ifyou remove the static keyword from both methods then it willbehave as expected.

Page 44: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Variable Hiding A field or variable with the same name in subclass and superclass

is known as variable hiding or field hiding in Java. When avariable is hidden, you can use super.variableName to access thevalue from a superclass.

you can access the superclass value using super.age.

Page 45: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Polymorphism: Static and Dynamic. Compile time Polymorphism (or Static polymorphism) Polymorphism that is resolved during compiler time is known as static

polymorphism. Method overloading is an example of compile timepolymorphism.

Method Overloading: This allows us to have more than one methodhaving the same name, if the parameters of methods are different innumber, sequence and data types of parameters.

Page 46: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Two definitions of the same method add() which add method would be called isdetermined by the parameter list at the compile time. That is the reason this is also knownas compile time polymorphism.

Page 47: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Runtime Polymorphism (or Dynamic polymorphism) It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a

process in which a call to an overridden method is resolved at runtime,thats why it is called runtime polymorphism.

Page 48: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Abstract A class that is declared using “abstract” keyword is known as abstract

class. It can have abstract methods(methods without body) as well asconcrete methods (regular methods with body).

A normal class(non-abstract class) cannot have abstract methods. Why we need an abstract class? Lets say we have a class Animal that has a method sound() and the

subclasses of it like Dog, Lion, Horse, Cat etc. Since the animal sounddiffers from one animal to another, there is no point toimplement this method in parent class. This is because every childclass must override this method to give its own implementation details, likeLion class will say “Roar” in this method and Dog class will say “Woof”.

Page 49: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example of Abstract class

Page 50: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Abstract method 1)Abstract method has no body.

2)Always end the declaration with a semicolon(;).3)It must be overridden. An abstract class must beextended and in a same way abstract method must beoverridden.

4) A class has to be declared abstract to have abstractmethods.

Page 51: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example of Abstract class and method

Page 52: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Exceptions in java In Java, an exception is an event that disrupts the normal flow of the

program. It is an object which is thrown at runtime.

Exception Handling is a mechanism to handle runtime errors suchas

ClassNotFoundException, IOException, SQLException, RemoteException, etc.

The core advantage of exception handling is to maintain thenormal flow of the application. An exception normally disruptsthe normal flow of the application that is why we use exceptionhandling.

Page 53: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Blocks & Keywords used for exception handling try: The try block contains set of statements where an exception

can occur. catch : Catch block is used to handle the uncertain condition of

try block. A try block is always followed by a catch block, whichhandles the exception that occurs in associated try block.

throw: Throw keyword is used to transfer control from try blockto catch block.

throws: Throws keyword is used for exception handling withouttry & catch block. It specifies the exceptions that a method canthrow to the caller and does not handle itself.

finally: It is executed after catch block. We basically use it to putsome common code when there are multiple catch blocks

Page 54: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

try The "try" keyword is used to specify a block where we shouldplace exception code. The try block must be followed by eithercatch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must bepreceded by try block which means we can't use catch blockalone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of theprogram. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.throws The "throws" keyword is used to declare exceptions. It doesn't

throw an exception. It specifies that there may occur anexception in the method. It is always used with methodsignature.

Java Exception Keyword

Page 55: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Difference between Checked and Unchecked Exceptions 1) Checked Exception The classes which directly inherit Throwable class except

RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked atcompile-time.

2) Unchecked Exception The classes which inherit RuntimeException are known as unchecked

exceptions e.g. ArithmeticException, NullPointerException,ArrayIndexOutOfBoundsException etc. Unchecked exceptions are notchecked at compile-time, but they are checked at runtime.

3) Error Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,

AssertionError etc.

Page 56: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Java try and catch The try statement allows you to define a block of code to

be tested for errors while it is being executed. The catch statement allows you to define a block of code

to be executed, if an error occurs in the try block. The try and catch keywords come in pairs:

Page 57: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Try catch example

Page 58: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Catch and finally

Page 59: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

throws

Page 60: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

1) A scenario where ArithmeticException occursIf we divide any number by zero, there occurs an ArithmeticException.

2) A scenario where NullPointerException occursIf we have a null value in any variable, performing any operation on the variable throws

a NullPointerException.

3) A scenario where NumberFormatException occursThe wrong formatting of any value may occur NumberFormatException. Suppose I

have a string variable that has characters, converting this variable into digit willoccur NumberFormatException.

4) A scenario where ArrayIndexOutOfBoundsException occursIf you are inserting any value in the wrong index, it would result in

ArrayIndexOutOfBoundsException as shown below:

Page 61: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

User define exception

Page 62: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Packages:API packages A java package is a group of similar types of classes, interfaces and sub-

packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io,util, sql etc.

Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they

can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Page 63: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

How to compile java packageIf you are not using any IDE, you need to follow the syntax given below:1.javac -d directory javafilenameFor example1.javac -d . Simple.javaThe -d switch specifies the destination where to put the generated class file.You can use any directory name like /home (in case of Linux), d:/abc (in case ofwindows) etc.If you want to keep the package within the same directory, you can use . (dot).

Example of packages

Page 64: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

How to access package from another package?There are three ways to access the package from outside the package.

import package.*;

import package.classname;

fully qualified name.

Sequence of the program must be package then import thenclass.

Page 65: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Using packagename.* If you use package.* then all the classes

and interfaces of this package will beaccessible but not subpackages.

The import keyword is used to makethe classes and interface of anotherpackage accessible to the currentpackage.

Page 66: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Using packagename.classname If you import package.classname

then only declared class of thispackage will be accessible.

Page 67: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Using fully qualified name If you use fully qualified name then

only declared class of this packagewill be accessible. Now there isno need to import. But you needto use fully qualified name everytime when you are accessing theclass or interface.

It is generally used when twopackages have same class namee.g. java.util and java.sql packagescontain Date class.

Page 68: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Subpackage in java Package inside the package is called the subpackage. It

should be created to categorize the package further.

Page 69: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

How to send the class file to another directory or drive? There is a scenario, I want to put the class file of A.java source file in classes

folder of c: drive. For example:

Page 70: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 71: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Threads

A thread is a basic unit of CPU utilization, consisting of aprogram counter, a stack, and a set of registers, ( and athread ID. )

Traditional processes have a single thread of control -There is one program counter, and one sequence ofinstructions that can be carried out at any given time.

Multi-threaded applications have multiple threadswithin a single process, each having their own programcounter, stack and set of registers, but sharing commoncode, data, and certain structures such as opened files

Page 72: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers
Page 73: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Threads are very useful in modern programming whenever a process has multiple tasks to be performed independently of the others

For example in a word processor, a background threadmay check spelling and grammar while a foreground threadprocesses user input ( keystrokes ), while yet a third threaddoes periodic automatic backups of the file being edited.

Thread Example

Page 74: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Single thread Example

Page 75: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Multitheding

Page 76: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Thread LifeCycle

Page 77: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

1. New: The thread is in new state if you create an instance of Thread class butbefore the invocation of start() method.

2. Runnable: The thread is in runnable state after invocation of start()method, but the thread scheduler has not selected it to be the running thread

3. Running: The thread is in running state if the thread scheduler has selectedit

4. Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently not eligible to run

5. Terminated (Dead): A thread is in terminated or dead state when its run() method exits.

In Java, Threads can be created by using two ways:1. Extending the Thread class2. Implementing the Runnable Interface:

We create a new class which implements java.lang.Runnable interface and then override run() method.

We create an object of our new class and call start() method to start the execution of a thread.

start() invokes the run() method on the thread object.

Page 78: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Thread Priority in Multithreading In a Multi threading environment, thread scheduler

assigns the processor to a thread based on priority ofthread.

Whenever we create a thread in Java, it always has somepriority assigned to it.

Priority can either be given by JVM while creating thethread or it can be given by programmer explicitly.

Priority for a thread is in range of 1 to 10, 1 having leastpriority.

Whenever a new Java thread is created it has the samepriority as the thread which created it.

Page 79: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

There are 3 static variables defined in Thread class forpriority.

1. public static int MIN_PRIORITY: This is minimumpriority that a thread can have. Value for this is 1.

2. public static int NORM_PRIORITY: This is defaultpriority of a thread if we do not explicitly define it.Value for this is 5.

3. public static int MAX_PRIORITY: This is maximumpriority of a thread can have. Value for this is 10.

Page 80: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example of priority thread

Page 81: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

I/O Streams

I/O Streams There are two types of Streams you can use to interact

with files: Character Streams Byte Streams

Page 82: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Character Streams Character Streams are used to read or write the characters data type. Let's look at the

most commonly used classes.All of these classes are defined under java.io package.

Here are some classes you should know that can be used to read character data:

Reader:An abstract class to read a character stream.

InputStreamReader: Class used to read the byte stream and converts to character stream.

FileReader:A class to read the characters from a file.

BufferedReader: This is a wrapper over the Reader class that supports buffering capabilities.In many cases this is most preferable class to read data because more data can been readfrom the file in one read() call, reducing the number of actual I/O operations with filesystem.

And here are some classes you can use to write character data to a file:

Writer:This is an abstract class to write the character streams.

OutputStreamWriter: This class is used to write character streams and also convert themto byte streams.

FileWriter:A class to actually write characters to the file.

BufferedWriter: This is a wrapper over the Writer class, which also supports bufferingcapabilities. This is most preferable class to write data to a file since more data can bewritten to the file in one write() call. And like the BufferedReader, this reduces the numberof total I/O operations with file system.

Page 83: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Byte Streams Byte Streams are used to read or write byte data with files. This is different from

before in the way they treat the data. Here you work with raw bytes, which couldbe characters, image data, unicode data (which takes 2 bytes to represent acharacter), etc.

All of these classes are defined under java.io package.

Here are the classes used to read the byte data:

InputStream:An abstract class to read the byte streams.

FileInputStream:A class to simply read bytes from a file.

BufferedInputStream: This is a wrapper over InputStream that supports bufferingcapabilities. As we saw in the character streams, this is a more efficient methodthan FileInputStream.

And here are the classes used to write the byte data:

OutputStream:An abstract class to write byte streams.

FileOutputStream:A class to write raw bytes to the file.

ByteOutputStream: This class is a wrapper over OutputStream to supportbuffering capabilities. And again, as we saw in the character streams, this is a moreefficient method than FileOutputStream thanks to the buffering.

Page 84: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Using FileReader and FileWriterclasses:

Page 85: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example 2Using BufferedReader and BufferedWriterclasses:

Page 86: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Console class, Print writer, Stream Benefits

PrintWriter supports the print( ) and println( ) methods for all typesincluding Object. Thus, you can use these methods in the same way as theyhave been used with System.out. If an argument is not a simple type, thePrintWriter methods call the object's toString( ) method and thenprint the result.

To write to the console by using a PrintWriter, specify System.out forthe output stream and flush the stream after each newline. For example,this line of code creates a PrintWriter that is connected to consoleoutput:

PrintWriter pw = new PrintWriter(System.out, true);

Page 87: Prof. R.B.Diwaterahuldiwate.com/Download/OOP-Complete -Section2.pdfAccess modifiers can be specified separately for a class, its constructors, fields and methods. Java access modifiers

Example