0% found this document useful (0 votes)
18 views9 pages

Java Exception Handling and Data Input

The document contains code snippets demonstrating different Java concepts like sorting names, exception handling, data input/output, linked lists, threads, and inheritance. Specifically, it includes code for sorting an array of names, using runtime type identification to check data types, nested try-catch blocks, validating number inputs, writing data to a file, implementing a linked list with insertion and deletion methods, using synchronized methods for thread-safe execution, implementing Runnable interface to create threads, and extending the Thread class.

Uploaded by

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

Java Exception Handling and Data Input

The document contains code snippets demonstrating different Java concepts like sorting names, exception handling, data input/output, linked lists, threads, and inheritance. Specifically, it includes code for sorting an array of names, using runtime type identification to check data types, nested try-catch blocks, validating number inputs, writing data to a file, implementing a linked list with insertion and deletion methods, using synchronized methods for thread-safe execution, implementing Runnable interface to create threads, and extending the Thread class.

Uploaded by

Mohit Malghade
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

@) Sortinh names.

public class SortingNames


{
public static void main(String[] args)
{
int k=0;
int ln = [Link];
for (int i = 0; i < ln-1; i++)
{
for (int j = i + 1; j < ln; j++)
{
if (args[i].compareTo(args[j]) > 0)
{
String temp = args[i];
args[i] = args[j];
args[j] = temp;
}
}
}
// for printing the elements of the string.
for( int i = 0 ; i< ln ; i++)
{
[Link](args[i]);
[Link](" ");
}
}
}

@) RTTI

public class RTTI


{
public static void main(String[] args)
{
try
{
try
{
int a = [Link](args[0]);
[Link]("It is a Integer.");
}
catch (Exception e1)
{
double a = [Link](args[0]);
[Link]("It is a double value.");
}
}
catch (Exception e2)
{
String b = args[0];
[Link]("It is a character value.");
}
}
}

@) Nested try

public class Nested_try{


public static void main(String[] args)
{
int a[]={10,20};
int b=10;
try
{
int d=a[0]/(b-a[0]);
try
{
int c=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
[Link]("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array index error");
}
catch(ArrayStoreException e)
{
[Link]("Array wrong data type");
}
}
catch(ArithmeticException e)
{
[Link]("Division by zero");
}
int y=a[1]/a[0];
[Link]("y= "+y); // only to check if the program ran
completely
}
}

@) Valid Invalid

public class Exceptionsss {


public static void main(String args[])
{
int invalid=0;
int number,count=0;

for(int i=0;i<[Link];i=i+1)
{
try
{
number=[Link](args[i]);
[Link]("Valid number:"+number);
}
catch(NumberFormatException e)
{
invalid=invalid+1;
[Link]("Inavalid number: "+args[i]);
continue;
}
count=count+1;
}
[Link]("Valid number count:"+count);
[Link]("Invalid number count:"+invalid);
}

@) Data input Stream

import [Link].*;

public class Inputing_data_to_a_file {


public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream([Link]);

[Link]("Enter name:");
String name=[Link]();
[Link]("The name is: "+name);

[Link]("Enter age:");
String s=[Link]();
int age=[Link](s);
[Link]("The age is:"+age);

[Link]("Enter salary:");
String sa=[Link]();
Double sal=[Link](sa);
[Link]("The Salary is:"+sal);
// Transferring above details in a file using DataOutputStream.
FileOutputStream fos =new FileOutputStream("[Link]");
DataOutputStream dos=new DataOutputStream(fos);

[Link](age);
[Link](name);
[Link](sal);

[Link]();
}
}

@) Linked List

// Java program to implement


// a Singly Linked List
public class LinkedList {

Node head; // head of list

// Linked list Node.


// Node is a static nested class
// so main() can access it
static class Node {

int data;
Node next;

// Constructor
Node(int d)
{
data = d;
next = null;
}
}

// Method to insert a new node


public static LinkedList insert(LinkedList list,
int data)
{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;

// If the Linked List is empty,


// then make the new node as head
if ([Link] == null) {
[Link] = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node there
Node last = [Link];
while ([Link] != null) {
last = [Link];
}

// Insert the new_node at last node


[Link] = new_node;
}

// Return the list by head


return list;
}

// Method to print the LinkedList.


public static void printList(LinkedList list)
{
Node currNode = [Link];

[Link]("LinkedList: ");

// Traverse through the LinkedList


while (currNode != null) {
// Print the data at current node
[Link]([Link] + " ");

// Go to next node
currNode = [Link];
}

[Link]();
}

// **************DELETION BY KEY**************

// Method to delete a node in the LinkedList by KEY


public static LinkedList deleteByKey(LinkedList list,
int key)
{
// Store head node
Node currNode = [Link], prev = null;

//
// CASE 1:
// If head node itself holds the key to be deleted

if (currNode != null && [Link] == key) {


[Link] = [Link]; // Changed head

// Display the message

// Return the updated List


return list;
}

//
// CASE 2:
// If the key is somewhere other than at head
//

// Search for the key to be deleted,


// keep track of the previous node
// as it is needed to change [Link]
while (currNode != null && [Link] != key) {
// If currNode does not hold key
// continue to next node
prev = currNode;
currNode = [Link];
}

// If the key was present, it should be at currNode


// Therefore the currNode shall not be null
if (currNode != null) {
// Since the key is at currNode
// Unlink currNode from linked list
[Link] = [Link];

// Display the message


[Link](key + " found and deleted");
}

//
// CASE 3: The key is not present
//

// If key was not present in linked list


// currNode should be null
if (currNode == null) {
// Display the message
[Link](key + " not found");
}

// return the List


return list;
}

// **************MAIN METHOD**************
// method to create a Singly linked list with n nodes
public static void main(String[] args)
{
/* Start with the empty list. */
LinkedList list = new LinkedList();

//
// ******INSERTION******
//

// Insert the values


list = insert(list, 1);
list = insert(list, 2);
list = insert(list, 3);
list = insert(list, 4);
list = insert(list, 5);
list = insert(list, 6);
list = insert(list, 7);
list = insert(list, 8);

// Print the LinkedList


printList(list);

//
// ******DELETION BY KEY******
//

// Delete node with value 1


// In this case the key is ***at head***
deleteByKey(list, 1);

// Print the LinkedList


printList(list);

// Delete node with value 4


// In this case the key is present ***in the
// middle***
deleteByKey(list, 4);

// Print the LinkedList


printList(list);

// Delete node with value 10


// In this case the key is ***not present***
deleteByKey(list, 10);

// Print the LinkedList


printList(list);
}
}

@) Synchronized

class Tablee
{
synchronized void printTable(int n) //method synchronized
{
for(int i=1;i<=5;i=i+1)
[Link](n*i);
try
{
[Link](400);
}
catch(Exception e)
{
[Link](e);
}
}
}
class MyThread11 extends Thread
{
Tablee t;
MyThread11(Tablee t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}
class MyThread22 extends Thread
{
Tablee t;
MyThread22(Tablee t)
{
this.t=t;
}
public void run()
{
[Link](100);
}
}

public class Synchronization {


public static void main(String[] args)
{
Tablee obj=new Tablee();
MyThread11 t1=new MyThread11(obj);
MyThread22 t2=new MyThread22(obj);
[Link]();
[Link]();

}
}

@) Runnable

class SumofaSeries implements Runnable


{
Thread t;
int num;
SumofaSeries(int n)
{
t=new Thread(this);
[Link]();
num=n;
}
public void run()
{
int sum=0;
try
{
for(int i=1;i<=num;i=i+1)
{

if(i==1)
{
sum=1;
[Link](i);
}
else if(i>1&&i%2==0)
{
sum=sum+i;
[Link]("+"+i);
}
else if(i>1&&i%2!=0)
{
sum=sum-i;
[Link]("-"+i);
}
}
[Link]("\nSum:"+sum);
}
catch(Exception e)
{
[Link]("Error:"+e);
}
}
public static void main(String[] args)
{
SumofaSeries s=new SumofaSeries(6);
}
}

@) Extending thread

class ExtendingThread extends Thread


