Monday, December 23, 2024

Machine Learning Course Assignments 2024(Dec)

 Machine Learning Course Assignments 2024

1)  Explain the concept of "generalization" in machine learning. Why is it a central goal in pattern recognition?

2)  What are the three main types of machine learning problems?Explain?

3)  What are the three components of a classification problem?

4)You have a Pandas DataFrame containing data on customer orders. Write Python code to export this DataFrame to:

○A CSV file named 'customer_orders.csv', without writing the index column.

○A tab-delimited text file named 'customer_orders.txt', also without the index column

5) Describe the difference between the map() and apply() methods in Pandas. Provide examples demonstrating their usage.

6)How do Bayesian and frequentist approaches contrast in machine learning?

7) What are some advantages of Bayesian methods?

8) Different types of the clustering techniques?

9)What are the limitations of maximum likelihood estimation?

Saturday, November 16, 2024

ml1

 click here

https://drive.google.com/file/d/1nQXzR7gQVBNIHbjtpId3bYJ3H8Lo5zzc/preview?usp=sharing

Wednesday, August 7, 2024

Assignment quesions 2024

 ASSIGNMENT QUESTIONS 2023

 Unit-1 
1 Write a java program to convert binary to decimal and decimal to binary(Do not use predefind methods)
2 Explain String class in Java. 

 Unit-2
1 Explain String Buffer Class Explain String Builder Class 
2 Explain the  terms static keyword and this keyword with example
 Unit-3
 1. Program to print the duplicate elements of an array. 
 2. Write a Java program to find the transpose of a Matrix

Thursday, August 1, 2024

2-1 syallabus LAB&THEORY

 2-1 java syallabus

2024 II-I java LAB Syllabus

 List of Experiments: 

Exercise – 1

 a. Write a JAVA program to display default value of all primitive data type of JAVA  

b.Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the discriminate D and basing on value of D, describe the nature of root. 

Exercise -2

 a. Write a JAVA program to search for an element in a given list of elements using binary search mechanism. 

 b. Write a JAVA program to sort for an element in a given list of elements using bubble sort 

Exercise - 3

 a. Write a JAVA program to implement class mechanism. Create a class, methods and invoke them inside main method. 

b. Write a JAVA program implement method overloading. 

c. Write a JAVA program to implement constructor. 

d. Write a JAVA program to implement constructor overloading.


Exercise - 4 

a. Write a JAVA program to implement Single Inheritance

 b. Write a JAVA program to implement multi level Inheritance 

c. Write a JAVA program for abstract class to find areas of different shapes 

Exercise - 5 

a. Write a JAVA program give example for “super” keyword. 

b. Write a JAVA program to implement Interface. What kind of Inheritance can be achieved? 

c. Write a JAVA program that implements Runtime polymorphism 

Exercise - 6

 a. Write a JAVA program that describes exception handling mechanism 

b. Write a JAVA program Illustrating Multiple catch clauses 

c. Write a JAVA program for creation of Java Built-in Exceptions d. Write a JAVA program for creation of User Defined Exception 

Exercise - 7 

a. Write a JAVA program that creates threads by extending Thread class. First thread display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome” every 3 seconds, (Repeat the same by implementing Runnable) 

b. Write a program illustrating is Alive and join () 

c. Write a Program illustrating Daemon Threads. d. Write a JAVA program Producer Consumer Problem

Exercise – 8 

a. Write a JAVA program that import and use the user defined packages 

b. Without writing any code, build a GUI that display text in label and image in an ImageView (use JavaFX) 

c. Build a Tip Calculator app using several JavaFX components and learn how to respond to user interactions with the GUI 

Exercise – 9 

a. Write a java program that connects to a database using JDBC

 b. Write a java program to connect to a database using JDBC and insert values into it. 

c. Write a java program to connect to a database using JDBC and delete values from it

2024 II-1 Syllabus

 UNIT 1

 Object Oriented Programming: Basic concepts, Principles. Data Types, Variables, and Operators: Introduction, Data Types in Java, Declaration of Variables, Data Types, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants, Formatted Output with printf() Method, Static Variables and Methods, Attribute, Final. Introduction to 

Operators: Precedence and Associativity of Operators, Assignment Operator (=), Basic Arithmetic Operators, Increment (++) and Decrement (--) Operators, Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical Operators. 

Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions, Ternary Operator, Switch Statement, Iteration Statements, while Expression, do–while Loop, for Loop, Nested for Loop, For–Each for Loop, Break Statement, Continue Statement. 

Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or Tokens in Java Programs, Java Statements, Command Line Arguments, User Input to Programs, Escape Sequences Comments, Programming Style. 

UNIT 2 

Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration of Class Objects, Assigning One Object to Another, Access Control for Class Members, Accessing Private Members of Class, Constructor Methods for Class, Overloaded  Constructor Methods, Nested Classes, Final Class and Methods, Passing Arguments by Value and by Reference, Keyword this. 

Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods, Class Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting of Methods, Overriding Methods, Attributes Final and Static. 

UNIT 3 

Arrays: Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer Memory, Accessing Elements of Arrays, Operations on Array Elements, Assigning Array to Another Array, Dynamic Change of Array Size, Sorting of Arrays, Search for Values in Arrays.

 Inheritance: Introduction, Process of Inheritance, Types of Inheritances, Universal Super Class-Object Class, Inhibiting Inheritance of Class Using Final, Access Control and Inheritance, Multilevel Inheritance, Application of Keyword Super, Constructor Method and Inheritance, Method Overriding, Dynamic Method Dispatch, Abstract Classes, Interfaces and Inheritance. 

Interfaces: Introduction, Declaration of Interface, Implementation of Interface, Multiple Interfaces, Nested Interfaces, Inheritance of Interfaces, Default Methods in Interfaces, Static Methods in Interface, Functional Interfaces.

 UNIT 4 

Packages and Java Library: Introduction, Defining Package, Importing Packages and Classes into Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang Package and its Classes, Class Object, class Math, Java util Classes and Interfaces. 

Exception Handling: Introduction, Hierarchy of Standard Exception Classes, Keywords throws and throw, try, catch, and finally Blocks, Multiple Catch Clauses, Class Throwable, Unchecked Exceptions, Checked Exceptions. 

UNIT 5

 Multithreaded Programming: Introduction, Need for Multiple Threads Multithreaded Programming for Multi-core Processor, Thread Class, Main Thread-Creation of New Threads, Thread States, Thread Priority-Synchronization. 

Java Database Connectivity: Introduction, JDBC Architecture, Installing MySQL and MySQL Connector/J, JDBC Environment Setup, Establishing JDBC Database Connections, ResultSet Interface 

Java FX GUI: Java FX Scene Builder, Java FX App Window Structure, displaying text and image, event handling.

 Text Books: 1. JAVA one step ahead, Anitha Seth, B.L.Juneja, Oxford. 

2. Joy with JAVA, Fundamentals of Object Oriented Programming, DebasisSamanta, MonalisaSarma, Cambridge, 2023. 

3. JAVA 9 for Programmers, Paul Deitel, Harvey Deitel, 4th Edition, Pearson. 

References Books: 1. The complete Reference Java, 11thedition, Herbert Schildt,TMH 

2. Introduction to Java programming, 7th Edition, Y Daniel Liang, Pearson 

Online Resources: 1. https://nptel.ac.in/courses/106/105/106105191/ 2.https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_012880464547618 816347_shared/overview 

Thursday, November 16, 2023

simple calculator program Using Applet

 import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*<applet code="calculator.class" width="700" height="200">

</applet>*/

public class calculator extends Applet implements ActionListener

{

    String str="";

TextField t1,t2,t3;

    Button b1,b2,b3,b4,b5;

    Label l1,l2,l3;

public void init() 

