0% found this document useful (0 votes)
2 views16 pages

Unit-3 Java

This document covers basic concepts of strings and exceptions in Java, detailing string operations, methods, and the StringBuffer class for mutable strings. It also introduces exception handling, explaining checked and unchecked exceptions, error types, and Java's exception keywords like try, catch, and finally. Additionally, it provides examples of exception handling and user-defined exceptions.

Uploaded by

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

Unit-3 Java

This document covers basic concepts of strings and exceptions in Java, detailing string operations, methods, and the StringBuffer class for mutable strings. It also introduces exception handling, explaining checked and unchecked exceptions, error types, and Java's exception keywords like try, catch, and finally. Additionally, it provides examples of exception handling and user-defined exceptions.

Uploaded by

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

Unit 3.

Basic Concepts of Strings and Exceptions

3.1 Strings
3.1.1 Basic String operations, String Comparison
The String class in Java is part of the java.lang package and is used to handle
and manipulate sequences of characters. Strings are immutable in Java,
meaning once a String object is created, its value cannot be changed.
Commonly Used Constructors
1. String(): Creates an empty string.
2. String(String original): Creates a new string initialized to the value of the
specified string.
3. String(char[] charArray): Constructs a string from a character array.
4. String(byte[] byteArray): Constructs a string from a byte array. Literal
Strings

• are anonymous objects of the String class


• are defined by enclosing text in double quotes. “This is a literal String” •
don’t have to be constructed.

• can be assigned to String variables.


• can be passed to methods and constructors as parameters. •
have methods you can call.

3.1.2 String methods (charAt(), concat(), equals(), indexOf(),


isEmpty(), join(), lastIndexOf(), length(), split(), substring(), trim())
charAt()
Returns the character at the specified index.
public class StringExample {
public static void main(String[] args) {
String str = "Hello, World!";
char ch = str.charAt(7); // Returns 'W'
System.out.println("Character at index 7: " + ch);

Unit 3. Basic Concepts of Strings and Exceptions


}
}

concat()
The Java String class concat() method combines specified string at the end of
string. It returns a combined string. It is just like appending another string. In
this section, we delve into the intricacies of Java String Concatenation,
exploring its nuances, best practices, and performance considerations.
public String concat(String string2)
class concatEx {

public static void main(String args[]) {

// String Initialization
String s = “Helllo";

// Use concat() method for string concatenation


s = s.concat("World");
System.out.println(s);
}
}

equals()
Compares two strings for equality.
equals(Object obj)
public class StringExample {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Java";
String str3 = "Python";

System.out.println("Equals str1 and str2: " + str1.equals(str2)); // true


System.out.println("Equals str1 and str3: " + str1.equals(str3)); // false }

Unit 3. Basic Concepts of Strings and Exceptions


}

indexOf()
Finds the first occurrence of the specified substring.
public class StringExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println("Index of 'Program': " + str.indexOf("Program")); // 5 }
}

equalsIgnoreCase(String anotherString)
Compares two strings, ignoring case differences.
public class StringExample {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "JAVA";

System.out.println("Equals ignoring case: " +


str1.equalsIgnoreCase(str2)); // true
}
}

length()
Returns the length of the string.
public class StringExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println("Length of the string: " + str.length()); // Outputs 16 }
}

substring()
Unit 3. Basic Concepts of Strings and Exceptions

Extracts a portion of the string from beginIndex to endIndex -


1. substring(int beginIndex, int endIndex)

public class StringExample {


public static void main(String[] args) {
String str = "Hello, World!";
String sub = str.substring(7, 12); // Returns "World"
System.out.println("Substring: " + sub);
}
}

trim()
Removes leading and trailing spaces from the string.
public class StringExample {
public static void main(String[] args) {
String str = " Hello, Java! ";
System.out.println("Trimmed String: " + str.trim()); // "Hello, Java!" }
}

join()
The join() method in Java is part of the String class and is used to join elements
of a sequence, such as an array or a collection, into a single string with a
specified delimiter between elements.
public static String join(CharSequence delimiter, CharSequence... elements)
public class Main {
public static void main(String[] args) {
String[] words = { "apple", "banana", "cherry" };
String result = String.join(", ", words);
System.out.println(result); // Output: apple, banana, cherry }
}

Unit 3. Basic Concepts of Strings and Exceptions

isEmpty()
The isEmpty() method in Java is used to check if a data structure or string is
empty. Here's how it works in different contexts:
public class Main {
public static void main(String[] args) {
String str1 = "";
String str2 = "Hello";

System.out.println("Is str1 empty? " + str1.isEmpty()); // true


System.out.println("Is str2 empty? " + str2.isEmpty()); // false }
}

lastIndexOf()
In Java, the lastIndexOf() method is used to find the index of the last
occurrence of a specified character or substring within a string. If the character
or substring is not found, the method returns -1.
public class Main {
public static void main(String[] args) {
String str = "Hello World";
int index = str.lastIndexOf('o'); // Finds the last 'o'
System.out.println(index); // Output: 7
}
}

split()
Splits the string into an array based on a specified delimiter.
public class StringExample {
public static void main(String[] args) {
String str = "Apple, Banana, Cherry";
String[] fruits = str.split(", ");

for (String fruit : fruits) {


System.out.println(fruit);
}

Unit 3. Basic Concepts of Strings and Exceptions


}
// Output:
// Apple
// Banana
// Cherry
}
}

3.1.3 StringBuffer class and its constructors


• In Java, the StringBuffer class is used to create mutable (modifiable)
strings.
• Unlike String objects, which are immutable (once created, their contents
cannot be changed), StringBuffer objects can be modified after they are
created.
• The main use case of StringBuffer is when you need to perform a lot of
string manipulation, such as appending, inserting, or deleting characters,
without creating a new object every time. This can significantly improve
performance in situations where strings are frequently modified.
Key Features of StringBuffer:
1. Mutable: The content of a StringBuffer can be modified after it is
created.
2. Thread-Safe: StringBuffer methods are synchronized, meaning they are
thread-safe. However, this comes with a performance trade-off.
3. Dynamic Sizing: StringBuffer can automatically grow in size as needed.
Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity


of 16.

StringBuffer(String str) It creates a String buffer with the specified string.

StringBuffer(int It creates an empty String buffer with the specified


capacity) capacity as length.

Unit 3. Basic Concepts of Strings and Exceptions

3.1.4 StringBuffer methods: (append(), insert(), update(), delete(),


reverse(), capacity())
append()
The append() method concatenates the given argument with this String.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is cha
nged
System.out.println(sb);//prints Hello Java
}
}

