0% found this document useful (0 votes)
13 views23 pages

Module 2 Own

Uploaded by

Pravallika Reddy
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)
13 views23 pages

Module 2 Own

Uploaded by

Pravallika Reddy
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/ 23

Module 2

Behavior: Creates an empty string with no characters ("").

Behavior: Initializes the string with all characters from the array.
Behavior: Creates string starting from index 2, taking 3 characters.

Behavior: Creates a new string that is a copy of the existing string.

Behavior: Converts each byte (ASCII value) to its character equivalent using
the default charset.
Behavior: Starts at index 2 and takes 3 bytes to form the string.
StringBuffer sb = new StringBuffer("Hello");

String s = new String(sb);

System.out.println(s); // Output: Hello

Behavior: Converts StringBuffer to String.

StringBuilder sb = new StringBuilder("World");

String s = new String(sb);


System.out.println(s); // Output: World

Behavior: Converts StringBuilder to String.


h). Constructor from Unicode Code Points (int[])

int[] codePoints = {65,66,67,68,69,70};

String s = new String(codePoints, 2, 3);

System.out.println(s); // Output: CDE

Behavior: Converts a subrange of Unicode code points to a string.

int length( )
• A new string is created using the char array.
• s.length() returns the total number of characters in the string.
• Since "abc" has 3 characters, the output is 3.
4.Special String Operations
a. String Literals
• Java automatically creates a String object for each string literal.
• You can use literals anywhere a String object is expected.
Example:
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // using a string literal
"abc" is automatically converted to a String object.
b. String Concatenation Using + Operator
• The + operator is overloaded to perform string concatenation.
• You can concatenate multiple strings directly.
Example:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s); // Output: He is 9 years old.
Use Case: Useful for combining strings across multiple lines.
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
c. Concatenation with Other Data Types
• Java automatically converts non-string types to string when used with +.
Example:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s); // Output: He is 9 years old.
String s1 = "four: " + 2 + 2;
System.out.println(s1); // Output: four: 22
• The integer is converted into a string before concatenation.
Note: Be careful when mixing numeric operations and string concatenation. Use
parentheses to clarify intent.

d.String Conversion and toString( )


➢ valueOf( ) is overloaded for all the primitive types and for type Object.
➢ For the primitive types, valueOf( ) returns a string that contains the
human readable equivalent of the value with which it is called.
➢ For objects, valueOf( ) calls the toString( ) method on the object.
toString( ) method returns the string representation for objects.
➢ toString() is pre-defined method present in Object class.
➢ You should override toString() in your classes to return a human-
readable string that describes the object.
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
public String toString() {
return "Dimensions: " + width + " x " + height + " x " + depth;
}
}
public class Demo {
public static void main(String[] args) {
Box b = new Box(10, 20, 15);
System.out.println(b); // Calls b.toString() automatically
}
}
Output: Dimensions: 10.0 x 20.0 x 15.0
We can see, Box’s toString( ) method is automatically invoked when a Box
object is used in a concatenation expression or in a call to println( )

//demo
for(char c:a{
System.out.print(c)
String s = "Hello"; }

char[] a = s.toCharArray();
iv) getBytes()
• Converts a string to a byte array, based on the platform’s
default character encoding.
Syntax:
byte[] getBytes()
Use Case: When exporting strings to environments using 8-bit
String str = "Hello";
ASCII. byte[] byteArray = str.getBytes();

// Print the byte array representation


