0% found this document useful (0 votes)
6 views24 pages

Module 2 Java Revision

The document provides an overview of the String class in Java, detailing its immutability and various constructors for creating String objects from different data types. It also covers string operations such as concatenation, modification methods, and comparison techniques, along with examples for clarity. Additionally, it introduces StringBuffer methods and character extraction methods, highlighting their functionalities.

Uploaded by

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

Module 2 Java Revision

The document provides an overview of the String class in Java, detailing its immutability and various constructors for creating String objects from different data types. It also covers string operations such as concatenation, modification methods, and comparison techniques, along with examples for clarity. Additionally, it introduces StringBuffer methods and character extraction methods, highlighting their functionalities.

Uploaded by

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

1.

Define String
Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters.
 The java.lang.String class is used to create a string object.
 Java implements strings as objects of type String.
 when you create a String object, you are creating a string that cannot be changed.
That is, once a String object has been created, you cannot change the characters
that comprise that string. String is immutable
 when we perform string operations on the strings, a new String object is created
that contains the modifications. The original string is left unchanged.
1. Default Constructor
 Syntax: String()
Creates a new empty string with no characters and length zero.
Example:
String str1 = new String();
System.out.println("Default constructor: "" + str1 );

2. Constructor with Character Array


 Syntax: String(char[] chars)
Creates a string by converting the entire character array into a string.
Example:
char[] charArray = { 'H', 'e', 'l', 'l', 'o' };
String str2 = new String(charArray);
System.out.println("Char array constructor: \"" + str2 + "\"");
3. Constructor with Subset of Character Array
 Syntax: String(char[] chars, int startIndex, int count)
 Description:
Creates a string using a portion of a character array starting at startIndex and
including count characters.
Example:
char[] chars = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3); // Output: cde
System.out.println("Subset char array: \"" + s + "\"");

✅ 4. Constructor from Another String


 Syntax: String(String str)
 Description:
Creates a new string object that contains the same character sequence as the
given string object.
Example:
String original = "Hello";
String s = new String(original);
System.out.println("Copy constructor: \"" + s + "\"");

✅ 5. Constructor with Byte Array (default charset)


 Syntax: String(byte[] bytes)
 Description:
Converts the entire byte array into characters using the platform's default
character set.
Example:
byte[] byteArray = {72, 101, 108, 108, 111}; // H e l l o
String str3 = new String(byteArray);
System.out.println("Byte array (default): \"" + str3 + "\"");

✅ 6. Constructor with Byte Array and Charset


 Syntax: String(byte[] bytes, Charset charset)
 Description:
Constructs a new string by decoding the byte array using the specified character
encoding.
Example:
String str4 = new String(byteArray, StandardCharsets.UTF_8);
System.out.println("Byte array (UTF-8): \"" + str4 + "\"");

byte[] byteArrayUtf16 = {0, 72, 0, 101, 0, 108, 0, 108, 0, 111}; // UTF-16 for Hello
String str5 = new String(byteArrayUtf16, StandardCharsets.UTF_16);
System.out.println("Byte array (UTF-16): \"" + str5 + "\"");
✅ 7. Constructor with StringBuffer
 Syntax: String(StringBuffer buffer)
 Description:
Creates a string that contains the same characters as the given StringBuffer
object.
Example:
StringBuffer sbf = new StringBuffer("Hello");
String str6 = new String(sbf);
System.out.println("StringBuffer constructor: \"" + str6 + "\"");
✅ 8. Constructor with StringBuilder
 Syntax: String(StringBuilder builder)
 Description:
Creates a string from the character sequence currently in the StringBuilder.
Example:
StringBuilder sbd = new StringBuilder("Hello");
String str7 = new String(sbd);
System.out.println("StringBuilder constructor: \"" + str7 + "\"");
\
CHARACTER EXTRACTION METHOD
String Special Operations
❖ These operations include the automatic creation of new String instances from string
literals,
❖ Concatenation of multiple String objects by use of the + operator,
❖ And the conversion of other data types to a string representation.

String Literals
❖ There is an easier way to create a String using a string literal.
❖ For each string literal in your program, Java automatically constructs a String object.
❖ Thus, you can use a string literal to initialize a String object. ❖ Example:
 char chars[] = { 'a', 'b', 'c' };
 String s1 = new String(chars); // using character array
 String s2 = "abc"; // using string literal