insert()
The insert() method inserts the given String with this string at the given
position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

delete()
The delete() method of the StringBuffer class deletes the String from the
specified beginIndex to endIndex.
class StringBufferExample4{

Unit 3. Basic Concepts of Strings and Exceptions


public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

reverse()
The reverse() method of the StringBuilder class reverses the current String.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

capacity()
The capacity() method of the StringBuffer class returns the current capacity of
the buffer. The default capacity of the buffer is 16. If the number of character
increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");

Unit 3. Basic Concepts of Strings and Exceptions

System.out.println(sb.capacity());//now (16*2)+2=34 i.e


(oldcapacity*2)+2
}
}

Unit 3. Basic Concepts of Strings and Exceptions

3.2 Introduction to Exceptions


• The Exception Handling in Java is one of the powerful mechanisms to
handle the runtime errors so that the normal flow of the application can
be maintained.
• In Java, an exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions.
• These exceptions can occur for various reasons, such as invalid user input,
file not found, or division by zero. When an exception occurs, it is
typically represented by an object of a subclass of the
java.lang.Exception class.

Hierarchy of Java Exception classes


Unit 3. Basic Concepts of Strings and Exceptions

Types of Java Exceptions


1. Checked Exceptions
• Checked exceptions are the exceptions that are checked at
compile-time.
• This means that the compiler verifies that the code handles these
exceptions either by catching them or declaring them in the
method signature using the throws keyword.
• Examples of checked exceptions include:

IOException: An exception is thrown when an input/output operation


fails, such as when reading from or writing to a file.

SQLException: It is thrown when an error occurs while accessing a


database.

ParseException: Indicates a problem while parsing a string into another


data type, such as parsing a date.
Unit 3. Basic Concepts of Strings and Exceptions

ClassNotFoundException: It is thrown when an application tries to load a


class through its string name using methods like Class.forName(), but the
class with the specified name cannot be found in the classpath.

2. Unchecked Exceptions (Runtime Exceptions)


• Unchecked exceptions, also known as runtime exceptions, are not
checked at compile-time.
• These exceptions usually occur due to programming errors, such as
logic errors or incorrect assumptions in the code.
• They do not need to be declared in the method signature using the
throws keyword, making it optional to handle them.
• Examples of unchecked exceptions include:
NullPointerException: It is thrown when trying to access or call a method
on an object reference that is null.

ArrayIndexOutOfBoundsException: It occurs when we try to access an


array element with an invalid index.

ArithmeticException: It is thrown when an arithmetic operation fails,


such as division by zero.

IllegalArgumentException: It indicates that a method has been passed an


illegal or inappropriate argument.

3. Errors
• Errors represent exceptional conditions that are not expected to be
caught under normal circumstances.
• They are typically caused by issues outside the control of the
application, such as system failures or resource exhaustion. • Errors are
not meant to be caught or handled by application code. • Examples of
errors include:
OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot
allocate enough memory for the application.
StackOverflowError: It is thrown when the stack memory is exhausted due
to excessive recursion.
Unit 3. Basic Concepts of Strings and Exceptions

NoClassDefFoundError: It indicates that the JVM cannot find the definition


of a class that was available at compile-time.

Java Exception Keywords


Keyword Description

Try The "try" keyword is used to


specify a block where we should
place an exception code. It means
we can't use try block alone. The
try block must be followed by
either catch or finally.

catch The "catch" block is used to


handle the exception. It must be
preceded by try block which
means we can't use catch block
alone. It can be followed by
finally block later.

finally The "finally" block is used to


execute the necessary code of the
program. It is executed whether
an exception is handled or not.

throw The "throw" keyword is used to


throw an exception.

throws The "throws" keyword is used to


declare exceptions. It specifies
that there may occur an
exception in the method. It
doesn't throw an exception. It is
always used with method
signature.

Unit 3. Basic Concepts of Strings and Exceptions

The try-catch Block


try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
}

Handling Multiple Exceptions


try {
// Code that may throw an exception
} catch (IOException e) {
// Handle IOException
} catch (NumberFormatException e) {
// Handle NumberFormatException
} catch (Exception e) {
// Handle any other exceptions
}

The finally Block


try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling code
} finally {
// Cleanup code
}

Java Exception Handling Example


public class JavaExceptionExample{

Unit 3. Basic Concepts of Strings and Exceptions


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e)
{System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

User defined Exception


// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
throw new InvalidAgeException("age is not valid to
vote"); }
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
Unit 3. Basic Concepts of Strings and Exceptions
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy