0% found this document useful (0 votes)
43 views17 pages

Unit Iii Q & A

The document is a question bank for a Computer Science and Engineering course on Object-Oriented Programming, covering various topics such as deadlock, thread priority, exception handling, and thread synchronization in Java. It includes definitions, examples, and explanations of built-in exceptions, user-defined exceptions, and methods to create threads. The content is structured into questions and answers, providing a comprehensive overview of key concepts in Java programming.

Uploaded by

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

Unit Iii Q & A

The document is a question bank for a Computer Science and Engineering course on Object-Oriented Programming, covering various topics such as deadlock, thread priority, exception handling, and thread synchronization in Java. It includes definitions, examples, and explanations of built-in exceptions, user-defined exceptions, and methods to create threads. The content is structured into questions and answers, providing a comprehensive overview of key concepts in Java programming.

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS3391 OBJECT ORIENTED PROGRAMMING


QUESTION BANK WITH ANSWERS
UNIT III
1. Define Deadlock. Apr/May 2023
Deadlock is a situation in computing where two or more processes are unable to
proceed because each is waiting for the other to release a resource. This can result in a
standstill where none of the processes can make progress, leading to system
inefficiency or failure.

2. List the values associated with the parameters of setpriority() method of Thread
class. Apr/May 2023
The priority values Java, the Thread class has a method named setPriority (int
newPriority) that allows you to set the priority of a thread. The priority of a thread
affects its scheduling relative to other threads. Java provides a range of priority values
that you can use with the setPriority method. for threads in Java are defined as
constants in the Thread class:
1. Thread.MIN_PRIORITY: Represents the minimum priority value a thread
can have. The value is 1.
2. Thread.NORM_PRIORITY: Represents the default priority value for
threads. The value is 5.
3. Thread.MAX_PRIORITY: Represents the maximum priority value a thread
can have. The value is 10.

3. Why to handle exceptions? Apr/May 2024


Reasons for Handling Exceptions
Improved Program Stability
Error Detection and Correction
Enhanced User Experience
Control Flow Management
Resource Management
Maintainability and Debugging

4. What is Thread priority? How it can be set for a Thread? Apr/May 2024
Thread priority is a mechanism in Java that allows you to influence the scheduling
order of threads. Each thread in Java can be assigned a priority, which is a number
indicating the relative importance of the thread compared to other threads. This
priority affects how the Java Virtual Machine (JVM) schedules threads for execution.
Setting Thread Priority
To set the priority of a thread in Java, you use the setPriority(int newPriority) method
of the Thread class. The priority value must be between Thread.MIN_PRIORITY and
Thread.MAX_PRIORITY, inclusive.

5. What is chained exceptions? Nov/Dec 2021


Chained exceptions in Java refer to a mechanism where one exception causes
another exception to be thrown, and the second exception contains the original
exception as its cause. This concept is useful for providing more detailed information
about errors and maintaining the context of the original exception while handling or
propagating it.

6. How character streams are defined? Nov/Dec 2021


Character streams are used for reading and writing data in a character-based format,
which makes them more suitable for handling text data compared to byte streams.
Character streams handle the encoding and decoding of characters, making it easier to
work with text in different character sets.

7. Define Arithmetic Exceptions with example. Nov/Dec 2022


ArithmeticException in Java is a runtime exception that is thrown when an
exceptional arithmetic condition occurs. This exception is a subclass of
RuntimeException and is used to indicate errors related to mathematical operations
that cannot be represented or handled by the Java runtime.
Example:
The divide method performs division of two integers. It checks if the denominator is
zero and throws an ArithmeticException if it is.
In the main method, the divide method is called within a try block. If an
ArithmeticException is thrown, it is caught in the catch block. The catch block then
prints a meaningful error message.
If the denominator is zero, the output will be: An arithmetic error occurred:
Division by zero is not allowed.
If the denominator is non-zero, it will display the result of the division.
8. Name the two ways to create a thread in Java. Nov/Dec 2022
In Java, there are two primary ways to create and execute threads:
By Extending the Thread Class
By Implementing the Runnable Interface

9. Outline the difference between unchecked exceptions and checked exceptions.


