0% found this document useful (0 votes)
17 views26 pages

Java String Methods: 50 Examples

Uploaded by

thomasshelby5998
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)
17 views26 pages

Java String Methods: 50 Examples

Uploaded by

thomasshelby5998
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

Section 1: Single String Methods (50 Programs)

Program 1.1 - length() - Find the length of a single word.


public class Program1_1 {
public static void main(String[] args) {
String s = "Hello";
[Link]("Length: " + [Link]());
}
}

Expected Output:
Length: 5
Explanation: length() returns number of characters.

Program 1.2 - length() - Find length of a sentence with spaces.


public class Program1_2 {
public static void main(String[] args) {
String s = "Hello Java";
[Link]("Length: " + [Link]());
}
}

Expected Output:
Length: 10
Explanation: Spaces count as characters.

Program 1.3 - length() - Compare lengths of two strings.


public class Program1_3 {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Programming";
[Link]("Length s1: " + [Link]());
[Link]("Length s2: " + [Link]());
}
}

Expected Output:
Length s1: 4
Length s2: 11
Explanation: Shows length() on two strings.

Program 1.4 - length() - Check if string is empty using length.


public class Program1_4 {
public static void main(String[] args) {
String s = "";
[Link]("Empty: " + ([Link]()==0));
}
}

Expected Output:
Empty: true
Explanation: length()==0 indicates empty.

Program 1.5 - length() - Use length to access last char index.


public class Program1_5 {
public static void main(String[] args) {
String s = "Hello";
[Link]([Link]([Link]()-1));
}
}

Expected Output:
o
Explanation: Use length()-1 to get last char.

Program 1.6 - charAt() - Get first character of a word.


public class Program1_6 {
public static void main(String[] args) {
String s = "apple";
[Link]("First char: " + [Link](0));
}
}

Expected Output:
First char: a
Explanation: charAt(0) returns first character.

Program 1.7 - charAt() - Get last character using length()-1.


public class Program1_7 {
public static void main(String[] args) {
String s = "banana";
[Link]("Last char: " + [Link]([Link]()-1));
}
}

Expected Output:
Last char: a
Explanation: Use length()-1 to access last char.

Program 1.8 - charAt() - Print characters one per line.


public class Program1_8 {
public static void main(String[] args) {
String s = "cat";
for(int i=0;i<[Link]();i++){ [Link]([Link](i)); }
}
}

Expected Output:
c
a
t
Explanation: Print each character using charAt in a loop.

Program 1.9 - charAt() - Check if first char is uppercase.


public class Program1_9 {
public static void main(String[] args) {
String s = "Hello";
[Link]("Starts with uppercase: " + [Link]([Link](0)));
}
}

Expected Output:
Starts with uppercase: true
Explanation: Check case of first character.

Program 1.10 - charAt() - Compare two chars at same index.


public class Program1_10 {
public static void main(String[] args) {
String a = "java";
String b = "jada";
[Link]("Same at idx 1: " + ([Link](1)==[Link](1)));
}
}

Expected Output:
Same at idx 1: true
Explanation: Compare chars at specific index.

Program 1.11 - substring() - Extract first three letters.


public class Program1_11 {
public static void main(String[] args) {
String s = "program";
[Link]([Link](0,3));
}
}

Expected Output:
pro
Explanation: substring(0,3) extracts first three chars.

Program 1.12 - substring() - Extract file extension from filename.


public class Program1_12 {
public static void main(String[] args) {
String s = "[Link]";
int pos = [Link](".");
[Link]([Link](pos+1));
}
}

Expected Output:
jpg
Explanation: Find dot and substring after it.

Program 1.13 - substring() - Get last 4 chars of a string.


public class Program1_13 {
public static void main(String[] args) {
String s = "archive";
[Link]([Link]([Link]()-5));
}
}

Expected Output:
hive
Explanation: Extract last few characters (adjust indices).

Program 1.14 - substring() - Remove first and last char using substring.
public class Program1_14 {
public static void main(String[] args) {
String s = "hello";
[Link]([Link](1, [Link]()-1));
}
}

Expected Output:
ell
Explanation: Remove first and last characters.

Program 1.15 - substring() - Extract middle part from even-length string.


public class Program1_15 {
public static void main(String[] args) {
String s = "coding";
int mid = [Link]()/2;
[Link]([Link](mid-1, mid+1));
}
}

Expected Output:
di
Explanation: Extract middle two characters.

Program 1.16 - equals() - Compare two identical strings.


public class Program1_16 {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
[Link]([Link](b));
}
}

Expected Output:
true
Explanation: equals compares contents.

Program 1.17 - equals() - Compare different strings.


public class Program1_17 {
public static void main(String[] args) {
String a = "Java";
String b = "java";
[Link]([Link](b));
}
}

Expected Output:
false
Explanation: equals is case-sensitive.

Program 1.18 - equals() - Check if string equals yes.


public class Program1_18 {
public static void main(String[] args) {
String ans = "yes";
[Link]("Confirmed: " + [Link]("yes"));
}
}

Expected Output:
Confirmed: true
Explanation: Compare with a literal.

Program 1.19 - equals() - Compare after trim to ensure equality.


public class Program1_19 {
public static void main(String[] args) {
String a = "hi";
String b = " hi ".trim();
[Link]([Link](b));
}
}

Expected Output:
true
Explanation: Trim before comparing.

Program 1.20 - equals() - Use equals to compare constructed strings.


public class Program1_20 {
public static void main(String[] args) {
String a = new String("test");
String b = "test";
[Link]([Link](b));
}
}

Expected Output:
true
Explanation: equals compares content even between objects.

Program 1.21 - equalsIgnoreCase() - Compare same text different case.


public class Program1_21 {
public static void main(String[] args) {
String a = "Hello";
String b = "hello";
[Link]([Link](b));
}
}

Expected Output:
true
Explanation: Ignore case when comparing.

Program 1.22 - equalsIgnoreCase() - Check user answer ignoring case.


public class Program1_22 {
public static void main(String[] args) {
String ans = "YeS";
[Link]("Accepted: " + [Link]("yes"));
}
}

Expected Output:
Accepted: true
Explanation: Useful for user input checks.

Program 1.23 - equalsIgnoreCase() - Compare after toLowerCase.


public class Program1_23 {
public static void main(String[] args) {
String a = "JAVA";
String b = "java";
[Link]([Link]().equals(b));
}
}

Expected Output:
true
Explanation: Alternative normalization using toLowerCase.

Program 1.24 - equalsIgnoreCase() - Email local part check ignoring case.


public class Program1_24 {
public static void main(String[] args) {
String mail = "User@[Link]";
String exp = "user@[Link]";
[Link]([Link](exp));
}
}

Expected Output:
true
Explanation: Case-insensitive check for emails.

Program 1.25 - equalsIgnoreCase() - Password check (not recommended).


public class Program1_25 {
public static void main(String[] args) {
String p1="Pass";
String p2="pass";
[Link]([Link](p2));
}
}

Expected Output:
true
Explanation: Shows behavior (not secure for real passwords).

Program 1.26 - toLowerCase() - Convert uppercase to lowercase.


public class Program1_26 {
public static void main(String[] args) {
String s = "JAVA";
[Link]([Link]());
}
}

Expected Output:
java
Explanation: Convert letters to lowercase.

Program 1.27 - toLowerCase() - Normalize before comparison.


public class Program1_27 {
public static void main(String[] args) {
String a="Hello";
String b="hello";
[Link]([Link]().equals(b));
}
}

Expected Output:
true
Explanation: Normalize case for comparison.

Program 1.28 - toLowerCase() - Count occurrences case-insensitively.


public class Program1_28 {
public static void main(String[] args) {
String s="AaAa";
String low = [Link]();
int count=0;
for(int i=0;i<[Link]();i++) if([Link](i)=='a') count++;
[Link]("Count of a: " + count);
}
}

Expected Output:
Count of a: 4
Explanation: Lowercase then count.

Program 1.29 - toLowerCase() - Find index after converting to lower.


public class Program1_29 {
public static void main(String[] args) {
String s = "Hello World";
[Link]("Index of w: " + [Link]().indexOf("w"));
}
}

Expected Output:
Index of w: 6
Explanation: Lowercase then indexOf.

Program 1.30 - toLowerCase() - Format for display in logs.


public class Program1_30 {
public static void main(String[] args) {
String s = "UserName";
[Link]([Link]());
}
}

Expected Output:
username
Explanation: Lowercase strings for consistent logs.
Program 1.31 - toUpperCase() - Convert to uppercase.
public class Program1_31 {
public static void main(String[] args) {
String s = "java";
[Link]([Link]());
}
}

Expected Output:
JAVA
Explanation: Convert letters to uppercase.

Program 1.32 - toUpperCase() - Make an acronym from words.


public class Program1_32 {
public static void main(String[] args) {
String s = "java virtual machine";
String[] parts = [Link](" ");
String ac="";
for(String p:parts) ac += [Link](0);
[Link]([Link]());
}
}

Expected Output:
JVM
Explanation: Take initials and uppercase.

Program 1.33 - toUpperCase() - Highlight word in uppercase.


public class Program1_33 {
public static void main(String[] args) {
String s = "hello world";
String first = [Link](0,5).toUpperCase();
[Link](first + [Link](5));
}
}

Expected Output:
HELLO world
Explanation: Uppercase part of the string.

Program 1.34 - toUpperCase() - Compare after toUpperCase()


public class Program1_34 {
public static void main(String[] args) {
String a="test";
String b="TEST";
[Link]([Link]().equals(b));
}
}

Expected Output:
true
Explanation: Normalize and compare.

Program 1.35 - toUpperCase() - Uppercase for environment variables.


public class Program1_35 {
public static void main(String[] args) {
String env="prod";
[Link]([Link]());
}
}

Expected Output:
PROD
Explanation: Uppercase commonly used for env names.

Program 1.36 - indexOf() - Find position of letter.


public class Program1_36 {
public static void main(String[] args) {
String s = "developer";
[Link]("Index of e: " + [Link]("e"));
}
}

Expected Output:
Index of e: 1
Explanation: indexOf returns first occurrence index.

Program 1.37 - indexOf() - Find position of substring.


public class Program1_37 {
public static void main(String[] args) {
String s = "hello world";
[Link]("Index of world: " + [Link]("world"));
}
}

Expected Output:
Index of world: 6
Explanation: indexOf with substring.

Program 1.38 - indexOf() - Check if char absent.


public class Program1_38 {
public static void main(String[] args) {
String s = "abc";
[Link]("Not found: " + [Link]("z"));
}
}

Expected Output:
Not found: -1
Explanation: indexOf returns -1 if not found.

Program 1.39 - indexOf() - Find first and last index.


public class Program1_39 {
public static void main(String[] args) {
String s = "banana";
[Link]("First index of a: " + [Link]("a"));
[Link]("Last index of a: " + [Link]("a"));
}
}
Expected Output:
First index of a: 1
Last index of a: 5
Explanation: Use indexOf and lastIndexOf.

Program 1.40 - indexOf() - Find '@' in email to split username.


public class Program1_40 {
public static void main(String[] args) {
String s = "me@[Link]";
int pos = [Link]("@");
[Link]("Index of @: " + pos);
[Link]("Username: " + [Link](0,pos));
}
}

Expected Output:
Index of @: 2
Username: me
Explanation: Locate separator and substring username.

Program 1.41 - replace() - Replace character globally.


public class Program1_41 {
public static void main(String[] args) {
String s = "banana";
[Link]([Link]("a","o"));
}
}

Expected Output:
bonono
Explanation: Replace characters globally.

Program 1.42 - replace() - Replace substring.


public class Program1_42 {
public static void main(String[] args) {
String s = "I love Java";
[Link]([Link]("Java","Python"));
}
}

Expected Output:
I love Python
Explanation: Replace substring with another.

Program 1.43 - replace() - Remove vowels by replacing with empty.


public class Program1_43 {
public static void main(String[] args) {
String s = "apple";
String r =
[Link]("a","").replace("e","").replace("i","").replace("o","").replace("u","");
[Link](r);
}
}
Expected Output:
ppl
Explanation: Chain replace calls to remove vowels.

Program 1.44 - replace() - Mask digits in a string (simple).


public class Program1_44 {
public static void main(String[] args) {
String s = "a1b2";
[Link]([Link]("1","*").replace("2","*"));
}
}

Expected Output:
a*b*
Explanation: Replace digits with mask.

Program 1.45 - replace() - Replace only first occurrence (note).


public class Program1_45 {
public static void main(String[] args) {
String s = "apple apple";
[Link]([Link]("apple","orange"));
}
}

Expected Output:
orange apple
Explanation: replaceFirst replaces only the first occurrence.

Program 1.46 - trim() - Trim surrounding spaces.


public class Program1_46 {
public static void main(String[] args) {
String s = " hello ";
[Link](">" + [Link]() + "<");
}
}

Expected Output:
>hello<
Explanation: Trim removes leading and trailing spaces.

Program 1.47 - trim() - Check length before and after trim.


public class Program1_47 {
public static void main(String[] args) {
String s = " java ";
[Link]("Before: " + [Link]());
[Link]("After: " + [Link]().length());
}
}

Expected Output:
Before: 8
After: 4
Explanation: Trim affects length.
Program 1.48 - trim() - Trim then compare with literal.
public class Program1_48 {
public static void main(String[] args) {
String s = " hi ";
[Link]("Equal to "hi": " + [Link]().equals("hi"));
}
}

Expected Output:
Equal to "hi": true
Explanation: Trim before comparing.

Program 1.49 - trim() - Trim does not remove inner spaces.


public class Program1_49 {
public static void main(String[] args) {
String s = " a b ";
[Link]([Link]());
}
}

Expected Output:
a b
Explanation: Trim leaves inner spaces intact.

Program 1.50 - trim() - Use trim before splitting (demo).


public class Program1_50 {
public static void main(String[] args) {
String s = " x ";
[Link]([Link]());
}
}

Expected Output:
x
Explanation: Trim to normalize string edges.
Page 12
Section 2: Mixed String Methods (20 Programs)

Program 2.1 - substring() + toUpperCase()


public class Program2_1 {
public static void main(String[] args) {
String s = "hello world";
[Link]([Link](0,5).toUpperCase());
}
}

Expected Output:
HELLO
Explanation: Extract substring and uppercase.

Program 2.2 - replace() + equalsIgnoreCase()


public class Program2_2 {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "hallo";
String r = [Link]("e","a");
[Link]([Link](s2));
}
}

Expected Output:
true
Explanation: Replace then compare ignoring case.

Program 2.3 - trim() + length()


public class Program2_3 {
public static void main(String[] args) {
String s = " Java ";
[Link]("Length before: " + [Link]());
[Link]("Length after: " + [Link]().length());
}
}

Expected Output:
Length before: 8
Length after: 4
Explanation: Trim and length.

Program 2.4 - toLowerCase() + indexOf()


public class Program2_4 {
public static void main(String[] args) {
String s = "HELLO";
[Link]([Link]().indexOf("l"));
}
}

Expected Output:
2
Explanation: Lowercase then indexOf.
Program 2.5 - charAt() + substring()
public class Program2_5 {
public static void main(String[] args) {
String s = "developer";
[Link]([Link](0) + [Link](1,4));
}
}

Expected Output:
ddev
Explanation: charAt plus substring.

Program 2.6 - toUpperCase() + replace()


public class Program2_6 {
public static void main(String[] args) {
String s = "java";
[Link]([Link]().replace("A","O"));
}
}

Expected Output:
JOVO
Explanation: Uppercase then replace.

Program 2.7 - length() + substring()


public class Program2_7 {
public static void main(String[] args) {
String s = "coding";
[Link]([Link](0, [Link]()/2));
}
}

Expected Output:
cod
Explanation: Use length for substring.

Program 2.8 - toLowerCase() + equalsIgnoreCase()


public class Program2_8 {
public static void main(String[] args) {
String a = "JAVA";
String b = "java";
[Link]([Link]().equalsIgnoreCase(b));
}
}

Expected Output:
true
Explanation: Normalize and compare.

Program 2.9 - indexOf() + substring()


public class Program2_9 {
public static void main(String[] args) {
String s = "email@[Link]";
int pos = [Link]("@");
[Link]("Username: " + [Link](0,pos));
}
}

Expected Output:
Username: email
Explanation: Use indexOf then substring.

Program 2.10 - trim() + toUpperCase() + replace()


public class Program2_10 {
public static void main(String[] args) {
String s = " java rocks ";
[Link]([Link]().toUpperCase().replace(" ", "_"));
}
}

Expected Output:
JAVA_ROCKS
Explanation: Chain methods.

Program 2.11 - charAt() + toUpperCase()


public class Program2_11 {
public static void main(String[] args) {
String s = "java";
[Link]([Link]([Link](0)).toUpperCase());
}
}

Expected Output:
J
Explanation: Char to string then uppercase.

