Sei sulla pagina 1di 11

B.E.

Computer Science & Engineering


Batch-2018-2022

Assignment-1
Java Programming lab
CSP-279

Submitted by : Submitted to :

Yogesh Kumar Er. Jaspreet

18BCS1809 Assistant Professor (CSE)

CSE-8A
UNIT – 2 ASSIGNMENT-2(Set-6) JAVA PROGRAMMING (CST-254) 1. How do you share data between
two thread in Java? 2. What is the difference between notify( ) and notifyAll( ) in Java? 3. What is the
difference between the interrupted() and isInterrupted() method in Java? 4. Write code to solve
Producer Consumer problem in Java? 5. What class would you use to read a few pieces of data that
are at known positions near the end of a large file? 6. Why is Serialization required? What is the
need to Serialize? 7. Write a Program to demonstrate yield(),stop() and Sleep() method in java.

Q.1. What are the advantages of using exception handling?


Sol. Java provides a sophisticated exception handling mechanism that enables
you to detect exceptional conditions in your programs and fix the exceptions as
and when they occur. Using exception handling features offers several
advantages. Let’s examine these advantages in detail.

Provision to Complete Program Execution:One of the important purposes of


exception handling in Java is to continue program execution after an exception
is caught and handled.The execution of a Java program does not terminate when
an exception occurs. Once the exception is resolved, program execution
continues till completion.

By using well-structured try, catch, and finally blocks, you can create programs
that fix exceptions and continue execution as if there were no errors. If there is a
possibility of more than one exception, you can use multiple catch blocks to
handle the different exceptions.

Easy Identification of Program Code and Error-Handling Code: The use of


try/catch blocks segregates error-handling code and program code making it
easier to identify the logical flow of a program. The logic in the program code
does not include details of the actions to be performed when
an exception occurs. Such details are present in the catch blocks.
Unlike many traditional programming languages that include confusing error
reporting and error handling code in between the program code, Java allows you
to create well-organized code. Separating error handling and program logic in
this way makes it easier to understand and maintain programs in the long run.

Propagation of Errors: Java’s exception handling mechanism works in such a


way that error reports are propagated up the call stack. This is because
whenever an exception occurs, Java’s runtime environment checks the call stack
backwards to identify methods that can catch the exception.
When a program includes several calls between methods, propagation of
exceptions up the call stack ensures that exceptions are caught by the right
methods.

Meaningful Error Reporting: The exceptions thrown in a Java program are


objects of a class. Since the Throwable class overrides the toString() method,
you can obtain a description of an exception in the form of a string and display
the description using a println() statement.Traditional programming languages
use error codes for error reporting. In the case of large programs, debugging
errors using their error codes gets complex. The meaningful descriptions
provided by Java’s exception handling mechanism are helpful when you need to
debug large programs or experiment with complex code.
Identifying Error Types:Java provides several super classes and sub classes
that group exceptions based on their type. While the super classes
like IOException provide functionality to handle exceptions of a general type,
sub classes like FileNotFoundException provide functionality to handle specific
exception types

Q.2. What are the types of Exceptions in Java?


Sol. Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions. Two types of
exceptions in java are:
1. Buit-in-Exceptions
2. User-defined exception
Built-in Exceptions
Built-in exceptions are the exceptions which 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. Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic
operation.
2. Array Index Out Of Bounds Exception
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. Class Not Found Exception
This Exception is raised when we try to access a class whose definition is
not found
4. File Not Found Exception
This Exception is raised when a file is not accessible or does not open.
5. IO Exception
It is thrown when an input-output operation failed or interrupted
6. Interrupted Exception
It is thrown when a thread is waiting , sleeping , or doing some processing ,
and it is interrupted.
7. No Such Field Exception
It is thrown when a class does not contain the field (or variable) specified
8. No Such Method Exception
It is thrown when accessing a method which is not found.
9. Null Pointer Exception
This exception is raised when referring to the members of a null object.
Null represents nothing
10.Number Format Exception
This exception is raised when a method could not convert a string into a
numeric format.
11.Run time Exception
This represents any exception which occurs during runtime.
12.String Index Out Of Bounds Exception
It is thrown by String class methods to indicate that an index is either
negative than the size of the string

User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, user can also create exceptions which are called ‘user-
defined Exceptions’.

Q.3. What is the difference between exception and error?


Sol.

ERRORS EXCEPTIONS

We can recover from exceptions

by either using try-catch block or

Recovering from Error is not throwing exceptions back to

possible. caller.
Exceptions include both checked

All errors in java are unchecked type. as well as unchecked type.

Errors are mostly caused by the

environment in which program is Program itself is responsible for

running. causing exceptions.

All exceptions occurs at runtime

but checked exceptions are known

Errors occur at runtime and not to compiler while unchecked are

known to the compiler. not.

They are defined in java.lang.Error They are defined in

package. java.lang.Exception package

Examples :

Checked Exceptions : SQL

Exception, IO Exception

Unchecked Exceptions : Array

Examples : Index Out Of Bound Exception,

java.lang.StackOverflowError, Null Pointer Exception,

java.lang.OutOfMemoryError Arithmetic Exception.

Q.4. What are the different ways to handle exceptions?


Sol. Java provides specific keywords for exception handling purposes, we will
look after them first and then we will write a simple program showing how to
use them for exception handling.

1. throw – We know that if any exception occurs, an exception object is


getting created and then Java runtime starts processing to handle them.
Sometime we might want to generate exception explicitly in our code, for
example in a user authentication program we should throw exception to
client if the password is null. throw keyword is used to throw exception to
the runtime to handle it.
2. throws – When we are throwing any exception in a method and not
handling it, then we need to use throws keyword in method signature to
let caller program know the exceptions that might be thrown by the
method. The caller method might handle these exceptions or propagate it
to it’s caller method using throws keyword. We can provide multiple
exceptions in the throws clause and it can be used with main() method
also.
3. try-catch – We use try-catch block for exception handling in our code. try
is the start of the block and catch is at the end of try block to handle the
exceptions. We can have multiple catch blocks with a try and try-catch
block can be nested also. catch block requires a parameter that should be
of type Exception.
4. finally – finally block is optional and can be used only with try-catch
block. Since exception halts the process of execution, we might have some
resources open that will not get closed, so we can use finally block. finally
block gets executed always, whether exception occurred or not.

Q.5. Write a Java program to test if an array contains a specific value.


Sol. class specificvalue {
public static boolean contains(int[] arr, int item) {
for (int n : arr) {
if (item == n) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2265, 1457, 2456};
System.out.println(contains(my_array1, 2013));
System.out.println(contains(my_array1, 2015));
}
}
Output:

Q.6.Write a Java program to find the index of an array element.


Sol. class Index {
public static int findIndex (int[] my_array, int t) {
if (my_array == null) return -1;
int len = my_array.length;
int i = 0;
while (i < len) {
if (my_array[i] == t) return i;
else i=i+1;
}
return -1;
}
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
System.out.println("Index position of 25 is: " + findIndex(my_array,
25));
System.out.println("Index position of 77 is: " + findIndex(my_array,
77));
}
}
Output:

Q.7. Write a Java program to copy an array by iterating the array.


Sol. import java.util.Arrays;
class copyArray {
public static void main(String[] args) {
int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
int[] new_array = new int[10];

System.out.println("Source Array : "+Arrays.toString(my_array));

for(int i=0; i < my_array.length; i++) {


new_array[i] = my_array[i];
}
System.out.println("New Array: "+Arrays.toString(new_array));
}
}
Output:
Q.8. Write a Java program that accepts two integers from the user and
then prints the sum, the difference, the product, the average, the distance
(the difference between integer), the maximum (the larger of the two
integers), the minimum (smaller of the two integers).
Sol. import java.util.Scanner;
class calculator {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input 1st integer: ");
int firstInt = in.nextInt();
System.out.print("Input 2nd integer: ");
int secondInt = in.nextInt();

System.out.printf("Sum of two integers: %d%n", firstInt + secondInt);


System.out.printf("Difference of two integers: %d%n", firstInt -
secondInt);
System.out.printf("Product of two integers: %d%n", firstInt * secondInt);
System.out.printf("Average of two integers: %.2f%n", (double) (firstInt +
secondInt) / 2);
System.out.printf("Distance of two integers: %d%n", Math.abs(firstInt -
secondInt));
System.out.printf("Max integer: %d%n", Math.max(firstInt, secondInt));
System.out.printf("Min integer: %d%n", Math.min(firstInt, secondInt));
}
}
Output:

Q.9. Write program to explain abstract classes and methods.


abstract class A
{ abstract void callme(); }
class B extends A
{ void callme()
{ System.out.println("this is callme."); }
public static void main(String[] args)
{ B b = new B(); b.callme(); } }
Output:

Q.10. What are reflection byte codes.


Sol. Java compiler produces an intermediate code known as byte code for a
machine, known as JVM.
Reflection is an API which is used to examine or modify the behavior of methods,
classes, interfaces at runtime.
 The required classes for reflection are provided under java.lang.reflect
package.
 Reflection gives us information about the class to which an object belongs
and also the methods of that class which can be executed by using the object.
 Through reflection we can invoke methods at runtime irrespective of the
access specifier used with them.

Reflection can be used to get information about –


1. Class The getClass() method is used to get the name of the class to which
an object belongs.
2. Constructors The getConstructors() method is used to get the public
constructors of the class to which an object belongs.
3. Methods The getMethods() method is used to get the public methods of
the class to which an objects belongs.

Potrebbero piacerti anche