Nov/Dec 2023
Feature Checked Exceptions Unchecked Exceptions
Inheritance Subclass of Exception, Subclass of RuntimeException
not RuntimeException
Compile-Time Must be handled or Not required to be handled or
Checking declared declared
Examples IOException, NullPointerException,
SQLException ArrayIndexOutOfBoundsException
Usage Typically used for Typically used for programming
recoverable conditions errors (e.g., logic errors)
(e.g., I/O errors)
Feature Checked Exceptions Unchecked Exceptions
Inheritance Subclass of Exception, Subclass of RuntimeException
not RuntimeException

10. Name the methods used by Java for interprocess communication to avoid
polling. Nov/Dec 2023
Interprocess communication (IPC) is a crucial aspect of developing applications that
need to coordinate or share data between different processes. To avoid the
inefficiency of polling, Java provides several mechanisms for interprocess
communication.
PART B(5 X 13 =65)
1. Discuss about user defined exceptions in Java. Give suitable examples. Apr/May 2024
User-defined exceptions in Java allow you to create custom exception classes that
represent specific error conditions in your application. These exceptions extend the built-in
Exception class or one of its subclasses, enabling you to handle application-specific scenarios
in a meaningful way.
Why Use User-Defined Exceptions?
1. Clarity: Custom exceptions make your code more readable by providing meaningful
names and messages for specific error conditions.
2. Control: They allow you to handle specific exceptions more precisely and provide
tailored responses.
3. Separation: They help in separating different types of errors and their handling logic,
improving maintainability.
Creating User-Defined Exceptions
To create a user-defined exception in Java, follow these steps:
1. Extend the Exception Class:
o Create a new class that extends the Exception class (or a subclass like
RuntimeException if you want it to be an unchecked exception).
2. Define Constructors:
o Provide constructors to initialize the exception with a message and/or a cause.
You can use the default constructor, a constructor with a message, or a
constructor with both a message and a cause.
3. Add Additional Methods (if needed):
o You can add additional methods or fields if your exception needs extra
information.
Example of User-Defined Exception
Let’s create a custom exception called InsufficientFundsException for a banking application
where a withdrawal operation cannot be completed due to insufficient funds.
Define the Custom Exception:
// File: InsufficientFundsException.java
public class InsufficientFundsException extends Exception
{
// Default constructor
public InsufficientFundsException()
{s
uper();
}
// Constructor that accepts a message
public InsufficientFundsException(String message)
{
super(message);
}
// Constructor that accepts a message and a cause
public InsufficientFundsException(String message, Throwable cause)
{
super(message, cause);
}
// Constructor that accepts a cause
public InsufficientFundsException(Throwable cause) { super(cause);
}
}
2. How Thread Synchronization is managed in Java. Write example code. Apr/May
2024
Thread synchronization in Java is a mechanism used to ensure that multiple threads can
safely access and modify shared resources or data without causing data inconsistency or
corruption. Synchronization is crucial when multiple threads interact with shared data to
avoid issues like race conditions.
Key Concepts of Thread Synchronization
1. Critical Section:
o A block of code that accesses shared resources and must be executed by only
one thread at a time.
2. Synchronization:
o The process of controlling access to critical sections to ensure that only one
thread executes a critical section at any given time.
3. Monitor:
o Java provides a built-in monitor for every object. When a thread locks an
object’s monitor, no other thread can access the synchronized methods or
blocks of that object until the lock is released.
Mechanisms for Synchronization in Java
1. Synchronized Methods:
o Methods can be declared synchronized to ensure that only one thread executes
the method on a particular object at a time.
2. Synchronized Blocks:
o Blocks of code within a method can be synchronized to allow more granular
control over synchronization.
3. Locks:
o The java.util.concurrent.locks package provides explicit locking mechanisms
through classes like ReentrantLock and ReadWriteLock.
Example of Synchronization with Synchronized Methods
Here is a simple example demonstrating thread synchronization using synchronized methods:
Example Code:
java
Copy code
// File: Counter.java
public class Counter {
private int count = 0;

// Synchronized method to ensure only one thread updates the count at a time
public synchronized void increment() {
count++;
}

public int getCount() {


return count;
}
}