System.out.println("Byte array representation:");
for (byte b : byteArray) {
System.out.println(b);
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";

System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
System.out.println(s1.equals(s4)); // false
System.out.println(s1.equalsIgnoreCase(s4)); // true
Example:

public class CompareToExample {

public static void main(String[] args) {

String s1 = "apple";

String s2 = "banana";

String s3 = "apple";

System.out.println(s1.compareTo(s2)); // Output: negative value -1


System.out.println(s2.compareTo(s1)); // Output: positive value 1

System.out.println(s1.compareTo(s3)); // Output: 0 0

}
}
E . regionMatches( )
The regionMatches( ) method compares a specific region inside a string with another specific
region in another string. There is an overloaded form that allows you to ignore case in such
comparisons. Here are the general forms for these two methods
Example:
public class Main {
public static void main(String[] args) {

String s = "Java is the best language for coding.";


System.out.println(s);

// Basic indexOf and lastIndexOf with char

System.out.println("indexOf('t') = " + s.indexOf('t')); //8

System.out.println("lastIndexOf('t') = " + s.lastIndexOf('t')); //15

// indexOf and lastIndexOf with String

System.out.println("indexOf(\"the\") = " + s.indexOf("the")); //8


System.out.println("lastIndexOf(\"the\") = " + s.lastIndexOf("the")); //8

// With fromIndex - char

System.out.println("indexOf('t', 10) = " + s.indexOf('t', 10)); //15

System.out.println("lastIndexOf('t', 25) = " + s.lastIndexOf('t', 25)); //15

// With fromIndex - String


System.out.println("indexOf(\"the\", 5) = " + s.indexOf("the", 5)); //8
System.out.println("lastIndexOf(\"the\", 20) = " + s.lastIndexOf("the", 20)); //8

Example:

public class Main {

public static void main(String[] args) {

String message = "Java Programming";

// Using substring(startIndex)
String sub1 = message.substring(5);

System.out.println("Substring from index 5: " + sub1); // Programming

// Using substring(startIndex, endIndex)

String sub2 = message.substring(0, 4);

System.out.println("Substring from index 0 to 3: " + sub2); //Java

}
public class Main {

public static void main(String[] args) {

String str1 = "Hello, ";


String str2 = "World!";

// Using concat() method

String result1 = str1.concat(str2);

System.out.println("Using concat(): " + result1);

// Using + operator (same result)

String result2 = str1 + str2;

System.out.println("Using + operator: " + result2);

}
}
Example

public class Main {

public static void main(String[] args) {

String original = "Java is lang";


// Replace character: 'l' with 'g'

String result1 = original.replace('l', 'g');

System.out.println("After replacing 'l' with 'g': " + result1);

// Replace substring: "Java" with "Python"

String result2 = original.replace("Java", "Python");

System.out.println("After replacing \"Java\" with \"Python\": " + result2);

}
}

Example

String s = " Hello, World! ";


System.out.println(s.trim());

CLOD
Example
public class SimpleValueOfExample {

public static void main(String[] args) {

System.out.println("Double: " + String.valueOf(10.5)); // Output: 10.5

System.out.println("Long: " + String.valueOf(123456789L)); // Output: 123456789


Object obj = new Integer(25);

System.out.println("Object: " + String.valueOf(obj)); // Output: 25

char[] arr = {'J', 'a', 'v', 'a'};

System.out.println("Char Array: " + String.valueOf(arr)); // Output: Java

System.out.println("Char Array Subrange: " + String.valueOf(arr, 1, 2)); // Output: av

}
Example:

public class JoinExample {

public static void main(String[] args) {

String result = String.join(", ", "Java", "Python", "C++", "JavaScript");


System.out.println("Joined String: " + result);

}
Since sb is initialized with the string "Hello" when it is created, its length is 5. Its capacity is
21 because room for 16 additional characters is automatically added.
SON
public class CharAtSetCharAtDemo {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

// charAt() - get character at index 1


char ch = sb.charAt(1);

System.out.println("Character at index 1: " + ch); // Output: e

// setCharAt() - change character at index 1

sb.setCharAt(1, 'a');
System.out.println("After modification: " + sb); // Output: Hallo

}
Performance

String: Slow in modifications (due to immutability).

StringBuffer: Slower than StringBuilder (due to synchronization).

StringBuilder: Faster than both String and StringBuffer in single-threaded contexts.


P-Performance
I- Immutable/Introduced
IMPOTNI +
N-New
O-Overriden
M-Memory
t-Thread
+ - + operator
String str1 = "HelloWorld";
String str2 = "worldwide";

// Case-sensitive comparison
boolean match1 = str1.regionMatches(5, str2, 0, 5);
System.out.println("Case-sensitive match: " + match1); // false

// Case-insensitive comparison
boolean match2 = str1.regionMatches(true, 5, str2, 0, 5);
System.out.println("Case-insensitive match: " + match2); // true

You might also like