SlideShare a Scribd company logo
Arrays and Strings
Ms. Shilpa
Department of IT
Arrays in Java
• Array is an object which contains elements of a similar data type.
Additionally, It is a data structure where we store similar elements.
• The elements of an array are stored in a contiguous memory location.
• Array in Java is index-based, the first element of the array is stored at
the 0th index, 2nd element is stored on 1st index and so on.
Declaring an Array:
To declare an array in Java, you specify the data type of the array elements followed by
square brackets [] and then the array name.
Example:
int[] numbers;
String[] names;
Creating an Array:
To create an array, you use the new keyword along with the data type and the size
(number of elements) of the array.
Example:
int[] numbers = new int[5]; // Creates an array of 5 integers
Initializing an Array:
You can initialize the elements of an array at the time of declaration or later:
// Initializing at the time of declaration
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie", "David", "Eva"};
// Initializing later
numbers[0] = 10;
numbers[1] = 20;
// ...
Accessing Elements:
Array elements are accessed using an index. The index starts from 0 for the first
element and goes up to length - 1 for an array of length length.
For example:
int firstElement = numbers[0];
Array Length:
The length property is used to get the number of elements in an array
int arrayLength = numbers.length;
Sorting an array
The sorting is a way to arrange elements of a list or array in a certain
order. The order may be in ascending or descending order.
Sorting an array in Java can be done using the Arrays.sort() method for
primitive arrays (eg, int[])
How you can declare and initialize an array to store 5
numbers in Java:
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array to store 5 numbers
int[] numbers = {10, 20, 30, 40, 50};
// Access and print each element of the array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
The for loop will iterate for values of i starting from 0 up
to numbers.length, which is 5 in this case. Therefore,
the loop will run for i equal to 0, 1, 2, 3 and 4 making a
total of 5 iterations
Java program to sort an array of integers
import java.util.Arrays;
public class ArraySorting {
public static void main(String[] args) {
// Array of integers
int[] numbers = {5, 2, 8, 1, 6};
// Sorting the array in ascending order
Arrays.sort(numbers);
// Displaying the sorted array
System.out.println("Sorted Array (Ascending): " + Arrays.toString(numbers));
}
}
• An array named numbers is declared and initialized with five integer values: 5, 2, 8, 1, and 6.
• The Arrays.sort() method is used to sort the elements of the numbers array in ascending order
• Arrays.toString(numbers) method is used to convert the array into a readable string representation.
Java program to sort the array of strings
import java.util.Arrays;
public class StringArraySorting {
public static void main(String[] args) {
// Array of strings
String[] names = {"Eva" , "Alice", "Charlie", "Bob", "David"};
// Sorting the array in ascending order
Arrays.sort(names);
// Displaying the sorted array
System.out.println("Sorted Array (Ascending): " +
Arrays.toString(names));
}
}
Multidimensional Array
A multidimensional array is an array that contains other arrays. The
most common types are 2D and 3D arrays, representing matrices and
cubes, respectively.
// Declaration and Initialization of a 2D array
int[][] twoDArray = new int[3][4];
int[][] twoDArray = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
public class MultidimensionalArrayExample {
public static void main(String[] args) {
// Declaration and Initialization of a 2D array
int[][] twoDArray = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Accessing and printing elements
System.out.println("Element at row 1, column 2: " + twoDArray[0][1]);
System.out.println("Element at row 2, column 3: " + twoDArray[1][2]);
}
}
In the example above, we have twoDArray with three rows and four columns. The key idea
is that each element in the array is accessed using two indices: the row index and the
column index.
String
• String is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.
• Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.
How to create a string object?
• There are two ways to create String object:
• By string literal
• By new keyword
1) String Literal
Java String literal is created by using double quotes.
For Example: String s="welcome";
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a reference
to the pooled instance is returned. If the string doesn't exist in the
pool, a new string instance is created and placed in the pool
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
String objects are stored in a special
memory area known as the "string constant
pool"
Here only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will
create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create a new object but will return the
reference to the same instance
2. By new keyword
• String s=new String("Welcome");//creates two objects and one reference
variable
• In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-pool).
Declaration and Initialization:
// Using String literal
String str1 = "Hello";
// Using the new keyword
String str2 = new String("World");
String Concatenation: Strings can be concatenated using the + operator:
String firstName = "John";
String lastName = “AB";
String fullName = firstName + " " + lastName;
String class:
String Comparison:
You can compare strings using the equals() method for content equality
Example:
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // Returns false
String charAt() Method
The String class charAt() method returns a character at specified index.
Example:
public class Stringoperation4
{
public static void main(String args[])
{
String s="Sachin";
System.out.println(s.charAt(0)); //S
System.out.println(s.charAt(3));//h
}
}
String length() Method
• The String class length() method returns length of the specified String.i e you can
find the length of a string.
Example:
public class Stringoperation5
{
public static void main(String args[])
{
String s="Sachin";
System.out.println(s.length());//6
}
}
String startsWith() and endsWith() method
The method startsWith() checks whether the String starts with the letters
passed as arguments and endsWith() method checks whether the String
ends with the letters passed as arguments.
Example:
public class Stringoperation3
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
}
}
String replace() Method
The String class replace() method replaces all occurrence of first sequence of character
with second sequence of character.
Example:
public class Stringoperation8
{
public static void main(String args[])
{
String s1="Java is fun.";
String replaceString=s1.replace(“fun",“Awesome");//replaces all occurrences of “fun" to “
Awesome "
System.out.println(replaceString);
}
}
String trim() method
The String class trim() method eliminates white spaces before and after the
String.
Example:
public class Stringoperation2
{
public static void main(String ar[])
{
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
}
}
String Case Conversion:
The Java String toUpperCase() method converts this String into uppercase letter and
String toLowerCase() method into lowercase letter.
Example:
public class Stringoperation1
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}
StringBuffer Class
• StringBuffer class is used to create mutable (modifiable) String objects. i.e. it can
be changed.
• A String that can be modified or changed is known as mutable String.
• StringBuffer is synchronized, which means it is thread-safe. Multiple threads can
safely access a StringBuffer object without any issues.
• StringBuffer contains various methods for string manipulation, such as append,
insert, delete, reverse, etc
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 capacity) It creates an empty String buffer with the specified capacity as length
StringBuffer append() Method:
The append() method concatenates the given argument with this String.
Example:
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
StringBuffer insert() Method:
The insert() method inserts the given String with this string at the given
position.
Example:
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
}
}
StringBuffer delete() Method:
The delete() method of the StringBuffer class deletes the String from the
specified beginIndex to endIndex.
Example:
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
The delete(1, 3) method deletes characters from index 1 to index 2
(excluding index 3).
StringBuffer reverse() Method:
The reverse() method of the StringBuilder class reverses the current String.
Example:
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String.
The Java StringBuilder class is same as StringBuffer class except that it is
non-synchronized.
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String str) It creates a String Builder with the specified string.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as
length.
StringBuilder append() method:
The StringBuilder append() method concatenates the given argument with
this String.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the
given position.
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
StringBuilder replace() method
• The StringBuilder replace() method replaces the given string from the
specified beginIndex and endIndex.
class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
StringBuilder delete() method:
The delete() method of StringBuilder class deletes the string from the
specified beginIndex to endIndex.
class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
StringBuilder reverse() method:
The reverse() method of StringBuilder class reverses the current string.
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
String Constructor.
1. Empty Constructor:
2. Constructor with String Argument:
3. Constructor with Byte Array Argument:
4. Constructor with Character Array Argument:
1. Empty Constructor: This creates an empty string object with no
characters.
Example:
public class StringClassExample {
public static void main(String[] args) {
String str = new String();
System.out.print("Value of str is ""+str+""");
}
}
Here an empty string is created using the String constructor with no
arguments.
2. Constructor from another string
Creates a string object initialized with the specified string.
Example:
String greeting = new String("Hello, World!");
System.out.println("Greeting: " + greeting);
3. Constructor with Byte Array:
Creates a string from an array of bytes.
// Create a byte array
byte[] byteArray = {72, 101, 108, 108, 111};
String str = new String(byteArray);
4. Constructor with Character Array:
This creates a string object from a character array.
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String fromCharArray = new String(charArray);
Java program demonstrating the use of string constructors:
public class StringConstructorExample {
public static void main(String[] args) {
// Using different string constructors
String str1 = new String(); // Empty constructor
String str2 = new String("Hello"); // Constructor with string argument
char[] charArray = {'W', 'o', 'r', 'l', 'd'};
String str3 = new String(charArray); // Constructor with char array argument
// Displaying the strings
System.out.println("String 1: " + str1);
System.out.println("String 2: " + str2);
System.out.println("String 3: " + str3);
}
}

More Related Content

PPTX
Arrays in Java with example and types of array.pptx
PDF
Class notes(week 4) on arrays and strings
DOCX
Class notes(week 4) on arrays and strings
PPTX
String in java, string constructors and operations
PPTX
CH1 ARRAY (1).pptx
PDF
PPTX
6_Array.pptx
PPTX
SessionPlans_f3efa1.6 Array in java.pptx
Arrays in Java with example and types of array.pptx
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
String in java, string constructors and operations
CH1 ARRAY (1).pptx
6_Array.pptx
SessionPlans_f3efa1.6 Array in java.pptx

Similar to Unit-2.Arrays and Strings.pptx................. (20)

PPTX
arrays in c# including Classes handling arrays
PPT
17-Arrays en java presentación documento
PDF
M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf)
PPT
Csharp4 arrays and_tuples
DOC
Array properties
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
PPTX
Arrays in programming
PDF
Introduction to Arrays in C
PDF
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
PPTX
DOC-20240812-WA0000 array string and.pptx
PDF
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
PPTX
Computer programming 2 Lesson 13
PDF
Arrays a detailed explanation and presentation
PPTX
Arrays in java
PPTX
Chap1 array
PPTX
Module-5-hjhjhjkhdjkhjhjhhhjhjhhhhj.pptx
PPT
Arrays in Java Programming Language slides
PPT
Arrays JavaScript presentacion en power point
PPT
Charcater and Strings.ppt Charcater and Strings.ppt
arrays in c# including Classes handling arrays
17-Arrays en java presentación documento
M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf)
Csharp4 arrays and_tuples
Array properties
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arrays in programming
Introduction to Arrays in C
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
DOC-20240812-WA0000 array string and.pptx
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Computer programming 2 Lesson 13
Arrays a detailed explanation and presentation
Arrays in java
Chap1 array
Module-5-hjhjhjkhdjkhjhjhhhjhjhhhhj.pptx
Arrays in Java Programming Language slides
Arrays JavaScript presentacion en power point
Charcater and Strings.ppt Charcater and Strings.ppt
Ad