String Concatenation
❖ In general, 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 new String object.
❖ Example:
 String age = "9";
 String s = "He is " + age + " years old.";
 System.out.println(s);
❖ This displays the string "He is 9 years old."

String Conversion (valueOf() )


❖ valueOf() is a static method in the String class.
❖ It is used to convert primitive types and objects into a string representation.
 int num = 25;
 String s = String.valueOf(num); // Converts int to string
 System.out.println(s); // Output: "25"

String Modification method


1) SUBSTRING(): The substring () method is used to extract a portion of a string.
It has two forms:
1. String substring (int startIndex)
o Returns the substring starting from startIndex to the end.
o Example:
 String str = "HelloWorld";
 String sub = str.substring(5); // Output: "World"
2. String substring(int startIndex, int endIndex)
o Returns the substring from startIndex to (endIndex - 1).
o Example:
 String str = "HelloWorld";
 String sub = str.substring(0, 5); // Output: "Hello"
2) REPLACE (): The replace () method replaces characters or sequences in a string.
It has two forms:
1. String replace (char original, char replacement)
o Replaces all occurrences of one character with another.
o Example: String s = "Hello".replace('l', 'w'); // Output: "Hewwo"
2. String replace (CharSequence original, CharSequence replacement)
o Replaces all occurrences of a sequence with another sequence.
o Example:
 String sentence = "Java is fun. Java is powerful.";
 String modified = sentence.replace("Java", "Python");
 // Output: "Python is fun. Python is powerful."
3) REPLACEALL (): The replaceAll() method replaces all occurrences of a pattern (regular
expression) with a replacement string.
 Syntax: String replaceAll(String regex, String replacement)

 Example:
 String str = "abc123abc";
 String result = str.replaceAll("[a-z]", "*"); // Output: "***123***"

4) CONCAT() : The concat() method joins two strings.


 Syntax: String concat(String str)
 Description: Appends str to the end of the invoking string and returns a new
string.
 Example:
 String s1 = "one";
 String s2 = s1.concat("two"); // Output: "onetwo"

5) TOUPPERCASE (): The toUpperCase() method converts all characters in a string to


uppercase.
 Syntax: String toUpperCase()
 Example:
 String s = "hello";
 String upper = s.toUpperCase(); // Output: "HELLO"
6) TOLOWERCASE (): The toLowerCase() method converts all characters in a string to
lowercase.
 Syntax: String toLowerCase()
 Example:
 String s = "HELLO123";
 String lower = s.toLowerCase(); // Output: "hello123"
 non-alphabet characters like digits are not affected.
 Both methods return a new String and follow the default locale rules.

7) TRIM(): The trim() method removes leading and trailing whitespace from a string.
 Syntax: String trim()
 Example:
 String s = " Hello World ";
 String trimmed = s.trim(); // Output: "Hello World"

EQUALS AND ==
equals () ==

Compares the memory reference (i.e.,


Compares the content of two strings.
whether both refer to same object).

Performs character-by-character Checks if both references point to the same


comparison. memory location.

Works whether the strings are in the string Returns true only if both are the same
pool or heap. object in memory.

"Hello" == "Hello" → true (because of string


"Hello".equals("Hello") → true
pool)

new String("Hello").equals("Hello") → true new String("Hello") == "Hello" → false


(same content) (different objects)

⚠️Use only for comparing object


✅ Use when comparing string values
references
Write a program to remove duplicate characters from the given string
and display the resultant string.
This program:
 Takes a string input from the user.
 Removes all duplicate characters while preserving the original order of first
occurrences.
 Displays both the original and modified strings.
🔹 Key Concepts Used:
 Scanner – for user input.
 LinkedHashSet – stores characters uniquely and maintains insertion order.
 StringBuilder – used to build the final result string efficiently.
STRING BUFFER METHODS
1. append (String s)
 The append() method adds the string representation of any data type to the
end of the StringBuffer object.
 Several overloaded versions exist:
o StringBuffer append(String str)
o StringBuffer append(int num)
o StringBuffer append(Object obj)
 The string representation of each parameter is usually obtained using
String.valueOf().
 The result is added to the current StringBuffer, and the modified object is
returned.
2. insert(int offset, String s)
 Used to insert the specified string at a given position.
 Overloaded to accept Strings, Objects, CharSequences, and all primitive
