0% found this document useful (0 votes)
26 views4 pages

Java String Programs for Beginners

Uploaded by

jyotsnas99
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)
26 views4 pages

Java String Programs for Beginners

Uploaded by

jyotsnas99
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

Java String Programs


// string buffer class demo
public class StringBuffDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1= "Hello";
StringBuffer sb= new StringBuffer("Hello");
[Link]("Java");
[Link]("Java");
[Link]("String s1:"+s1);
[Link]("String sb:"+sb);

}
}

// program to find whether the given string is palindrome or not


import [Link];
public class StringPalindrome {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str, rev = "";
Scanner sc = new Scanner([Link]);
[Link]("Enter a string:");
str = [Link]();
int length = [Link]();
for ( int i = length - 1; i >= 0; i-- )
rev = rev + [Link](i);
if ([Link](rev))
[Link](str+"is a palindrome");
else
[Link](str+"is not a
palindrome");
}
}
// program to demonstrate string methods
public class StringDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1=" Welcome JAVA ";
String s2= new String("Hello World ");
String s3= [Link](s2);
String s4= "Hello world ";
[Link]([Link](s2));
[Link]([Link]());
[Link]([Link](6));
[Link]([Link](s2));
[Link]([Link]("Hello"));
[Link]([Link](s4));
[Link]([Link](6));
[Link]([Link](8, 12));
//[Link]([Link](s1));
[Link]([Link]("World",
"Globe"));
[Link]([Link](s2, s1));
[Link]([Link](" "));
[Link]([Link]());
}
}

// program to count the occurrences of a character


public class Charcount {
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "aaaabbccAAdd";
char search = 'a'; // Character to
search is 'a'.
int count=0;
for(int i=0; i<[Link](); i++)
{
if([Link](i) == search)
count++;
}

[Link]("The Character
'"+search+"' appears "+count+" times.");
}
}

// program to compare the strings


public class CompareString {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1 = "This is Exercise 1";
String str2 = "This is Exercise 2";
String str3 = "this is exercise 2";
[Link]("String 1: " + str1);
[Link]("String 2: " + str2);
// Compare the two strings.
int result = [Link](str2);
int result1 = [Link](str2);
// Display the results of the comparison.
if (result < 0)
{
[Link]("\"" + str1 + "\"" +
" is less than " +
"\"" + str2 + "\"");
}
else if (result == 0)
{
[Link]("\"" + str1 + "\"" +
" is equal to " +
"\"" + str2 + "\"");
}
else // if (result > 0)
{
[Link]("\"" + str1 + "\"" +
" is greater than " +
"\"" + str2 + "\"");
}
}
}

Common questions

Powered by AI

The `startsWith` method checks if a string begins with a specified prefix and returns a boolean value. It is useful for scenarios where verification of a string's preliminary segment is necessary, such as validating input formats or protocols. For example, it can be used in URL validation to ensure that an address begins with "http:" or "https:" .

`String` in Java is immutable and suited for scenarios with minimal modification needs, but this immutability can lead to performance overhead due to frequent reallocation in mutable operations. `StringBuilder` and `StringBuffer` are mutable and more efficient for frequent modifications. `StringBuffer` is synchronized and thread-safe, making it slower due to overhead for multi-threading scenarios, whereas `StringBuilder` is non-synchronized, making it faster but unsafe for concurrent use. Selection depends on use case, emphasizing balancing thread-safety and performance .

The Java program determines if a given string is a palindrome by reversing the string and comparing it to the original. The method is effective because a palindrome reads the same backward as forward. It first reads user input for a string, reverses it through iteration from the end to the start, and then uses the `equals()` method to compare the original and reversed strings to check if they are the same .

The primary difference between the "String" and "StringBuffer" classes in Java, as demonstrated, is mutability. Strings in Java are immutable, meaning once created, their values cannot be changed. The "StringBuffer" class, on the other hand, is mutable, allowing for modification of the content without creating a new object each time a change is made. In the provided program, the `concat()` method on "String" does not change the original string, whereas `append()` on "StringBuffer" modifies the original object .

The order of string concatenation affects performance due to intermediate object creation in Java. Using `+` in loops can inadvertently create numerous intermediate `String` objects, impacting performance negatively. Instead, `StringBuilder` or `StringBuffer` should be used for iterative or complex concatenations due to their mutable nature, enhancing performance by minimizing unnecessary object creation. Such practices optimize memory usage and execution speed in Java applications .

Methods like `substring` and `replace` provide powerful mechanisms for textual transformations in Java. `substring` allows extraction of specified parts of a string, crucial for text splitting, data parsing, and reducing input to necessary content. `replace` enables substitution of part of the string, useful for data sanitization, format correction, or simple content changes without modifying the original string. Such operations are central in handling and manipulating text data effectively .

The Java `Character` class provides essential utilities for handling character data types, moving beyond basic ASCII representation to support Unicode. This is critical for operations involving mixed-case characters and non-Latin scripts, ensuring consistency in operations like conversions to uppercase/lowercase, checking character types, or validating character properties. By accommodating different alphabets and symbol sets, it facilitates internationalization and adherence to global standards in Java applications .

The program uses `compareToIgnoreCase` instead of `compareTo` to perform a case-insensitive comparison of two strings. This is necessary when strings are intended to be logically equivalent regardless of case differences, such as capitalized versus lowercase letters. For instance, "Hello" and "hello" would be considered equal using `compareToIgnoreCase`, whereas `compareTo` would identify them as different, since ASCII values of uppercase letters differ from their lowercase equivalents .

Having a case-sensitive or case-insensitive search is critical when counting character occurrences to ensure accurate results based on case significance context. A case-sensitive count differentiates 'A' from 'a', while a case-insensitive count treats them as the same character. Programmatically, to perform a case-insensitive count, the string and character can be converted to the same case (either upper or lower) before comparisons. This distinction can prevent errors when case uniformity isn't vital to the intended logic .

The `split` method might be commented out because its use could be inappropriate or result in runtime exceptions given the current context and input strings. Using `split` on unreasonable or incompatible patterns could lead to `PatternSyntaxException`, and processing an empty string or `null` could result in a `NullPointerException`. This could also be for demonstration control, ensuring the main logic focus stays intact .

You might also like