    {

        l1=new Label("Enter 1st value:");

add(l1);

        l2=new Label("Enter 2nd value:");

add(l2);

        l3=new Label("Result: ");

add(l3);

        t1=new TextField(10);

add(t1);

        t2=new TextField(10);

add(t2);

  t3=new TextField(10);

add(t3);

        b1=new Button("add");

        b2=new Button("sub");

        b3=new Button("mul");

        b4=new Button("div");

        b5=new Button("mod");

add(b1);

add(b2);

add(b3);

add(b4);

add(b5);

l1.setBounds(50,100,100,20);

l2.setBounds(50,140,100,20);

l3.setBounds(50,180,100,20);

t1.setBounds(200,100,100,20);

t2.setBounds(200,140,100,20);

t3.setBounds(200,180,100,20);

b1.setBounds(50,250,50,20);

b2.setBounds(110,250,50,20);

b3.setBounds(170,250,50,20);

b4.setBounds(230,250,50,20);

b5.setBounds(290,250,50,20);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

b5.addActionListener(this);

setLayout(null);

setVisible(true);

setSize(400,350);

setBackground(Color.black);

setForeground(Color.white);

    }

public void paint(){}

public void actionPerformed(ActionEvent e) 

    {

str=e.getActionCommand();

double a=Double.parseDouble(t1.getText());

double b= Double.parseDouble(t2.getText());

if(str=="add") 

        {

double sum=a+b;

t3.setText(""+sum);

        }

else if(str=="sub") 

        {   

double sub=a-b;

t3.setText(""+sub);

        }

else if(str=="mul") 

       {  

double mul=a*b;

t3.setText(""+mul);

        }

else if(str=="div") 

        {  

double div=a/b;

t3.setText(""+div);

        }

else if(str=="mod") 

        {  

int x=Integer.parseInt(t1.getText());

int y=Integer.parseInt(t2.getText());

int mod=x%y;

t3.setText(""+mod);

        }

repaint();

    }

}


Thursday, October 12, 2023

Thread synchronization block

Using  synchronized Block

class Callme {

void call(String msg) {

System.out.print("[" + msg);

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("Interrupted");

}

System.out.println("]");

}

}

class Caller implements Runnable {

String msg;

Callme target;

Thread t;

public Caller(Callme targ, String s) {

target = targ;

msg = s;

t = new Thread(this);

t.start();

}

// synchronize calls to call()

public void run() {

synchronized(target) { // synchronized block

target.call(msg);

}

}

}

class Synch1 {

public static void main(String args[]) {

Callme target = new Callme();

Caller ob1 = new Caller(target, "Hello");

Caller ob2 = new Caller(target, "Synchronized");

Caller ob3 = new Caller(target, "World");

// wait for threads to end

try {

ob1.t.join();

ob2.t.join();

ob3.t.join();

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

}

}

Thread synchronization method

 Thread  synchronization

Before  synchronization

class Callme {

void call(String msg) {

System.out.print("[" + msg);

try {

Thread.sleep(1000);

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

System.out.println("]");

}

}

class Caller implements Runnable {

String msg;

Callme target;

Thread t;

public Caller(Callme targ, String s) {

target = targ;

msg = s;

t = new Thread(this);

t.start();

}

public void run() {

target.call(msg);

}

}

class Synch {

public static void main(String args[]) {

Callme target = new Callme();

Caller ob1 = new Caller(target, "Hello");

Caller ob2 = new Caller(target, "Synchronized");

Caller ob3 = new Caller(target, "World");

// wait for threads to end

try {

ob1.t.join();

ob2.t.join();

ob3.t.join();

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

}

}

----------------------------------------------------------------

After  synchronization :

class Callme {

synchronized void call(String msg) {

System.out.print("[" + msg);

try {

Thread.sleep(1000);

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

System.out.println("]");

}

}

class Caller implements Runnable {

String msg;

Callme target;

Thread t;

public Caller(Callme targ, String s) {

target = targ;

msg = s;

t = new Thread(this);

t.start();

}

public void run() {

target.call(msg);

}

}

class Synch {

public static void main(String args[]) {

Callme target = new Callme();

Caller ob1 = new Caller(target, "Hello");

Caller ob2 = new Caller(target, "Synchronized");

Caller ob3 = new Caller(target, "World");

// wait for threads to end

try {

ob1.t.join();

ob2.t.join();

ob3.t.join();

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

}

}

Thread class methods isAlive(), join()

 Thread class methods isAlive(), join()

class NewThread implements Runnable{
    String name;
    Thread t;
    NewThread(String n){
        name = n;
        t = new Thread(this,name);
        System.out.println("Child: "+t);
        t.start();
    }
    public void run(){
        try{
            for(int i=5;i>0;i--){
                System.out.println("Name: "+i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e){
            System.out.println("Thread "+name+" Interrupted");
        }
        System.out.println(name+" Exiting");
    }
}
class AliveJoin {
    public static void main(String[] args){
        NewThread obj1 = new NewThread("One");
        NewThread obj2 = new NewThread("Two");
        NewThread obj3 = new NewThread("Three");
        System.out.println("Thread One is Alive: "+obj1.t.isAlive());
        System.out.println("Thread Two is Alive: "+obj2.t.isAlive());
        System.out.println("Thread Three is Alive: "+obj3.t.isAlive());
        try {
            System.out.println("Waiting for Threads");
            obj1.t.join();
            obj2.t.join();
            obj3.t.join();
        } catch (InterruptedException e) {
            System.out.println("Main Interrupted");
        }
        System.out.println("Thread One is Alive: "+obj1.t.isAlive());
        System.out.println("Thread Two is Alive: "+obj2.t.isAlive());
        System.out.println("Thread Three is Alive: "+obj3.t.isAlive());
    }
}


Thread Priorities with program

Thread Priorities with program 

public class Tpriority extends Thread {

   public void run() {
        System.out.println("Current Thread Name: " + Thread.currentThread().getName());
        System.out.println("Current Thread Priority: " + Thread.currentThread().getPriority());
    }
    public static void main(String[] args){
        Tpriority t1 = new Tpriority();
        Tpriority t2 = new Tpriority();
        t1.setName("One");
        t2.setName("Two");
        t1.setPriority(Thread.MAX_PRIORITY);
        t2.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.start();
    }
}

Thursday, September 28, 2023

Exception 5 keywords in 1 program

 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 {

      System.out.println("This is the finally block");

       }

    }

}

Important topics for Final exams

Important topics for Final  exams


 Explain about  data types and their sizes

java program to apply addition of  two three dimensional matrices

Explain method overriding

Explain method overloading

Explain  differences between method overriding and method overloading

Explain  constructor and its types

Explain  copy constructor 

Explain inheritance and types

differences between this and super

super class reference variable referring sub class object  Explain 

Write a program in Java to find  prime number where n is any integer and read input from the user


Explain  about single and multiple dimensional array.

how to create packages and their usage

various uses of ‘final’ keyword

Explain  about control statements

Explain  about  for each loop in java

explain about call by value and call by reference 

Explain about Dynamic method dispatch

Explain  importance of exception handling

Explain   checked and unchecked exceptions 

 Explain   keywords of exception handling

how to create your own exception

 

Wednesday, September 27, 2023

Exception notes