types.
 The string form of the value is inserted at the specified index.
 Common forms:
o StringBuffer insert(int index, String str)
o StringBuffer insert(int index, char ch)
o StringBuffer insert(int index, Object obj)
 index specifies where the value will be inserted in the StringBuffer.
3. delete()
 Deletes a sequence of characters from the StringBuffer.
 Syntax: StringBuffer delete(int startIndex, int endIndex)
 startIndex: Index of the first character to remove.
 endIndex: Index one past the last character to remove.
 Deletes characters from startIndex to endIndex - 1.
4. deleteCharAt()
 Deletes a single character from a specific index.
 Syntax: StringBuffer deleteCharAt(int loc)
 loc: Index of the character to delete.
 Returns the modified StringBuffer.

5. reverse()
 Reverses the characters in the StringBuffer.
 Syntax: StringBuffer reverse()
 Returns the reversed buffer.

6. replace()
 Replaces a portion of the string with another string.
 Syntax: StringBuffer replace(int startIndex, int endIndex, String str)
 Replaces characters from startIndex to endIndex - 1 with str.
 Returns the updated StringBuffer.

7. setLength()
 Sets the length of the string in the StringBuffer.
 Syntax: void setLength(int len)
 len must be nonnegative.
 If length is increased, null characters (\u0000) are added.
 If decreased, extra characters are lost.

8. ensureCapacity()
 Pre-allocates space in the buffer for future characters.
 Syntax: void ensureCapacity(int minCapacity)
 minCapacity is the minimum buffer size to allocate.
9. capacity()
 Returns the total allocated space of the buffer.
 Syntax: int capacity()

10. charAt()
 Retrieves a character at a specific index.
 Syntax: char charAt(int where)
 where: Index of the character to retrieve.
 Index must be valid (not negative and within the string length).

11. substring(int beginIndex, int endIndex)


 Retrieves a part of the string.
 Two forms:
o String substring(int startIndex)
o String substring(int startIndex, int endIndex)
 First form: Returns from startIndex to end of string.
 Second form: Returns from startIndex to endIndex - 1.
12. indexOf()
 Returns the index of the first occurrence of a specified substring.
 Syntax: int indexOf(String str)
 Returns the index of the beginning of the substring if found, or -1 if not
found.
String comparison
1) equals()
 Used to compare two strings for exact equality.
 Case-sensitive: "Java" and "java" are considered different.
 Syntax: boolean equals(Object str)
 Example:
 String s1 = "Java";
 String s2 = "Java";
 boolean result = s1.equals(s2); // true

2) equalsIgnoreCase()
 Compares two strings for equality, ignoring case differences.
 "Java" and "java" are considered equal.
 Syntax: boolean equalsIgnoreCase(String str)
 Example:
 String s1 = "Java";
 String s2 = "java";
 boolean result = s1.equalsIgnoreCase(s2); // true

3) compareTo()
 Compares two strings based on dictionary (lexicographical) order.
 Returns:
o 0 if strings are equal
o Negative value if calling string comes before the other
o Positive value if it comes after
 Case-sensitive
 Syntax: int compareTo(String str)
 Example:
 String s1 = "Apple";
 String s2 = "Banana";
 int result = s1.compareTo(s2); // negative (Apple < Banana)

4) compareToIgnoreCase()
 Same as compareTo() but ignores case differences.
 Syntax: int compareToIgnoreCase(String str)
 Example:
 String s1 = "apple";
 String s2 = "Apple";
 int result = s1.compareToIgnoreCase(s2); // 0

5) matches()
 Checks if the entire string matches the given regular expression.
 Useful for pattern validation (e.g., phone number, email).
 Syntax: boolean matches(String regex)
 Example:
 String s = "abc123";
 boolean result = s.matches("[a-z]+[0-9]+"); // true

6) startsWith()
 Checks whether a string starts with a specified prefix.
 Can also start checking from a given index.
 Syntax: boolean startsWith(String str)
 boolean startsWith(String str, int startIndex)
 Examples:
 String s = "Foobar";
 s.startsWith("Foo"); // true
 s.startsWith("bar", 3); // true (starts from index 3)

7) endsWith()
 Checks whether a string ends with a specific suffix.
 Syntax: boolean endsWith(String str)
 Example:
 String s = "Foobar";
 boolean result = s.endsWith("bar"); // true

