Java String: Exercises, Practice, Solution
Java String Exercises [112 exercises with solution]
[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]
1. Write a Java program to get the character at the given index within the string.
Sample Output:
Original String = Java Exercises! The character at position 0 is J The character at position 10 is i
2. Write a Java program to get the character (Unicode code point) at the given index within the string.
Sample Output:
Original String : w3resource.com Character(unicode point) = 51 Character(unicode point) = 101
3. Write a Java program to get the character (Unicode code point) before the specified index within the string.
Sample Output:
Original String : w3resource.com Character(unicode point) = 119 Character(unicode point) = 99
4. Write a Java program to count Unicode code points in the specified text range of a string.
Sample Output:
Original String : w3rsource.com Codepoint count = 9
5. Write a Java program to compare two strings lexicographically.
Two strings are lexicographically equal if they are the same length and contain the same characters in the same positions.
Sample Output:
String 1: This is Exercise 1 String 2: This is Exercise 2 "This is Exercise 1" is less than "This is Exercise 2"
6. Write a Java program to compare two strings lexicographically, ignoring case differences.
Sample Output:
String 1: This is exercise 1 String 2: This is Exercise 1 "This is exercise 1" is equal to "This is Exercise 1"
7. Write a Java program to concatenate a given string to the end of another string.
Sample Output:
String 1: PHP Exercises and String 2: Python Exercises The concatenated string: PHP Exercises and Python Exercises
8. Write a Java program to test if a given string contains the specified sequence of char values.
Sample Output:
Original String: PHP Exercises and Python Exercises Specified sequence of char values: and true
9. Write a Java program to compare a given string to the specified character sequence.
Sample Output:
Comparing example.com and example.com: true Comparing Example.com and example.com: false
10. Write a Java program to compare a given string to a specified string buffer.
Sample Output:
Comparing example.com and example.com: true Comparing Example.com and example.com: false
11. Write a Java program to create a String object with a character array.
Sample Output:
The book contains 234 pages.
12. Write a Java program to check whether a given string ends with another string.
Sample Output:
"Python Exercises" ends with "se"? false "Python Exercise" ends with "se"? true
13. Write a Java program to check whether two String objects contain the same data.
Sample Output:
"Stephen Edwin King" equals "Walter Winchell"? false "Stephen Edwin King" equals "Mike Royko"? false
14. Write a Java program to compare a given string to another string, ignoring case considerations.
Sample Output:
"Stephen Edwin King" equals "Walter Winchell"? false "Stephen Edwin King" equals "stephen edwin king"? true
15. Write a Java program to print the current date and time in the specified format.
Sample Output:
Current Date and Time : June 19, 2017 3:13 pmN.B. : The current date and time will change according to your system date and time.
16. Write a Java program to get the contents of a given string as a byte array.
Sample Output:
The new String equals This is a sample String.
17. Write a Java program to get the contents of a given string as a character array.
Sample Output:
The char array equals "[C@2a139a55"
18. Write a Java program to create a distinct identifier for a given string.
Sample Output:
The hash for Python Exercises. is 863132599
19. Write a Java program to get the index of all the characters of the alphabet.
Sample Output:
a b c d e f g h i j ========================= 36 10 7 40 2 16 42 1 6 20 k l m n o p q r s t =========================== 8 35 22 14 12 23 4 11 24 31 u v w x y z ================ 5 27 13 18 38 37
Sample string of all alphabet: "The quick brown fox jumps over the lazy dog."
20. Write a Java program to get the Canonical representation of the string object.
Sample Output:
str1 == str2? false str1 == str3? true
21. Write a Java program to get the last index of a string within a string.
Sample Output:
a b c d e f g h i j =========================== 36 10 7 40 33 16 42 32 6 20 k l m n o p q r s t =========================== 8 35 22 14 41 23 4 29 24 31 u v w x y z ================= 21 27 13 18 38 37
Sample string of all alphabet: "The quick brown fox jumps over the lazy dog."
22. Write a Java program to get the length of a given string.
Sample Output:
The string length of 'example.com' is: 11
23. Write a Java program to find out whether a region in the current string matches a region in another string.
Sample Output:
str1[0 - 7] == str2[28 - 35]? true str1[9 - 15] == str2[9 - 15]? false
24. Write a Java program to replace a specified character with another character.
Sample Output:
Original string: The quick brown fox jumps over the lazy dog. New String: The quick brown fox jumps over the lazy fog.
25. Write a Java program to replace each substring of a given string that matches the given regular expression with the given replacement.
Sample string : "The quick brown fox jumps over the lazy dog."
In the above string replace all the fox with cat.
Sample Output:
Original string: The quick brown fox jumps over the lazy dog. New String: The quick brown cat jumps over the lazy dog.
26. Write a Java program to check whether a given string starts with another string.
Sample Output:
Red is favorite color. starts with Red? true Orange is also my favorite color. starts with Red? false
27. Write a Java program to get a substring of a given string at two specified positions.
Sample Output:
old = The quick brown fox jumps over the lazy dog. new = brown fox jumps
28. Write a Java program to create a character array containing a string.
Sample Output:
Java Exercises.
29. Write a Java program to convert all characters in a string to lowercase.
Sample Output:
Original String: The Quick BroWn FoX! String in lowercase: the quick brown fox!
30. Write a Java program to convert all characters in a string to uppercase.
Sample Output:
Original String: The Quick BroWn FoX! String in uppercase: THE QUICK BROWN FOX!
31. Write a Java program to trim leading or trailing whitespace from a given string.
Sample Output:
Original String: Java Exercises New String: Java Exercises
32. Write a Java program to find the longest Palindromic Substring within a string.
Sample Output:
The given string is: thequickbrownfoxxofnworbquickthe The longest palindrome substring in the giv en string is; brownfoxxofnworb The length of the palindromic substring is: 16
33. Write a Java program to find all interleavings of given strings.
Sample Output:
The given strings are: WX YZ The interleavings strings are: YWZX WYZX YWXZ WXYZ YZWX WYXZ
34. Write a Java program to find the second most frequent character in a given string.
Sample Output:
The given string is: successes The second most frequent char in the string is: c
35. Write a Java program to print all permutations of a given string with repetition.
Sample Output:
The given string is: PQR The permuted strings are: PPP PPQ PPR ... RRP RRQ RRR
36. Write a Java program to check whether two strings interlive of a given string. Assuming that unique characters are present in both strings.
Sample Output:
The given string is: PMQNO The interleaving strings are MNO and PQ The given string is interleaving: true The given string is: PNQMO The interleaving strings are MNO and PQ The given string is interleaving: false
37. Write a Java program to find the length of the longest substring of a given string without repeating characters.
Sample Output:
Input String : pickoutthelongestsubstring The longest substring : [u, b, s, t, r, i, n, g] The longest Substring Length : 8
38. Write a Java program to print the result of removing duplicates from a given string.
Sample Output:
The given string is: w3resource After removing duplicates characters the new string is: w3resouc
39. Write a Java program to find the first non-repeating character in a string.
Sample Output:
The given string is: gibblegabbler The first non repeated character in String is: i
40. Write a Java program to divide a string into n equal parts.
Sample Output:
The given string is: abcdefghijklmnopqrstuvwxy The string divided into 5 parts and they are: abcde fghij klmno pqrst uvwxy
41. Write a Java program to remove duplicate characters from a given string that appear in another given string.
Sample Output:
The given string is: the quick brown fox The given mask string is: queen The new string is: th ick brow fox
42. Write a Java program to print a list of items containing all characters of a given word.
Sample Output:
The given strings are: rabbit bribe dog The given word is: bib The strings containing all the letters of the given word are: rabbit bribe
43. Write a Java program to find the character in a string that occurs the most frequently.
Sample Output:
The given string is: test string Max occurring character in the given string is: t
44. Write a Java program to reverse a string using recursion.
Sample Output:
The given string is: The quick brown fox jumps The string in reverse order is: spmuj xof nworb kciuq ehT
45. Write a Java program to reverse words in a given string.
Sample Output:
The given string is: Reverse words in a given string The new string after reversed the words: string given a in words Reverse
46. Write a Java program to reverse every word in a string using methods.
Sample Output:
The given string is: This is a test string The string reversed word by word is: sihT si a tset gnirts
47. Write a Java program to rearrange a string so that the same characters are positioned a distance away.
Sample Output:
The given string is: accessories The string after arrange newly is: secrsecisao
48. Write a Java program to remove "b" and "ac" from a given string.
Sample Output:
The given string is: abrambabasc After removing the new string is: aramaasc
49. Write a Java program to find the first non-repeating character from a stream of characters.
Sample Output:
String: godisgood Reading: g The first non-repeating character so far is: g Reading: o The first non-repeating character so far is: g Reading: d The first non-repeating character so far is: g Reading: i The first non-repeating character so far is: g Reading: s The first non-repeating character so far is: g Reading: g The first non-repeating character so far is: o Reading: o The first non-repeating character so far is: d Reading: o The first non-repeating character so far is: d Reading: d The first non-repeating character so far is: i
50. Write a Java program to find the lexicographic rank of a given string.
Sample Output:
The Given String is: BDCA The Lexicographic rank of the given string is: 12
N.B.: Total possible permutations of BDCA are(lexicographic order) :
ABCD ABDC ACBD ACDB ADBC ADCB BACD BADC BCAD BCDA BDAC BDCA
1 2 3 4 5 6 7 8 9 10 11 12
The BDCA appear in 12 position of permutation (lexicographic order).
51. Write a Java program to count and print all duplicates in the input string.
Sample Output:
The given string is: w3resource The duplicate characters and counts are: e appears 2 times r appears 2 times
52. Write a Java program to check if two given strings are rotations of each other.
Sample Output:
The given strings are: ABACD and CDABA The concatination of 1st string twice is: ABACDABACD The 2nd string CDABA exists in the new string. Strings are rotations of each other
53. Write a Java program to match two strings where one string contains wildcard characters.
Sample Output:
The given string is: abcdhgh The given pattern string is: abc*d?* The given pattern is matching.
54. Write a Java program to find the smallest window in a string containing all characters in another string.
Sample Output:
The given string is: welcome to w3resource Characters to find in the main sring are: tower The smallest window which contains the finding characters is : to w3re
55. Write a Java program to remove all adjacent duplicates recursively from a given string.
Sample Output:
The given string is: aabaarbarccrabmq The new string after removing all adjacent duplicates is: brmq
56. Write a Java program that appends two strings, omitting one character if the concatenation creates double characters.
Sample Output:
The given strings are: food and door The string after concatination are: foodoor
57. Write a Java program to create a string from a given string by swapping the last two characters of the given string. The string length must be two or more.
Sample Output:
The given strings is: string The string after swap last two characters are: strign
58. Write a Java program to read a string and return true if it ends with a specified string of length 2.
Sample Output:
The given strings is: string The string containing ng at last: true The given strings is: strign The string containing ng at last: false
59. Write a Java program to read a string. If the string begins with "red" or "black" return that color string, otherwise return the empty string.
Sample Output:
The given strings is: blacksea The string begins with the color: black
60. Write a Java program to read two strings append them together and return the result. If the strings are different lengths, remove characters from the beginning of the longer string and make them equal lengths.
Sample Output:
The given strings is: Welcome and home The new string is: comehome
61. Write a Java program to create a new string taking specified number of characters from first and last position of a given string.
Sample Output:
The given strings is: Welcome The given numbers is: 3 The new string is: Welome
62. Write a Java program to read a string and return true if "good" appears starting at index 0 or 1 in the given string.
Sample Output:
The given strings is: goodboy The 'good' appear in the string is: true
63. Write a Java program to check whether the first two characters appear at the end of a given string.
Sample Output:
The given strings is: educated The first two characters appear in the last is: true
64. Write a Java program to read a string. If a substring of length two appears at both its beginning and end, return a string without the substring at the beginning; otherwise, return the original string unchanged.
Sample Output:
The given strings is: educated The new string is: ucated
65. Write a Java program to read a given string and return the string without the first or last characters if they are the same, otherwise return the string without the characters.
Sample Output:
The given strings is: testcricket The new string is: estcricke
66. Write a Java program to read a string and return it without the first two characters. Keep the first character if it is 'g' and keep the second character if it is 'h'.
Sample Output:
The given strings is: goat The new string is: gat he given strings is: photo The new string is: hoto The given strings is: ghost The new string is: ghost
67. Write a Java program to read a string and remove the first two characters if one or both are equal to a specified character, otherwise leave them unchanged.
Sample Output:
The given strings is: oocyte The new string is: cyte The given strings is: boat The new string is: bat The given strings is: own The new string is: wn
68. Write Java program to read a string and return after removing specified characters and their immediate left and right adjacent characters.
Sample Output:
The given strings is: test#string The new string is: testring The given strings is: test##string The new string is: testring The given strings is: test#the#string The new string is: teshtring
69. Write a Java program to return the substring that is between the first and last appearance of the substring 'toast' in the given string, or return an empty string if the substring 'toast' does not exist.
Sample Output:
The given strings is: sweettoastbuttertoast The new string is: butter
70. Write a Java program that checks if a string has pq-balance if it contains at least one 'q' directly after each ‘p’. But a 'q' before the 'p' invalidates pq-balance.
Sample Output:
The given strings is: gfpmpnppqab The string is pq-balanced? true The given strings is: gfpmpnpqpab The string is pq-balanced? false
71. Write a Java program to check two given strings whether any of them appears at the end of the other string (ignore case sensitivity).
Sample Output:
The given strings are: xyz and pqrxyz Is one string appears at the end of other? true The given strings are: pqrxyz and xyz Is one string appears at the end of other? true
72. Write a Java program to return true if a given string contains the string 'pop', but the middle 'o' also may contain another character.
Sample Output:
The given string is: dikchapop Is p?p appear in the given string? true The given string is: dikp$pdik Is p?p appear in the given string? true
73. Write a Java program to check whether a substring appears before a period(.) within a given string.
Sample Output:
The given strings is: testabc.test Is 'abc' appear before period? true The given string is: test.abctest Is 'abc' appear before period? false
74. Write a Java program to check whether a prefix string created using the first specific character in a given string appears somewhere else in the string.
Sample Output:
The given strings is: MrsJemsmrsam The prefix string length is: 3 Is 'Mrs' appear else where in the string? false The given string is: MrsJemsMrsam The prefix string length is: 3 Is 'Mrs' appear else where in the string? true
75. Write a Java program to check whether a given substring appears in the middle of another string. Here middle means the difference between the number of characters to the left and right of the given substring is not more than 1.
Sample Output:
The given string is: xxxabcxxxxx Is abc appear in middle? false The given string is: xxabcxxx Is abc appear in middle? true
76. Write a Java program to count how many times the substring 'life' appears anywhere in a given string. Counting can also happen with the substring 'li?e', any character instead of 'f'.
Sample Output:
The given string is: liveonwildlife The substring life or li?e appear number of times: 2
77. Write a Java program to add a string with a specific number of times separated by a substring.
Sample Output:
The given strings are: try and best Number to times to be repeat: 3 The new string is: trybesttrybesttry
78. Write a Java program to repeat a specific number of characters for a specific number of times from the last part of a given string.
Sample Output:
The given string is: string The new string after repetition: inginging
79. Write a Java program to create a string from a given string. This is done after removing the 2nd character from the substring of length three starting with 'z' and ending with 'g' presents in the said string.
Sample Output:
The given string is: zzgkitandkatcaketoket The new string is: zgkitandkatcaketoket
80. Write a Java program to check whether the character immediately before and after a specified character is the same in a given string.
Sample Output:
The given string is: moon#night The before and after character are same: true The given string is: bat##ball The before and after character are same: false The given string is: #moon#night The before and after character are same: true
81. Write a Java program to check whether two strings of length 3 and 4 appear the same number of times in a given string.
Sample Output:
The given string is: redcapmanwithbluecar The appearance of red and blue are same: true
82. Write a Java program to create a string containing every character twice of a given string.
Sample Output:
The given string is: welcome The new string is: wweellccoommee
83. Write a Java program to create a string from two given strings. This is so that each character of the two strings appears individually in the created string.
Sample Output:
The given strings are: welcome and w3resource The new string is: wwe3lrceosmoeurce
84. Write a Java program to make an original string made of p number of characters from the first character in a given string. This is followed by p-1 number of characters till p is greater than zero.
Sample Output:
The given string is: welcome Number of repetition characters and repetition: 4 The new string is: welcwelwew
85. Write a Java program to make up a string with each character before and after a non-empty substring whichever it appears in a non-empty given string.
Sample Output:
The given string are: weablcoabmeab and ab The new string is: elome
86. Write a Java program to count the number of triples (characters appearing three times in a row) in a given string.
Sample Output:
The given string is: welllcommmmeee The number of triples in the string is: 4
87. Write a Java program to check whether a specified character is happy or not. A character is happy when the same character appears to its left or right in a string.
Sample Output:
The given string is: azzlea Is z happy in the string: true The given string is: azmzlea Is z happy in the string: falses
88. Write a Java program to return a string where every appearance of the lowercase word 'is' has been replaced with 'is not'.
Sample Output:
The given string is: it is a string The new string is: it is not a string
89. Write a Java program to calculate the sum of the numbers that appear in a given string.
Sample Output:
The given string is: it 15 is25 a 20string The sum of numbers in the string is: 60
90. Write a Java program to check the number of times the two substrings appearing anywhere in a string.
Sample Output:
The given string is: Thisisthethesis Are the appearance of 'the' and 'is' equal? false
91. Write a Java program to count the number of words ending in 'm' or 'n' (not case sensitive) in a given text.
Sample Output:
The given string is: mam is in the room The number of words ends eith m or n is: 3
92. Write a Java program that returns a substring after removing all instances of remove string as given from the given main string.
Sample Output:
The main string is: This is the test string The removable string is: st The new string is: This is the te ring
93. Write a Java program to find the longest substring that appears at both ends of a given string.
Sample Output:
The given string is: playersplay The longest substring in the string is: play
94. Write a Java program to find the longest mirror image string at both ends of a given string.
Sample Output:
The given string is: rotavator The longest mirror image string in the string is: rotavator
95. Write a Java program to return the sum of the digits present in the given string. In the absence of digits, the sum is 0.
Sample Output:
The given string is: ab5c2d4ef12s The sum of the digits in the string is: 14
96. Write a Java program to create a new string after removing a specified character from a given string. This is except the first and last position.
Sample Output:
The given string is: zebrazone The new string is: zebraone
97. Write a Java program to return a string with characters at index positions 0,1,2,5,6,7, ... from a given string.
Sample Output:
The given string is: w3resource.com The new string is: w3rour.co
98. Write a Java program to check whether the first instance of a given character is immediately followed by the same character in a given string.
Sample Output:
The given string is: fizzez Is 'z' appear twice respectively? true
99. Write a Java program to return an updated string using every character of even position from a given string.
Sample Output:
The given string is: w3resource.com The new string is: wrsuc.o
100. Write a Java program to check if a given string contains another string. Returns true or false.
Sample Output:
Original string: Java is the foundation for virtually every type of networked application and is the global standard for developing and delivering embedded and mobile applications, games, Web-based content, and enterprise software. With more than 9 million developers worldwide, Java enables you to efficiently develop, deploy and use exciting applications and services. Is 'million' present in the said text? true Is 'millions' present in the said text? false
101. Write a Java program to test if a string contains only digits. Returns true or false.
Sample Output:
First string: 131231231231231231231231231212312312 true Second string: 13123123123Z1231231231231231212312312 false
102. Write a Java program to convert a given string to int, long, floating and double.
Sample Output:
Convert String to int/Integer: "1323" as int is 1323 and as Integer is 1323 Convert String to long/Long: "13625478965325" as long is 13625478965325 and as Long is 13625478965325 Convert String to float/Float: "25.135F" as float is 25.135 and as Float is 25.135 Convert String to double/Double: "21.25478254D" as double is 21.25478254 and as Double is 21.25478254 false
103. Write a Java program to remove a specified character from a given string.
Sample Output:
Original string: abcdefabcdeabcdaaa Second string: bcdefbcdebcd
104. Write a Java program to sort in ascending and descending order by the length of the given array of strings.
Sample Output:
Original unsorted colors: [Green, White, Black, Pink, Orange, Blue, Champagne, Indigo, Ivory] Sorted color (descending order): [Champagne, Orange, Indigo, Green, White, Black, Ivory, Pink, Blue] Sorted color (ascending order): [Pink, Blue, Green, White, Black, Ivory, Orange, Indigo, Champagne]
105. Write a Java program to count the occurrences of a given string in another given string.
Sample Output:
aa' has occured 3 times in 'abcd abc aabc baa abcaa'
106. Write a Java program to concatenate a given string with itself a given number of times.
Sample Output:
Original string: PHP After repeating 7 times: PHPPHPPHPPHPPHPPHPPHP
107. Write a Java program to count occurrences of a certain character in a given string.
108. Write a Java program to check whether there are two consecutive (following each other continuously), identical letters in a given string.
Sample Output:
Original word: Follow If there are two consecutive identical letters in the said string: true Original word: Java If there are two consecutive identical letters in the said string: false Original word: Yellow If there are two consecutive identical letters in the said string: true
109. Write a Java program that reverses all odd-length words in a string.
Sample Output:
Original text: Check two consecutive identical letters in a given string Reverses the words in the string that have odd lengths: Check two consecutive identical letters ni a given gnirts Original text: Create a Date object using the Calendar class Reverses the words in the string that have odd lengths: etaerC a etaD tcejbo using the radnelaC class
110. Write a Java program to count the number of characters (alphanumeric only) that occur more than twice in a given string.
Sample Output:
Original String: abcdaa Number of duplicate characters in the said String (Occurs more than twice.): 1 Original String: Create a Date Calendar. Number of duplicate characters in the said String (Occurs more than twice.): 3
111. Write a Java program that removes a specified word from given text. Return the updated string..
Sample Output:
Input a string: Exercises Practice Solution Input a word to remove: Solution New string, after removing the said word: Exercises Practice
112. A string is created by using another string's letters. Letters are case sensitive. Write a Java program that checks the letters of the second string are present in the first string. Return true otherwise false.
Sample Output:
Input the first string: Java Input the second string: Ja Check first string contains letters from the second string: true
Java Code Editor
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/string/index.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics