0% found this document useful (0 votes)
20 views18 pages

UNIT-4 Notes

Unit 4 exam paper social

Uploaded by

kumarshet16
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)
20 views18 pages

UNIT-4 Notes

Unit 4 exam paper social

Uploaded by

kumarshet16
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/ 18

Module-4

Packages:

A package is simply a namespace under which you can categorize classes, analogous to a
"folder" or "path", so you can group classes with related purpose or functionality.
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
● Preventing naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cse.Employee and college.staff.ee.Employee
● Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
● Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
● Packages can be considered as data encapsulation (or data-hiding).
import java.util.*;
util is a subpackage created inside java package.

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
1. java.lang: Contains language support classes(e.g classes which defines primitive data types,
math operations). This package is automatically imported.
2. java.io: Contains classes 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. java.applet: Contains classes for creating Applets.
5. java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc). 6)
6. java.net: Contain classes for supporting networking operations.
User-defined packages: These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}

public class PrintName


{
public static void main(String args[])
{
String name = "VTU";
MyClass obj = new MyClass();

obj.getNames(name);
}
}
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.

Syntax:

package package-name;

Steps to create User-defined Packages

Step 1: Creating a package in java class. The format is very simple and easy. Just write a
package by following its name.
package example1;
Step 2: Include class in java package, But remember that class only has one package
declaration.
package example1;

class gfg {
public static void main(Strings[] args){
-------function--------
}
}
Step 3: Now the user-defined package is successfully created, we can import it into other
packages and use its functions it.

package example;

// Class
public class University {

public void show()


{
System.out.println("Hello VTU");
}

public static void main(String args[])


{
University obj = new University ();
obj.show();
}
}

Packages and Member Access:

Public: Allows any object to access the item.


Private: Only other members within a class can see and modify the item.
Protected: Only descendants of the class can access the item.
Default: The default access modifier, which means that only other classes in the same
package can access the item

Public Access Modifiers:


If a class is declared as public then we can access that class from anywhere.
We will be creating a package pack1 inside that package we declare a class A which is public
and inside that class, we declare a method m1 which is also public. Now we create another
package pack2 and inside that pack2 we import pack1 and declare a class B and in class B’s main
method we create an object of type class A and trying to access the data of method m1.
package pack1;
import java.io.*;
import java.util.*;
public class A {

// declaring method m1
public void m1() { System.out.println("GFG"); }
}
Package (Default) Access Modifier:
A class or method or variable declare without any access modifier then is considered that it has a
package(default)access modifier The default modifier act as public within the same package and
acts as private outside the package. If a class is declared as default then we can access that class
only within the current package i.e from the outside package we can’t access it. Hence, the
default access modifier is also known as the package–level access modifier. A similar rule also
applies for variables and methods in java.
import java.io.*;
import java.util.*;
class Package {
String s = "VTU";
String s1 = "KARNATAKA";

String fullName()
{

return s + s1;
}

public static void main(String[] args)


{
Package g = new Package();
System.out.println(g.fullName());
}
}

Public Access Modifier Package Access Modifier

Public members can be accessed from a This modifier can’t be accessed from a non-child
non-child class of outside package. class of the outside package.

Public members can be accessed from child We cannot access this modifier from the child
class of outside package. class of the outside package.

The public modifier is more accessible than This modifier is more restricted than the public
the package access modifier. access modifier.

Protected Access Modifier:


This modifier can be applied to the data member, method, and constructor, but this modifier can’t
be applied to the top-level classes and interface.
A member is declared as protected as we can access that member within the current package and
only in the child class of the outside package.

import java.io.*;
import java.util.*;

// declaring a parent class A


class A {

// declaring a protected method m1()


protected void m1()
{ System.out.println("VTU"); }
}

// creating a child class by extending the class A


class B extends A {

// main method
public static void main(String[] args)
{
// creating an object of parent class
// using parent reference
A a = new A();

/// calling method m1


a.m1();

// creating an object of child class


// using child reference
B b = new B();

// calling method m1
b.m1();

// creating an object of child class


// using parent reference
A a1 = new B();

// calling m1 method
a1.m1();
}
}

Private Access Modifiers:


This modifier is not applicable for top-level classes or interfaces. It is only applicable to
constructors, methods, and fields inside the classes.
If a variable or methods or constructor is declared as private then we can access them only from
within the class i.e from outside the class we can’t access them.
import java.io.*;
import java.util.*;
// helper class
class A {

// helper method
private void m1() { System.out.println("VTU"); }
}

// driver class
class B {

// main method
public static void main(String[] args)
{
// creating an object of type class A
A a = new A();

// accessing the method m1()


a.m1();
}
}
Public Access Private Access Protected access Package access
Modifier Modifier modifier modifier

This modifier is This modifier is


This modifier is not This modifier is
applicable for not applicable for
applicable for both applicable for both
both top-level both top-level
top-level classes and top-level classes and
classes and classes and
interfaces. interfaces.
interfaces. interfaces.

Public members Private members Protected members can


Package members can
can be accessed cannot be accessed be accessed anywhere
be accessed from the
from the child from the child from the same package
child class of the same
class of the same class of the same and only by child classes
package.
package. package. outside the package.

Public member Private members


Protected member can be Package member can
can be accessed cannot be accessed
accessed from non-child be accessed from
from non-child from non-child
classes of the same non-child class of the
classes of the classes of the same
package. same package.
same package. package.

Public members Private members Protected members can


Package members
can be accessed cannot be accessed be accessed from the
cannot be accessed
from the child from the child child class of the outside
from the child class of
class of outside class of outside package, but we should
outside package.
package. package. use child reference only.

Public members Private members


Protected members Package members
can be accessed cannot be accessed
cannot be accessed from cannot be accessed
from non-child from non-child
the non-child class of from non-child class of
class of outside class of outside
outside package. outside package.
package. package.

Protected modifier is Package modifier is


Public modifier is
Private modifier is more accessible than the more restricted than the
the most
the most restricted package and private public and protected
accessible
modifier among all modifier but less modifier but less
modifier among
modifiers. accessible than public restricted than the
all modifiers.
modifier. private modifier.
Importing Packages:

Package import is a feature in java which allows us to reuse the classes available in a package.
Java provides import keyword to import classes of another package inside your class. Once a
class is imported, you can use the imported class anywhere in your class.

Package import basically makes availability of classes of that package in your class, so that you
can use the functionalities of that classes. To access a class of another package, first you need to
import that class or package in your class.

// To import all classes of a package


import packagename.*;
// To import specific class of a package
import packagename.classname;
// To import all classes of a sub package
import packagename.subpackagename.*;
// To import specific class of a sub package
import packagename.subpackagename.classname;

Example

import mypack.*;
import mypack.MyFirstPackageProgram;
import java.util.*;
How to import packages in Java?
Java has an import statement that allows you to import an entire package (as in earlier
examples), or use only certain classes and interfaces defined in the package.
The general form of import statement is:
import package.name.ClassName; // To import a certain class only

import package.name.* // To import the whole package

For example,

import java.util.Date; // imports only Date class

import java.io.*; // imports everything inside java.io package

The import statement is optional in Java.


If you want to use class/interface from a certain package, you can also use its fully qualified
name, which includes its full package hierarchy.
Here is an example to import a package using the import statement.
import java.util.Date;

class MyClass implements Date {

// body
}

The same task can be done using the fully qualified name as follows:

class MyClass implements java.util.Date {

//body

Example: Package and importing package


Suppose, you have defined a package com.programiz that contains a class Helper.
package com.programiz;

public class Helper {

public static String getFormattedDollar (double value){

return String.format("$%.2f", value);

Now, you can import Helper class from com.programiz package to your implementation class.
Once you import it, the class can be referred directly by its name. Here's how:
import com.programiz.Helper;

class UseHelper {

public static void main(String[] args) {

double value = 99.5;

String formattedValue = Helper.getFormattedDollar(value);

System.out.println("formattedValue = " + formattedValue);

Output:
formattedValue = $99.50
Exceptions:

Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
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.
import java.io.*;

class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
return (a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}

OUTPUT:
/ by zero

Exception-Handling Fundamentals:

Java exception handling is managed via five keywords:

try, catch, throw, throws, and finally.

They form an interrelated subsystem in which the use of one implies the use of another.

Try: The try block contains a set of statements where an exception can occur.

try
{
// statement(s) that might cause exception
}

Catch: The catch block is used to handle the uncertain condition of a try block. A try block is
always followed by a catch block, which handles the exception that occurs in the associated try
block.

catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}

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

class ThrowExcep {
static void help()
{
try {
throw new NullPointerException("error_unknown");
}
catch (NullPointerException e) {
System.out.println("Caught inside help().");
// rethrowing the exception
throw e;
}
}

public static void main(String args[])


{
try {
help();
}
catch (NullPointerException e) {
System.out.println("Caught in main error name given below:");
System.out.println(e);
}
}
}

Throws: The throws keyword is used for exception handling without try & catch block. It
specifies the exceptions that a method can throw to the caller and does not handle itself.

// Java program to demonstrate working of throws


class ThrowsExecp {
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}

Finally: It is executed after the catch block. We use it to put some common code (to be executed
irrespective of whether an exception has occurred or not ) when there are multiple catch blocks.

class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}

finally {
System.out.println("I am in final block");
}
}
}
Exception Types:

Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to
explain certain error situations. Below is the list of important built-in exceptions in Java.
1. ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic
operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException: This Exception is raised when we try to access a class whose definition is
not found
4. FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
5. IOException: It is thrown when an input-output operation failed or interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing, and
it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException: It is thrown when accessing a method that is not found.
9. NullPointerException: This exception is raised when referring to the members of a null object. Null
represents nothing
10. NumberFormatException: This exception is raised when a method could not convert a string into a
numeric format.
11. RuntimeException: This represents an exception that occurs during runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is
either negative or greater than the size of the string
13. IllegalArgumentException : This exception will throw the error or error statement when the method
receives an argument which is not accurately fit to the given relation or condition. It comes under the
unchecked exception.
14. IllegalStateException : This exception will throw an error or error message when the method is not
accessed for the particular operation in the application. It comes under the unchecked exception.

Arithmetic exception:

// Java program to demonstrate ArithmeticException


class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}