// File: CounterTest.java
public class CounterTest {
public static void main(String[] args) {
Counter counter = new Counter();

// Create two threads that will increment the counter


Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread thread2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

// Start the threads


thread1.start();
thread2.start();

try {
// Wait for both threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// Print the final count


System.out.println("Final count: " + counter.getCount());
}
}

3. Explain detain about Java Built in exceptions. Explain any three exceptions. Apr/May
2023
Java built-in exceptions are a part of the Java Standard Library and are used to handle various
error conditions that can occur during the execution of a program. These exceptions are
subclasses of java.lang.Exception and are designed to address common issues like invalid
input, resource unavailability, and arithmetic errors.
Java Built-In Exception Hierarchy
The Java exception hierarchy is structured as follows:
 java.lang.Throwable
o java.lang.Exception
 java.lang.RuntimeException
 java.lang.NullPointerException
 java.lang.ArithmeticException
 java.lang.ArrayIndexOutOfBoundsException
 java.lang.IllegalArgumentException
 java.lang.NumberFormatException
 java.io.IOException
 java.lang.ClassNotFoundException
 java.lang.NoSuchMethodException
 java.lang.InterruptedException
 java.lang.FileNotFoundException
Examples of Built-In Exceptions
Let's discuss three commonly encountered built-in exceptions:
1. ArithmeticException
Description:
 Type: Runtime Exception
 Cause: Thrown when an exceptional arithmetic condition has occurred, such as
division by zero.
Example:
java
Copy code
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int a = 10;
int b = 0;

try {
int result = a / b; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}
Explanation:
 In this example, dividing 10 by 0 throws an ArithmeticException. The catch block
handles the exception and prints an error message.
2. NullPointerException
Description:
 Type: Runtime Exception
 Cause: Thrown when the application attempts to use null where an object is required.
For example, accessing a method or field on a null reference.
Example:
java
Copy code
public class NullPointerExceptionExample {
public static void main(String[] args) {
String str = null;

try {
int length = str.length(); // This will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Error: Attempted to access method on a null object.");
}
}
}
3. ArrayIndexOutOfBoundsException
Description:
 Type: Runtime Exception
 Cause: Thrown when an application attempts to access an array with an illegal index.
For example, accessing an index that is negative or beyond the array's length.
Example:
java
Copy code
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] array = {1, 2, 3};

try {
int value = array[5]; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index is out of bounds.");
}}}

4. Discuss in detail about methods to create a thread in Java

