Nothing Special   »   [go: up one dir, main page]

Java Impo

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

JAVA INTERNAL EXAM 2

Exceptional Handling

Types of Error:
1. Compile time error – Syntax Error
2. Run-Time error – Logical Error

Definition of Exception
1. An Exception is condition that is caused by run-time error in
program.
2. 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
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file

Difference between Errors 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.
Methods to print the Exception information:

1. printStackTrace()
This method prints exception information in the format of the Name of the
exception: description of the exception, stack trace.

//program to print the exception information using


printStackTrace() method

import java.io.*;

class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}
Features of Exception
1. Find the problem( Hit the exception )
2. Inform that an error has occurred ( throws Exception )
3. Receives the error information ( Catch exception )
4. Take corrective actions (handle the Exception)

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:


Syntax:

try {

// Block of code to try

catch(Exception e) {

// Block of code to handle errors

Example
public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};


System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

The output will be:

Something went wrong.

Some important Types of Exception

1. ArithmeticException: It is thrown when an exceptional condition has


occurred in an arithmetic operation.

2. StringIndexOutOfBoundsException: It is thrown by String class


methods to indicate that an index is either negative or greater than
the size of the string

// Java program to demonstrate StringIndexOutOfBoundsException


class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}}}
3. ClassNotFoundException: This Exception is raised when we try to
access a class whose definition is not found

// Java program to demonstrate ClassNotFoundException


public class ClassNotFoundException_Demo
{
public static void main(String[] args) {
try{
Class.forName("Class1"); // Class1 is not defined
}
catch(ClassNotFoundException e){
System.out.println(e);
System.out.println("Class Not Found...");
}
}
}
Array:

Java Arrays
Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.

To declare an array, define the variable type with square


brackets:

String[] cars;

We have now declared a variable that holds an array of strings.


To insert values to it, you can place the values in a comma-
separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

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

// Outputs Volvo
CHANGE ELEMENT IN ARRAY:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

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

// Now outputs Opel instead of Volvo

ARRAY LENGTH:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars.length);

// Outputs 4
CONSTRUCTOR:

Meaning:
A constructor in Java is a special type of method that is called
when an object of a class is created. It is used to initialize the
object's state.
Syntax:
The syntax of a constructor in Java is:
public ClassName()
{
// constructor body
}
Rules to Create a Constructor:
1. The constructor method must have the same name as the
class.
2. Constructors do not have a return type, not even void.
3. Constructors can be overloaded, meaning a class can have
multiple constructors with different parameters.
4. If you don't define any constructor in your class, Java
provides a default constructor (without parameters)
automatically.
Types:
There are mainly two types of constructors:
1. Default Constructor: Constructor without any parameters.
2. Parameterized Constructor: Constructor with parameters.
EXAMPLE – note book
VISIBILITY CONTROL:

Visibility control in Java refers to the ability to control the access levels of classes, fields,
methods, and constructors. This is crucial for encapsulation and data hiding in object-
oriented programming.

Meaning:

Visibility control defines who can access the members (fields, methods, constructors) of
a class.

Uses:

1. Encapsulation: It allows you to hide the internal state of an object and only
expose what is necessary, improving the maintainability and robustness of code.
2. Access Control: It prevents unauthorized access and manipulation of sensitive
data.
3. Modularity: By controlling visibility, you can control how different components
of your program interact, enhancing modularity.

Koncham note landhu padichiko …


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
Simple example of java package
The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -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 of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
How to access package from another package?
There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

Method Overriding:
Meaning:
Method overriding in Java occurs when a subclass provides a
specific implementation of a method that is already provided
by its superclass.

SYNTAX
@Override
<access_modifier> <return_type>
methodName(<parameter_list>) {
// method body
}

EXAMPLE:
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
public void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal animal = new Animal();
animal.sound(); // Output: Animal makes a sound

Animal dog = new Dog();


dog.sound(); // Output: Dog barks
}
}

OUTPUT:
Animal makes a sound
Dog barks

Method Overloading:
Meaning:
Method overloading in Java allows a class to have multiple
methods with the same name but with different parameters.

SYNTAX:
<access_modifier> <return_type>
methodName(<parameter_list>) {
// method body
}

// Example of overloading:
<access_modifier> <return_type>
methodName(<parameter_list_1>) {
// method body
}

<access_modifier> <return_type>
methodName(<parameter_list_2>) {
// method body
}

EXAMPLE:

public class Calculator {


// Overloaded method
public int add(int a, int b) {
return a + b;
}

// Overloaded method
public double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


Calculator calc = new Calculator();
int result1 = calc.add(2, 3); // Calls the first add method
double result2 = calc.add(2.5, 3.5); // Calls the second add
method
System.out.println("Result 1: " + result1); // Output: Result
1: 5
System.out.println("Result 2: " + result2); // Output: Result
2: 6.0
}
}

OUTPUT:
Result 1: 5
Result 2: 6.0

You might also like