String in java, string constructors and operations

manjeshbngowda 64 views 72 slides Sep 18, 2024
Slide 1
Slide 1 of 72
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72

About This Presentation

Ppt on strings in java.. String constructors and operations


Slide Content

MODULE 2 String Handling

Java Strings In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'. We use double quotes to represent a string in Java. For example / create a string String type = "Java programming“ Here, we have created a string variable named type . The variable is initialized with the string Java Programming.

Example: Create a String in Java class Main { public static void main(String[] args ) { // create strings String first = "Java"; String second = "Python"; String third = "JavaScript"; // print strings System.out.println (first); // print Java System.out.println (second); // print Python System.out.println (third); // print JavaScript } }

String length The length() method returns the number of characters in a string. Example class Main { public static void main(String[] args ) { String str1 = "Java is fun"; // returns the length of str1 int length = str1.length(); System.out.println (str1.length()); } } // Output: 11

String length length() Syntax The syntax of the string's length() method is: string.length () length() Arguments The length() method doesn't take any arguments. length() Return Value The length() method returns the length of a given string.

Example: Java String length() class Main { public static void main(String[] args ) { String str1 = "Java"; String str2 = ""; System.out.println (str1.length()); // 4 System.out.println (" Java".length ()); // 4 // length of empty string System.out.println (str2.length()); // 0 // new line is considered a single character System.out.println ("Java\ n".length ()); // 5 System.out.println ("Learn Java".length ()); // 10 } }

String constructors In Java, strings are represented by the String class, which is part of the java.lang package (automatically imported in every Java program). The String class provides multiple ways (constructors) to create and initialize string objects.

String constructors in java String() String(String str) String(char chars[ ]) String(char chars[ ], int startIndex , int count) String(byte byteArr [ ]) String(byte byteArr [ ], int startIndex , int count)

String() To create an empty string, we will call the default constructor. The general syntax to create an empty string in Java program is as follows: String s = new String(); It will create a string object in the heap area with no value.

  String(String str) This constructor will create a new string object in the heap area and stores the given value in it. The general syntax to construct a string object with the specified string str is as follows: String st = new String(String str); For example: String s2 = new String("Hello Java"); Here, the object str contains Hello Java.

String(char chars[ ]) This string constructor creates a string object and stores the array of characters in it. The general syntax to create a string object with a specified array of characters is as follows: String str = new String(char char[]) For example: char chars[] = { 'a', 'b', 'c', 'd' }; String s3 = new String(chars); The object reference variable s3 contains the address of the value stored in the heap area.

// we will create a string object and store an array of characters in it. package stringPrograms ; public class Science { public static void main(String[ ] args ) { char chars[] = {'s', 'c', ' i ', 'e', 'n', 'c', 'e'}; String s = new String(chars); System.out.println (s); } } Output: science

4.  String(char chars[ ], int startIndex , int count) This constructor creates and initializes a string object with a subrange of a character array. The argument startIndex specifies the index at which the subrange begins and count specifies the number of characters to be copied. The general syntax to create a string object with the specified subrange of character array is as follows:

4.  String(char chars[ ], int startIndex , int count) String str = new String(char chars[ ], int startIndex , int count); For example: char chars[] = { 'w', ' i ', 'n', 'd', 'o', 'w', 's' }; String str = new String(chars, 2, 3); The object str contains the address of the value ” ndo ” stored in the heap area because the starting index is 2 and the total number of characters to be copied is 3.

package stringPrograms ; public class Windows { public static void main(String[] args ) { char chars[] = { 'w', ' i ', 'n', 'd', 'o', 'w', 's' }; String s = new String(chars, 0,4); System.out.println (s); } } Output: wind

Java program where we will create a string object that contains the same characters sequence as another string object. package stringPrograms ; public class MakeString { public static void main(String[] args ) { char chars[] = { 'F', 'A', 'N' }; String s1 = new String(chars); String s2 = new String(s1); System.out.println (s1); System.out.println (s2); } } Output: FAN FAN

5.  String(byte byteArr [ ]) This type of string constructor constructs a new string object by decoding the given array of bytes (i.e., by decoding ASCII values into the characters) according to the system’s default character set. package stringPrograms ; public class ByteArray { public static void main(String[] args ) { byte b[] = { 97, 98, 99, 100 }; // Range of bytes: -128 to 127. These byte values will be converted into corresponding characters. String s = new String(b); System.out.println (s); } } Output: abcd

Special string operations in JAVA String literals Concatenation of strings String Conversion using toString ( )  Character extraction String comparison

string literals string literal in your program, Java automatically constructs a String object. Thus string literal can be used to initialize a String object. For example, the following code fragment creates two equivalent strings: char chars[] = { 'a', 'b', 'c' }; String s1 = new String(chars); String s2 = " abc "; // use string literal String object is created for every string literal, you can use a string literal any place you can use a String object. For example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. It calls the length( ) method on the string “ abc ”. As expected, it prints “3”. System.out.println (" abc ".length());

Concatenation of Strings Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. String age = "9"; String s = "He is " + age + " years old."; This displays the string “He is 9 years old.” String Concatenation with Other Data Types You can concatenate strings with other types of data. Be careful when you mix other types of operations with string concatenation expressions, however.

String Conversion using toString ( )  If you want to represent any object as a string,  toString () method  comes into existence. The toString () method returns the String representation of the object. If you print any object, Java compiler internally invokes the toString () method on the object. So overriding the toString () method, returns the desired output, it can be the state of an object etc. depending on your implementation. By overriding the toString () method of the Object class, we can return values of the object, so we don't need to write much code.

Understanding problem without toString () method class Student{ int rollno ; String name; String city; Student(int rollno , String name, String city){ this.rollno = rollno ; this.name=name; this.city =city; } public static void main(String args []){ Student s1=new Student(101,"Raj","lucknow"); Student s2=new Student(102,"Vijay","ghaziabad"); System.out.println (s1);//compiler writes here s1.toString() System.out.println (s2);//compiler writes here s2.toString() } } Output: Student@1fee6fc Student@1eed786 in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since Java compiler internally calls toString () method, overriding this method will return the specified values.

Example of Java toString () method class Student{ int rollno ; String name; String city; Student(int rollno , String name, String city){ this.rollno = rollno ; this.name=name; this.city =city; } public String toString (){//overriding the toString () method return rollno +" "+name+" "+city; } public static void main(String args []){ Student s1=new Student(101,"Raj","lucknow"); Student s2=new Student(102,"Vijay","ghaziabad"); System.out.println (s1);//compiler writes here s1.toString() System.out.println (s2);//compiler writes here s2.toString() } } Output: 101 Raj lucknow 102 Vijay ghaziabad

Character extraction The String class in Java provides several ways to extract characters from a String object charAt (int index):  This method is used to return the char value at the specified index. The value of the index must be nonnegative and specify a location within the string. For example: char ch ; ch = " abc ". charAt (1); Result: assigns the value “b” to ch.

Character extraction 2. getChars ( ) To extract more than one character from a String object, we can use this method. General form:  void getChars (int sourceStart , int sourceEnd , char target[ ], int targetStart ) Here,  sourceStart  specifies the starting index of the substring, and  sourceEnd  specifies an index that is one past the end of the desired substring. The variable target specifies the resultant array. 

class getCharsDemo { public static void main(String args []) { String s = "This is a demo of the getChars method."; int start = 10; int end = 14; char buf [] = new char[end - start]; s.getChars (start, end, buf , 0); System.out.println ( buf ); } } Output: demo

3. getBytes ( ): This is an alternative method to getChars ( ). It stores the characters in a byte array. General form: byte[ ] getBytes ( ) 4. toCharArray ( ) To convert all the characters of a String object into a character array, this method is used. It returns a character array for the given string. General form: char[ ] toCharArray ( )

String Comparison The String class in Java includes several methods to compare strings or substrings Some of the important string operations in Java to compare strings are given below: equals( ) and equalsIgnoreCase ( ) compareTo () compareToIgnoreCase ():

1. equals( ) and equalsIgnoreCase ( ) equals( ) and equalsIgnoreCase ( ) To compare two strings for equality, use equals( ). It has this general form: boolean equals(Object str) Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive. equalsIgnoreCase ( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form: boolean equalsIgnoreCase (String str) Here, str is the String object being compared with the invoking String object. It, too, returns true if the strings contain the same characters in the same order, and false otherwise.

class equalsDemo { public static void main(String args []) { String s1 = "Hello"; String s2 = "Hello"; String s3 = "Good-bye"; String s4 = "HELLO"; System.out.println (s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println (s1 + " equals " + s3 + " -> " + s1.equals(s3)); System.out.println (s1 + " equals " + s4 + " -> " + s1.equals(s4)); System.out.println (s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4)); } } Output : Hello equals Hello -> true Hello equals Good-bye -> false Hello equals HELLO -> false Hello equalsIgnoreCase HELLO -> true

The equals( ) method and the “==”operator perform different functions. The equals( ) method compares the characters of a String object, whereas the == operator compares the references of two string objects to see whether they refer to the same instance. A simple program to demonstrate the above difference is given below: The variable s1 is pointing to the String "Hello". The object pointed by s2 is constructed with the help of s1. Thus, the values inside the two String objects are the same, but they are distinct objects.

class Demo { public static void main(String args []) { String s1 = "Hello"; String s2 = new String(s1); System.out.println (s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println (s1 + " == " + s2 + " -> " + (s1 == s2)); } } Output: Hello equals Hello -> true Hello == Hello -> false

2. compareTo () The compareTo () method of the Java String class compares the string lexicographically. It returns a positive, negative, or zero value. To perform a sorting operation on strings, the compareTo () method comes in handy. A string is less than another if it comes before in the dictionary order. A string is greater than another if it comes after in the dictionary order. General form: int compareTo (String str) Here, str is the string being compared with the invoking string.

class SortStringFunc { static String arr [] = {"Now", "is", "the", "time", "for", "all", "good", " men","to ", "come", "to", "the", "aid", "of", "their", "country" }; public static void main(String args []) { for(int j = 0; j < arr.length ; j++ ) { for(int i = j + 1; i < arr.length ; i ++) { if( arr [ i ]. compareTo ( arr [j]) < 0) { String t = arr [j]; arr [j] = arr [ i ]; arr [ i ] = t; } } System.out.println ( arr [j]); } } } Output: Now aid all come country for good is men of the the their time to to

3. compareToIgnoreCase (): This method is the same as compareTo ( ), but it ignores the lowercase and uppercase differences of the strings while comparing.

Searching Strings The Java String class provides two methods that allow us to search a character or substring in another string. indexOf ( ): It searches the first occurrence of a character or substring. lastIndexOf ( ): It searches the last occurrence of a character or substring.

class indexOfDemo { public static void main(String args []) { String s = "Now is the time for all good men " + "to come to the aid of their country."; System.out.println (s); System.out.println (" indexOf (t) = " + s.indexOf ('t')); System.out.println (" lastIndexOf (t) = " + s.lastIndexOf ('t')); System.out.println (" indexOf (the) = " + s.indexOf ("the")); System.out.println (" lastIndexOf (the) = " + s.lastIndexOf ("the")); System.out.println (" indexOf (t, 10) = " + s.indexOf ('t', 10)); System.out.println (" lastIndexOf (t, 60) = " + s.lastIndexOf ('t', 60)); System.out.println (" indexOf (the, 10) = " + s.indexOf ("the", 10)); System.out.println (" lastIndexOf (the, 60) = " + s.lastIndexOf ("the", 60)); } } Output: Now is the time for all good men to come to the aid of their country. indexOf (t) = 7 lastIndexOf (t) = 65 indexOf (the) = 7 lastIndexOf (the) = 55 indexOf (t, 10) = 11 lastIndexOf (t, 60) = 55 indexOf (the, 10) = 44 lastIndexOf (the, 60) = 55

Modifying a String substring( ) 2. concat ( ) 3. replace( ) 4. trim( )

1. substring( ) As the name suggests, ‘sub + string’, is a subset of a string. By subset, we mean the contiguous part of a character array or string. The  substring()  method is used to fetch a substring from a string in Java.  General form: String substring(int startIndex ) String substring(int startIndex , int endIndex )   Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index i.e [startindex,endindex-1]

/ Substring replacement. class StringReplace { public static void main(String args []) { String org = "This is a test. This is, too."; String search = "is"; String sub = "was"; String result = ""; int i ; do { // replace all matching substrings System.out.println (org); i = org.indexOf (search); if( i != -1) { result = org.substring (0, i ); result = result + sub; result = result + org.substring ( i + search.length ()); org = result; } } while( i != -1); } } Output : This is a test. This is, too. Thwas is a test. This is, too. Thwas was a test. This is, too. Thwas was a test. Thwas is, too. Thwas was a test. Thwas was, too.

2. concat ( ) To concatenate two strings in Java, we can use the  concat ( )  method apart from the “+” operator.  General form: String concat (String str)   This method creates a new object containing the invoking string with the str appended to the end. This performs the same function as the + operator. Refer to the comparison table below:

3. replace( ) This method is used to replace a character with some other character in a string. It has two forms. The first replaces all occurrences of one character in the invoking string with another character. General form: String replace(char original, char replacement) Here, the original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example: String s = " Hello".replace ('l', 'w’); Result:  s= “ Hewwo ”

3. replace( ) The second form replaces one character sequence with another.    General form: String replace( CharSequence original, CharSequence replacement)

4. trim( ) The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. General form: String trim( ) For example: String s = " Hello World ".trim(); Result: s= “Hello World”

Data Conversion Using valueOf ( ) For converting different data types into strings, the  valueOf ()  method is used. It is a static method defined in the Java String class.  General form: static String valueOf (double num)  static String valueOf (long num)  static String valueOf (Object ob )  static String valueOf (char chars[ ]) For example: int num=20; String s1= String.valueOf (num); s1 = s1+10; //concatenating string s1 with 10 Result s1=2010

Changing the Case of Characters in a String The method  toLowerCase ( )  converts all the characters in a string from uppercase to lowercase.  The  toUpperCase ( )   method converts all the characters in a string from lowercase to uppercase.

// Demonstrate toUpperCase () and toLowerCase (). class ChangeCase { public static void main(String args []) { String s = "This is a test."; System.out.println ("Original: " + s); String upper = s.toUpperCase (); String lower = s.toLowerCase (); System.out.println ("Uppercase: " + upper); System.out.println ("Lowercase: " + lower); } } Output: Original: This is a test. Uppercase: THIS IS A TEST. Lowercase: this is a test.

Joining strings In Java, you can join strings using the String.join () method. This method allows you to concatenate multiple strings with a specified delimiter. String fruits = String.join (" ", "Orange", "Apple", "Mango"); System.out.println (fruits); The join() method takes two parameters. delimiter - the delimiter to be joined with the elements elements - elements to be joined

Syntax() String.join ( CharSequence delimiter, CharSequence ... elements) Here, ... signifies there can be one or more CharSequence . String.join ( CharSequence delimiter, Iterable elements)

class Main { public static void main(String[] args ) { String str1 = "I"; String str2 = "love"; String str3 = "Java"; // join strings with space between them String joinedStr = String.join (" ", str1, str2, str3); System.out.println ( joinedStr ); } } // Output: I love Java

class Main { public static void main(String[] args ) { String result; result = String.join ("-", "Java", "is", "fun"); System.out.println (result); // Java-is-fun } }

StringBuffer in Java StringBuffer  is a class in the  java.lang  package that represents a mutable sequence of characters. Unlike the  String class , StringBuffer allows you to modify the content of the string object after it has been created. 

StringBuffer buffer = new StringBuffer ("Hello, "); buffer.append ("World!"); // appends to the existing value buffer.insert (7, "Java "); // inserts at a specified index buffer.reverse (); // reverses the characters System.out.println (buffer); // prints: "! dlroW avaJ , olleH "

Key Features of StringBuffer   Mutable: StringBuffer provides the flexibility to change the content, making it ideal for scenarios where you have to modify strings frequently. Synchronized: Being thread-safe, it ensures that only one thread can access the buffer's methods at a time, making it suitable for multi-threaded environments. Performance Efficient: For repeated string manipulation, using StringBuffer can be more efficient than the String class. Method Availability: StringBuffer offers several methods to manipulate strings. These include append(), insert(), delete(), reverse(), and replace().

When to Use StringBuffer ?  When you need to perform several modifications to strings, using  StringBuffer  is an efficient choice. Due to the mutability of  StringBuffer , it doesn't create a new object for every modification, leading to less memory consumption and improved performance.  StringBuffer  is especially beneficial in a multithreaded environment due to its synchronized methods, ensuring thread safety

1. append()  The append() method adds the specified value to the end of the current string. StringBuffer buffer = new StringBuffer (" javaguides "); buffer.append (" - For Beginners"); System.out.println (buffer); // Output: " javaguides - For Beginners "

2. insert()  The  insert()  method adds the specified value at the given index. import java.io.*; class A { public static void main(String args []) { StringBuffer sb = new StringBuffer ("Hello "); sb.insert (1, "Java"); // Now original string is changed System.out.println (sb); } } Output HJavaello

3. delete()  The delete() method of the StringBuffer class deletes the string from the specified beginIndex to endIndex-1. import java.io.*; class A { public static void main(String args []) { StringBuffer sb = new StringBuffer ("Hello"); sb.delete (1, 3); System.out.println ( sb ); }} Output Hlo

  4.replace()  The replace() method replaces the given string from the specified beginIndex and endIndex-1. import java.io.*; class A { public static void main(String args []) { StringBuffer sb = new StringBuffer ("Hello"); sb.replace (1, 3, "Java"); System.out.println ( sb ); } } Output HJavalo

5.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 } }

6.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"); System.out.println ( sb.capacity ());//now (16*2)+2=34 i.e ( oldcapacity *2)+2 } } Output: 16 16 34

7.ensureCapacity() The ensureCapacity () method of the StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the 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 StringBufferExample7{ 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"); System.out.println ( sb.capacity ());//now (16*2)+2=34 i.e ( oldcapacity *2)+2 sb.ensureCapacity (10);//now no change System.out.println ( sb.capacity ());//now 34 sb.ensureCapacity (50);//now (34*2)+2 System.out.println ( sb.capacity ());//now 70 } } Output: 16 16 34 34 70

Important Constructors of StringBuffer Class Constructor with CharSequence StringBuilder sb = new StringBuilder( CharSequence seq); This constructor creates a StringBuilder instance that contains the same characters as the specified CharSequence . Like the constructor with a string, the initial capacity will be the length of the CharSequence plus 16.

public class StringBuilderExample { public static void main(String[] args ) { // Default constructor StringBuilder sb1 = new StringBuilder(); sb1.append("Hello, World!"); System.out.println (sb1); // Constructor with initial capacity StringBuilder sb2 = new StringBuilder(50); sb2.append("Initial capacity set to 50."); System.out.println (sb2); // Constructor with initial string StringBuilder sb3 = new StringBuilder("Initial String"); sb3.append(" appended text."); System.out.println (sb3); // Constructor with CharSequence CharSequence seq = " CharSequence example"; StringBuilder sb4 = new StringBuilder( seq ); sb4.append(" additional text."); System.out.println (sb4); } } output Hello, World! Initial capacity set to 50. Initial String appended text. CharSequence example additional text.

String builder A StringBuilder is a mutable sequence of characters used in programming languages such as Java, C#, and others. It is designed to efficiently handle strings that undergo multiple modifications, such as concatenations, insertions, deletions, or appending operations. Unlike immutable string objects, StringBuilder allows for these operations without creating new string objects, making it more performance-efficient, especially in scenarios involving extensive string manipulation.

append: Appends the specified data to the end of the StringBuilder. sb.append ("Hello"); sb.append (123); sb.append (true); insert : Inserts the specified data at the specified position. sb.insert (0, "Start: "); delete : Removes the characters in a substring of this sequence. sb.delete (5, 10); deleteCharAt : Removes the character at the specified position. sb.deleteCharAt (0); commonly used methods of StringBuilder:

replace : Replaces the characters in a substring of this sequence with characters in the specified string. sb.replace (0, 5, "Hi"); reverse : Reverses the sequence of characters. sb.reverse (); toString : Converts the StringBuilder to a String. String result = sb.toString (); setLength : Sets the length of the character sequence. sb.setLength (10); commonly used methods of StringBuilder:

public class StringBuilderExample { public static void main(String[] args ) { // Default constructor StringBuilder sb = new StringBuilder(); // Appending different types of data sb.append ("Hello, "); sb.append ("World!"); sb.append (" Number: ").append(42); sb.append (" Boolean: ").append(true); System.out.println ( sb.toString ()); // Inserting text sb.insert (7, "Java "); System.out.println ( sb.toString ()); // Deleting text sb.delete (7, 12); System.out.println ( sb.toString ()); // Replacing text sb.replace (7, 12, "Universe"); System.out.println ( sb.toString ()); // Reversing the sequence sb.reverse (); System.out.println ( sb.toString ()); // Converting to String String result = sb.toString (); System.out.println ("Final result: " + result); } } OUTPUT Hello, World! Number: 42 Boolean: true Hello, Java World! Number: 42 Boolean: true Hello, World! Number: 42 Boolean: true Hello, Universe! Number: 42 Boolean: true eurt : naelooB 24 : rebmuN ! esrevinU , olleH Final result: eurt : naelooB 24 : rebmuN ! esrevinU , olleH