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

➢ Interface. • Java does not support multiple inheritance.

ritance. That is, classes in java can not have more than one super class. • Java provides How to compare two objects? >To compare two objects in Java, you can use the equals() method. The equals() method is a method inherited
an alternate approach known as interface to support the concept of multiple inheritance. • Although a java can not be a sub class of more than from the Object class, and can be overridden by any class to specify custom comparison logic.
one super class, it can implement more than one interface. >Here's an example of using the equals() method to compare two String objects:
String str1 = "hello"; String str2 = "world"; String str3 = "hello";
❖ Defining an interface : • An interface is basically a kind
of class. • Like classes, interfaces contain methods and variables ➢ Partially implemented interface. • If a class includes an interface boolean equal1and2 = str1.equals(str2); // false
but does not fully implement the methods defined by that interface, boolean equal1and3 = str1.equals(str3); // true
but with a major difference. • The difference is that interfaces
then that class must be declared as abstract. • E.g. What is difference between equals() and ==? >In Java, equals() and == are two different operators used for different purposes.
define only abstract methods and final fields/variables. • This
abstract class incomplete implements callback >The == operator is used to compare the memory addresses of two objects. When you use == to compare two objects, you are checking if they
means that interfaces do not specify any code to implement these
{ int a,b; void show() are the exact same object in memory. In other words, == checks for reference equality. >Here's an example:
methods and data fields contain only constants. • Therefore, it is
{ System.out.println(a+” “+b); String str1 = "hello"; String str2 = "hello"; boolean equalByReference = (str1 == str2); // true
the responsibility of the class that implements an interface to
} abstract public void callback_meth(int p); >On the other hand, the equals() method is used to compare the contents of two objects. When you use equals() to compare two objects, you
define the code for implementation of these methods. • So, the
} class compl extends incomplete are checking if they have the same values. The equals() method is often overridden in Java classes to provide custom comparison logic. Here's
class that implements interface must define the code for the
{ public void callback_meth(int p) an example: String str1 = "hello"; String str2 = "world"; String str3 = "hello";
methods.• Syntax:
{ System.out.println(“Method of demo_in”); boolean equal1and2 = str1.equals(str2); // false boolean equal1and3 = str1.equals(str3); // true
interface <interface_name>
System.out.println(“Callback called with “ + (p*p*p)); } } What do you mean by immutable object? Explain with example. >>In Java, an immutable object is an object that cannot be modified once
{ Variable declaration;
Method declaration; } ➢ Extending Interface / Interface Inheritance. • Like classes, it is created. Any attempt to modify the state of an immutable object results in the creation of a new object. Immutable objects are useful
interfaces can also be extended. • That is, interface can be because they are thread-safe and can be safely shared across threads without the risk of unexpected changes. >Here is an example of an
• All the variables in an interface are treated as constants although
subinterfaced from other interfaces. • The new subinterface will immutable class in Java:
the keyword final and static are not present. • Methods are abstract
inherit all the members of the superinterface in the manner similar public class ImmutableStringExample { Write difference between length() and length. >>In Java, length() is a method that is used to
methods, there can be no default implementation of any method
to subclasses. • This is achieved using the keyword extends.•Syntax : public static void main(String[] args) { find the length of a string, while length is a property of an array that is used to find the number
specified within an interface. • So, methods declaration will contain
interface <interface_name> extends <interface_name>, String s1 = "hello"; of elements in the array. Here are some key differences between the two:
only a list of methods without any body of statements.
<interface_name> String s2 = s1.concat(" world"); >length() is a method of the String class, while length is a property of the array data type.
Return_type method_name(parameter list); • So, here each class
that includes an interface must implement all of the methods. • E.g. { Body of interface. } >length() returns the number of characters in a string, while length returns the number of
• An interface can extend another interface, which is called interface System.out.println("s1 = " + s1); elements in an array.
interface callback
inheritance. When an interface extends another interface, it inherits System.out.println("s2 = " + s2); >length() is a method call, which means that it requires the use of parentheses, while length is
{ void callback_meth(int param); }
all of the abstract methods and constants from the parent interface. // s1 remains unchanged simply a property access, which means that it does not require parentheses.
❖ Implementing interface : • Once an interface has been defined,
interface Animal { System.out.println("s1 = " + s1); >length() can be called on any string object, while length can only be used with arrays.
one or more classes can implement that interface. • To implement
void eat(); } >>Here is an example to illustrate the difference:
an interface, include the implements clause in a class definition,
} interface Mammal extends Animal { } String myString = "Hello, world!";
and then create the methods defined by the interface. • Syntax:
void run(); Output : int[] myArray = {1, 2, 3, 4, 5};
class <class_name> implements <interface1>,<interface2>,….
} class Dog implements Mammal { Original string: hello int stringLength = myString.length(); // Returns 13
{ //Class body }
public void eat() { Modified string: hello world int arrayLength = myArray.length; // Returns 5
• If class implements more than one interface, than interfaces
System.out.println("Dog is eating"); Original string after modification: hello
are separated with a comma. • E.g.
} public void run() { Differentiate checked and unchecked exception.
class client implements callback
System.out.println("Dog is running"); } >In Java, there are two types of exceptions: checked exceptions and unchecked exceptions.
{ Must → public void callback_meth(int p)
} public class Main { Checked Exceptions: >>Checked exceptions are the exceptions that the compiler forces the programmer to handle. They are also called
{ System.out.println(“Callback called with “ +p);
public static void main(String[] args) { compile-time exceptions. Checked exceptions are thrown by the methods that are declared with the throws keyword in their signature. S ome
} void nonifacemeth()
Dog myDog = new Dog(); examples of checked exceptions include IOException, SQLException, ClassNotFoundException, etc.
{ System.out.println(“Other method”); }
myDog.eat(); Unchecked Exceptions:>>Unchecked exceptions are also called runtime exceptions. These exceptions occur at runtime and are not checked by
} class anotherclient implements callback
myDog.run(); } } the compiler. Some examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException,
{ Must → public void callback_meth(int p)
Output : Dog is eating Dog is running etc. >>In summary, the main difference between checked and unchecked exceptions is that checked exceptions are checked at compile-time
{ System.out.println(“Another version of callback”);
and must be handled or propagated, while unchecked exceptions occur at runtime and do not need to be handled or declared.
System.out.printn(“p squaed is :”+(p*p)); } }
What type of exceptions must be caught or declared? >>Checked exceptions must be caught or declared.
• Here, these classes also defined additional members of their own.
>Checked exceptions are the exceptions that are checked at compile-time, meaning the compiler will check if the code handles the exception or
❖ Accessing methods through interface references – • You can declare variables as object references that use an interface rather than a class not. If the code does not handle the exception, it will not compile. Examples of checked exceptions include IOException, SQLException, and
type. • Any instance of any class that implements the declared interface can be referred to by such a variable. • When you call a method ClassNotFoundException. >On the other hand, unchecked exceptions do not need to be caught or declared. Unchecked exceptions are
through one of these references, the correct version will be called based on the actual instance of the interface being retrieved to. • E.g. runtime exceptions that occur at the time of execution and are not checked by the compiler. Examples of unchecked exceptions include
class p38_interfacedemo NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
{ public static void main(String args[]) Give different ways of creating string object.
{ callback c; >>There are different ways to create a string object in Java:
client ob1=new client(); c=ob1; 1. String literal: String can be created by directly assigning a value to it, using double quotes. For example: String str = "Hello";
c.callback_meth(42); Call method of client class 2. Using the new keyword: String can also be created by using the new keyword and invoking the String constructor. For exampl e:
c.nonifacemeth(); not valid because not a method of callback interface String str = new String("Hello"); 3. Using the char array: String can be created by using a char array and invoking the String constructor. For
anotherclient ob2=new anotherclient(); c=ob2; example: char[] charArray = {'H', 'e', 'l', 'l', 'o'};
c.callback_meth(4); call method of anotherclient class } } String str = new String(charArray);
→ Advantages of Interface : 1) Through interfaces we can implement multiple inheritances in java. 2) Interfaces function to break up the 4. Using the StringBuffer or StringBuilder class: String can also be created by using the StringBuffer or StringBuilder class. For example:
complex designs and clear the dependencies between objects. 3) Interfaces make your application loosely coupled. 4) Interfaces are mainly StringBuffer buffer = new StringBuffer("Hello");
used to provide polymorphic behavior. ➢ Class Vs Interface. String str1 = buffer.toString();
Class 1. We can create an object of the class. 2. A class have simple member variable and method. 3. Methods in class have body part. 4. It is StringBuilder builder = new StringBuilder("World");
not necessary to inherit the class. String str2 = builder.toString();
Interface 1. We can not create an object of an interface. 2. An interface have only final member variable and abstract methods in it. 3. There is
only declaration of method in an interface. 4. But to implement all methods defined in interface, it is necessary to implement the interface.

Exception handling in java. >Exception handling is a mechanism in Java that enables you to handle runtime errors that may occur ➢ Thread. • A multithreaded program contains two or more parts that can run concurrently. • Each part of such a program is called a
during program execution. Exceptions are objects that are thrown by the Java Virtual Machine (JVM) or explicitly by your program when an thread and each thread defines a separate path of execution. • Thread is a lightweight sub process, a smallest unit of processing. • They are
error occurs. >Java provides a set of keywords and constructs to handle exceptions. The basic construct for exception handling is the try-catch independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area. • In a thread based
block. The try block contains the code that may throw an exception, and the catch block catches the exception and handles it appropriately. multitasking, the thread is the smallest unit of dispatchable code. • This means that a single program can perform two or more tasks
>The general syntax for the try-catch block is as follows: simultaneously. • E.g. In Ms word, you can do printing into the background and continue to perform other task in word document.
try { >// code that may throw an exception >} catch (ExceptionType1 e1) { >// exception handler for ExceptionType1
➢ main thread. • When a java program starts up, one thread begins running immediately. This is usually called main thread because it
} catch (ExceptionType2 e2) { > // exception handler for ExceptionType2 > } finally {
is executed when your program begins. • The main thread is the tread f rom which other child threads will be created. • The main thread must
// optional block of code that is executed regardless of whether an exception is thrown or not >}
be the last thread to finish execution because it performs various shut down actions.
>The try block contains the code that may throw an exception. If an exception is thrown, it is caught by the appropriate catch block. Multiple
catch blocks can be specified to handle different types of exceptions. >The finally block is optional and contains code that is executed ➢ Advantages of using threads. 1) It doesn't block the user because threads are independent and you can perform multiple
regardless of whether an exception is thrown or not. This block is often used to release resources that were acquired in the try block. operations at same time. 2) You can perform many operations together so it saves time. 3) Threads are independent so it doesn't affect other
>Java provides a number of built-in exception classes, such as NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, threads if exception occurs in a single thread. 4) It improves performance and concurrency. 5) It simplifies the coding of remote procedure calls.
and IOException, among others. You can also create your own exception classes by extending the Exception class. ➢ Life cycle of Thread. OR States of thread. • During the life time of a thread, there are many states it can enter. • They
>Here is an example of exception handling in Java: include: 1. New born state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state
public class ExceptionExample { >public static void main(String[] args) { • A thread is always in one of these five states. 1. New born state – • When we create a thread object, the thread is born and is said to be in
try { > int x = 5 / 0; // division by zero new born state. • The thread is not yet scheduled for running. • At this state, we can do only one of the following things with it. (1) Schedule it
} catch (ArithmeticException e) { > System.out.println("Caught arithmetic exception: " + e.getMessage()); for running using start() method. (2) Kill it using stop() method. • If scheduled, it moves to the runnable state. 2. Runnable State – • The
} finally { > System.out.println("Inside finally block"); } } } runnable state means that the thread is ready for execution and is waiting for the availability of the processor. • That is, the thread has joined
Output: >Caught arithmetic exception: / by zero >Inside finally block the queue of threads that are waiting for execution. • If all threads have equal priority, then they are given time slots for execution in round
Discuss about try, catch and finally blocks with example.>In Java, try, catch and finally blocks are used for exception handling. robin fashion i.e. first come, first serve manner. • The thread that relinquishes control, joins the queue at the end and again waits for its turn. •
The try block contains the code that may throw an exception. If an exception is thrown, it is caught by the catch block, which handles the However, if we want a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by using the yield()
exception. The finally block is executed regardless of whether an exception is thrown or caught. It is used for cleaning up resources, closing method. 3. Running State – • Running means that the processor has given its time to the thread for its execution. • The thread runs until it
connections or files, etc. >Here is an example that demonstrates the use of try, catch, and finally blocks: relinquishes control on its own or it is preempted by a higher priority thread. • The running thread may relinquishes its control in one of the
import java.util.Scanner; >public class ExceptionExample { > public static void main(String[] args) { following situations : (1) It has been suspended using suspend() method. A suspended thread can be revived by using the resume() method.
Scanner sc = new Scanner(System.in); >try { > System.out.println("Enter two integers:"); >int num1 = sc.nextInt(); This approach is useful when we want to suspend a thread for some time due to some reason, but don’t want to kill it. (2) It has been made to
int num2 = sc.nextInt(); > int result = num1 / num2; > System.out.println("Result: " + result); sleep. We can put a thread to sleep for a specified time period using the method sleep(time) where time is in milliseconds. This meansthat the
} catch (ArithmeticException e) { > System.out.println("Exception caught: " + e.getMessage()); thread is out of the queue during this time period. The thread re-enters the runnable state as soon as this period is elapsed. (3) It has been told
} finally { > System.out.println("Closing scanner..."); > sc.close(); } } } to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method. 4.
Output: Enter two integers: 10 >0 >Exception caught: / by zero >Closing scanner... Blocked State – • A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state.
What is exception ? Explain user defined exception with example. >An exception in Java is an event that occurs during the • This happens when the thread is suspended, sleeping or waiting. • A blocked thread is considered “not runnable” but not dead and therefore
execution of a program and disrupts the normal flow of the program's instructions. When an exception occurs, it may be handled by the fully qualified to run again. 5. Dead State – • Every thread has a life cycle. • A running thread ends its life when it has completed execution its
program using the try-catch-finally block. >In Java, we can create our own exceptions that are specific to our application or problem run() method. It is natural death. • However, we can kill it by sending the stop() message to it at any state thus causing a premature death to it.
domain. These exceptions are known as user-defined exceptions. >To create a user-defined exception in Java, we need to extend the A thread can be killed as soon as it is born or while it is running or even when it is in “not runnable” (blocked) condition.
Exception class or any of its subclasses. We can define our own fields and methods in our custom exception class to provide a dditional ➢ isAlive( ) and join( ) methods. • The main thread always finished last. This is accomplished by calling sleep() within main().
information about the exception. >Here is an example of a user-defined exception in Java: • But it is not always the case because how can one thread know when another thread has ended. • For this, two ways exist to know whether a
public class InvalidAgeException extends Exception { > public InvalidAgeException(String message) { > super(message); } } thread has finished. 1. isAlive() method – • You can call isAlive() on the thread. This method is defined by Thread. • Syntax : final Boolean
Example >public class Example { > public static void main(String[] args) { isAlive() • The isAlive() method returns true if the thread upon which it is called is still running. It returns false otherwise. • But this method is
try { > int age = Integer.parseInt(args[0]); > if (age < 0 || age > 120) { >throw new InvalidAgeException("Invalid age: " + age); occasionally useful. 2. join() method – • The commonly used method that wait for a thread to finish is join() method. • Syntax : final void join()
} >System.out.println("Valid age: " + age); > } catch (InvalidAgeException e) { throws InterruptedException • This method waits until the thread on which it is called terminates. • Its name come f rom the concept of the
System.out.println("Caught invalid age exception: " + e.getMessage()); calling thread waiting until the specified thread joins it. • Example :
} catch (NumberFormatException e) { > System.out.println("Invalid input: " + e.getMessage()); public class MyThread extends Thread { > private String threadName; > public MyThread(String threadName) {
} finally { > System.out.println("End of program."); } } } > this.threadName = threadName; > }
Output >>Caught MyException: This is a custom exception message > public void run() { > System.out.println("Thread " + threadName + " is running."); > try { > Thread.sleep(5000);
What is the way to handle exception? Which can not be caught by catch block? > } catch (InterruptedException e) { > System.out.println("Thread " + threadName + " was interrupted."); }
>There are different ways to handle exceptions in Java. One way is to use the try-catch-finally blocks to catch the exception and perform some System.out.println("Thread " + threadName + " is finished."); } }
action based on it. Another way is to declare the exception using the throws keyword, indicating that the method can throw a certain type of public class Main { > public static void main(String[] args) { > MyThread thread1 = new MyThread("Thread 1"); > thread1.start();
exception and leaving the responsibility of handling it to the calling method. > MyThread thread2 = new MyThread("Thread 2"); > thread2.start(); > // Wait for both threads to finish
>There is an exception called "Error" that cannot be caught by catch blocks. Errors are usually caused by serious problems in the JVM or try { > thread1.join(); > thread2.join(); > } catch (InterruptedException e) { > System.out.println("Main thread was
hardware, such as OutOfMemoryError or StackOverflowError. These types of exceptions are not recoverable and should not be handled by the interrupted."); } > // Check if the threads are alive > System.out.println("Thread 1 is alive: " + thread1.isAlive());
program. Instead, they should be allowed to propagate up the call stack and be handled by the system. > System.out.println("Thread 2 is alive: " + thread2.isAlive()); > System.out.println("Main thread is finished."); } }
What is difference between user defined exceptions and system exceptions? Output Thread 1 is running. >Thread 2 is running. >Thread 1 is finished. >Thread 2 is finished.
>>User-defined exceptions are exceptions that are created by the programmer to handle specific error conditions in their code. These >Thread 1 is alive: false >Thread 2 is alive: false >Main thread is finished.
exceptions are created by extending the Exception class or one of its subclasses. User-defined exceptions can be checked or unchecked, ➢ Packages Vs. Interfaces.
depending on the type of exception that they extend. >Packages is a group of classes and/or interfaces together.> Packages are created using "Package" keyword.> package package_name; public
>>System exceptions are exceptions that are provided by the Java runtime environment to handle errors that occur at the system level. class class_name { . (body of class) . } > A package can be imported.> Packages can be imported using "import" keyword.
Examples of system exceptions include NullPointerException and ArrayIndexOutOfBoundsException. These exceptions are unchecked, and the > Interfaces is a group of abstract methods and constant fields.> Interface are created using "Interface" keyword. > interface interface_name {
programmer is not required to handle them using try-catch blocks. variable declaration; method declaration; } > An interface can be extended by another interface and implemented by the class. > Interfaces can
be implemented using "implement" keyword.
Explain String class along with its methods with example. >>In Java, the String class is used to represent a sequence of Give the difference between throw and throws clause.>throw and throws are two different concepts in Java Exception Handling:
characters. It is one of the most commonly used classes in Java and is part of the java.lang package, which means it is automatically imported in >throw is a keyword in Java which is used to explicitly throw an exception from a method or block of code. When you use throw keyword, you
every Java program. The String class is immutable, which means that once a String object is created, its value cannot be changed. specify the type of exception that you want to throw, followed by an object that represents the exception.
>Here are some commonly used methods of the String class along with their brief explanations and examples: >throws is used in the method signature to indicate that the method may throw one or more types of exceptions. It specifies the types of
1. length(): Returns the length of the string. String str = "Hello"; int len = str.length(); // len will be 5 exceptions that a method may throw, but does not actually throw an exception. Instead, it delegates the responsibility of handling the
2. charAt(int index): Returns the character at the specified index. String str = "Hello"; char ch = str.charAt(1); // ch will be 'e' exception to the calling method or the JVM. >>Here are the differences between throw and throws:
3. substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string. The substring begins at the specified beginIndex >Usage: throw is used inside the method or block of code to throw an exception, whereas throws is used in the method signature to declare
and extends to the character at index endIndex - 1. String str = "Hello World"; String substr = str.substring(6, 11); // substr will be "World" the type of exceptions that a method can throw.
4. toUpperCase(): Returns a new string that is all uppercase. String str = "Hello"; String upper = str.toUpperCase(); // upper will be "HELLO" >Functionality: throw is used to throw an exception manually, whereas throws is used to specify the type of exceptions that a method may
5. toLowerCase(): Returns a new string that is all lowercase. String str = "HELLO"; String lower = str.toLowerCase(); // lower will be "hello" throw, without actually throwing an exception.
6. equals(Object obj): Returns true if the specified object is equal to this string. String str1 = "Hello"; String str2 = "hello"; >Responsibility: When you use throw, the responsibility of handling the exception is with the caller of the method, whereas when you use
boolean equal = str1.equals(str2); // equal will be false throws, the responsibility of handling the exception is with the calling method or the JVM.
7. equalsIgnoreCase(String anotherString): Returns true if the specified string is equal to this string, ignoring case differences. >Syntax: The throw keyword is followed by the instance of an exception, while throws is followed by the type of exception that may be thrown
String str1 = "Hello"; String str2 = "hello"; boolean equal = str1.equalsIgnoreCase(str2); // equal will be true by a method. >>Example of using throw:
8. indexOf(int ch): Returns the index within this string of the first occurrence of the specified character. public void divide(int a, int b) {
String str = "Hello World"; int index = str.indexOf('o'); // index will be 4 if (b == 0) {
9. replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. throw new ArithmeticException("Division by zero is not allowed");
String str = "Hello World"; String replaced = str.replace('o', '0'); // replaced will be "Hell0 W0rld" }
These are just a few examples of the many methods available in the String class. By utilizing these methods, you can manipulate and analyze int result = a / b;
strings in a variety of ways. Explain various constructors of String class with examples. >>The String class in Java provides System.out.println("Result = " + result);
several constructors for creating String objects. Here are the various constructors of the String class along with their examples: } >>Example of using throws:
1. String(): This constructor creates an empty string. Example: String str = new String(); System.out.println(str); // Output: "" public void readFile(String fileName) throws IOException {
2. String(String original): This constructor creates a new string that contains the same character sequence as the specified string. Exa mple: File file = new File(fileName);
String str1 = new String("Hello"); String str2 = new String(str1); System.out.println(str2); // Output: "Hello" FileInputStream fis = new FileInputStream(file);
3. String(char[] value): This constructor creates a new string that contains the same characters as the specified character array. Example: // Code to read from file
char[] charArray = {'H', 'e', 'l', 'l', 'o'}; String str = new String(charArray); System.out.println(str); // Output: "Hello" } Explain with example any three inbuilt Exceptions and any three inbuilt methods of exception provided by
4. String(char[] value, int offset, int count): This constructor creates a new string that contains the same characters as the specified subarray of Exception class. Three inbuilt exceptions:
the character array. Example: char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}; 1. NullPointerException: This exception is thrown when a null reference is used in a method or an operation. For example:
String str = new String(charArray, 0, 5); System.out.println(str); // Output: "Hello" String str = null;
5. String(StringBuffer buffer): This constructor creates a new string that contains the same character sequence as the specified StringBuffer. System.out.println(str.length()); // This will throw a NullPointerException
Example: StringBuffer buffer = new StringBuffer("Hello"); String str = new String(buffer); System.out.println(str); // Output: "Hello" 2. ArrayIndexOutOfBoundsException: This exception is thrown when an array is accessed with an invalid index. For example:
6. String(StringBuilder builder): This constructor creates a new string that contains the same character sequence as the specified StringBuilder. int[] arr = new int[5];
Example: StringBuilder builder = new StringBuilder("Hello"); String str = new String(builder); System.out.println(str); // Output: "Hello" System.out.println(arr[6]); // This will throw an ArrayIndexOutOfBoundsException
Write a short note on String Buffer class and its methods with example. >In Java, StringBuffer class is used to create 3. IOException: This exception is thrown when an input or output operation fails. For example:
mutable strings, which means that the content of the string can be modified after it is created. The StringBuffer class provides several methods try {
for appending, inserting, and deleting characters in the string.>Here's an example of how to use StringBuffer class and its methods: FileReader fileReader = new FileReader("file.txt");
// Creating a StringBuffer object with initial capacity of 16 >StringBuffer sb = new StringBuffer(); } catch (IOException e) {
// Appending a string to the buffer >sb.append("Hello"); // Inserting a string at a specific position in the buffer >sb.insert(5, " World"); System.out.println("Error reading file: " + e.getMessage());
// Replacing a portion of the string in the buffer >sb.replace(0, 5, "Hi"); // Deleting a portion of the string in the buffer >sb.delete(2, 4); }
// Converting the StringBuffer to a String >String str = sb.toString(); System.out.println(str); // Output: Hi lo World Three inbuilt methods of Exception class:
>In the above example, we first create a StringBuffer object with an initial capacity of 16. We then use the append() method to add the string 1. getMessage(): This method returns the message associated with the exception.
"Hello" to the buffer.>Next, we use the insert() method to insert the string " World" at position 5 in the buffer. This results in the string "Hello try {
World" being stored in the buffer.>We then use the replace() method to replace the first 5 characters of the string with "Hi" . This results in the int x = 5 / 0;
string "Hi World" being stored in the buffer.>Next, we use the delete() method to delete characters 2 through 4 of the string. This results in the } catch (ArithmeticException e) {
string "Hi lo World" being stored in the buffer.>Finally, we convert the StringBuffer object to a String using the toString() method and print it to System.out.println(e.getMessage()); // This will print " / by zero"
the console. >Some other useful methods of the StringBuffer class include reverse(), which reverses the order of the characters in the string, }
and capacity(), which returns the current capacity of the buffer. 2. printStackTrace(): This method prints the stack trace of the exception.
What is difference between String() and StringBuffer() class? >The main difference between the String and StringBuffer classes try {
is that String objects are immutable, while StringBuffer objects are mutable. >When a String object is created, it cannot be modified. If any int x = 5 / 0;
modification is done to the string, a new String object is created. On the other hand, a StringBuffer object can be modified, as it has methods to } catch (ArithmeticException e) {
append, insert, or delete characters in the existing string. >Here's an example to illustrate the difference: e.printStackTrace();
String str = "Hello"; // create a new String object }
str = str + " World"; // this creates a new String object 3. toString(): This method returns a string representation of the exception.
StringBuffer sb = new StringBuffer("Hello"); // create a new StringBuffer object try {
sb.append(" World"); // modify the existing StringBuffer object int x = 5 / 0;
>In the above code, when the + operator is used with String objects, a new String object is created. However, when the append() method is } catch (ArithmeticException e) {
used with a StringBuffer object, the existing object is modified. System.out.println(e.toString()); // This will print "java.lang.ArithmeticException: / by zero"
>In summary, use String when you need an immutable sequence of characters, and use StringBuffer when you need a mutable sequence of }
characters.

➢ Methods of Thread class. • The Thread class defines several methods that help to manage threads. 1. getName() – o Syntax : ➢ Package. • A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space
String getName(); o To obtain the name of a thread. 2. setName() – o Syntax : void setName(String thread_name); o To change the name of a management. ➢ Java API packages. • Java API provides a large number of classes grouped into different packages according to functionality.
thread. 3. getPriority() – o Syntax : int getPriority() o To obtain thread’s priority. 4. setPriority() – o Syntax : void setPriority(int priority); o To set • Java API packages are : 1. java.lang → language support classes. 2. java.util → language utility classes. 3. java.io → input / output support
thread’s priority. 5. sleep() – o Syntax : void sleep(long milliseconds) throws InterruptedException o To suspend a thread for the specified classes. 4. java.awt → classes for implementing graphical user interface. 5. java.net → classes for networking. 6. java.applet → classes for
period of time in milliseconds. This method throw Interrupted Exception, which must be caught. 6. start() – o Syntax : void start(); o To start a creating and implementing applets.
thread by calling its run method. 7. run() – o Syntax : void run(); o It is the entry point for the thread. 8. isAlive() – o Syntax : Boolean isAlive(); o
➢ Package types and benefits. • If we need to use classes from other programs, without physically copying them into the program. •
It returns true if the thread upon which it is called, is still running, it returns false otherwise. 9. Join() – o Syntax : void join() throws
This is accomplished in Java by using the concept of Packages, which is similar to “Class Libraries”. • Using packages, we can also achieve
InterruptedException o This method waits until the thread on which it is called, terminates. It is used to wait for a thread to finish.
reusability. • Packages are java’s way of grouping a variety of classes and interfaces together. • Packages act as “Containers” for classes. • Java
➢ Different ways of creating thread. • Java defines two ways by which a thread can be created. 1. By implementing the Runnable packages are classified into two types : 1. Java API / built in packages 2. User defined packages
interface. 2. By extending the Thread class. 1. Implementing the Runnable Interface • The easiest way to create a thread is to create ❖ Significances / Benefits of Package :- 1. The classes contained in the packages of other programs can be easily reused. 2. In
a class that implements the Runnable interface. • After implementing runnable interface, the class needs to implement the run() method, packages, classes can be unique compared with class in other packages. That is, two classes in two different packages can have the same na me.
which is of form, public void run() • Inside run(), you will define the code that constitutes the new thread. • Run() establishes the entry point They may be referred by their fully qualified name, comprising the package name and the class name. 3. Packages provide a way to “hide”
for another concurrent thread of execution within your program. • This thread will end when run() method terminates. • Af ter you create a classes thus preventing other programs or packages from accessing classes that are meant for internal use only. ➢ User Defined Package. • To
class that implements Runnable, you will instantiate an object of type Thread from within that class. Thred(Runnable threadOb, String create a package, at first declare the name of the package using the ‘package’ keyword followed by a package name. This must be the first
threadname) • Here, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will statement in a Java source file. • Then we define a class, just as we normally define a class. • If you omit the package statement, the class
begin. • The name of the new thread is specified by threadname. • After the new thread is created, it will not start running until you call its names are put into the default package, which has no name. • Syntax:
start() method, which is declared within Thread. • Start() executes a call to run(). >Void start() Example>> package firstpackage; → Package Declaration > public class firstclass → Class Definition >>{ //Body of class }
public class MyRunnable implements Runnable { • Here, the package name is firstpackage. The class firstclass is now considered a part of this package. • This listing would be saved as a file
> private String threadName; > public MyRunnable(String threadName) { > this.threadName = threadName; > } called firstclass.java and located in a directory named firstpackage. When we compile the source file, java will create a .class file and store it in
> public void run() { > System.out.println("Thread " + threadName + " is running."); } } the same directory. • Here, .class file must be located in a directory that has the same name as the package and this directory should be a
public class Main { > public static void main(String[] args) { > MyRunnable runnable1 = new MyRunnable("Thread 1"); subdirectory of the directory where classes that will import the package are located. • A java package file can have more than one class
> Thread thread1 = new Thread(runnable1); > thread1.start(); > MyRunnable runnable2 = new MyRunnable("Thread 2"); definitions. In such cases only one of the classes may be declared public and that class name with .java extension is the source file name. And
> Thread thread2 = new Thread(runnable2); > thread2.start(); } } when this source file with more than one class is compiled, it creates independent .class files.
Output >Thread 1 is running. >Thread 2 is running.
❖ Accessing a Package :- • The import statement can be used to search list of packages for a particular class. • Syntax:
2. Extending Thread class • This is another way to create a thread by a new class that extends Threadclass and create an instance of that
import package1[.package2][.package3].classname | *; • Here, package1 is the name of the top level package, package2 is the name of the
class. • The extending class must override run() method which is the entry point of new thread. • It must also call start() to began execution of
package that is inside the package1 and so on. • We can have any number of packages in a package hierarchy. • Finally, the class name is
the new thread. • Example :
specified. • This import statement must end with semicolon. Multiple import statements are also allowed. • E.g. import fristpackage.
public class MyThread extends Thread {
Secondpackage myclass; • After defining this statement, all the members of the class myclass can be directly accessed using t he classname or
> private String threadName; > public MyThread(String threadName) { > this.threadName = threadName; > }
its objects directly without using the package name. • Another approach is, import packagename.*; • Here, packagename denotes a single
> public void run() { > System.out.println("Thread " + threadName + " is running."); > } }
package or a hierarchy of packages. • The * indicates that the compiler should search this entire package hierarchy when it encounters a class
public class Main { > public static void main(String[] args) { > MyThread thread1 = new MyThread("Thread 1"); > thread1.start();
name. • This implies that we can access all classes contained in the above package directly. ❖ Example :
> MyThread thread2 = new MyThread("Thread 2"); > thread2.start(); > } }
import package1.MyClass1; >import package2.MyClass2; >public class Main { > public static void main(String[] args) {
Output >Thread 1 is running. >Thread 2 is running.
MyClass1 obj1 = new MyClass1(); > MyClass2 obj2 = new MyClass2(); > obj1.method1(); > obj2.method2(); } }
➢ Thread Priorities. • Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. • In
➢ Concept of Sub package. • Java also supports the concept of package hierarchy. This is done by specifying multiple names in a
theory concept, highest priority threads get more CPU time than lower priority threads. • A higher priority thread can also preempt a lower
package statement, separated by dots. • This is the concept of sub package. • The package that we are putting into another package is called
priority one. • For example, when a lower priority thread is running and a higher priority thread resumes (sleeping or waiting for I/O), it will
sub package. • E.g. package firstpackage.secondpackage; Multilevel package statement • This approach allows us to group related classes
preempt the lower priority thread. • In theory concept, threads of equal priority should get equal access to the CPU. • But actually the threads
into a package and then group related packages into a larger package. • To store this package in a subdirectory named
that share the same priority should yield control once a while. That ensures that all threads have a chance to run under a non preemptive
firstpackage\secondpackage. • E.g.
operating system. • To set a thread’s priority, use the setPriority() method, which is a member of Thread. • Syntax : final void setPriority ( int
import com.myCompany.package1.MyClass1; >import com.myCompany.package2.MyClass2;
level ); • Here, level specifies the new priority setting for the calling thread. • The value of level must be within the range MIN_PRIORITY and
public class Main { > public static void main(String[] args) {
MAX_PRIORITY. • These values are 1 and 10 respectively. • The default priority of thread is NORM_PRIORITY, which is 5. These priorities are
MyClass1 obj1 = new MyClass1(); > MyClass2 obj2 = new MyClass2(); > obj1.method1(); > obj2.method2(); } }
defined as static final variables within Thread. • You can obtain the current priority setting by calling the getPriority() method of Thread. •
Syntax : final int getPriority(); • Example : ➢ Different forms of the import statement. 1. import packagename.classname; • It allows the specified class in the specified package to be
public class MyThread extends Thread { > private String threadName; > public MyThread(String threadName) { imported. • E.g. import java.awt.color; • Here, it imports the class color and therefore the class name can now directly used in the program.
> this.threadName = threadName; > } > public void run() { > for (int i = 0; i < 5; i++) { There is no need to used the package name to qualify the class. 2. import packagename.*; • It imports every class contained in the specified
> System.out.println("Thread " + threadName + " is running with priority " + getPriority()); > try { > Thread.sleep(1000); package. • E.g. import java.awt.*; • Here, it imports all the classes of java.awt package.
> } catch (InterruptedException e) { > System.out.println("Thread " + threadName + " was interrupted."); > } > } > } } Give the difference between multiprocessing and multithreading >The main difference between multiprocessing and multithreading is
public class Main { > public static void main(String[] args) { > MyThread thread1 = new MyThread("Thread 1"); that multiprocessing involves running multiple processes, while multithreading involves running multiple threads within the same process.
> MyThread thread2 = new MyThread("Thread 2"); > // Set thread priorities >>Here are some key differences between the two: >Memory: In multiprocessing, each process has its own separate memory space, while in
> thread1.setPriority(Thread.MIN_PRIORITY); > thread2.setPriority(Thread.MAX_PRIORITY); multithreading, all threads share the same memory space. This means that data can be easily shared between threads, but data sharing
> // Start threads > thread1.start(); > thread2.start(); > // Wait for threads to finish > try { > thread1.join(); between processes requires additional communication mechanisms like inter-process communication (IPC). >CPU usage: In multiprocessing,
> thread2.join(); > } catch (InterruptedException e) { > System.out.println("Main thread was interrupted."); > } each process can run on a separate CPU core, allowing for true parallel processing. In multithreading, all threads share the same CPU core and
> System.out.println("Main thread is finished."); > } } take turns executing, which is known as time-slicing. This can result in slower overall performance if the threads are competing for CPU time.
Output >Thread 1 is running with priority 1 >Thread 2 is running with priority 10 >Thread 1 is running with priority 1 >Concurrency: Multiprocessing allows for true concurrency, since each process runs independently of the others. In multithreading,
>Thread 2 is running with priority 10 >Thread 1 is running with priority 1 >Thread 2 is running with priority 10 concurrency is simulated through time-slicing, which can lead to performance issues if the threads are not properly synchronized.
>Thread 1 is running with priority 1 >Thread 2 is running with priority 10 >Thread 1 is running with priority 1 >Ease of use: Multithreading is generally easier to implement and debug than multiprocessing, since threa ds share the same memory space
>Thread 2 is running with priority 10 >Main thread is finished. and don't require additional communication mechanisms. Multiprocessing, on the other hand, requires more complex coordination and
communication mechanisms.

You might also like