0% found this document useful (0 votes)
2 views

java_unit_3

The document outlines the Java Programming course objectives and learning outcomes, focusing on fundamental concepts, object-oriented principles, exception handling, multithreading, and GUI design. It includes detailed explanations of interfaces, packages, exception handling, and inner classes in Java, along with examples and comparisons between interfaces and abstract classes. Additionally, it covers the importance of packages in organizing code and maintaining code modularity.

Uploaded by

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

java_unit_3

The document outlines the Java Programming course objectives and learning outcomes, focusing on fundamental concepts, object-oriented principles, exception handling, multithreading, and GUI design. It includes detailed explanations of interfaces, packages, exception handling, and inner classes in Java, along with examples and comparisons between interfaces and abstract classes. Additionally, it covers the importance of packages in organizing code and maintaining code modularity.

Uploaded by

rishiadik55
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

1

PCET’S Pimpri Chinchwad University

Department of Computer Science and Engineering


Course Name : Java Programming
Course Code/Course Type : UBTCE212/PCC
SY. B.Tech

Prepared By: Mr. Rahul Sonkamble

PIMPRI CHINCHWAD UNIVERSITY


2

Course Objectives (CO):


• The objectives of Java Programming are:
To learn the fundamentals of the Java programming language.
To learn object-oriented principles like abstraction, encapsulation,
inheritance, and polymorphism and apply them in solving problems using
java.
To apply the concepts of exception handling, multithreading and collection
classes using java.

To develop software applications using JDBC connectivity.


To design the Graphical User Interface using applets and swing controls.
PIMPRI CHINCHWAD UNIVERSITY
3

Course Learning Outcomes (CLO):


• Students would be able to:
To grasp the fundamentals programming concepts of Java programming
language.

To apply object-oriented principles like abstraction, encapsulation,


inheritance, polymorphism in solving problems using java.
To perform exception handling, multithreading code using java.
To develop software applications using JDBC connectivity.
To design the Graphical User Interface using event handling.

PIMPRI CHINCHWAD UNIVERSITY


UNIT- III
Interfaces, Packages,
Exception Handling in Java
Interface
• It has static constants and abstract methods.

• There can be only abstract methods in the Java interface, not method body.

• It is used to achieve abstraction and multiple inheritance in Java

• Since Java 8, we can have default and static methods in an interface.

• Since Java 9, we can have private methods in an interface.


