1. Write a Java program to compare two strings?
Answer:
public class EqualCheck {
public static void main(String args[]) {
String a = "JAVA";
String b = "java";
if (a.equals(b)) {
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}
if (a.equalsIgnoreCase(b)) {
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}
if (a==b) {
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}
System.out.println(a.compareTo(b));
System.out.println(b.compareTo(a));
}
}
Output:
Both strings are not equal.
Both strings are equal.
Both strings are not equal.
-32
32
2. Write a Java program to find all the sub-string of given string?
Answer:
public class SubstringsOfStringMain {
public static void main(String args[]) {
String str = "abbc";
System.out.println("All substring of abbc are:");
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
System.out.println(str.substring(i, j));
}
}
}
}
Ouput:
All substring of abbc are:
a
ab
abb
abbc
b
bb
bbc
b
bc
c
3. Write a Java program to print the given string in reverse?
For Example: Input : HELLOJAVA ,Output: AVAJOLLEH
Answer:
public class ReverseString1 {
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1 ; i >= 0 ; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of the string: " + reverse);
}
}
Output:
Enter a string to reverse
HELLOJAVA
Reverse of the string: AVAJOLLEH
4. How to find whether a String ends with a specific character or text using Java program?
Answer:
public class EndsWith {
public static void main(String[] args) {
String str_Sample = "Java String endsWith example";
//Check if ends with a particular sequence
System.out.println("EndsWith character 'e': " + str_Sample.endsWith("e"));
System.out.println("EndsWith character 'ple': " + str_Sample.endsWith("ple"));
System.out.println("EndsWith character 'Java': " + str_Sample.endsWith("Java"));
}
}
Output:
EndsWith character 'e': true
EndsWith character 'ple': true
EndsWith character 'Java': false
5. Write a Java program to demonstrate how to replace a string with another string?
Answer:
public class ReplaceExample {
public static void main(String args[]) {
String s1 = "Hello Java";
String replaceString = s1.replace("Hello", "Welcome");
System.out.println(replaceString);
}
}
Output:
Welcome Java
6. Write a Java program to split the given string?
Answer: While programming, we may need to break a string based on some attributes. Mostly this attribute will be a separator or a common - with which you want to break or split the string.
split() method splits a String into an array of substrings given a specific delimiter.
Syntax:
--public String split(String regex)
--public String split(String regex, int limit)
Where: Regex: The regular expression is applied to the text/string
Limit: A limit is a maximum number of values the array. If it is omitted or zero, it will return all the strings matching a regex.
public class StrSplit {
public static void main(String[] args) {
String strMain = "Java, Two, Three, Four, Five";
String[] arrSplit = strMain.split(", ");
for (int i = 0; i < arrSplit.length; i++) {
System.out.println(arrSplit[i]);
}
}
}
Output:
Java
Two
Three
Four
Five
7. Write a Java program to remove the spaces before and after the given string?
Answer:
public class BlankSpace {
public static void main(String[] args) {
String str = " Hello Java ";
// Call the replaceAll() method
str = str.replaceAll("\\s", "");
System.out.println(str);
}
}
Output:
HelloJava
8. Write a Java program to convert all the characters in given string to lower case?
Answer:
public class UpperCaseToLowerCase {
public static void main(String args[]) {
String S1 = new String("UPPERCASE CONVERTED TO LOWERCASE");
// Convert to LowerCase
System.out.println(S1.toLowerCase());
}
}
Output:
uppercase converted to lowercase
9. Write a Java program to find the length of the given string?
Answer:
public class LengthExample {
public static void main(String args[]) {
String s1 = "java";
String s2 = "python";
System.out.println("string length is: " + s1.length());// 4 is the length of java string
System.out.println("string length is: " + s2.length());// 6 is the length of python string
}
}
Output:
string length is: 4
string length is: 6
10. Write a Java program to concatenate the given strings?
Answer:
import java.util.Scanner;
public class ConcatString {
public static void main(String args[])
{
String str1, str2;
Scanner scan = new Scanner(System.in);
System.out.print("Enter First String : ");
str1 = scan.nextLine();
System.out.print("Enter Second String : ");
str2 = scan.nextLine();
System.out.println("Concatenating String 2 into String 1");
str1 = str1.concat(str2);
System.out.print("String 1 after Concatenation is: " +str1);
}
}
Output:
Enter First String : Java
Enter Second String : World
Concatenating String 2 into String 1
String 1 after Concatenation is: JavaWorld
11. Write a Java program to convert string to integer?
Answer:
public class StringToIntExample {
public static void main(String args[]) {
// Declaring String variable
String s = "300";
// Converting String into int using Integer.parseInt()
int i = Integer.parseInt(s);
System.out.println(s + 100);// 300100, because "200"+100, here + is a string concatenation operator
System.out.println(i + 100);// 400, because 200+100, here + is a binary plus operator
}
}
Output:
300100
400
12. Write a Java program to convert integer to string?
Answer:
public class IntToStringExample {
public static void main(String args[]) {
int i = 200;
String s = Integer.toString(i);
System.out.println(i + 100);// 300 because + is binary plus operator
System.out.println(s + 100);// 200100 because + is string concatenation operator
}
}
Output:
300
200100
13. Write a Java program to convert string to long?
Answer:
public class StringToLongExample {
public static void main(String args[]) {
String s = "88898678765";
long l = Long.parseLong(s);
System.out.println(l);
}
}
Output:
88898678765
14. Write a Java program to convert string to float?
Answer:
public class StringToFloatExample {
public static void main(String args[]) {
String s = "56.6";
float f = Float.parseFloat(s);
System.out.println(f);
}
}
Output:
56.6
15. Write a Java program to convert string to double?
Answer:
public class StringToDoubleExample {
public static void main(String args[]) {
String s = "56.6";
double d = Double.parseDouble(s);
System.out.println(d);
}
}
Output:
56.6
16. Write a Java program to convert string to date?
Answer:
public class StringToDate {
public static void main(String[] args) throws ParseException {
// Format y-M-d or yyyy-MM-dd
String string1 = "2017-07-25";
LocalDate date1 = LocalDate.parse(string1, DateTimeFormatter.ISO_DATE);
System.out.println(date1); //first way
String string2="31/12/1998";
Date date2=new SimpleDateFormat("dd/MM/yyyy").parse(string2);
System.out.println(string2+"\t"+date2); //second way
}
}
Output:
2017-07-25
31/12/1998 Thu Dec 31 00:00:00 IST 1998
17. Check whether a string is anagram of another string? Ex: Keep and Peek are anagrams.
Answer:
public class AnagramString {
static void isAnagram(String str1, String str2) {
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
boolean status = true;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toLowerCase().toCharArray();
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status) {
System.out.println(s1 + " and " + s2 + " are anagrams");
} else {
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
public static void main(String[] args) {
isAnagram("Keep", "Peek");
isAnagram("Java", "Selenium");
}
}
Output:
Keep and Peek are anagrams
Java and Selenium are not anagrams
18. In a given string, change few characters to upper case as asked?
Answer:
public class LowerCaseToUpperCase {
public static void main(String args[]) {
String S1 = new String("lowercase converted to upercase");
// Convert to LowerCase
System.out.println(S1.toUpperCase());
}
}
Output:
LOWERCASE CONVERTED TO UPERCASE
19. In a given string, print the occurrence of each character?
Answer:
import java.util.HashMap;
public class OccurenceOfCharacter {
public static void main(String[] args) {
String str = "JAVAFORSELENIUM";
HashMap <Character, Integer> hMap = new HashMap<>();
for (int i = str.length()-1; i>= 0; i--) {
if (hMap.containsKey(str.charAt(i))) {
int count = hMap.get(str.charAt(i));
hMap.put(str.charAt(i), ++count);
} else {
hMap.put(str.charAt(i),1);
}
}
System.out.println(hMap);
}
}
Output:
{A=2, E=2, F=1, I=1, J=1, L=1, M=1, N=1, O=1, R=1, S=1, U=1, V=1}
20.Write a Java program where input-> I Love India, output-> India Love I
Answer:
import java.util.Scanner;
public class StringReverseByWords {
public static void main(String[] args) {
//Scanner in=new Scanner(System.in);
//System.out.println("Enter a String");
String s="I Love India";
System.out.println("Input: "+s);
char arr[]=s.toCharArray();
int count=0;
for(int i=arr.length-1; i >=0; i--)
{
if(arr[i]==' '||i==0)
{
if(i==0)
{
i--;
count++;
}
for(int j=i+1; count >0; j++ )
{
System.out.print(arr[j]);
count--;
}
System.out.print(" ");
}
else
{
count++;
}
}
}
}
Output:
Input: I Love India
India Love I
Another Way:
public class ReverseWords {
// Method to reverse words of a String
static String reverseWords(String str) {
// Specifying the pattern to be searched
Pattern pattern = Pattern.compile("\\s");
// splitting String str with a pattern
// (i.e )splitting the string whenever their
// is whitespace and store in temp array.
String[] temp = pattern.split(str);
String result = "";
// Iterate over the temp array and store
// the string in reverse order.
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
public static void main(String[] args) {
String s1 = "I Love India";
System.out.println(reverseWords(s1));
}
}
Output:
India Love I
21. Write a Java program where input- i love java, output- java evol i
Answer:
public class ExchangeFirstLastReverseMiddle {
static void print(String s) {
// Taking an Empty String
String fst = "";
int i = 0;
for (i = 0; i < s.length();) {
// Iterating from starting index
// When we get space, loop terminates
while (s.charAt(i) != ' ') {
fst = fst + s.charAt(i);
i++;
}
// After getting one Word
break;
}
// Taking an Empty String
String last = "";
int j = 0;
for (j = s.length() - 1; j >= i;) {
// Iterating from last index
// When we get space, loop terminates
while (s.charAt(j) != ' ') {
last = s.charAt(j) + last;
j--;
}
// After getting one Word
break;
}
// Printing last word
System.out.print(last);
for (int m = j; m >= i; m--) {
// Reversing the left characters
System.out.print(s.charAt(m));
}
// Printing the first word
System.out.println(fst);
}
public static void main(String[] args) {
String s = "i love java";
print(s);
}
}
Output:
java evol i
22. Write a Java program where String s ="abc,bbc,ccd" output- ccd,bbc,abc, should not use third variable.
Answer:
public class StringReverseByWords {
public static void main(String[] args) {
//Scanner in=new Scanner(System.in);
//System.out.println("Enter a String");
String s="abc,bbc,ccd";
System.out.println("Input: "+s);
char arr[]=s.toCharArray();
int count=0;
for(int i=arr.length-1; i >=0; i--)
{
if(arr[i]==','||i==0)
{
if(i==0)
{
i--;
count++;
}
for(int j=i+1; count >0; j++ )
{
System.out.print(arr[j]);
count--;
}
System.out.print(",");
}
else
{
count++;
}
}
}
}
Output:
Input: abc,bbc,ccd
ccd,bbc,abc,
23. Write a Java program to find out length of string without .length() method.
Answer:
public class StringLength {
public static void main(String args[]) throws Exception {
String str = "HelloWorld";
int i = 0;
for (char c : str.toCharArray()) {
i++;
}
System.out.println("Length of the given string ::" + i);
}
}
Output:
Length of the given string ::10
24. Write a Java program where String s= AuthenticationA, count the no of A?
Answer:
public class CountGivenCharacterInString {
// Method that return count of the given
// character in the string
public static int count(String s, char c) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
// checking character in string
if (s.charAt(i) == c)
res++;
}
return res;
}
public static void main(String args[]) {
String str = "AuthenticationA";
char c = 'A';
System.out.println("No of "+c+" is: "+count(str, c));
}
}
Output:
No of A is: 2
25. Find out no from string? for Example String s= "BSG234JGJH", output should be 234
Answer:
public class NumberContainsString {
public static void main(String args[]){
String sample = "BSG234JGJH";
char[] chars = sample.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c : chars){
if(Character.isDigit(c)){
sb.append(c);
}
}
System.out.println("No in String is: "+sb);
}
}
Output:
No in String is: 234
26. How to find duplicate adjecent characters recursively in a given string?
Answer:
public class DuplicateAdjecent {
public static void check(String str)
{
if(str.length()<=1)
{
System.out.println(str);
return;
}
String n=new String();
int count=0;
for(int i=0;i<str.length();i++)
{
while(i<str.length()-1 && str.charAt(i)==str.charAt(i+1))
{
if(i<str.length()-2 &&str.charAt(i)!=str.charAt(i+2))
i+=2;
else
i++;
count++;
}
if(i!=str.length()-1)
n=n+str.charAt(i);
else
{if(i==str.length()-1 && str.charAt(i)!=str.charAt(i-1))
n=n+str.charAt(i);
}
}
if(count>0)
check(n);
else
System.out.println(n);
}
public static void main (String[] args)
{
String ab="aabbcddeffghh";
System.out.println("The given string is: "+ab);
System.out.println("The new string after removing all adjacent duplicates is:");
check(ab);
}
}
Output:
The given string is: aabbcddeffghh
The new string after removing all adjacent duplicates is:
ceg
27. How to remove repeated char in a string? Input: Java, Output: Jav
Answer:
import java.util.Arrays;
public class RemoveDuplicateFromString {
static String removeDuplicate(char str[], int n)
{
// Used as index in the modified string
int index = 0;
// Traverse through all characters
for (int i = 0; i < n; i++)
{
// Check if str[i] is present before it
int j;
for (j = 0; j < i; j++)
{
if (str[i] == str[j])
{
break;
}
}
// If not present, then add it to
// result.
if (j == i)
{
str[index++] = str[i];
}
}
return String.valueOf(Arrays.copyOf(str, index));
}
public static void main(String[] args)
{
char str[] = "Java".toCharArray();
int n = str.length;
System.out.println(removeDuplicate(str, n));
}
}
Output:
Jav
28. How to remove repeated word in a string? Input: Learn Java for Selenium Learn Java, output: Learn Java for Selenium.
Answer:
public class RemoveDuplicateWord {
public static void main(String[] args) {
String input = "Learn Java for Selenium Learn Java"; // Input String
String[] words = input.split(" "); // Split the word from String
for (int i = 0; i < words.length; i++) // Outer loop for Comparison
{
if (words[i] != null) {
for (int j = i + 1; j < words.length; j++) // Inner loop for Comparison
{
if (words[i].equals(words[j])) // Checking for both strings are equal
{
words[j] = null; // Delete the duplicate words
}
}
}
}
for (int k = 0; k < words.length; k++) // Displaying the String without duplicate words
{
if (words[k] != null) {
System.out.print(words[k]+" ");
}
}
}
}
Output:
Learn Java for Selenium
29. WAP Where String s="aaabbbwerqerta", input ch='a', output should be true if char is present
Answer:
public class CharacterContains {
public static void main(String args[])
{
String s1 = "aaabbbwerqerta";
System.out.println(s1.contains("a"));
}
}
Output:
true
30. WAP where string s= "test1test2test3test4", count no of test present
Answer:
public class DuplicateWord {
public static void main(String[] args) {
String input = "test1test2test3test4"; // Input String
String regex = "([0-9])";
String[] words = input.split(regex); // Split the word from String
int wrc = 1; // Variable for getting Repeated word count
for (int i = 0; i < words.length; i++) // Outer loop for Comparison
{
for (int j = i + 1; j < words.length; j++) // Inner loop for Comparison
{
if (words[i].equals(words[j])) // Checking for both strings are equal
{
wrc = wrc + 1; // if equal increment the count
words[j] = "0"; // Replace repeated words by zero
}
}
if (words[i] != "0")
System.out.println(words[i] + "--" + wrc); // Printing the word along with count
wrc = 1;
}
}
}
Output:
test--4
31. When String s="hello". s2=null, s3=new String(null), s4=s3, System.out.println(s1+s2+s3+s4)?
Answer: compilation error, The constructor String(String) is ambiguous
32. How to remove extra white spaces between words I have string str= "#raj @ 100#abc @102#e fg @103"
Answer:
public class RemoveWhiteSpace {
public static void main(String[] args) {
String str = "#raj @ 100#abc @102#e fg @103";
//1st way
String noSpaceStr = str.replaceAll("\\s", ""); // using built in method
System.out.println(noSpaceStr);
}
}
Output:
#raj@100#abc@102#efg@103
33. Find the duplicate strings in a given statement and remove them? Input: Welcome to Java Welcome Java, Output: Welcome to Java
Answer:
public class RemoveDuplicateFromSentence {
public static void main(String[] args) {
String input = "Welcome to Java Welcome Java"; // Input String
String[] words = input.split(" "); // Split the word from String
for (int i = 0; i < words.length; i++) // Outer loop for Comparison
{
if (words[i] != null) {
for (int j = i + 1; j < words.length; j++) // Inner loop for Comparison
{
if (words[i].equals(words[j])) // Checking for both strings are equal
{
words[j] = null; // Delete the duplicate words
}
}
}
}
for (int k = 0; k < words.length; k++) // Displaying the String without duplicate words
{
if (words[k] != null) {
System.out.println(words[k]);
}
}
}
}
Output:
Welcome
to
Java
34. Use split method to print each word of a statement?
Answer:
public class SplitWords {
public static void main(String[] args) {
String s = "This is Java for Selenium";
String[] arr = s.split(" ");
for (String ss : arr) {
System.out.println(ss);
}
}
}
Output:
This
is
Java
for
Selenium
35. How to remove Junk or special characters in a String?
Answer:
public class RemoveSpacialChar {
public static void main(String args[]) {
String text = "This - text ! has \\ /allot # of % special % characters";
text = text.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(text);
}
}
Output:
Thistexthasallotofspecialcharacters
36. Write a Java program to swap two strings without using temp or third variable? Input: Java Selenium, Output: Selenium Java
Answer:
public class SwapWithoutTemp {
public static void main(String args[]) {
String a = "Java";
String b = "Selenium";
System.out.println("Before swap: " + a + " " + b);
a = a + b;
b = a.substring(0, a.length() - b.length());
a = a.substring(b.length());
System.out.println("After : " + a + " " + b);
}
}
Output:
Before swap: Java Selenium
After : Selenium Java
37. How will you display the characters count in a String “Steve Jobs” by ignoring the spaces in between?
Answer:
public class DisplayCountIgnoringSpaces {
public static void main(String[] args) {
String test = "SteveJobs";
System.out.println(test.replace(" ", "").length());
}
}
Output:
9
38. Write a code to find the occurrence of sub string say “hello” in the given String say “helloslkhellodjladfjhello” ?
Answer:
public class OccurrenceOfSubsString {
public static void main(String[] args) {
String str = "helloslkhellodjladfjhello";
String strFind = "hello";
int count = 0, fromIndex = 0;
while ((fromIndex = str.indexOf(strFind, fromIndex)) != -1) {
System.out.println("Found at index: " + fromIndex);
count++;
fromIndex++;
}
System.out.println("Total occurrences: " + count);
}
}
Output:
Found at index: 0
Found at index: 8
Found at index: 20
Total occurrences: 3
39. Java Program: Sort a string which has only 0, 1, 2 in it. Sample input: 010201010100222112 | Sample output: 000000011111122222?
Answer:
import java.util.Arrays;
public class SortingStrinArray {
public static void main(String[] args) {
// Orig String
String s = "010201010100222112";
System.out.println("Original String: " + s);
// Converting to Char Array
char[] charArray = s.toCharArray();
// Sorting
Arrays.sort(charArray);
// Convert Back to String
String s1 = String.valueOf(charArray);
// Printing Sorted String
System.out.println("After Sorting: " + s1);
}
}
Output:
Original String: 010201010100222112
After Sorting: 000000011111122222
40. Java Program: String s = “sub53od73th”; Eliminate the numbers alone. Print the Alphabets.
Answer:
public class EliminateNumbersFromString {
public static void main(String[] args) {
String s = "sub53od73th";
s = s.replaceAll("[0-9]", "");
System.out.println(s);
}
}
Output:
subodth
41. Write a program to reverse a string without using inbuilt functions? Input: Java, Output: avaJ
Answer:
public class ReverseStringWithoutMethod {
public static void main(String args[]) {
int i, n;
String s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string");
s = sc.nextLine();
char str[] = s.toCharArray();
n = str.length;
System.out.println("Reversed string is");
for (i = n - 1; i >= 0; i--) {
System.out.print(str[i]);
}
}
}
Output:
Enter the string
Java
Reversed string is
avaJ
42. Write a program to find out the repeated character in a string? Input: JAVA, Output: A is 2 times.
Answer:
public class DuplicateCharFinder {
public void findIt(String str) {
Map<Character, Integer> baseMap = new HashMap<Character, Integer>();
char[] charArray = str.toCharArray();
for (Character ch : charArray) {
if (baseMap.containsKey(ch)) {
baseMap.put(ch, baseMap.get(ch) + 1);
} else {
baseMap.put(ch, 1);
}
}
Set<Character> keys = baseMap.keySet();
for (Character ch : keys) {
if (baseMap.get(ch) > 1) {
System.out.println(ch + " is " + baseMap.get(ch) + " times");
}
}
}
public static void main(String a[]) {
DuplicateCharFinder dcf = new DuplicateCharFinder();
dcf.findIt("JAVA");
}
}
Output:
A is 2 times
43. Write a program to delete duplicate values in string array?
Input: [red, blue, green, red, yellow, green]
Output: [red, blue, green, yellow]
Answer:
import java.util.Arrays;
import java.util.LinkedHashSet;
public class RemoveDuplicatesFromStringArrayExample {
public static void main(String[] args) {
String[] strColors = { "red", "blue", "green", "red", // duplicate
"yellow", "green" // duplicate
};
System.out.println("Original array: " + Arrays.toString(strColors));
LinkedHashSet<String> lhSetColors = new LinkedHashSet<String>(Arrays.asList(strColors));
// create array from the LinkedHashSet
String[] newArray = lhSetColors.toArray(new String[lhSetColors.size()]);
System.out.println("Array after removing duplicates: " + Arrays.toString(newArray));
}
}
Output:
Original array: [red, blue, green, red, yellow, green]
Array after removing duplicates: [red, blue, green, yellow]
44. String [] str={“abc”,”efg”,”fgh”}; convert array to string?
Answer:
public class StringArrayToString {
public static void main(String[] args) {
String[] strArray = { "abc", "efg", "fgh" };
System.out.println(convertArrayToString(strArray));
System.out.println(convertArrayToStringMethod(strArray));
System.out.println(convertArrayToStringUsingStreamAPI(strArray));
System.out.println(convertArrayToStringUsingCollectors(strArray));
// convert string to array
String[] strArray1 = "javaguides".split(" ");
}
// Using Arrays.toString()
public static String convertArrayToString(String[] strArray) {
return Arrays.toString(strArray);
}
// using StringBuilder.append()
public static String convertArrayToStringMethod(String[] strArray) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < strArray.length; i++) {
stringBuilder.append(strArray[i]);
}
return stringBuilder.toString();
}
// Using Stream API
public static String convertArrayToStringUsingStreamAPI(String[] strArray) {
String joinedString = String.join(" ", strArray);
return joinedString;
}
// Using Stream API and Collectors
public static String convertArrayToStringUsingCollectors(String[] strArray) {
String joinedString = Arrays.stream(strArray).collect(Collectors.joining());
return joinedString;
}
}
Output:
[abc, efg, fgh]
abcefgfgh
abc efg fgh
abcefgfgh
45. Java Program: Change a string such that first character is upper case, second is lower case and so on?
Input: Java, Output: JaVa
Answer:
public class FirstUpperSecondLower {
public static void main(String args[]) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String : ");
String s = in.next(); // if it is a word, else in.nextLine()
String word = "";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i); // taking the characters
if (i % 2 == 0) // position alteration
ch = Character.toUpperCase(ch);
word = word + ch; // making the new word
}
System.out.println("Required String : " + word);
} // close of main method
}
Output:
Enter a String :
Java
Required String : JaVa
46. WAP where input -- aabbcccaaa, output- a2b2c3a3
Answer:
public class CountEachCharInString1 {
public static void main(String[] args) {
String input = "aabbcccaaa";
int count = 0;
char temp = input.charAt(0);
for(int i=0;i<input.length();i++)
{
if(input.charAt(i)==temp)
count++;
else
{
System.out.print(temp+""+count);
count = 1;
temp = input.charAt(i);
}
}
System.out.print(temp+""+count);
}
}
Output:
a2b2c3a3
47. What will this Java code print: String x = “Latest version”; String y = “of Selenium”; int z = 3; System.out.println(“We are learning Selenium”+” and the “+x+” “+y+” is “+z); ?
Answer:
public class Program2 {
public static void main(String[] args) {
String x = "Latest version";
String y = "of Selenium";
int z = 3;
System.out.println("We are learning Selenium"+" and the "+x+" "+y+" is "+z);
}
}
Output:
We are learning Selenium and the Latest version of Selenium is 3
48. How to find duplicate element in an array (Integer).
Input: { 4, 2, 4, 5, 2, 3, 1 };
Output: 4 2
Answer:
public class RepeatElementIntegerArray {
void printRepeating(int arr[], int size) {
int i, j;
System.out.println("Repeated Elements are :");
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
if (arr[i] == arr[j])
System.out.print(arr[i] + " ");
}
}
}
public static void main(String[] args) {
RepeatElementIntegerArray repeat = new RepeatElementIntegerArray();
int arr[] = { 4, 2, 4, 5, 2, 3, 1 };
int arr_size = arr.length;
repeat.printRepeating(arr, arr_size);
}
}
Output:
Repeated Elements are :
4 2
49. Find duplicate characters in a String. String s=”AutoMationTestingInsider”
Answer:
public class DuplicateCharacterInString {
public static void main(String[] args) {
String s = "WELCOMEJAVA";
int count = 0;
char[] inp = s.toCharArray();
System.out.println("Duplicate Char are:");
for (int i = 0; i < s.length(); i++)
for (int j = i + 1; j < s.length(); j++)
if (inp[i] == inp[j]) {
System.out.print(inp[i]+" ");
count++;
break;
}
}
}
Output:
Duplicate Char are:
E A
50. How to count duplicate character in a String array. Input: SELENIUMJAVA, Output: A: 2, E:2
Answer:
public class CountDuplicateCharacterInString {
public static void main(String[] args) {
String str = "SELENIUMJAVA";
HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
// Converting given string to char array
char[] strArray = str.toCharArray();
// checking each char of strArray
for (char c : strArray) {
if (charCountMap.containsKey(c)) {
// If char is present in charCountMap, incrementing it's count by 1
charCountMap.put(c, charCountMap.get(c) + 1);
} else {
// If char is not present in charCountMap,
// putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
// Getting a Set containing all keys of charCountMap
Set<Character> charsInString = charCountMap.keySet();
System.out.println("Duplicate Characters In " + str);
// Iterating through Set 'charsInString'
for (Character ch : charsInString) {
if (charCountMap.get(ch) > 1) {
// If any char has a count of more than 1, printing it's count
System.out.println(ch + " : " + charCountMap.get(ch));
}
}
}
}
Output:
Duplicate Characters In SELENIUMJAVA
A : 2
E : 2
51. How to find duplicate word in String array
Answer:
public class DuplicateWordInStringArray {
public static void main(String[] args) {
String[] names = { "Java", "JavaScript", "HTML", "Java", "HTML" };
//using For Loop
for (int i = 0; i < names.length; i++) {
for (int j = i + 1; j < names.length; j++) {
if (names[i] == names[j]) {
System.out.println(names[j]);
}
}
}
//Another Way
Set<String> store = new HashSet();
for (String name : names) {
if (store.add(name) == false) {
System.out.println(name);
}
}
}
}
Output:
Java
HTML
52. How to find duplicate word in Sentence.
Answer:
public class DuplicateWordInSentence {
public static void main(String[] args) {
String string = "Java for Selenium Java for";
int count;
// Converts the string into lowercase
string = string.toLowerCase();
// Split the string into words using built-in function
String words[] = string.split(" ");
System.out.println("Duplicate words in a given string : ");
for (int i = 0; i < words.length; i++) {
count = 1;
for (int j = i + 1; j < words.length; j++) {
if (words[i].equals(words[j])) {
count++;
// Set words[j] to 0 to avoid printing visited word
words[j] = "0";
}
}
// Displays the duplicate word if count is greater than 1
if (count > 1 && words[i] != "0")
System.out.println(words[i]);
}
}
}
Answer:
Duplicate words in a given string :
java
for
No comments:
Post a Comment