0% found this document useful (0 votes)
11 views16 pages

Unit 3-1

The document provides an overview of Java packages, including built-in and user-defined packages, and their usage in organizing classes. It also covers interfaces in Java, explaining their role in achieving abstraction, and details exception handling mechanisms, including try-catch blocks and the use of the throw keyword. Examples are provided to illustrate the concepts of packages, interfaces, and exception handling in Java.

Uploaded by

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

Unit 3-1

The document provides an overview of Java packages, including built-in and user-defined packages, and their usage in organizing classes. It also covers interfaces in Java, explaining their role in achieving abstraction, and details exception handling mechanisms, including try-catch blocks and the use of the throw keyword. Examples are provided to illustrate the concepts of packages, interfaces, and exception handling in Java.

Uploaded by

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

Java Packages

A package in Java is used to group related classes. Think of it as a folder in a file


directory. We use packages to avoid name conflicts, and to write a better
maintainable code.

Packages are divided into two categories:


•Built-in Packages (packages from the Java API)
•User-defined Packages (create your own packages)
Built-in Packages:

The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.

The library is divided into packages and classes.


Meaning you can either import a single class (along with its methods and attributes),
or a whole package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:

Syntax:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Example
import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation
Example,
we will use the nextLine() method, which is used to read a complete line:

Example
Using the Scanner class to get user input:
import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
User-defined Packages:

User-defined packages are those packages that are designed or created by the developer
to categorize classes and packages. They are much similar to the built-in that java offers.
It can be imported into other classes and used the same as we use built-in packages.
But If we omit the package statement, the class names are put into the default package,
which has no name.
To create a package, we’re supposed to use the package keyword.
Syntax:
package package-name;
User-defined Packages (create your own packages)
Step 3: Compile and Run the Program
Step 1: Create the First Package
javac mypackage1/ClassA.java
package mypackage1; javac mypackage2/ClassB.java
public class ClassA
{
public void display()
{ Run the ClassB program:
System.out.println("Hello from ClassA in mypackage1!");
} java mypackage2.ClassB
}

Step 2: Create the Second Package


package mypackage2; Output
import mypackage1.ClassA; Hello from ClassA in mypackage1!
public class ClassB
{
public static void main(String[] args)
{
ClassA obj = new ClassA();
obj.display();
}
}
// File: student/Student.java // Method to display student details
package student; public void displayInfo()
{
public class Student { System.out.println("Student Name: " + name);
private String name; System.out.println("Student Age: " + age);
private int age; }
}
// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}

// Getter methods
public String getName() {
return name;
}

public int getAge() {


return age;
}
package mainapp;
import student.Student;
public class Main
{
public static void main(String[] args)
{
// Creating a Student object
Student student = new Student("Alice", 20); // Displaying student information
student.displayInfo();
}
}

Step 3: Compile and Run the Program Output:


Student Name: Alice
javac student/Student.java Student Age: 20
javac mainapp/Main.java

Run the Main program:

java mainapp.Main
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction.
An interface is a kind of class. The interface contains methods and variables.

Syntax:
Interface interfacename
{
variables declaration;
methods declaration;
}

Example:

interface Animal
{
void sound();
void sleep()
{
System.out.println("The animal is sleeping");
}
}
Extending interface

Like class, interfaces can also extended. An interface can be sub interfaced from other interface.

Syntax:
Interface interfacename2 extends interfacename1
{
………..
……
}

The relationship between classes and interfaces


A class extends another class, an interface extends another interface, but a class implements an interface.
Implementing interface
Interfaces are used as “super classes” whose properties are inherited by classes.

Syntax: Example:
Class classname implements interfacename // Defining an interface
{ interface Animal {
Body of the class // Abstract method (does not have a body)
} void sound();

// Default method
default void sleep() {
System.out.println("The animal is sleeping");
}
}

// Implementing the interface


class Dog implements Animal {
// Providing implementation for the abstract method
public void sound() {
System.out.println("The dog says: bark bark");
}
}
class Cat implements Animal {
// Providing implementation for the abstract method
public void sound() {
System.out.println("The cat says: meow meow");
}
The dog says: bark bark
}
The animal is sleeping
The cat says: meow meow
public class Main {
The animal is sleeping
public static void main(String[] args) {
// Creating objects of Dog and Cat

Animal myDog = new Dog();


Animal myCat = new Cat();

// Calling methods
myDog.sound();
myDog.sleep();

myCat.sound();
myCat.sleep();
}
}
Exception Handling:
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.

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException,
IOException,
SQLException,
RemoteException, etc.

Difference between Error and Exception

•Error: An Error indicates a serious problem that a reasonable application should not try to catch.
•Exception: Exception indicates conditions that a reasonable application might try to catch.
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:

SyntaxGe Example: Output:


Something went wrong
try public class Main
{ {
// Block of code to try public static void main(String[ ] args)
} {
catch(Exception e) try
{ {
// Block of code to handle errors int[] myNumbers = {1, 2, 3};
} System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println("Something went wrong.");
}
}
}
Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

Example:public class Main {


public static void main(String[] args) { Something went wrong
try { The 'try catch' is finished
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
throw
The "throw" keyword is used to throw an exception.
The throw statement is used together with an exception type.
There are many exception types available in Java:
ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:
Example:
public class ExceptionHandlingExample {
public static void main(String[] args) { Output:
try {
// Code that may throw an exception Cannot divide by zero: / by zero
int result = divide(10, 0); Finally block executed
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
// Handle the exception
System.out.println("Cannot divide by zero: " + e.getMessage());
}
finally {
// This block will always execute
System.out.println("Finally block executed");
}
}

public static int divide(int a, int b) {


return a / b; // This may throw an ArithmeticException if b is 0
}
}

You might also like