Program 2.12 - substring() + replace()


public class Program2_12 {
public static void main(String[] args) {
String s = "abc123abc";
[Link]([Link]("abc","xyz"));
}
}

Expected Output:
xyz123xyz
Explanation: Replace substring occurrences.

Program 2.13 - toLowerCase() + replace()


public class Program2_13 {
public static void main(String[] args) {
String s = "JavaJAVA";
[Link]([Link]().replace("java","jav"));
}
}

Expected Output:
javjav
Explanation: Lowercase then replace.
Program 2.14 - indexOf() + replace()
public class Program2_14 {
public static void main(String[] args) {
String s = "a-b-c";
[Link]([Link]("-","_"));
}
}

Expected Output:
a_b_c
Explanation: Replace separators.

Program 2.15 - trim() + equals()


public class Program2_15 {
public static void main(String[] args) {
String s1 = " hi ";
String s2 = "hi";
[Link]([Link]().equals(s2));
}
}

Expected Output:
true
Explanation: Trim then compare.

Program 2.16 - length() + toUpperCase()


public class Program2_16 {
public static void main(String[] args) {
String s = "ok";
if ([Link]()==2) [Link]([Link]()); else [Link](s);
}
}

Expected Output:
OK
Explanation: Use length and then uppercase.

Program 2.17 - charAt() + indexOf()


public class Program2_17 {
public static void main(String[] args) {
String s = "apple";
char c = [Link](1);
[Link](c + " at " + [Link](c));
}
}

Expected Output:
p at 1
Explanation: Find index of char obtained via charAt.

Program 2.18 - substring() + equals()


public class Program2_18 {
public static void main(String[] args) {
String s = "hello";
String sub = [Link](0,5);
[Link]([Link]("hello"));
}
}

Expected Output:
true
Explanation: Extract substring then compare.

Program 2.19 - replace() + trim()


public class Program2_19 {
public static void main(String[] args) {
String s = " a b ";
[Link]([Link](" ","_").trim());
}
}

Expected Output:
_a_b
Explanation: Replace spaces then trim.

Program 2.20 - toUpperCase() + indexOf() + substring()


public class Program2_20 {
public static void main(String[] args) {
String s = "hello world";
String up = [Link]();
int pos = [Link]("WORLD");
[Link]([Link](pos));
}
}

Expected Output:
WORLD
Explanation: Uppercase then substring.
Page 18
Section 3: String Methods with Loops (20 Programs)

Program 3.1 - Count vowels in a string.


public class Program3_1 {
public static void main(String[] args) {
String s = "education";
int count = 0;
for (int i=0;i<[Link]();i++) {
char ch = [Link](i);
if ("aeiou".indexOf(ch) != -1) count++;
}
[Link]("Vowels: " + count);
}
}

Expected Output:
Vowels: 5
Explanation: Iterate and count vowels.

Program 3.2 - Reverse a string using loop.


public class Program3_2 {
public static void main(String[] args) {
String s = "hello";
String rev = "";
for (int i = [Link]()-1; i>=0; i--) { rev += [Link](i); }
[Link](rev);
}
}

Expected Output:
olleh
Explanation: Reverse by iterating from end.

Program 3.3 - Check palindrome.


public class Program3_3 {
public static void main(String[] args) {
String s = "madam";
String rev = "";
for (int i = [Link]()-1; i>=0; i--) rev += [Link](i);
[Link]([Link](rev));
}
}

Expected Output:
true
Explanation: Reverse and compare.

Program 3.4 - Count spaces in a string.


public class Program3_4 {
public static void main(String[] args) {
String s = "Java is fun";
int cnt=0;
for(int i=0;i<[Link]();i++) if([Link](i)==' ') cnt++;
[Link]("Spaces: " + cnt);
}
}

Expected Output:
Spaces: 2
Explanation: Count spaces.

Program 3.5 - Count words (simple split).


public class Program3_5 {
public static void main(String[] args) {
String s = "I love Java programming";
String trimmed = [Link]();
String[] parts = [Link](" ");
[Link]("Words: " + [Link]);
}
}

Expected Output:
Words: 4
Explanation: Trim and split to count words.

Program 3.6 - Count occurrences of a letter.