In Java, there are two primary ways to create and run threads: by extending the Thread class
and by implementing the Runnable interface. Both approaches enable concurrent execution of
code, but they differ in their implementation details and use cases. Let’s discuss both methods
in detail.
1. Extending the Thread Class
To create a thread by extending the Thread class, you need to follow these steps:
1. Extend the Thread Class:
o Create a new class that extends the Thread class.
o Override the run() method to define the code that will be executed by the
thread.
2. Create an Instance and Start the Thread:
o Instantiate your custom thread class.
o Call the start() method on the thread instance to begin execution.
Example:
// File: MyThread.java
public class MyThread extends Thread {
@Override
public void run() {
// Code to be executed by the thread
for (int i = 0; i < 5; i++) {
System.out.println("Thread is running: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {


// Create an instance of the thread
MyThread thread = new MyThread();
// Start the thread
thread.start();
}
}
Explanation:
 The MyThread class extends Thread and overrides the run() method to specify the
task to be executed.
 In the main method, a MyThread instance is created and started. The start() method
internally calls the run() method in a new thread.
2. Implementing the Runnable Interface
To create a thread by implementing the Runnable interface, follow these steps:
1. Implement the Runnable Interface:
o Create a class that implements the Runnable interface.
o Implement the run() method to define the code to be executed by the thread.
2. Create a Thread Instance and Start It:
o Instantiate a Thread object, passing an instance of your Runnable
implementation to its constructor.
o Call the start() method on the Thread instance.
Example:
// File: MyRunnable.java
public class MyRunnable implements Runnable {
@Override
public void run() {
// Code to be executed by the thread
for (int i = 0; i < 5; i++) {
System.out.println("Runnable thread is running: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {


// Create an instance of MyRunnable
MyRunnable myRunnable = new MyRunnable();
// Create a Thread object and pass MyRunnable instance to it
Thread thread = new Thread(myRunnable);
// Start the thread
thread.start();
}
}
Explanation:
 The MyRunnable class implements the Runnable interface and provides the run()
method with the task to execute.
 In the main method, a MyRunnable instance is created and passed to a Thread object,
which is then started.
Comparison and Use Cases
 Extending Thread:
o Pros:
 Simpler when you have only one task to perform in the thread.
 Can be convenient for small or straightforward applications.
o Cons:
 Java supports single inheritance, so you cannot extend another class if
you extend Thread.
 Less flexible for complex applications that require multiple tasks or
need to inherit from other classes.
 Implementing Runnable:
o Pros:
 More flexible, allowing you to implement multiple interfaces or extend
other classes.
 Promotes better separation of concerns, as the task and thread
management are separate.
o Cons:
 Slightly more verbose, as you need to create an instance of Thread and
pass the Runnable instance to it.
Advanced Thread Creation
1. Using Callable and Future:
o Callable is similar to Runnable but can return a result and throw checked
exceptions.
o Future is used to obtain the result of a Callable and manage the task’s
execution.
Example:
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;

public class CallableExample {


public static void main(String[] args) {
Callable<Integer> callableTask = () -> {
Thread.sleep(1000);
return 123;
};

FutureTask<Integer> futureTask = new FutureTask<>(callableTask);


Thread thread = new Thread(futureTask);
thread.start();

try {
Integer result = futureTask.get(); // Retrieve result from the callable task
System.out.println("Result from callable: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
2. Using ExecutorService:
o Provides a higher-level replacement for managing threads and task execution
with a thread pool.

Example:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample {


public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);

Runnable task1 = () -> {


System.out.println("Task 1 is running");
};

Runnable task2 = () -> {


System.out.println("Task 2 is running");
};

executor.execute(task1);
executor.execute(task2);

executor.shutdown();
}}
5. Discuss about try, catch and finally keywords in Exception handling with an example.
In Java, the try, catch, and finally keywords are used to handle exceptions and ensure that
specific code is executed regardless of whether an exception occurs. These keywords form
the core of Java's exception handling mechanism, allowing developers to manage runtime
errors effectively.
Overview of try, catch, and finally
1. try Block:
o The try block contains code that might throw an exception. It is used to wrap
the code that you want to monitor for exceptions.
2. catch Block:
o The catch block is used to handle the exception thrown by the try block. You
can have multiple catch blocks to handle different types of exceptions. Each
catch block specifies a type of exception and provides a way to respond to that
exception.
3. finally Block:
o The finally block contains code that is executed after the try and catch blocks,
regardless of whether an exception was thrown or not. It is typically used for
cleaning up resources like closing files or releasing database connections.
Basic Syntax
try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
} finally {
// Code that will always be executed
}
Example: File Reading with Exception Handling
Here is an example that demonstrates the use of try, catch, and finally for handling exceptions
while reading from a file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReadingExample {


public static void main(String[] args) {
BufferedReader reader = null;

try {
// Attempt to open and read from the file
reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle file I/O exceptions
System.out.println("An error occurred while reading the file: " + e.getMessage());
} finally {
// Ensure the file reader is closed
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while closing the file: " +
e.getMessage());
}
}
}
}
}
Explanation
1. try Block:
o The try block attempts to open and read from a file using BufferedReader and
FileReader. If the file does not exist or there is an issue reading the file, an
IOException may be thrown.
2. catch Block:
o The catch block catches IOException if an error occurs during file reading. It
prints an error message to indicate the problem.
3. finally Block:
o The finally block ensures that the BufferedReader is closed, regardless of
whether an exception was thrown or not. This is important to prevent resource
leaks. If closing the reader itself throws an exception, it is caught and handled
inside another try-catch block within the finally block.
Key Points
 Execution Order:
o The finally block is always executed after the try block and any catch blocks,
even if no exception is thrown. It is not executed if the JVM shuts down or if
the thread executing the try block is terminated.
 Resource Management:
o The finally block is commonly used for resource management, such as closing
files, releasing database connections, or cleaning up resources.
 Multiple catch Blocks:
o You can have multiple catch blocks to handle different types of exceptions.
The order of catch blocks is important; more specific exceptions should be
caught before more general ones.
 Re-throwing Exceptions:
o If you need to re-throw an exception after handling it in the catch block, you
can use the throw keyword. This can be useful for logging exceptions and then
propagating them.
catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
throw e; // Re-throw the exception
}

PART C (1 x 15)
Case study 1:
create software departmental stores to maintain the following details like item_no,
item_description, requested quantity, cost price provide the options to upadate the stock
calculate the selling price(SP=CP*20%). Create an exception whenever the selling price
of item exceeds the given amount.
Custom Exception Class
Define a custom exception for handling cases where the selling price exceeds a specified
amount.
java
Copy code
// File: PriceExceededException.java
public class PriceExceededException extends Exception {
public PriceExceededException(String message) {
super(message);
}
}
Item Class
Create a class to represent an item and handle the required operations.
java
Copy code
// File: Item.java
public class Item {
private int item_no;
private String item_description;
private int requested_quantity;
private double cost_price;

public Item(int item_no, String item_description, int requested_quantity, double


cost_price) {
this.item_no = item_no;
this.item_description = item_description;
this.requested_quantity = requested_quantity;
this.cost_price = cost_price;
}

public int getItemNo() {


return item_no;
}

public String getItemDescription() {


return item_description;
}

public int getRequestedQuantity() {


return requested_quantity;
}

public void setRequestedQuantity(int requested_quantity) {


this.requested_quantity = requested_quantity;
}

public double getCostPrice() {


return cost_price;
}

public void setCostPrice(double cost_price) {


this.cost_price = cost_price;
}

public double calculateSellingPrice() {


return cost_price * 1.20; // Selling price = Cost price * 20%
}
public void validateSellingPrice(double maxAllowedPrice) throws
PriceExceededException {
if (calculateSellingPrice() > maxAllowedPrice) {
throw new PriceExceededException("Selling price exceeds the allowed maximum
price.");
}
}
}
Main Class
Implement the main class to interact with the user, update stock, and handle exceptions.
java
Copy code
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class DepartmentalStore {


private static final double MAX_ALLOWED_PRICE = 200.00; // Example maximum
price

private Map<Integer, Item> inventory = new HashMap<>();

public void addItem(Item item) {


inventory.put(item.getItemNo(), item);
}

public void updateStock(int item_no, int new_quantity) {


Item item = inventory.get(item_no);
if (item != null) {
item.setRequestedQuantity(new_quantity);
} else {
System.out.println("Item not found.");
}
}

public void displayItemDetails(int item_no) {


Item item = inventory.get(item_no);
if (item != null) {
System.out.println("Item No: " + item.getItemNo());
System.out.println("Description: " + item.getItemDescription());
System.out.println("Requested Quantity: " + item.getRequestedQuantity());
System.out.println("Cost Price: " + item.getCostPrice());
System.out.println("Selling Price: " + item.calculateSellingPrice());
} else {
System.out.println("Item not found.");
}
}

public void validateAndDisplaySellingPrice(int item_no) {


Item item = inventory.get(item_no);
if (item != null) {
try {
item.validateSellingPrice(MAX_ALLOWED_PRICE);
System.out.println("Selling Price for Item No " + item_no + " is " +
item.calculateSellingPrice());
} catch (PriceExceededException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("Item not found.");
}
}

public static void main(String[] args) {


DepartmentalStore store = new DepartmentalStore();
Scanner scanner = new Scanner(System.in);

// Sample data
store.addItem(new Item(1, "Laptop", 10, 150.00));
store.addItem(new Item(2, "Mouse", 50, 20.00));

while (true) {
System.out.println("Departmental Store Menu:");
System.out.println("1. Update Stock");
System.out.println("2. Display Item Details");
System.out.println("3. Validate and Display Selling Price");
System.out.println("4. Exit");
System.out.print("Choose an option: ");

int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter Item No: ");
int itemNoForUpdate = scanner.nextInt();
System.out.print("Enter New Quantity: ");
int newQuantity = scanner.nextInt();
store.updateStock(itemNoForUpdate, newQuantity);
break;
case 2:
System.out.print("Enter Item No: ");
int itemNoForDetails = scanner.nextInt();
store.displayItemDetails(itemNoForDetails);
break;
case 3:
System.out.print("Enter Item No: ");
int itemNoForValidation = scanner.nextInt();
store.validateAndDisplaySellingPrice(itemNoForValidation);
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid option. Please try again.");
}
}
}
}

Case Study 2:
Define Wrapper class. Give the following wrapper class method with syntax and use
1. To convert integer number of string
2. To convert numeric string to integer number
1. To convert integer number of string
In Java, the Integer wrapper class provides a method to convert a String to an int. The
Integer.parseInt(String s) method is used for this purpose. This method takes a String
argument and converts it into an int. It throws a NumberFormatException if the String is not
a valid representation of an integer.
Here's a detailed explanation and example of how to use this method:
Using Integer.parseInt(String s)
Method Signature
java
Copy code
public static int parseInt(String s) throws NumberFormatException
Parameters
 s: A String containing the integer representation to be parsed.
Returns
 An int representing the integer value of the specified String.
Throws
 NumberFormatException: If the String cannot be parsed as an integer.
Example Code
Here's an example that demonstrates how to use Integer.parseInt(String s) to convert a String
to an int:
java
Copy code
public class StringToIntegerExample {
public static void main(String[] args) {
try {
// Example 1: Converting a valid integer string
String numberStr = "12345";
int number = Integer.parseInt(numberStr);
System.out.println("Converted number: " + number); // Output: 12345

// Example 2: Converting a valid negative integer string


String negativeNumberStr = "-6789";
int negativeNumber = Integer.parseInt(negativeNumberStr);
System.out.println("Converted negative number: " + negativeNumber); // Output: -
6789

// Example 3: Handling invalid input


String invalidNumberStr = "123abc";
int invalidNumber = Integer.parseInt(invalidNumberStr); // This will throw
NumberFormatException
System.out.println("Converted invalid number: " + invalidNumber);

} catch (NumberFormatException e) {
System.out.println("Error: The provided string is not a valid integer.");
e.printStackTrace();
}
}
}
Explanation of the Code
1. Valid Integer String Conversion:
o String numberStr = "12345";
o int number = Integer.parseInt(numberStr);
o The parseInt method converts the string "12345" to the integer 12345.
2. Valid Negative Integer String Conversion:
o String negativeNumberStr = "-6789";
o int negativeNumber = Integer.parseInt(negativeNumberStr);
o The parseInt method correctly handles negative numbers and converts "-6789"
to the integer -6789.
3. Handling Invalid Input:
o String invalidNumberStr = "123abc";
o int invalidNumber = Integer.parseInt(invalidNumberStr);
o Since "123abc" is not a valid integer representation, parseInt throws a
NumberFormatException. This exception is caught and handled in the catch
block, where an error message is printed.

2. To convert numeric string to integer number


public class NumericStringToInteger {
public static void main(String[] args) {
try {
// Example 1: Using Integer.parseInt(String s)
String numericString1 = "12345";
int number1 = Integer.parseInt(numericString1);
System.out.println("Converted number using parseInt: " + number1);
// Output: 12345

// Example 2: Using Integer.valueOf(String s)


String numericString2 = "6789";
Integer number2 = Integer.valueOf(numericString2);
System.out.println("Converted number using valueOf: " + number2);
// Output: 6789

// Example 3: Using Integer.valueOf(String s, int radix)


String hexString = "1A";
int radix = 16;
Integer number3 = Integer.valueOf(hexString, radix);
System.out.println("Converted number using valueOf with radix: " + number3); //
Output: 26 (hexadecimal 1A is decimal 26)

// Example 4: Handling invalid input


String invalidString = "123abc";
int number4 = Integer.parseInt(invalidString);
// This will throw NumberFormatException
System.out.println("Converted invalid number: " + number4);

} catch (NumberFormatException e) {
System.out.println("Error: The provided string is not a valid integer.");
e.printStackTrace();
}
}
}

You might also like