{
ExtendingThread(String nm)
{
super(nm);
start();
}
public void run()
{
try
{
for(int i=0;i<=15;i=i+1)
{
[Link]("Value of counter:"+i);
sleep(1000);
}
}
catch(Exception e)
{
[Link]("Error:"+e);
}
}
public static void main (String[] args)
{
ExtendingThread s1=new ExtendingThread("Sample");
try
{
[Link](2000);
}
catch(Exception e)
{
[Link]("Error:"+e);
}
[Link]("Main thread existing");
}

Common questions

Powered by AI

Dynamic method dispatch in Java, not directly shown but implied in context, allows a program to decide at runtime which method to execute. This is achieved by method calls to overridden methods through references of the parent class. In such examples as potentially having different print implementations in classes extending a common base (like with nodes or threads), it ensures that the method corresponding to the actual object's type is called. This mechanism underpins runtime polymorphism, allowing flexibility and scalability in designing systems that respond dynamically to various data types or object instances .

The LinkedList class handles node insertion by creating a new node and appending it to the list. If the head is null, the new node becomes the head; otherwise, it traverses to the last node and appends the new node there. Deletion is implemented through the deleteByKey method, which covers three cases: If the head node holds the key, it sets the head to the next node. If the key is found post-head, it traverses to locate the key, keeps track of the previous node, and links it to the node after the key node. If the key is not present, the method confirms the absence by checking if the traversal ends with a null current node, returning a message that the key is not found .

The 'RTTI' class uses nested try-catch blocks to determine the data type by attempting to parse the input string into different data types sequentially. It first tries to parse the input into an Integer, and if it fails (catching an Exception), it attempts to parse it as a Double. If both parsing attempts fail, it defaults to recognizing the input as a String type, indicating that it is a character value. The process leverages Java's exception handling to identify data types .

The 'SumofaSeries' class calculates the sum of a series by creating a cyclical pattern of operations on integer values from 1 to a specified number. It starts a new thread and executes a loop where it adds even numbers to the sum and subtracts odd numbers (except the first number which is added) to create an alternating pattern of addition and subtraction. This pattern results in a cumulative sum displayed after the loop completes .

The SortingNames class implements a sorting function using a nested loop structure, akin to the Bubble Sort algorithm. It compares pairs of elements in the array and swaps them if they are in the wrong order based on lexicographical comparison. The outer loop iterates over each element, while the inner loop compares the current element with the subsequent elements. This ensures that the smallest element bubbles to the top in each iteration .

The 'Inputing_data_to_a_file' class reads user data using DataInputStream to obtain strings that are then converted to appropriate data types (age as int, salary as double). It employs DataOutputStream to store these data points into a file. Challenges include handling exceptions related to I/O operations, ensuring data format consistency during storage (particularly with readLine inaccuracies), and managing memory and resource leaks by ensuring streams are properly closed after operations .

In the 'ExtendingThread' example, exception handling is used to manage potential interruptions and sleep errors in the thread's execution. The run method includes exception handling to catch any interruptions during the sleep period. By doing so, the program prevents runtime crashes due to unhandled exceptions, allowing it to print error messages and continue execution gracefully. These measures ensure the main thread remains unaffected by exceptions in the child thread, as shown by the successful termination message .

The 'Exceptionsss' class differentiates between valid and invalid numeric inputs by attempting to parse each argument as an integer within a for-loop. When parsing fails, a NumberFormatException is caught, classifying the input as invalid, incrementing the invalid counter, and printing an indicative message. If parsing succeeds, the input is treated as valid, incrementing the valid count. By counting both, the program provides statistics on the number of valid and invalid entries, demonstrating robust input validation through exception handling .

Synchronization in the 'Synchronization' class is achieved by adding the 'synchronized' keyword to the printTable method within the Tablee class. This ensures that when one thread is executing this method on a given Tablee object, no other thread can execute it on the same object, thus preventing race conditions where multiple threads might modify shared resources concurrently. By synchronizing the method, the program ensures thread safety and consistency when multiple threads invoke the method simultaneously .

The Nested_try class anticipates and manages several exceptions within its blocks: ArithmeticException for division by zero, ArrayIndexOutOfBoundsException for accessing invalid array indices, and ArrayStoreException for incorrect data type usage in arrays. The outer try block attempts a division that could cause an ArithmeticException, while the nested try block is designed to handle both division by zero and array index issues specifically within a secondary operation. Each catch block provides specific error messages, ensuring that different exceptions are appropriately handled, and the program can continue execution, as evidenced by the final arithmetic operation .

You might also like