Recently uploaded (20)

PDF
Introduction to Data Science and Data Analysis
PPTX
DS-40-Pre-Engagement and Kickoff deck - v8.0.pptx
PPTX
New ISO 27001_2022 standard and the changes
PDF
[EN] Industrial Machine Downtime Prediction
PDF
Data Engineering Interview Questions & Answers Batch Processing (Spark, Hadoo...
PDF
REAL ILLUMINATI AGENT IN KAMPALA UGANDA CALL ON+256765750853/0705037305
PPTX
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
PPTX
QUANTUM_COMPUTING_AND_ITS_POTENTIAL_APPLICATIONS[2].pptx
PPTX
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
PDF
Business Analytics and business intelligence.pdf
PPTX
Introduction to Inferential Statistics.pptx
PDF
Data Engineering Interview Questions & Answers Cloud Data Stacks (AWS, Azure,...
PDF
OneRead_20250728_1808.pdfhdhddhshahwhwwjjaaja
PDF
annual-report-2024-2025 original latest.
PPTX
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
PPTX
modul_python (1).pptx for professional and student
PPTX
IBA_Chapter_11_Slides_Final_Accessible.pptx
PDF
Microsoft 365 products and services descrption
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
PPTX
Qualitative Qantitative and Mixed Methods.pptx
Introduction to Data Science and Data Analysis
DS-40-Pre-Engagement and Kickoff deck - v8.0.pptx
New ISO 27001_2022 standard and the changes
[EN] Industrial Machine Downtime Prediction
Data Engineering Interview Questions & Answers Batch Processing (Spark, Hadoo...
REAL ILLUMINATI AGENT IN KAMPALA UGANDA CALL ON+256765750853/0705037305
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
QUANTUM_COMPUTING_AND_ITS_POTENTIAL_APPLICATIONS[2].pptx
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
Business Analytics and business intelligence.pdf
Introduction to Inferential Statistics.pptx
Data Engineering Interview Questions & Answers Cloud Data Stacks (AWS, Azure,...
OneRead_20250728_1808.pdfhdhddhshahwhwwjjaaja
annual-report-2024-2025 original latest.
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
modul_python (1).pptx for professional and student
IBA_Chapter_11_Slides_Final_Accessible.pptx
Microsoft 365 products and services descrption
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
Qualitative Qantitative and Mixed Methods.pptx
Ad

Unit-2.Arrays and Strings.pptx.................

  • 1. Arrays and Strings Ms. Shilpa Department of IT
  • 2. Arrays in Java • Array is an object which contains elements of a similar data type. Additionally, It is a data structure where we store similar elements. • The elements of an array are stored in a contiguous memory location. • Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.
  • 3. Declaring an Array: To declare an array in Java, you specify the data type of the array elements followed by square brackets [] and then the array name. Example: int[] numbers; String[] names; Creating an Array: To create an array, you use the new keyword along with the data type and the size (number of elements) of the array. Example: int[] numbers = new int[5]; // Creates an array of 5 integers
  • 4. Initializing an Array: You can initialize the elements of an array at the time of declaration or later: // Initializing at the time of declaration int[] numbers = {1, 2, 3, 4, 5}; String[] names = {"Alice", "Bob", "Charlie", "David", "Eva"}; // Initializing later numbers[0] = 10; numbers[1] = 20; // ...
  • 5. Accessing Elements: Array elements are accessed using an index. The index starts from 0 for the first element and goes up to length - 1 for an array of length length. For example: int firstElement = numbers[0]; Array Length: The length property is used to get the number of elements in an array int arrayLength = numbers.length;
  • 6. Sorting an array The sorting is a way to arrange elements of a list or array in a certain order. The order may be in ascending or descending order. Sorting an array in Java can be done using the Arrays.sort() method for primitive arrays (eg, int[])
  • 7. How you can declare and initialize an array to store 5 numbers in Java: public class ArrayExample { public static void main(String[] args) { // Declare and initialize an array to store 5 numbers int[] numbers = {10, 20, 30, 40, 50}; // Access and print each element of the array for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } } } Output: Element at index 0: 10 Element at index 1: 20 Element at index 2: 30 Element at index 3: 40 Element at index 4: 50 The for loop will iterate for values of i starting from 0 up to numbers.length, which is 5 in this case. Therefore, the loop will run for i equal to 0, 1, 2, 3 and 4 making a total of 5 iterations
  • 8. Java program to sort an array of integers import java.util.Arrays; public class ArraySorting { public static void main(String[] args) { // Array of integers int[] numbers = {5, 2, 8, 1, 6}; // Sorting the array in ascending order Arrays.sort(numbers); // Displaying the sorted array System.out.println("Sorted Array (Ascending): " + Arrays.toString(numbers)); } } • An array named numbers is declared and initialized with five integer values: 5, 2, 8, 1, and 6. • The Arrays.sort() method is used to sort the elements of the numbers array in ascending order • Arrays.toString(numbers) method is used to convert the array into a readable string representation.
  • 9. Java program to sort the array of strings import java.util.Arrays; public class StringArraySorting { public static void main(String[] args) { // Array of strings String[] names = {"Eva" , "Alice", "Charlie", "Bob", "David"}; // Sorting the array in ascending order Arrays.sort(names); // Displaying the sorted array System.out.println("Sorted Array (Ascending): " + Arrays.toString(names)); } }
  • 10. Multidimensional Array A multidimensional array is an array that contains other arrays. The most common types are 2D and 3D arrays, representing matrices and cubes, respectively. // Declaration and Initialization of a 2D array int[][] twoDArray = new int[3][4]; int[][] twoDArray = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
  • 11. public class MultidimensionalArrayExample { public static void main(String[] args) { // Declaration and Initialization of a 2D array int[][] twoDArray = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; // Accessing and printing elements System.out.println("Element at row 1, column 2: " + twoDArray[0][1]); System.out.println("Element at row 2, column 3: " + twoDArray[1][2]); } } In the example above, we have twoDArray with three rows and four columns. The key idea is that each element in the array is accessed using two indices: the row index and the column index.
  • 12. String • String is an object that represents a sequence of characters. The java.lang.String class is used to create a string object. • Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
  • 13. How to create a string object? • There are two ways to create String object: • By string literal • By new keyword 1) String Literal Java String literal is created by using double quotes. For Example: String s="welcome"; Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool
  • 14. String s1="Welcome"; String s2="Welcome";//It doesn't create a new instance String objects are stored in a special memory area known as the "string constant pool" Here only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in string constant pool that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance
  • 15. 2. By new keyword • String s=new String("Welcome");//creates two objects and one reference variable • In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
  • 16. Declaration and Initialization: // Using String literal String str1 = "Hello"; // Using the new keyword String str2 = new String("World"); String Concatenation: Strings can be concatenated using the + operator: String firstName = "John"; String lastName = “AB"; String fullName = firstName + " " + lastName; String class:
  • 17. String Comparison: You can compare strings using the equals() method for content equality Example: String str1 = "Hello"; String str2 = "hello"; boolean isEqual = str1.equals(str2); // Returns false
  • 18. String charAt() Method The String class charAt() method returns a character at specified index. Example: public class Stringoperation4 { public static void main(String args[]) { String s="Sachin"; System.out.println(s.charAt(0)); //S System.out.println(s.charAt(3));//h } }
  • 19. String length() Method • The String class length() method returns length of the specified String.i e you can find the length of a string. Example: public class Stringoperation5 { public static void main(String args[]) { String s="Sachin"; System.out.println(s.length());//6 } }
  • 20. String startsWith() and endsWith() method The method startsWith() checks whether the String starts with the letters passed as arguments and endsWith() method checks whether the String ends with the letters passed as arguments. Example: public class Stringoperation3 { public static void main(String ar[]) { String s="Sachin"; System.out.println(s.startsWith("Sa"));//true System.out.println(s.endsWith("n"));//true } }
  • 21. String replace() Method The String class replace() method replaces all occurrence of first sequence of character with second sequence of character. Example: public class Stringoperation8 { public static void main(String args[]) { String s1="Java is fun."; String replaceString=s1.replace(“fun",“Awesome");//replaces all occurrences of “fun" to “ Awesome " System.out.println(replaceString); } }
  • 22. String trim() method The String class trim() method eliminates white spaces before and after the String. Example: public class Stringoperation2 { public static void main(String ar[]) { String s=" Sachin "; System.out.println(s);// Sachin System.out.println(s.trim());//Sachin } }
  • 23. String Case Conversion: The Java String toUpperCase() method converts this String into uppercase letter and String toLowerCase() method into lowercase letter. Example: public class Stringoperation1 { public static void main(String ar[]) { String s="Sachin"; System.out.println(s.toUpperCase());//SACHIN System.out.println(s.toLowerCase());//sachin System.out.println(s);//Sachin(no change in original) } }
  • 24. StringBuffer Class • StringBuffer class is used to create mutable (modifiable) String objects. i.e. it can be changed. • A String that can be modified or changed is known as mutable String. • StringBuffer is synchronized, which means it is thread-safe. Multiple threads can safely access a StringBuffer object without any issues. • StringBuffer contains various methods for string manipulation, such as append, insert, delete, reverse, etc 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 capacity) It creates an empty String buffer with the specified capacity as length
  • 25. StringBuffer append() Method: The append() method concatenates the given argument with this String. Example: class StringBufferExample{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java } }
  • 26. StringBuffer insert() Method: The insert() method inserts the given String with this string at the given position. Example: 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 } }
  • 27. StringBuffer delete() Method: The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex. Example: class StringBufferExample4{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.delete(1,3); System.out.println(sb);//prints Hlo } } The delete(1, 3) method deletes characters from index 1 to index 2 (excluding index 3).
  • 28. StringBuffer reverse() Method: The reverse() method of the StringBuilder class reverses the current String. Example: class StringBufferExample5{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.reverse(); System.out.println(sb);//prints olleH } }
  • 29. StringBuilder Class Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. Constructor Description StringBuilder() It creates an empty String Builder with the initial capacity of 16. StringBuilder(String str) It creates a String Builder with the specified string. StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
  • 30. StringBuilder append() method: The StringBuilder append() method concatenates the given argument with this String. class StringBuilderExample{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java } }
  • 31. StringBuilder insert() method The StringBuilder insert() method inserts the given string with this string at the given position. class StringBuilderExample2{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } }
  • 32. StringBuilder replace() method • The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex. class StringBuilderExample3{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello"); sb.replace(1,3,"Java"); System.out.println(sb);//prints HJavalo } }
  • 33. StringBuilder delete() method: The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex. class StringBuilderExample4{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello"); sb.delete(1,3); System.out.println(sb);//prints Hlo } }
  • 34. StringBuilder reverse() method: The reverse() method of StringBuilder class reverses the current string. class StringBuilderExample5{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello"); sb.reverse(); System.out.println(sb);//prints olleH } }
  • 35. String Constructor. 1. Empty Constructor: 2. Constructor with String Argument: 3. Constructor with Byte Array Argument: 4. Constructor with Character Array Argument:
  • 36. 1. Empty Constructor: This creates an empty string object with no characters. Example: public class StringClassExample { public static void main(String[] args) { String str = new String(); System.out.print("Value of str is ""+str+"""); } } Here an empty string is created using the String constructor with no arguments.
  • 37. 2. Constructor from another string Creates a string object initialized with the specified string. Example: String greeting = new String("Hello, World!"); System.out.println("Greeting: " + greeting);
  • 38. 3. Constructor with Byte Array: Creates a string from an array of bytes. // Create a byte array byte[] byteArray = {72, 101, 108, 108, 111}; String str = new String(byteArray);
  • 39. 4. Constructor with Character Array: This creates a string object from a character array. char[] charArray = {'H', 'e', 'l', 'l', 'o'}; String fromCharArray = new String(charArray);
  • 40. Java program demonstrating the use of string constructors: public class StringConstructorExample { public static void main(String[] args) { // Using different string constructors String str1 = new String(); // Empty constructor String str2 = new String("Hello"); // Constructor with string argument char[] charArray = {'W', 'o', 'r', 'l', 'd'}; String str3 = new String(charArray); // Constructor with char array argument // Displaying the strings System.out.println("String 1: " + str1); System.out.println("String 2: " + str2); System.out.println("String 3: " + str3); } }