Syntax
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
interface printable{
void print();
}
class A6 implements printable{
public void print()
{
System.out.println("Hello");
}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable{
public void draw()
{System.out.println("drawing circle");}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}}
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest() {return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest() {return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Multiple Inheritance

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Default Method in Interface

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Static Method in Interface

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Difference Between Interface and Abstract Class in Java

Feature Interface Abstract Class


An interface is a blueprint of a class that contains An abstract class is a class that cannot be
Definition only abstract methods (until Java 8, later instantiated and may contain both abstract and
default/static methods were introduced). non-abstract methods.
Only abstract methods (before Java 8). Java 8+ Can have both abstract and concrete (non-
Methods
allows `default` and `static` methods. abstract) methods.
Variables are `public`, `static`, and `final` by Can have instance variables, with any access
Variables
default. modifier (private, protected, public).
Constructors Cannot have constructors. Can have constructors.
A class implements an interface using the A class extends an abstract class using the
Implementation
`implements` keyword. `extends` keyword.
Supports multiple inheritance (a class can Does not support multiple inheritance (a class
Multiple Inheritance
implement multiple interfaces). can extend only one abstract class).
Methods can have any access modifier
Access Modifiers Methods are `public` by default.
(`private`, `protected`, `public`).
Difference Between Interface and Abstract Class in Java

Feature Interface Abstract Class


Used when multiple classes should follow a
Used when classes share common behavior but
Usage common contract but with different
require method overriding.
implementations.
Slower as it requires extra lookups for method
Performance Faster compared to interfaces.
calls.
Default Methods
Allows default methods with implementation. Already supports concrete methods.
(Java 8+)
Static Methods (Java
Can have static methods. Can have static methods.
8+)
When different classes need to follow the same When classes share some functionality and need
Best Use Case
behavior but are unrelated. to extend common logic.
Inner classes
• An inner class is a class defined inside another class.
• It helps to logically group classes that are only used within a specific outer class.
• Inner classes have access to the outer class's private members, which makes them
useful for encapsulation.

Types of Inner Classes in Java


Java provides four types of inner classes:
• Member Inner Class
• Static Nested Class
• Local Inner Class
• Anonymous Inner Class
Member Inner Class
//A member inner class is a non-static class declared inside another class.
class Outer {
private String message = "Hello from Outer class";

class Inner { public class Main {


void display() { public static void main(String[] args) {
System.out.println(message); Outer outer = new Outer();
Outer.Inner inner = outer.new Inner(); // Creating an
// Inner class can access outer class’s object of Inner class
private members inner.display();
} }
}
}
}
Static Nested Class
A static nested class is a static class inside another class. Unlike member inner
classes, it cannot access non-static members of the outer class.
class Outer {
static String message = "Hello from Static Nested Class";
static class Nested {
void display() {
System.out.println(message); public class Main
// Can access static members only {
public static void main(String[] args)
} { Outer.Nested nested = new Outer.Nested();
} // No need to create Outer class object
} nested.display();
}
}
Static Nested Class
A local inner class is a class declared inside a method. It can only be used within
that method.
class Outer {
void outerMethod() {
class LocalInner {
void display() {
System.out.println("Inside Local Inner Class");
}
}
LocalInner local = new LocalInner(); public class Main {
public static void main(String[] args) {
local.display(); Outer outer = new Outer();
} outer.outerMethod();
} }
}
Anonymous Inner Class
An anonymous inner class is a class without a name. It is used when a class is
needed only once.
abstract class Greeting {
abstract void sayHello();
}

public class Main {


public static void main(String[] args) {
Greeting greet = new Greeting() { // Anonymous Inner Class
void sayHello() {
System.out.println("Hello from Anonymous Inner Class");
}
};
greet.sayHello();
}
}
Anonymous Inner Class
An anonymous inner class is a class without a name. It is used when a class is
needed only once.
abstract class Greeting {
abstract void sayHello();
}

public class Main {


public static void main(String[] args) {
Greeting greet = new Greeting() { // Anonymous Inner Class
void sayHello() {
System.out.println("Hello from Anonymous Inner Class");
}
};
greet.sayHello();
}
}
An inner class can implement an interface

interface Message { public class Main {


void display(); public static void main(String[] args) {
} Outer.Inner inner = new Outer().new Inner();
inner.display();
class Outer { }
class Inner implements Message { }
public void display() {
System.out.println("Inner class implementing interface");
}
}
}
java

An interface can have a nested class inside it

interface Vehicle {
class Engine {
void start() {
System.out.println("Engine started");
}
}
}

public class Main {


public static void main(String[] args) {
Vehicle.Engine engine = new Vehicle.Engine();
engine.start();
}
}
java

Anonymous inner classes are often used to


implement interfaces
interface Greeting {
void sayHello();
}

public class Main {


public static void main(String[] args) {
Greeting greet = new Greeting() {
public void sayHello() {
System.out.println("Hello from Anonymous Inner Class
implementing an Interface");
}
};
greet.sayHello();
}
}
java

What is a Package in Java?


A package in Java is a namespace that organizes classes and interfaces into logical groups. It
helps avoid name conflicts, makes code modular, and improves maintainability.

Why Use Packages?


Avoids class name conflicts
Organizes code logically
Provides access protection (public, private, protected)
Helps in reusability of code
java

Types of Packages in Java


1️⃣ Built-in Packages (Predefined)
Java provides built-in packages like:
•java.lang (Default package, no need to import)
•java.util (Contains ArrayList, HashMap, etc.)
•java.io (For input/output operations)
•java.net (For networking)
•java.sql (For database connectivity)

2️⃣ User-Defined Packages


These are packages created by developers to organize code efficiently.
java

Creating a User-Defined Package

package mypackage; // Define package

public class Hello {


public void sayHello() {
System.out.println("Hello from mypackage!");
}
}

Save the file as Hello.java in a folder named mypackage.


java

Accessing a Package (Using Fully Qualified


Name)
public class Main {
public static void main(String[] args) {
mypackage.Hello obj = new mypackage.Hello(); // Using fully qualified name
obj.sayHello();
}
}

No import required
Uses mypackage.Hello instead of Hello
java

Importing a Package
Instead of using fully qualified names, we can import a package using the import statement.

import mypackage.Hello; // Importing Hello class

public class Main {


public static void main(String[] args) {
Hello obj = new Hello();
obj.sayHello();
}
}

Now we can use Hello directly without prefixing mypackage.


java

Importing All Classes from a Package

import mypackage.*; // Import all classes from the package

public class Main {


public static void main(String[] args) {
Hello obj = new Hello();
obj.sayHello();
}
}

* imports all classes in mypackage.


java

Working with Java API Packages (Built-in


Packages)
import java.util.ArrayList;

public class Example {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list);
}
}

Imports ArrayList from java.util


Uses list.add() to store data
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.

Dictionary Meaning: Exception is an abnormal condition.

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that
is why we need to handle exceptions.
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception
occurs at statement 5; the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is
why we use exception handling in Java.
Types of Java Exceptions
Checked Exception: Checked exceptions are checked at compile-time.

Unchecked Exception: Unchecked exceptions are not checked at compile-time, but


they are checked at runtime.

Error: Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.
Java Exception Keywords
1.public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10.}

11.(Try without try catch as well)


Common Exceptions
int a=50/0;//ArithmeticException
String s=null;
System.out.println(s.length());//NullPointerException
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block must be followed by either catch or finally block.
Syntax of try catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Syntax of try finally


try{
//code that may throw an exception
}finally{}
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not e
xceute
System.out.println("rest of the code"); //This will not get execute
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
Exception parent class

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e); //We can write our statement as well just
remove e and put message
}
System.out.println("rest of the code");
}
resolve the exception in a catch block

public static void main(String[] args) {


int i=50, int j=0, data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
Another code
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e) // Can also write
Exception
{
System.out.println(e);
}
System.out.println("rest of the code");
Java Catch Multiple Exceptions

At a time only one exception occurs and at a time only one catch block is executed.

All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0; }
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception
occurs"); }
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0; //Only one catch will get execute
System.out.println(a[10]) }//
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception
occurs"); }
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
public static void main(String[] args) {
try{
String s=null; //As no exception is written parent class Exception will be called
System.out.println(s.length());
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs"); }
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
Java Nested try Example

public class NestedTryBlock2 {


public static void main(String args[])
{
// outer (main) try block
try {
//inner try block 1
try {
// inner try block 2
try {
int arr[] = { 1, 2, 3, 4 };
//printing the array element out of its bounds
System.out.println(arr[10]);
}
// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
Java Nested try Example

} }
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
finally block

Java finally block is always executed whether an exception is handled or not.

Therefore, it contains all the necessary statements that need to be printed


regardless of the exception occurs or not.
When an exception does not occur

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}
When an exception occurr but not
handled by the catch block
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/0;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}
When an exception occurs and is
handled by the catch block
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/0;
System.out.println(data);
}
//catch won't be executed
catch(ArithmeticException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}
throw Exception
The Java throw keyword is used to throw an exception explicitly.
Throwing Unchecked Exception

public class TestThrow1 {


//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Throwing User-defined Exception

// class represents user-defined exception


class UserDefinedException extends Exception {
public UserDefinedException(String str)
{ // Calling constructor of parent Exception
super(str);
} }
// Class that uses above MyException
public class TestThrow3 {
public static void main(String args[]) {
try {
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude) {
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
} } }
Throws keyword

import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
48

Assignment Questions
1. Explain the differences between interfaces and abstract classes with proper examples in
Java.Write a program that demonstrates both interface and abstract class usage.
2. Define an interface Vehicle with methods startEngine() and stopEngine().
Implement this interface in two classes: Car and Bike.
Write a Main class that demonstrates polymorphism using interface references.
3. Define an interface Bank with a method getInterestRate().
Create two classes, SBI and HDFC, that implement this interface with different interest
rates. In the Main class, create an interface reference to access different
implementations.
PIMPRI CHINCHWAD UNIVERSITY
49

Assignment Questions
4. Define an interface Animal with method makeSound().
Extend this interface in another interface Pet which includes a method play().
Implement Pet in a class Dog and provide implementations for both methods.
5. Write a program where an inner class implements an interface.
Define an interface Greeting with a method sayHello().
Create an outer class Person that has an inner class Friendly which
implements Greeting. Access the inner class method using an instance of
the outer class.

PIMPRI CHINCHWAD UNIVERSITY


50

Assignment Questions
6. Define a package mypackage and create a class Calculator inside it with methods
add(), subtract(), multiply(), and divide(). Write a separate Java program to import
and use this package.
7. Write a Java program that demonstrates the use of the java.util package.
Use ArrayList and HashMap to store and retrieve data.
8. Explain the Exception Hierarchy in Java with a diagram.
Write a Java program that demonstrates handling multiple exceptions using try,
catch, and finally.

PIMPRI CHINCHWAD UNIVERSITY


51

Assignment Questions
9. Write a Java program that demonstrates both Checked and Unchecked Exceptions.
Use FileNotFoundException (Checked Exception)
Use ArithmeticException (Unchecked Exception)
Handle them using try, catch, and finally.

9. Define a custom exception InsufficientFundsException.


Write a BankAccount class with methods deposit() and withdraw().
Throw the custom exception if the withdrawal amount is greater than the balance.

You might also like