Unit-3 Java
Unit-3 Java
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
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 {
// String Initialization
String s = “Helllo";
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";
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";
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
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 }
}
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";
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(", ");
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{
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");
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
// 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");
}
}
}