public class Program3_6 {
public static void main(String[] args) {
String s = "banana";
char target = 'a';
int c=0;
for(int i=0;i<[Link]();i++) if([Link](i)==target) c++;
[Link]("Count of a: " + c);
}
}

Expected Output:
Count of a: 3
Explanation: Count specific character.

Program 3.7 - Replace vowels with * using loop.


public class Program3_7 {
public static void main(String[] args) {
String s = "education";
String res = "";
for(int i=0;i<[Link]();i++){
char ch = [Link](i);
if("aeiou".indexOf(ch)!=-1) res += "*"; else res += ch;
}
[Link](res);
}
}

Expected Output:
*d*c*t**n
Explanation: Replace vowels in loop.

Program 3.8 - Compare two strings char by char.


public class Program3_8 {
public static void main(String[] args) {
String a = "java";
String b = "lava";
int diff=0;
for(int i=0;i<[Link]();i++) if([Link](i)!=[Link](i)) diff++;
[Link]("Different chars: " + diff);
}
}

Expected Output:
Different chars: 1
Explanation: Compare characters at each index.

Program 3.9 - Alternate casing.


public class Program3_9 {
public static void main(String[] args) {
String s = "java";
String res="";
for(int i=0;i<[Link]();i++){
if(i%2==0) res += [Link]([Link](i)); else res += [Link](i);
}
[Link](res);
}
}

Expected Output:
JaVa
Explanation: Alternate characters uppercased.

Program 3.10 - Remove spaces using loop.


public class Program3_10 {
public static void main(String[] args) {
String s = "Java is awesome";
String out="";
for(int i=0;i<[Link]();i++) if([Link](i)!=' ') out += [Link](i);
[Link](out);
}
}

Expected Output:
Javaisawesome
Explanation: Remove spaces manually.

Program 3.11 - Count digits in a string.


public class Program3_11 {
public static void main(String[] args) {
String s = "a1b2c3";
int d=0;
for(int i=0;i<[Link]();i++) if([Link](i)>='0' && [Link](i)<='9') d++;
[Link]("Digits: " + d);
}
}

Expected Output:
Digits: 3
Explanation: Count numeric characters.

Program 3.12 - Find most frequent character (simple).


public class Program3_12 {
public static void main(String[] args) {
String s = "aabbbc";
char best = [Link](0);
int bestCount=0;
for(int i=0;i<[Link]();i++){
char c = [Link](i);
int cnt=0;
for(int j=0;j<[Link]();j++) if([Link](j)==c) cnt++;
if(cnt>bestCount){bestCount=cnt; best=c;}
}
[Link]("Most frequent: " + best);
}
}

Expected Output:
Most frequent: b
Explanation: Simple nested loop frequency.

Program 3.13 - Check if all characters are letters.


public class Program3_13 {
public static void main(String[] args) {
String s = "Hello";
boolean all=true;
for(int i=0;i<[Link]();i++) if(![Link]([Link](i))) all=false;
[Link]("All letters: " + all);
}
}

Expected Output:
All letters: true
Explanation: Verify all are letters.

Program 3.14 - Capitalize first letter of each word.


public class Program3_14 {
public static void main(String[] args) {
String s = "hello world";
String[] parts = [Link](" ");
String out="";
for(int i=0;i<[Link];i++){
String p = parts[i];
out += [Link]([Link](0)) + [Link](1);
if(i<[Link]-1) out += " ";
}
[Link](out);
}
}

Expected Output:
Hello World
Explanation: Capitalize each word start.
Program 3.15 - Count uppercase letters.
public class Program3_15 {
public static void main(String[] args) {
String s = "HeLLo";
int u=0;
for(int i=0;i<[Link]();i++) if([Link]([Link](i))) u++;
[Link]("Uppercase count: " + u);
}
}

Expected Output:
Uppercase count: 3
Explanation: Count uppercase chars.

Program 3.16 - Shift characters by 1 (a->b).


public class Program3_16 {
public static void main(String[] args) {
String s = "abc";
String res="";
for(int i=0;i<[Link]();i++) res += (char)([Link](i)+1);
[Link](res);
}
}

Expected Output:
bcd
Explanation: Shift each char by one.

Program 3.17 - Check if string contains only vowels.


public class Program3_17 {
public static void main(String[] args) {
String s = "aeiou";
boolean only=true;
for(int i=0;i<[Link]();i++) if("aeiou".indexOf([Link](i))==-1) only=false;
[Link]("Only vowels: " + only);
}
}