Output:

Can't divide a number by 0

NullPointer Exception:

class NullPointer_Demo

public static void main(String args[])

try {

String a = null; //null value

System.out.println(a.charAt(0));

} catch(NullPointerException e) {

System.out.println("NullPointerException..");

}
Output: NullPointerException..

Uncaught Exceptions:

public class UncaughtExceptionsExample {


public static void main(String[] args) {
// Divide by zero will throw ArithmeticException
int num = 10 / 0;

// Null pointer exception


String str = null;
System.out.println(str.length());
// ArrayIndexOutOfBoundsException
int[] arr = new int[5];
System.out.println(arr[10]);
}
}

Using try and catch:

Multiple catch Clauses:

public class MultipleCatchClausesExample {


public static void main(String[] args) {
try {
int[] arr = new int[5];
System.out.println(arr[10]); // ArrayIndexOutOfBoundsException
String str = null;
System.out.println(str.length()); // NullPointerException
int num = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds!");
} catch (NullPointerException e) {
System.out.println("String is null!");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} catch (Exception e) { // Catch-all clause
System.out.println("An unexpected error occurred: " + e.getMessage());
}
}
}

Nested try Statements:


public class NestedTryStatements {
public static void main(String[] args) {
try {
// Outer try block
System.out.println("Outer try block started");

try {
// Inner try block
System.out.println("Inner try block started");
int num = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch block: Cannot divide by zero!");
}

System.out.println("Outer try block continued");


String str = null;
System.out.println(str.length()); // NullPointerException
} catch (NullPointerException e) {
System.out.println("Outer catch block: String is null!");
} catch (Exception e) {
System.out.println("Outer catch block: An unexpected error occurred");
}
}
}

Output:

Outer try block started


Inner try block started
Inner catch block: Cannot divide by zero!
Outer try block continued
Outer catch block: String is null!

User-defined Custom Exception/ Creating Your Own Exception


Subclasses in java

An exception is an issue (run time error) that occurred during the execution of a program. When
an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets executed.
Java provides us the facility to create our own exceptions which are basically derived classes of
Exception. Creating our own Exception is known as a custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the exception according to
user needs. In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’ keyword.
// A Class that represents use-defined exception

class MyException extends Exception {


}

// A Class that uses above MyException


public class setText {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
Chained Exceptions:

Chained Exceptions allows to relate one exception with another exception, i.e one exception
describes cause of another exception. For example, consider a situation in which a method
throws an ArithmeticException because of an attempt to divide by zero but the actual cause of
exception was an I/O error which caused the divisor to be zero. The method will throw only
ArithmeticException to the caller. So the caller would not come to know about the actual cause
of exception. Chained Exception is used in such type of situations.
// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
// Creating an exception
NumberFormatException ex =
new NumberFormatException("Exception");

// Setting a cause of the exception


ex.initCause(new NullPointerException(
"This is actual cause of the exception"));

// Throwing an exception with cause.


throw ex;
}

catch(NumberFormatException ex)
{
// displaying the exception
System.out.println(ex);

// Getting the actual cause of the exception


System.out.println(ex.getCause());
}
}
}
Output:

java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception

In Java, chain exceptions using the constructor of the Throwable class.

public class ExceptionExample {


public static void main(String[] args) {
try {
// code that might throw an exception
int[] numbers = new int[5];
int divisor = 0;
for (int i = 0; i < numbers.length; i++) {
int result = numbers[i] / divisor;
System.out.println(result);
}
} catch (ArithmeticException e) {
// create a new exception with the original exception as the cause
throw new RuntimeException("Error: division by zero", e);
}
}
}

You might also like