 Exception Handling:

An exception is an abnormal condition that arises in a code sequence at run time. Exception is a run time error.

Java and other programming languages have mechanisms for handling exceptions that you can use to keep your program from crashing.  In Java, this is known as catching an exception/exception handling.

When java interpreter encounters an error, it creates an exception object and throws it( informs us that an error occurred).

If the exception object is not caught and handled properly, the interpreter will display a message and stops the program execution.

If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions.


Errors are broadly classified into two categories.

1. Compile time exception(error)

2. Run Time exception(error)


Compile-time errors:

All syntax errors will be detected and displayed by the java compiler and therefore these errors are known as compile-time errors.

Whenever the compiler displays an error, it will not create the .class file.


Run-time errors:

Sometimes a program may compile successfully creating the .class file but may not run properly because of abnormal conditions.

Common run-time errors are

o The file you try to open may not exist.

o Dividing an integer by Zero.

o Accessing an element that is out of the bonds of an array type.

o Trying to store a value into an array of an incompatiable class or type.

o Trying to cast an instance of a class to one of its subclasses.

o And many more……………..



Each exception is a class, part of java.lang package and it is derived from Throwable class.


Java Exception handling is managed by 5 keywords.

1. try

2. catch

3. throw

4. throws

5. finally


If these abnormal conditions are not handled properly, either the program will be aborted or the incorrect result will be carried on causing more and more abnormal conditions.


Example to see what happens if the exceptions are not handled:

class NoException 

{

public static void main(String[] args) 

{

int no=10;

int r=0;

r=no/0;

System.out.println("Result is:"+r);

}

}

The above program gives the following error:

Exception in thread "main" java.lang.ArithmeticException: / by zero

        at NoException.main(NoException.java:8)


In the above program the error is handled by the default exception handler which is provided by java run-time system.


If the exception is handled by the user then it gives two benefits.

1. Fixes the error.

2. Avoids automatic termination of program.


Syntax:

       try

       {

        statement;   // generates exception

       }

       catch(Exception-type e)

       {

        statement;   // process the exception

       } 

Java uses a keyword try to preface a block of code that is likely to cause an error and “throw” an exception.

A catch block is defined by the keyword catch “catches” the exception “thrown” by the exception block.

Catch block should be immediately after the try block.

try block can have one or more statements that could generate an exception.

If any one statement generates an exception, the remaining statements in the block are skipped and control jumps to the catch block that is placed next to the try block.

The catch block too can have one or more statements that are necessary to process the exception.

Every try block should be followed by at least one catch statement.

Catch statement works like a method definition, contains one parameter, which is reference to the exception object thrown by the try block.


Program:

// program name:..\atish\java_new\core\exp\TryCatch.java

class TryCatch

{

  public static void main(String[] args) 