Expected Output:
Only vowels: true
Explanation: Ensure all chars are vowels.

Program 3.18 - Swap case of characters.


public class Program3_18 {
public static void main(String[] args) {
String s = "JaVa";
String res="";
for(int i=0;i<[Link]();i++){
char c=[Link](i);
if([Link](c)) res += [Link](c); else res +=
[Link](c);
}
[Link](res);
}
}

Expected Output:
jAvA
Explanation: Swap uppercase/lowercase.

Program 3.19 - Remove duplicate characters preserving first.


public class Program3_19 {
public static void main(String[] args) {
String s = "banana";
String out="";
for(int i=0;i<[Link]();i++){
char c=[Link](i);
if([Link](c)==-1) out += c;
}
[Link](out);
}
}

Expected Output:
ban
Explanation: Keep first occurrences only.

Program 3.20 - Count words by counting spaces+1.


public class Program3_20 {
public static void main(String[] args) {
String s = "one two three";
int cnt = [Link]().isEmpty()?0:1;
for(int i=0;i<[Link]();i++) if([Link](i)==' ') cnt++;
[Link]("Words: " + cnt);
}
}

Expected Output:
Words: 3
Explanation: Approximate word count by spaces.
Page 25

Common questions

Powered by AI

The toUpperCase() method converts all characters in a string to uppercase, allowing two strings to be compared case-insensitively. For example, in Program 1.34, after both 'test' and 'TEST' are converted to uppercase, their equality check returns true because 'TEST'.equals('TEST') evaluates to true .

The trim() method removes leading and trailing spaces from a string, which is crucial for accurate comparisons or operations. For instance, Program 1.48 uses trim() before comparing the string with a literal, ensuring that space-related discrepancies do not affect the outcome. After trimming, ' hi '.equals('hi') evaluates to true as extra spaces are removed .

The replace() method accommodates both character masking and substitutions by allowing replacement of specific characters or substrings with others. For masking, Program 1.44 uses replace() to change digits to '*', while in substitutions like Program 1.42, it swaps 'Java' with 'Python'. This flexibility makes replace() a powerful tool for various string modifications .

Chaining combines multiple operations in a single statement, improving code readability and efficiency by reducing overhead. Instead of handling intermediate results from separate executions, chaining immediately applies sequential transformations. In Program 2.10, chaining trim(), toUpperCase(), and replace() forms 'JAVA_ROCKS' efficiently, showcasing the streamlined approach's benefits over discrete operations .

Program 3.13 checks each character using Character.isLetter(), confirming whether it's an alphabet letter. The loop iterates over all characters, setting 'all' to false if any character fails this check. This verification ensures that non-letter strings are not mistakenly confirmed as alphabetic, maintaining accuracy when validating string contents .

The substring() function is beneficial for extracting specific parts of a string, especially when used with indexOf() to dynamically determine start and end positions. It's ideal for tasks like parsing emails, where indexOf() locates the '@' and substring() extracts the username as in Program 2.9. This combination caters to flexible and precise substring extraction based on dynamic content .

Nested loops effectively determine character frequency by comparing each character against all others, tallying occurrences. Program 3.12 uses this approach to find 'b' as the most frequent character in 'aabbbc'. The outer loop selects each character, and the inner loop counts its occurrences. This brute-force method ensures comprehensive and accurate frequency determination, albeit with increased computational complexity .

A loop iterates through a string from the last character to the first, appending each character to a new string variable. This method is effective for reversing because it systematically reconstructs the string in reverse order. In Program 3.2, the loop starts at the string's end ('hello', index 4) and decrements the index, appending each character to 'rev', effectively reversing the string to 'olleh' .

The indexOf() method returns the index of the first occurrence of a character, while lastIndexOf() finds the last occurrence. In Program 1.39, 'banana' is used with these methods: indexOf('a') returns 1, and lastIndexOf('a') returns 5, identifying the positions of the first and last occurrences within the string .

Combining substring(), toUpperCase(), and replace() methods allows complex string manipulations. For instance, in Program 2.10, the string ' java rocks ' is trimmed, converted to uppercase, and spaces are replaced with underscores, resulting in 'JAVA_ROCKS'. This showcases how method chaining can be employed for formatting and transforming strings for specific requirements .

You might also like