8) regionMatches()
 Compares specific regions (substrings) from two strings.
 Can be case-sensitive or case-insensitive.
 Syntax: boolean regionMatches(int startIndex, String str2, int
str2StartIndex, int numChars)
 boolean regionMatches(boolean ignoreCase, int startIndex,
String str2, int str2StartIndex, int numChars)
 Parameters:
o startIndex: Starting index in the calling string
o str2: Second string to compare with
o str2StartIndex: Starting index in the second string
o numChars: Number of characters to compare
o ignoreCase: If true, case will be ignored

 Examples:
 String s1 = "HelloWorld";
 String s2 = "WORLD";
 boolean result1 = s1.regionMatches(5, s2, 0, 5); // false
(case-sensitive)
 boolean result2 = s1.regionMatches(true, 5, s2, 0, 5);
// true (case-insensitive)

STRING SEARCH
1) contains()
 Checks if a string contains a specified sequence of characters (substring).
 Returns true if the substring exists, false otherwise.
 Syntax: boolean contains(CharSequence sequence)
 Example:
 String s = "Hello World";
 boolean result = s.contains("World"); // true

2) indexOf()
 Searches for the first occurrence of a character or substring.
 Returns the index where it is found, or -1 if not found.
 Syntax:
 int indexOf(char ch)
 int indexOf(String str)
 int indexOf(char ch, int startIndex)
 int indexOf(String str, int startIndex)
 Examples:
 String s = "Java Programming";
 int idx1 = s.indexOf('a'); // 1
 int idx2 = s.indexOf("gram"); // 8
 int idx3 = s.indexOf('a', 3); // 11
 int idx4 = s.indexOf("a", 5); // 11

3) lastIndexOf()
 Searches for the last occurrence of a character or substring.
 Returns the index where it was last found, or -1 if not found.

 Syntax:
 int lastIndexOf(char ch)
 int lastIndexOf(String str)
 int lastIndexOf(char ch, int startIndex)
 int lastIndexOf(String str, int startIndex)
 Examples:
 String s = "Programming in Java";
 int idx1 = s.lastIndexOf('a'); // 19
 int idx2 = s.lastIndexOf("Java"); // 16
 int idx3 = s.lastIndexOf('a', 15); // 11
 int idx4 = s.lastIndexOf("in", 10); // 5

4) startsWith()
 Checks if a string starts with a specified prefix.
 Can also specify an index to start checking from.
 Syntax:
 boolean startsWith(String prefix)
 boolean startsWith(String prefix, int startIndex)
 Examples:
 String s = "Foobar";
 s.startsWith("Foo"); // true
 s.startsWith("bar", 3); // true

5) endsWith()
 Checks if a string ends with a specified suffix.
 Returns true if it ends with the given string.
 Syntax: boolean endsWith(String suffix)

 Example:
 String s = "Foobar";
 boolean result = s.endsWith("bar"); // true

6) matches()
 Checks whether a string fully matches a regular expression pattern.
 Returns true if the pattern matches the entire string.
 Syntax: boolean matches(String regex)
 Example:
 String s = "abc123";
 boolean result = s.matches("[a-z]+[0-9]+"); // true
More
1) isEmpty()
 Checks if the string has zero characters.
 Returns true if the string is empty (""), otherwise false.
 Syntax: boolean isEmpty()
 Example:
 String s1 = "";
 String s2 = "Hello";
 System.out.println(s1.isEmpty()); // true
 System.out.println(s2.isEmpty()); // false

2) toString()
 Returns the string representation of an object.
 Commonly used to convert objects (like StringBuffer, arrays, etc.) into string
form.
 Every class in Java inherits this method from the Object class.
 Syntax: String toString()
 Example:
 StringBuffer sb = new StringBuffer("Hello");
 String str = sb.toString(); // Converts StringBuffer to String

3) valueOf()
 Converts different data types (like int, float, char, boolean, objects) to
String.
 It’s a static method of the String class.
 Syntax: static String valueOf(dataType data)

 Common forms:
 String.valueOf(int i)
 String.valueOf(float f)
 String.valueOf(Object obj)
 Example:
 int num = 100;
 String s = String.valueOf(num); // "100"

4) length()
 Returns the number of characters in a string.
 Spaces and special characters are also counted.
 Syntax: int length()
 Example:
 String s = "Hello";
 int len = s.length(); // 5

You might also like