  {

    int a=10;

    int b=5;

    int c=5;

    int r;


    try

    { r=a/(b-c); // exception here

      System.out.println("This will not be executed......");

    }

    catch(ArithmeticException e)

    { System.out.println("Cannot divide by 0....."); }

    System.out.println("After catch statement.....");

  }

}

Note: Once an exception is thrown, control is transferred to catch block and never returns to try block again.


***Statements after the exception statement(try block) never get xecuted.


Multiple catch statements:

Syntax:


try

{

 statement;

}

catch(Exception-type 1 e)

{

 statement;  // process exception type 1

catch(Exception-type 2 e)

{

 statement;  // process exception type 2

catch(Exception-type N e)

{

 statement;  // process exception type N

When an exception in a try block is generated, java treats the multiple catch statements like cases in switch statement.

The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped.

Code in the catch block is not compulsory.

o catch (Exception e){}

o the catch statement simply ends with a curly braces( {} ), which does nothing, this statement will catch an exception and then ignore it.


import java.util.*;


class MultiCatch

{

 public static void main(String args[])

 {

  int no,d,r;

  no=d=r=0;


 try

 {

  no=Integer.parseInt(args[0]);

  d=Integer.parseInt(args[1]);


  r=no/d;

  System.out.println("Result :"+r);

 }

 catch (NumberFormatException nf)

 {

   System.out.println(nf);

 }


catch (ArrayIndexOutOfBoundsException ai)

 {

 System.out.println(ai);

 }

 catch (ArithmeticException ae)

 {

  System.out.println(ae);

 }

 }

}


Finally:


Java supports another statement known as finally that can be used to handle an exception that is not caught by any one of the previous catch statements.

Finally block can be used to handle any exception generated with in a try block. 

It may be added immediately after the try block or the last catch block.


Syntax 1:                                    syntax 2:

try                                          try

{                                            {   

 statements;                                  statements;

}                                            }

finally                                      catch(..)

{                                            {

 statements;                                  statements;

}                                            }

                                             catch(..)

                                             {

                                              statements;

                                             }

                                             finally

                                             {

                                              statements;

                                             }

Note:

When a finally block is defined, this is guaranteed to execute, regardless whether exception is thrown or not.

Finally block is mainly used to close the files, releasing system resources.


throws clause:

Runtime Exceptions are referred to as unchecked exceptions. All other exceptions are checked exceptions, they don’t derive from java.lang.RuntimeException.

A Checked exception must be caught some where in the program code.

If you invoke a method that throws a checked exception but you don't catch the checked exception somewhere, your code will not compile. That's why they are called checked exceptions.

The compiler checks to make sure that they are handled or declared.


Syntax:


<return type> method name([parameters-list]) throws exp 1,exp 2,…………

Ex: 1

        import java.io.*;

        class ThrowsTest

        {

         public static void main() throws EOFException

         {

          throw new EOFException();

          }

         }


Ex: 2

import java.io.*;

 class Test

 {

  void doWork() throws IOException


  {

   throw new IOException();

  }

 }


 class ThrowsTest1

 {

  public static void main(String args[])  throws IOException

  {

   Test t1=new Test();

   t1.doWork();

  }

  }



Printing information about an exception:

it is useful to discover the cause of an exception. When you know the cause of an exception, it makes easier to fix programming bugs as soon as they discovered.

As all the exception classes are derived from Throwable, they all support the following methods provided by the Throwable.


Nested try statements:

Try statements can nested.


// program name:..\atish\java_new\core\exp\NestedTry.java

class NestedTry

 {

   public static void main(String args[])

    {

     try

     {

      int a=args.length;

      int b=10/a; // if no command line argument is passed

                 // it generates divide-by-zero exception

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

      try

      {

       if(a==1)

         a=a/(a-a); // divide-by-zero exception

       else

           if(a==2)

            {

             int c[]={1};

             c[5]=99; // generates out of bounds exception

             }

        }

        catch(ArrayIndexOutOfBoundsException e)

        { System.out.println("Array index out-of-bounds:"+e); }

      }

      catch(ArithmeticException e)

      { System.out.println("Divide by 0:"+e); }

    }

  }


Rethrowing the exceptions:


class ReThrow

{

 static void test()

 {

  try

  {

   throw new NullPointerException("Testing..");

   }

  catch(NullPointerException e)

  {

   System.out.println("Caught inside test method..");

   throw e; // rethrow the exception

  }

 }


  public static void main(String args[])

  {

   try

   {

    test();

    }

   catch(NullPointerException e)

   {

    System.out.println("Recaught..:"+e);

   }

  }

 }            


Example NullPointer Exception:

class Test

{

 int no=10;

 void disp()

 { System.out.println("no is:"+no);

    }

}

class NPE

{

 public static void main(String args[])

 {

  Test t=new Test();

  t=null;

  try{

  t.disp();

  }

  catch(NullPointerException np)

  { np.printStackTrace();

    }

 }

}









Thursday, September 14, 2023

Checked Exceptions & Unchecked Exceptions

                                                  Exceptions 

 

Exceptions are a mechanism used to handle unexpected or exceptional situations that can occur during the execution of a program. Java categorizes exceptions into two main types: checked exceptions and unchecked exceptions (also known as runtime exceptions). These two categories serve different purposes and have different characteristics.

 

Checked Exceptions:

 Checked exceptions are exceptions that the Java compiler requires you to handle explicitly in your code. This means that if a method can potentially throw a checked exception, you must either catch and handle that exception using a

try-catch block or declare that the method throws the exception using the throws keyword in its method signature.

Common examples of checked exceptions include IOException, SQLException, and ClassNotFoundException.

Checked exceptions typically represent external problems or issues that your program may encounter during its execution, such as file I/O errors or database connection problems. Handling these exceptions ensures that your program can gracefully recover from these situations or report errors to the user.

Example of handling a checked exception:

code:

try {

// Code that may throw a checked exception FileInputStream file = new FileInputStream("example.txt");

} catch (IOException e) {

// Handle the exception

System.out.println("An error occurred: " + e.getMessage());

}

 

Unchecked   Exceptions (Runtime Exceptions):

 Unchecked exceptions, also known as runtime exceptions, are exceptions that the compiler does not require you to handle explicitly. These exceptions usually

indicate programming errors or issues that can be avoided through proper coding practices.

Common examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.

Unchecked exceptions typically occur due to logical errors in the code, such as attempting to access a null reference or dividing by zero. While you are not forced to handle them, it's still a good practice to do so when possible to make your code more robust.

      

Example of an unchecked exception:

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

int result = numbers[5]; // This will throw an ArrayIndexOutOfBoundsException at runtime

 

In summary, the key difference between checked and unchecked exceptions in Java is that checked exceptions must be explicitly handled or declared, while unchecked exceptions (runtime exceptions) do not require explicit handling but should still be addressed when possible. Effective exception handling is an essential part of writing reliable and robust Java programs, as it allows you to gracefully handle unexpected situations and provide meaningful feedback to users.

 

 

 

**** Difference between checked                      and unchecked exceptions****


Aspect

Checked Exceptions

Unchecked Exceptions

Declaration in Code

Must be declared using the throws clause in the method signature or handled using a try-catch block.

Optional to declare or handle. You can still use a try-catch block, but it's not required.


Examples

IOException, SQLException, ClassNotFoundException

NullPointerException, ArrayIndexOutOfBoundsExceptio n, IllegalArgumentException

Compiler Enforcement

The compiler enforces handling or declaring checked exceptions at compile-time.

The compiler does not enforce handling or declaring unchecked exceptions at compile-time.

Handling Requirement

Mandatory handling or declaration, either through a try-catch block or by propagating the exception using the throws clause.

Optional handling; you can choose whether or not to handle unchecked exceptions.

Checked by Compiler

Checked exceptions are checked by the compiler to ensure that they are properly handled or declared

Unchecked exceptions are not checked by the compiler, meaning that the compiler does not enforce handling or declaration.

Extending Throwable

Subclasses of Exception (excluding RuntimeException) and its subclasses are considered checked exceptions.

Subclasses of RuntimeException and its subclasses are considered unchecked exceptions.

Inheritance Hierarchy

Checked exceptions are typically further up the exception hierarchy and inherit from Exceptions.

Unchecked exceptions are typically further down the hierarchy and inherit from RuntimeException

Propagating Exceptions

Checked exceptions need to be declared using the throws keyword in the method signature if they are not handled locally.

Unchecked exceptions do not need to be declared using the throws keyword, even if they are not handled locally.

Try- Catch Block Requirement

Required for checked exceptions if you don't use the throws clause for declaration.

Optional for unchecked exceptions; you can still use try-catch blocks if desired.


 

 

       *****Program for Checked Exception in Java*******

 

 

public class CheckedException {

public static void main(String[] args) { int dividend = 10;

int divisor = 0;

 

try {

int result = dividend / divisor; System.out.println("Result: " + result);

} catch (ArithmeticException e) {

// Handle the checked exception (ArithmeticException) System.err.println("An error occurred: " + e.getMessage());

}

}

}

 

 

 

Output:

An error occurred: / by zero

 

       *****Program for Unchecked Exception in java*****

 

public class UncheckedExceptionExample { public static void main(String[] args) {

int[] numbers = { 1, 2, 3, 4, 5 };

 

// Attempt to access an index that is out of bounds int index = 10;

int value = numbers[index];


System.out.println("Value at index " + index + ": " + value); // This line won't be reached

}

}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5

at UncheckedExceptionExample.main(UncheckedExceptionExample.java:8)

 

Machine Learning Course Assignments 2024(Dec)

 Machine Learning Course Assignments 2024 1)   Explain the concept of "generalization" in machine learning. Why is it a central go...