Unit - 7,8,9 Java PIET
Unit - 7,8,9 Java PIET
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string.
For example: String s1 = "Hello"; // Using string literal
String s2 = new String("World"); // Using new keyword
The Java String class charAt() method returns a char value at the given index
number.
public class CharAtExample {
public static void main(String args[]) {
String name="section";
The Java String class length() method finds the length of a string. The length of
the Java string is the same as the Unicode code units of the string.
The Java String class isEmpty() method checks if the input string is empty or
not. Note that here empty means the number of characters contained in a string is
zero.
Example:
public class IsEmptyExample {
public static void main(String args[]) {
String s1="";
String s2="University";
[Link]([Link]();
[Link]([Link]();
}
}
The Java String class replace() method returns a string replacing all the old char
or CharSequence to new char or CharSequence.
The given example returns total number of words in a string excluding space only. It
also includes special characters.
public class SplitExample{
public static void main(String args[]){
String s1="java string split method";
String[] words=[Link]("\\s");
//splits the string based on whitespace using java
//foreach loop to print elements of string array
for(String w:words){
[Link](w);
}
}
}
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
[Link]([Link](s2)); //true
[Link]([Link](s3)); //true
[Link]([Link](s4)); //false
}
}
Example 2
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
[Link]([Link](s2));//false
[Link]([Link](s2));//true
}
}
In Java, String concatenation forms a new String that is the combination of multiple
strings. There are two ways to concatenate strings in Java:
o By + (String concatenation) operator
o By concat() method
o String Concatenation by + (String concatenation) operator
o Java String concatenation operator (+) is used to add strings.
o For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
[Link](s);//Sachin Tendulkar
}
}
o String Concatenation by concat() method
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);//Sachin Tendulkar
}
}
Java Package:
PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It
helps organize your classes into a folder structure and make it easy to locate and
use them. More importantly, it helps improve code reusability.
Each package in Java has its unique name and organizes its classes and interfaces
into a separate namespace, or name group.
Although interfaces and classes with the same name cannot appear in the same
package, they can appear in different packages. This is possible by assigning a
separate namespace to each Java package.
Syntax:- package name_of_Package;
To create a package, follow the steps given below:
Implement a java program to create a package named mypack and import it in circle class.
Step-1: First create a folder for the package and the package_name is mypack.
Step-2: In that mypack folder, create a file_name on [Link].
Step-3: Then write a code for the "circle class'' by using (package mypack;)
source code:
package mypack;
public class Circle {
double r=10;
public void area() {
6|Page By [Link] (Technical Trainer)
[Link]("Area of the circle = " + (3.14 * r * r));
}
}
Step-4: After that create a file for main class for importing it in a circle class by using
(package mypack;)
source code:
package mypack;
public class Main {
public static void main(String args[]) {
Circle c = new Circle();
[Link]();
}
} //Output: Area of the circle = 314.0
• Path: Refers to the directory where Java tools (like javac, java) reside.
• Now, you can simply type:
javac [Link]
java MyProgram
• Classpath: Refers to where the Java compiler looks for classes and libraries.
• Setting Classpath Example (Windows):
set CLASSPATH=C:\myJavaClasses;
Interfaces in Java
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction and
multiple inheritance in Java. In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body. Java Interface also represents the
IS-A relationship.
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the
behaviour.
Interface do not have constructor.
7|Page By [Link] (Technical Trainer)
Syntax:
interface interface_name{
// by default.
switch (today) {
case MONDAY:
[Link]("Start of the week!");
break;
case FRIDAY:
[Link]("Weekend is near!");
break;
case SATURDAY:
case SUNDAY:
[Link]("It's weekend!");
break;
9|Page By [Link] (Technical Trainer)
default:
[Link]("Midweek day!");
}
}
} //Output: It's weekend!
// Constructor
Season(String description) {
[Link] = description;
}
// Method
public String getDescription() {
return description;
}
}
Advantages of Enum
Improves readability and maintainability of code.
Prevents invalid values (only predefined constants allowed).
Can be used in switch-case statements.
Checked Exceptions: These are exceptions that are checked at compile-time. For
example, IOException, SQLException.
Unchecked Exceptions: These exceptions are not checked at compile-time but at
runtime. For example, ArithmeticException, NullPointerException.
Errors: These are serious issues not intended to be caught by the application. For
example, OutOfMemoryError, StackOverflowError.
1. try Block: The code that might throw an exception is placed inside the try block.
2. catch Block: It catches and handles the exception thrown by the try block.
3. finally Block: This block always executes whether an exception is handled or not,
making it ideal for cleanup code like closing file streams or database connections.
4. throw Keyword: Used to explicitly throw an exception.
5. throws Keyword: Used to declare an exception that might be thrown by a
method but is not handled within the method itself.
• try block: Code that may throw an exception is placed inside this block.
• catch block: It catches the exception thrown by the try block.
• finally block: This block will execute whether an exception is handled or not.
Example:
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
[Link](result);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
} finally {
[Link]("Finally block executed.");
}
}}
Output:
You can catch multiple types of exceptions by using multiple catch blocks.
Example:
public class MultipleCatchExample { public static void
main(String[] args) { try {
int[] arr = new int[5];
arr[5] = 10; // Throws ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
[Link]("ArithmeticException caught."); } catch
(ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException caught.");
} catch (Exception e) {
[Link]("General Exception caught.");
}
}}
Output:
ArrayIndexOutOfBoundsException caught.
Example:
public class ThrowExample {
public static void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible for voting");
} else {
[Link]("Welcome to vote");
}
}
public static void main(String[] args) {
validateAge(16); // This will throw an exception
}}
Output:
throws Keyword:
• The throws keyword is used to declare exceptions.
• It indicates that a method can throw an exception, which must be handled by the
calling method.
Example:
import [Link].*;
public class ThrowsExample {
public static void method() throws IOException {
throw new IOException("File error");
}
public static void main(String[] args) {
try {
method(); // Calling method that throws an exception
} catch (IOException e) {
[Link]("Exception handled: " + [Link]());
}
}}
Output:
Exception handled: File error
Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Exception caught.");
} finally {
[Link]("This will always be executed.");
}
}}
Output:
Custom Exceptions:
You can create your own exception classes by extending the Exception class or
RuntimeException.
Example:
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age less than 18");
} else {
[Link]("Valid age.");
} }
public static void main(String[] args) {
try {
checkAge(16); // Throws custom exception
} catch (AgeException e) {
[Link]("Caught: " + [Link]());
}}}
Output:
Example:
import [Link];
import [Link];
import [Link];
If the file does not exist, the output will be: File not found.
2. Unchecked Exceptions:
These exceptions subclasses of RuntimeException. They are not checked at compile
time, meaning the programmer is not forced to handle them.
Like: NullPointerException, ArithmeticException.
Example:
Class Throwable:
The Throwable class is the superclass of all exceptions and errors in Java.
Example:
public class ThrowableExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (Exception e) {
[Link]("Message: " + [Link]());
[Link](); // Prints the stack trace
}
}}
Output:
Message: / by zero
[Link]: / by zero
at [Link]([Link])
Summary:
• Exception handling allows us to gracefully handle runtime errors and maintain the
normal flow of the application.
• Key concepts include try, catch, finally, throw, and throws.
• You can handle multiple exceptions using multiple catch blocks.
• You can create custom exceptions by extending the Exception class.
• Checked exceptions must be declared or caught, while unchecked exceptions do not
require explicit handling at compile-time.
Use Cases:
• Web Servers: Handle multiple client requests simultaneously.
• Media Players: Play audio while performing other tasks like UI updates.
• Video Games: Separate logic for game mechanics, rendering, and user input.
• Data Processing: Execute heavy computational tasks without blocking the UI.
Thread Class
Java provides the Thread class, which you can extend to create a new thread. The run()
method contains the code that the thread will execute.
The start() method is used to start a thread, which internally calls the run() method.
Output:
Thread is running: 0
Thread is running: 1
Thread is running: 2
Output:
Runnable thread is running: 0
Runnable thread is running: 1
Runnable thread is running: 2
Runnable thread is running: 3
Runnable thread is running: 4
Thread Priority
Thread priority helps to manage the execution order of threads.
Java assigns a priority from 1(MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5
being the default (NORM_PRIORITY).
Higher-priority threads are executed before lower-priority ones.
Synchronization
When multiple threads access shared resources (like variables, files, or databases), you may
encounter inconsistency in the data.
Synchronization ensures that only one thread can access a critical section of code at a time,
avoiding race conditions.
Explanation: The synchronized block ensures that only one thread can increment the
counter at a time.
Java provides wait(), notify(), and notifyAll() methods for threads to communicate with each
other.
Explanation:
The producer thread puts values into the queue, while the consumer thread retrieves them.
Both threads use wait() and notify() to communicate and ensure synchronization.
Output:
Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Daemon Threads
Daemon threads provide background services for user threads.
They terminate automatically when all user threads finish.
Explanation:
The daemon thread runs in the background, and when the main thread finishes, the
JVM automatically stops the daemon thread.
Output:
Daemon thread running...
Daemon thread running...
Daemon thread running...
Daemon thread running...
Main thread finished.
Conclusion
• Java multithreading enables efficient task management, especially in applications
requiring parallel execution.
• By understanding thread creation, synchronization, communication, and handling
common issues like deadlocks and race conditions, you can build robust, concurrent
applications suitable for modern multi-core processors.
• The thread management methods (join(), isAlive(), daemon threads) provide further
control, allowing precise coordination between threads.