Top 70 Java Program Interview Questions

Top 70 Java Program Interview Questions: Here, we will list down all the Java Programs. 

package com.softwaretestingo.sto000collectedpgms.interviewprograms;
import java.util.Arrays;
public class STO0001_1_InterviewPrograms 
{
	public static void main(String[] args) 
	{
		String[] strArray = { "Rama", "Test", "Type", "Tata" };
		int maxLength = 0;
		for (String str : strArray) 
		{
			maxLength = str.length();
		}
		String result = "";
		for (int i = 0; i < maxLength; i++) 
		{
			for (String str : strArray) 
			{
				if (i < str.length()) 
				{
					result = result + str.charAt(i);
				}
			}
		}
		System.out.println("Input: "+Arrays.toString(strArray));
		System.out.println("Output: "+result);//RTTTaeyamsptatea
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0002_0_ReverseWordsKeepNumbers 
{
	/**
	 * Input - today10is20my30interview 
	 * Output- yadot10si20ym30weivretni
	 */
	public static void main(String[] args) 
	{
		String input = "today10is20my30interview";
		System.out.println("Input:  "+input);
		StringBuilder res = new StringBuilder ( );
		StringBuilder temp = new StringBuilder ( );
		for ( int i = 0 ; i < input.length ( ) ; i ++ )
		{
			char ch = input.charAt (i);
			if ( Character.isDigit (ch) ) 
			{
				while ( i < input.length ( ) && Character.isDigit ( input.charAt ( i ) ) ) 
				{
					temp.append ( input.charAt ( i ) ) ;
					i ++ ;
				}

				res.append ( temp ) ;
				temp.setLength ( 0 ) ;
				i-- ;
			} 
			else 
			{
				temp.insert ( 0 , ch ) ;
			}
		}

		res.append(temp);
		System.out.println("Output: "+res.toString());
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms;
public class STO0003_0_NoOfOccuranceOfSubstringInString 
{
	/*
	 * String s =“lekhale” How many times “le” is Getting repeated, write a code to
	 * find out using java.
	 */
	public static void main(String[] args) 
	{

		String s="lekhale";
		System.out.println("Input:  "+s);
		//This will print the length of the string (7)
		//System.out.println(s.length());

		//this will give you the total length of the string after replace le with space(3)
		//System.out.println((s.replaceAll("le","").length()));

		//Need to divide the number of character 
		int result = (s.length()-s.replaceAll("le","").length())/2;
		System.out.println("Output: "+result);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms;
public class STO0003_1_NoOfOccuranceOfSubstringInString 
{
	/*
	 * String s =“lekhale” How many times “le” is Getting repeated, write a code to
	 * find out using java.
	 */
	public static void main(String[] args) 
	{

		String s = "lekhale";
		System.out.println("Input: "+s);
		int count = 0;
		int index = s.indexOf("le");
		while (index != -1) 
		{
			count++;
			index = s.indexOf("le", index + 1);
		}
		System.out.println("Output: "+"The substring 'le' is repeated " + count + " times in the given string.");
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms;
public class STO0003_2_NoOfOccuranceOfSubstringInString 
{
	public static void main(String[] args) 
	{
		String str="abababababaabb";
		String sub = "bab";

		int n = str.length();
		int m = sub.length();

		// index=-1 in case of no match, otherwise >=0(first match position)
		int index=str.indexOf(sub), i=index+1, count=(index>=0)?1:0;
		//System.out.println(i+" "+index+" "+count);

		// i will traverse up to only (m-n) position
		while(index!=-1 && i<=(n-m))
		{   
			index=str.substring(i, n).indexOf(sub);
			count=(index>=0)?count+1:count;
			i=i+index+1;  
			//System.out.println(i+" "+index);
		}
		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+sub);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class STO0003_3_NoOfOccuranceOfSubstringInString 
{
	static int countMatches(Pattern pattern, String string)
	{
		Matcher matcher = pattern.matcher(string);

		int count = 0;
		int pos = 0;
		while (matcher.find(pos))
		{
			count++;
			pos = matcher.start() + 1;
		}

		return count;
	}
	public static void main(String[] args) 
	{
		Scanner sc=new Scanner(System.in);
		System.out.print("Enter a sentence please:");
		String str = sc.nextLine();
		System.out.print("Enter a SubString:");
		String sub=sc.next();
		Pattern pattern = Pattern.compile(sub);
		int count = countMatches(pattern, str);
		System.out.println("No Of Times Sub String Appears: "+count);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms;
import java.util.Scanner;
public class STO0003_4_NoOfOccuranceOfSubstringInString 
{
	public  static  int getCountSubString(String str , String sub)
	{
		int n = 0, m = 0, counter = 0, counterSub = 0;
		while(n < str.length())
		{
			counter = 0;
			m = 0;
			while(m < sub.length() && str.charAt(n) == sub.charAt(m))
			{
				counter++;
				m++; n++;
			}
			if (counter == sub.length())
			{
				counterSub++;
				continue;
			}
			else if(counter > 0)
			{
				continue;
			}
			n++;
		}

		return  counterSub;
	}
	public static void main(String[] args) 
	{
		int count;
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter a sentence please:");
		String str = scanner.nextLine();
		System.out.print("Enter a Substring");
		String sub=scanner.next();
		STO0003_4_NoOfOccuranceOfSubstringInString obj=new STO0003_4_NoOfOccuranceOfSubstringInString();
		count=obj.getCountSubString(str, sub);

		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+sub);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms;
import java.util.Scanner;
public class STO0003_5_NoOfOccuranceOfSubstringInString 
{
	public static void main(String[] args) 
	{
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter a sentence please:");
		String str = scanner.nextLine();
		System.out.print("Enter a sentence please:");
		String sub=scanner.next();

		int count =0;
		int findStrLength = sub.length();
		for(int i=0;i<str.length();i++)
		{
			if(sub.startsWith(Character.toString(str.charAt(i))))
			{
				if(str.substring(i).length() >= findStrLength)
				{
					if(str.substring(i, i+findStrLength).equals(sub))
					{
						count++;
					}
				}
			}
		}


		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+sub);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms;
import java.util.LinkedList;
import java.util.List;
public class STO0004_0_SortingAsPerFrequency 
{
	/*
	 * Input string: "dadeadrs" 
	 * Output: "dddaaers"
	 */
	public static void main(String[] args) 
	{
		String s="dadeadrs";
		System.out.println("Input: "+s);
		List <Character> ls = new LinkedList<>( );
		for(int i=0;i<s.length();i++)
		{
			if(!ls.contains(s.charAt(i)))
			{
				ls.add(s.charAt(i));
				for (int j=i+1; j<s.length(); j++ )
				{
					if ( s.charAt ( i ) == s.charAt ( j ) ) 
					{
						ls.add (s.charAt (j)) ;
					}
				}
			}
		}
		String finals="";
		for ( Character character : ls)
		{
			finals=finals+character;
		}
		System.out.print ("Output: "+finals);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0006_0_StringDecrypt 
{
	public static void main(String[] args) 
	{
		String input = "Welcome to Mis2is2ip2i Bla4k Adam";
		System.out.println("Input: "+input);
		StringBuilder res = new StringBuilder();
		for ( int i = 0 ; i <input.length(); i ++ ) 
		{
			char currentCharacter = input.charAt(i);
			if ( Character.isDigit (currentCharacter))
			{
				int count = Character.getNumericValue (currentCharacter) ;
				char charToAppend = input.charAt (i-1);
				while (count -- >1) 
				{
					res.append (charToAppend);
				}
			}
			else
			{
				res.append (currentCharacter);
			}
		}
		System.out.println("Output:"+res);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class STO0007_0_CountNoOfOccuranceOfCharacter 
{
	/*
	 * Input= abbcccdeee 
	 * Output= a1b2c3d1e3
	 */
	public static void main(String[] args) 
	{
		String s="abbcccdeee";
		System.out.println("Input: "+s);
		char [ ] ch= s.toCharArray();
		Map<Character, Integer> maps= new LinkedHashMap<Character,Integer>();
		for (Character c:ch)
		{
			Integer count = maps.get(c);
			if (count != null)
			{
				maps.put (c, ++count);
			} 
			else 
			{
				maps.put(c,1);
			}
		}
		StringBuffer sb = new StringBuffer();
		for (Entry< Character , Integer > entry : maps.entrySet()) 
		{
			sb.append(entry.getKey()).append(entry.getValue());
		}
		System.out.println ("Output: "+sb);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
import java.util.ArrayList;
import java.util.List;
public class STO0008_0_ReverseStringByPreservingSpaces 
{
	/*
	 * Input:  Today is January 5th 
	 * Output: 5thja nu aryisTo day
	 */
	public static void main(String[] args) 
	{
		String input = "Today is January 5th";
		System.out.println("Input: "+input);
		String[] output = input.split(" ");
		StringBuffer sb = new StringBuffer();
		List<Integer> spaceIndex = new ArrayList<>();
		for (int i=0; i<output.length-1; i++ ) 
		{
			spaceIndex.add(input.indexOf(" ")+i);
			input=input.replaceFirst(" ","");
		}
		for ( int i=output.length-1; i>=0 ;i--)
		{
			sb.append(output[i]);
		}
		for ( int i : spaceIndex ) 
			sb.insert(i," ");
		System.out.println("Output: "+sb);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
import java.util.Arrays;
public class STO0008_1_ReverseStringByPreservingSpaces 
{
	/*
	 * Input : he is a good boy 
	 * Output: yo bd o ogas ieh
	 */
	public static void main(String[] args) 
	{
		String input="he is a good boy";
		System.out.println("Input: "+input);
		String[] split=input.split(" ");
		
		StringBuilder sb=new StringBuilder(input.replaceAll(" ", ""));
		sb.reverse();
		
		int count=0;
		for(String o:Arrays.asList(split).subList(0, split.length-1))
		{
			count=count+o.length();
			sb.insert(count, " ");
			count++;
		}
		System.out.println("Output: "+sb);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
import java.util.ArrayList;
import java.util.Scanner;
public class STO0008_2_ReverseStringByPreservingSpaces 
{
	/*
	 * Input : he is a good boy 
	 * Output: yo bd o ogas ieh
	 */
	public static void main(String[] args) 
	{
		String a = " he is a good boy " ;
		System.out.println("Input: "+a);
		// Output : yo bd o ogas ieh
		String a1 = " " ;
		String result = " " ;
		int k = 1 ;
		ArrayList < Integer > lenArrayList = new ArrayList < > ( ) ;
		Scanner scanner = new Scanner ( a ) ;
		while ( scanner.hasNext ( ) )
		{
			String word = scanner.next ( ) ;
			a1 = a1 + word ;
			lenArrayList.add(word.length());
		}

		for ( int i = 0 ; i <= lenArrayList.size ( )-1 ; i ++ )
		{
			for ( int j = 0 ; j <=lenArrayList.get( i ) -1 ; j ++ )
			{
				result= result + a1.charAt(a1.length ( ) - k ) ;
				k ++ ;
			}
			result = result + " " ;
		}
		System.out.println("Output: "+result);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms;
import java.util.ArrayList;
import java.util.List;
public class STO0009_0_InterviewPrograms 
{
	/*
	 * Input: 1234
	 * Output:{1234, 11223344, 111222333444, 1111222233334444}
	 */

	public static void main(String[] args) 
	{
		String num = "1234";
		System.out.println("Input: "+num);
		String finals = "";
		char arr[] = num.toCharArray();
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < arr.length; i++)
		{
			for (int j = 0; j < arr.length; j++) 
			{
				for (int k = 0; k < i + 1; k++) 
				{
					finals = finals + arr[j];
				}
			}
			list.add(finals);
			finals = "";
		}
		System.out.println("Output: "+list);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms;

import java.util.Arrays;

public class STO0010_0_InterviewPrograms 
{
	/*
	 * Input:{A, B, C, D} 
	 * Output:{AA, BB, CC, DD}
	 */
	public static void main(String[] args) 
	{
		char[] ch = {'A', 'B', 'C', 'D'};
		System.out.println("Input: "+Arrays.toString(ch));
		append(ch);
	}
	static void append(char ch[]) 
	{
		char[] ch1=ch.clone();
		//System.out.println(ch);
		//System.out.println(ch1);
		char[] result= new char[0];
		StringBuilder sb = new StringBuilder();
		for(int i=0;i<ch.length;i++)
		{
			sb.append(ch[i]);
			sb.append(ch1[i]);
			sb.append(' ');
			result = sb.toString().toCharArray();
		}
		System.out.print("Output: ");
		System.out.print(result);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms;
import java.util.ArrayList;
import java.util.Arrays;
public class STO0010_1_InterviewPrograms 
{
	/*
	 * Input:{A, B, C, D} 
	 * Output:{AA, BB, CC, DD}
	 */
	public static void main(String[] args) 
	{
		String[]arr= {"A","B","C","D"};
		System.out.println("Input: "+Arrays.toString(arr));
		ArrayList<String> AL=new ArrayList<>();
		for(int i=0;i<arr.length;i++)
		{
			String str=arr[i]+arr[i];
			AL.add(str);
		}
		//System.out.println(arr);
		System.out.println("Output: "+AL);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0011_0_PrintFrequencyOfEachCharacter 
{
	/*
	 * Input string =AAAADDDCCCA 
	 * Output= A4D3C3A1
	 */
	public static void main(String[] args) 
	{
		String s = "AAAADDDCCCA";
		System.out.println("Input: "+s);
		int count = 1;
		String re = "" ;
		for (int i = 0 ; i <=s.length()-1; i++ )
		{
			if ( i == s.length()-1 & count == 1 )
			{
				re = re + s.charAt(i)+count;
				break ;
			}
			if ( s.charAt(i) == s.charAt(i+1))
			{
				count++;
			}
			else
			{
				re = re + s.charAt ( i ) + count ;
				count=1;
			}

		}
		System.out.println ("Output: "+re);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0011_1_PrintFrequencyOfEachCharacter 
{
	/*
	 * Input string =abbcccdeee 
	 * Output= a1b2c3d1e3
	 */
	public static void main(String[] args) 
	{
		StringBuilder sb = new StringBuilder();
		String str = "abbcccdeee";
		System.out.println("Input: "+str);
		String[] strArray = str.split("");
		int i = 0 ;
		while ( i < strArray.length ) 
		{
			int counter=0 ;
			int j = i ;
			while ( j < strArray . length ) 
			{
				if ( ! strArray [ i ] .equals ( strArray [ j ] ) )
					break;
				counter++ ;
				j++;
			}
			sb.append ( strArray [ i ] ) . append ( counter ) ;
			i = j ;
		}
		System.out.println ("Output: "+sb.toString());
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.ArrayList;
public class STO0011_2_PrintFrequencyOfEachCharacter 
{
	/*
	 * Input string "AAAABBCCCDDDDEEEG" 
	 * Output string "A4B2C3D4E3G1"
	 */ 
	public static void main(String[] args) 
	{
		String s ="AAAABBCCCDDDDEEEG";
		System.out.println("Input: "+s);
		ArrayList<Character> list = new ArrayList<>();
		System.out.print("Output: ");
		for(int i=0;i<s.length();i++)
		{
			int count=1;
			if(!list.contains(s.charAt(i)))
			{
				list.add(s.charAt(i));
				for(int j=i+1;j<s.length();j++)
				{
					if(s.charAt(i)==s.charAt(j))
					{
						count++;
					}
				}
				System.out.print(s.charAt(i)+""+count);
			}
		}
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class STO0011_3_PrintFrequencyOfEachCharacter 
{
	/*
	 * Input string "AAAABBCCCDDDDEEEG" 
	 * Output string "A4B2C3D4E3G1"
	 */ 
	public static void main(String[] args) 
	{
		String s = "AAAABBCCCDDDDEEEG";
		System.out.println("Input: "+s);
		String[] sArray = s.split("");
		Map<String, Integer> map = new HashMap<>();
		for(String temp : sArray) 
		{
			if(map.containsKey(temp)) 
			{
				map.put(temp, map.get(temp)+1);
			}
			else 
			{
				map.put(temp, 1);
			}
		}
		System.out.println("Output: "+map.toString().replaceAll("\\W",""));
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class STO0011_4_PrintFrequencyOfEachCharacter 
{
	/*
	 * Input string "AAAABBCCCDDDDEEEG" 
	 * Output string "A4B2C3D4E3G1"
	 */ 
	public static void main (String [] args)
	{
		String str = "AAAABBCCCDDDDEEEG";
		System.out.println("Input: "+str);
		occurences (str);
	}
	public static void occurences(String str)
	{
		int count = 0 ;
		Map <Character, Integer> hs=new HashMap <Character ,Integer>();
		for ( int i = 0 ; i<str.length(); i++) 
		{
			if ( hs.containsKey(str.charAt(i))) 
			{
				count =hs.get(str.charAt(i));
				count = count+1;
				hs.put(str.charAt(i),count);
			} 
			else 
			{
				hs.put(str.charAt(i), 1);
			}
		}
		Set<Map.Entry <Character, Integer>> s = hs.entrySet();
		System.out.print("Output: ");
		for (Entry<Character,Integer> s1 : s ) 
		{
			System.out.print (s1.getKey()+ ""+s1.getValue());  
		}            
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0012_0_ReplacingSubstringswithIncrementalOrder 
{
	/*
	 * Input: tomorrow 
	 * Output: t#m##rr###w
	 */
	public static void main(String[] args) 
	{
		StringBuilder charactersToAppend = new StringBuilder("#");
		String input = "tomorrow";
		System.out.println("Input: "+input);
		while (input.contains("o")) 
		{
			input = input.replaceFirst("o", charactersToAppend.toString());
			charactersToAppend.append("#");
		}
		System.out.println("Output: "+input);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0012_1_ReplacingSubstringswithIncrementalOrder 
{
	/*
	 * Input: tomorrow 
	 * Output: t#m##rr###w
	 */

	public void getSolution(String input)
	{
		int count = 0;
		String output = "";
		char ch[] = input.toCharArray();
		for(int i=0; i<ch.length; i++)
		{
			if(ch[i] == 'o')
			{
				count++;
				for(int j=0; j<count; j++)
				{
					output = output+Character.toString(ch[i]);
					output = output.replace(ch[i], '#');
				}
			}
			else {
				output = output+Character.toString(ch[i]);
			}
		}
		System.out.println("Output: "+output);
	}
	public static void main(String[] args) 
	{
		String s = "tomorrow";
		System.out.println("Input: "+s);
		STO0012_1_ReplacingSubstringswithIncrementalOrder soluSoultionTest = new STO0012_1_ReplacingSubstringswithIncrementalOrder();
		soluSoultionTest.getSolution(s);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0012_2_ReplacingSubstringswithIncrementalOrder 
{
	/*
	 * Input: tomorrow 
	 * Output: t#m##rr###w
	 */
	public static String replaceWithString(String input,char present,String replace )
	{
		int count =0;
		String s ="";
		while(input.contains(Character.toString(present)))
		{
			int n = input.indexOf(present)>0?(count++):(count=0);
			if(count == n)
				break;
			for(int i= count; i>1; i--)
			{
				s+=replace;
			}
			input= input.replaceFirst(Character.toString(present),s);
		}
		return input;
	}

	public static void main(String[] args) 
	{
		String str="tomorrow";
		System.out.println("Input: "+str);
		String result=replaceWithString(str,'o',"#");
		System.out.println("Output: "+result);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class STO0002_0_RemoveAdjacentDuplicateElements 
{
	/**
	 * Input = [1,2,2,3,4,5,5,3] 
	 * Output = [1,3,4,3]
	 */
	public static void main(String[] args) 
	{
		int Input[] = {1,2,2,3,4,5,5,3};
		System.out.println("Input: "+Arrays.toString(Input));
		List<Integer> list= new ArrayList<>();
		List<Integer> list1= new ArrayList<>();
		for (int i = 0; i <= Input.length-1; i++) 
		{
			list.add(Input[i]);
		}
		for (int j = 0; j <= list.size()-1; j++)
		{
			if(j==list.size()-1)
			{
				if(list.get(j).equals(list.get(j-1)))
				{
				}
				else 
				{
					list1.add(list.get(j));
				}
				break;
			}
			if(list.get(j).equals(list.get(j+1)))
			{
				j=j+1;
			}
			else if ( j!=0 && list.get(j).equals(list.get(j-1)) ) 
			{
				//j=j+1;
			}
			else 
			{
				list1.add(list.get(j));
			}
		}
		System.out.print("Output: ");
		for(Integer d:list1)
		{
			System.out.print(d+",");
		}
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms;
public class STO0014_0_InterviewPrograms 
{
	/*
	 * Input="Selenium" 
	 * Output: 
	 * eleniumS
	 * leniumeS
	 * eniumleS
	 * niumeleS
	 * iumneleS
	 * umineleS
	 * muineleS
	 */
				
	public static void main(String[] args) 
	{
		String str= "Selenium";
		System.out.println("Input: "+str);
		// char [ ] chs str.toCharArray ( ) ;
		int len = str.length() , temp = 0 ;
		String out = "";
		System.out.println("Output: ");
		for (int k = 0 ; k<len-1; k++) 
		{
			for ( int i = k + 1 ; i < len ; i ++ ) 
			{
				out =out + str.charAt(i);
			}  
			temp= k ;
			while ( k >= 0 ) 
			{
				out= out + str.charAt ( k ) ;
				k -- ;
			}
			k=temp;
			System.out.println ( out ) ; 
			out="";
		}
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms;
public class STO0014_1_InterviewPrograms 
{
	/*
	 * Input="Selenium" 
	 * Output: 
	 * eleniumS
	 * leniumeS
	 * eniumleS
	 * niumeleS
	 * iumneleS
	 * umineleS
	 * muineleS
	 */

	public static void main(String[] args) 
	{
		String str = "Selenium";
		System.out.println("Input: "+str);
		char [ ] input = str.toCharArray();
		int len = input.length ;
		printArr(input, len);
	}

	public static void printArr (char[] input, int len) 
	{
		System.out.println("Output: ");
		for (int i = 0 ; i<input.length ; i++ ) 
		{
			char temp = input[0];
			for ( int j = 1 ; j < len ; j ++ )
			{
				input[j-1]=input[j];
			}
			input[len-1]=temp;
			len--;
			System.out.println(input);
		}
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms;
public class STO0015_0_ReverseWithoutReverseLastElement 
{
	/*
	 * Input: 1230 
	 * Output: 03210
	 */
	public static void main(String[] args) 
	{
		int n = 1230 ;
		System.out.println("Input: "+n);
		String s = String.format("%05d",n); // to get 1230 to 01230
		//System.out.println ( s ) ;
		int len = s.length ( ) ;
		String rev = "" ;
		for ( int i = len - 1 ; i >= 0 ; i-- )
		{
			rev = rev + s.charAt ( i ) ;
		}
		System.out.println("Output: "+rev); 
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms;
import java.util.Arrays;
public class STO0008_1_ReverseStringByPreservingSpaces 
{
	/*
	 * Input : he is a good boy 
	 * Output: yo bd o ogas ieh
	 */
	public static void main(String[] args) 
	{
		String input="he is a good boy";
		System.out.println("Input: "+input);
		String[] split=input.split(" ");
		
		StringBuilder sb=new StringBuilder(input.replaceAll(" ", ""));
		sb.reverse();
		
		int count=0;
		for(String o:Arrays.asList(split).subList(0, split.length-1))
		{
			count=count+o.length();
			sb.insert(count, " ");
			count++;
		}
		System.out.println("Output: "+sb);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Set;
import java.util.TreeMap;
public class STO0017_0_SortAlphabetByIgnoringCase 
{
	/*
	 * Input string: "AcBCbDEdea" 
	 * Output string:"AaBbCcDdEe"
	 */
	public static void main(String[] args) 
	{
		TreeMap<Character,Integer> map1 = new TreeMap<Character,Integer>();
		String S1="AcBCbDEdea";
		System.out.println("Input: "+S1);
		char[] array = S1.toLowerCase().toCharArray();
		for(char c:array)
		{
			if(map1.containsKey(c))
			{
				map1.put(c,map1.get(c)+1);
			}
			else
			{
				map1.put(c,1);
			}
		}
		Set<Character> set=map1.keySet();
		System.out.print("Output: ");
		for(Character character:set)
		{
			if(map1.get(character)==2)
			{
				System.out.print(Character.toUpperCase(character)+""+Character.toLowerCase(character));
			}
		}
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.numbers;

import java.util.Arrays;

public class STO0018_0_SortByOneAtFirstLaterZero 
{
	/*
	 * Input 11001101011 
	 * Output 1111100000 (first numeric 1 and followed by 0s)
	 */
	public static void main ( String args [ ] ) 
	{
		int arr [ ] = { 1,1,0,0,1,1,0,1,0,1,1 };
		System.out.println("Input: "+Arrays.toString(arr));
		int i = 0 , j = 0 ;

		while ( i < arr.length ) 
		{
			if ( arr [ i ] == 1 ) 
			{
				swap ( arr , i , j ) ;
				i ++ ;
				j ++ ;
			}
			else 
			{
				i ++ ;
			}
		}
		System.out.print("Output: ");
		for ( int k = 0 ; k < arr.length ; k ++ )
			System.out.print ( arr [ k ] ) ;
	}
	private static void swap ( int [ ] arr , int i , int j )
	{                                          
		int temp=arr[i] ;;
		arr [i]= arr [j] ;
		arr [j] = temp ;
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.numbers;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;

public class STO0018_1_SortByOneAtFirstLaterZero 
{
	/*
	 * Input 11001101011 
	 * Output 1111100000 (first numeric 1 and followed by 0s)
	 */
	public static void main ( String args [ ] ) 
	{
		int arr[] = { 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 , 0 , 0 , 1 };
		System.out.println("Input: "+Arrays.toString(arr));
		HashMap< Integer , Integer > h = new LinkedHashMap<>();
		for ( int i = 0 ; i < arr.length ; i ++ ) 
		{
			h.put(arr[i] , h.getOrDefault(arr[i] , 0 ) + 1);
		}
		int reset = 0 ;
		System.out.print("Output: ");
		for ( int x : h.values()) 
		{
			for ( int i = 1 ; i <= x ; i ++ ) 
			{
				if ( reset == 0 )
					System.out.print("1");
				else
					System.out.print("0");
			}
			reset = 1 ;
		}
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.numbers;

import java.util.Arrays;
import java.util.Comparator;

public class STO0018_2_SortByOneAtFirstLaterZero 
{
	/*
	 * Input 11001101011 
	 * Output 1111100000 (first numeric 1 and followed by 0s)
	 */
	public static void main ( String args [ ] ) 
	{
		int [] arr = { 1,1,0,0,1,0,1,0,1,1 };
		System.out.println("Input: "+Arrays.toString(arr));
		int [ ] arr1= Arrays.stream(arr).boxed(). sorted(Comparator.reverseOrder()).mapToInt(Integer::intValue).toArray();
		System.out.println("Output: "+Arrays.toString(arr1));
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.numbers;

import java.util.Arrays;
import java.util.Comparator;

public class STO0018_3_SortByOneAtFirstLaterZero 
{
	/*
	 * Input 11001101011 
	 * Output 1111100000 (first numeric 1 and followed by 0s)
	 */
	
	/*
	 * Their an array list consist of multiple 0 and 1 {0,0,1,0,1,1,0,0}etc . So I
	 * want an array list so that it's final outcome become {0,0,0,0 ,0,0,1,1,1,1,1}
	 * etc .
	 */	public static void main ( String args [ ] ) 
	{
		int arr[] = new int[]{ 0,1,0, 1, 0, 1, 1, 1 };
		System.out.println("Input: "+Arrays.toString(arr));
		int n = arr.length;
		int count = 0;

		for (int i = 0; i < n; i++) 
		{
			if (arr[i] == 0)
				count++;
		}

		for (int j = 0; j < count; j++)
		{
			arr[j] = 0;
		}
		for (int k = count; k < n; k++)
		{
			arr[k] = 1;
		}
		System.out.print("Output: ");
		for (int q = 0; q < n; q++)
		{
			System.out.print(arr[q] + " ");    
		}
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;

public class STO0009_1_RunLengthEncoding 
{
	public static void main(String[] args) 
	{
        String input = "AAAABBCCCDDDDEEEG";

        StringBuilder result = new StringBuilder();
        int count = 1;

        for (int i = 1; i < input.length(); i++)
        {
            if (input.charAt(i) == input.charAt(i - 1)) 
            {
                count++;
            } 
            else 
            {
                result.append(input.charAt(i - 1)).append(count);
                count = 1;
            }
        }

        // append last character and its count
        result.append(input.charAt(input.length() - 1)).append(count);

        System.out.println(result.toString());
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class STO0013_0_ExpandCharByCount 
{
	/**
	 * Input 1B3A2D4C 
	 * Output BAAADDCCCC
	 * WALLMART
	 */
	public static void main(String[] args)
	{
		String s = "1B3A2D4C";
		System.out.println("Input: "+s);
		String[] sArray = s.split("");
		List<String> intList = new ArrayList<>();
		List<String> sList = new ArrayList<>();
		for(String temp : sArray) {
			if(temp.matches("[a-zA-Z]")) {
				sList.add(temp);
			}
			else 
			{
				intList.add(temp);
			}
		}
		Map<String, Integer> map = new LinkedHashMap<>();
		Iterator<String> itr1 = sList.iterator();
		Iterator<String> itr2 = intList.iterator();
		while(itr1.hasNext() && itr2.hasNext()) 
		{
			map.put(itr1.next(), Integer.parseInt(itr2.next()));
		}
		System.out.print("Output: ");
		for(Map.Entry<String, Integer> m : map.entrySet()) 
		{
			for(int i=0;i<m.getValue();i++)
			{
				System.out.print(m.getKey());
			}
		}
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0020_1_PrintEachCharacterConsecutiveMentionedTimes 
{
	// Interview Questions Asked In Unify technologies
	// Suppose input string is "c3d4a2" then output should be "cccddddaa"
	public static void main(String[] args) 
	{
		String s="c3d4a2";
		String ans="";

		for (int i = 0; i<=s.length()-1; i++) 
		{
			String r=String.valueOf(s.charAt(i));
			int rep= Integer.valueOf(String.valueOf(s.charAt(i+1)));		

			for (int j =1 ; j<=rep; j++) 
			{
				ans=ans+r;
			}
			i=i+1;
		}
		System.out.println("Input: "+s);
		System.out.print("Output: "+ans);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
public class STO00027_0_MoveZerosToFront 
{
	/**
	 * Input:[5, 0, 4, 6, 0, 7, 0]
	 * Output: 0 0 0 5 4 6 7
	 * 
	 */
	public static void main(String[] args) 
	{
        int[] input = {5, 0, 4, 6, 0, 7, 0};
        int[] output = new int[input.length];

        int index = input.length - 1;

        // Place non-zero elements from the end
        for (int i = input.length - 1; i >= 0; i--) 
        {
            if (input[i] != 0)
            {
                output[index--] = input[i];
            }
        }

        // Remaining positions are zeros by default
        for (int num : output)
        {
            System.out.print(num + " ");
        }
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.others;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;
public class STO0022_0_PrintInJSONFormat
{
	/*
	 * Input:{01IND02AUS03ENG} 
	 * Output: 
	 * { 
	 * "01": IND, 
	 * "02":AUS, 
	 * "03":ENG 
	 * } 
	 * O/P should be printed in json array with key value pair.
	 * 
	 * Download Jar File From Here: https://code.google.com/archive/p/json-simple/downloads
	 * After that Add the Jar File In the Java Project build Path:  (right-click on the project, Properties->Libraries and add new JAR.)
	 */

	public static void main(String[] args) 
	{
		String s = "01IND02AUS03ENG";
		System.out.println("Input: "+s);
		STO0022_0_PrintInJSONFormat solution = new STO0022_0_PrintInJSONFormat();
		solution.getSolution(s);
	}
	public void getSolution(String test)
	{
		String word[] = test.split("([0-9])+");
		String num[] = test.split("([a-zA-z])+");
		Map<String, String> hasmMap = new HashMap<String, String>();
		for(int i=0; i<num.length; i++)
		{
			for(int j=i+1; j<=i+1; j++)
			{
				hasmMap.put(num[i], word[j]);
			}
		} 
		JSONObject data = new JSONObject(hasmMap);
		System.out.println("Output: "+data);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.others;
import java.util.HashMap;
public class STO0022_1_PrintInJSONFormat
{
	/*
	 * Input:{01IND02AUS03ENG} 
	 * Output: 
	 * { 
	 * "01": IND, 
	 * "02":AUS, 
	 * "03":ENG 
	 * } 
	 * O/P should be printed in json array with key value pair.
	 *
	 */

	public static void main(String[] args) 
	{
		String input = "01IND02AUS03ENG";
		System.out.println("Input: "+input);
		HashMap <String ,String> map= new HashMap <String,String>( );
		String [ ] intArr = input.split("([0-9])+");
		String [ ] StrArr = input.split("([a-z]|[A-Z])+");
		int iCount = 1 ;
		for (String b:StrArr) 
		{
			map.put(b,intArr[iCount]);
			iCount++;
		}
		System.out.println("Output: "+map);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
import java.util.Arrays;
public class STO0023_0_SortArrayByNumberFirstLaterAlphabet 
{
	/*
	 * input :list1--[3,R,M,4,89,f] 
	 * OutPut:list2--[3,4,89,M,R,f]
	 */
	public static void main(String[] args) 
	{
		String[] inputArr=new String[] {"3" ,"R", "M" , "4" , "89" , "f"};
		System.out.println("Input: "+Arrays.toString(inputArr));
		String[] arr = pushAllCharToRight(inputArr);
		System.out.println("Input: "+Arrays.toString(arr));
	}
	public static String[] pushAllCharToRight(String[] array)
	{
		int i= 0 ;
		int j = array.length-1;
		while (i < j)
		{
			if (Character.isLetter(array[j].charAt(0)))
			{
				j--;
			}
			try
			{
				Integer.parseInt(array[i]);
				i++;
			}
			catch (NumberFormatException e)
			{
				String temp = array[j];
				array[j--] = array[i];
				array[i] = temp;
			}
		}
		return array;
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
import java.util.ArrayList;
import java.util.Arrays;
public class STO0023_1_SortArrayByNumberFirstLaterAlphabet 
{
	/*
	 * input :list1--[3,R,M,4,89,f] 
	 * OutPut:list2--[3,4,89,M,R,f]
	 */
	public static void main(String[] args) 
	{
		ArrayList lst=new ArrayList();
		ArrayList lstSorted=new ArrayList();

		lst.add(3);
		lst.add("R");
		lst.add("M");
		lst.add(4);
		lst.add(89);
		lst.add("f");

		String [] stringLst=new String[lst.size()];

		for(int i=0;i<lst.size();i++)
		{
			if(lst.get(i).getClass().getSimpleName().equalsIgnoreCase("Integer"))
			{
				stringLst[i]=Integer.toString((int)lst.get(i));
			}
			else
				stringLst[i]=(String)lst.get(i);
		}

		Arrays.sort(stringLst);

		for(int b=0;b<stringLst.length;b++)
		{
			lstSorted.add(stringLst[b]);
		}

		System.out.println("Input: "+lst);
		System.out.println("Output: "+lstSorted);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.others;
import java.util.Arrays;
public class STO0025_0_InterviewPrograms 
{
	/*
	 * Input ( 1,2,3,4,5 ) 
	 * Output- { 3,4,5,1,2 )
	 */
	public static void main(String[] args) 
	{
		int [] a = {1 , 2 , 3 , 4 , 5 };
		System.out.println("Input: " + Arrays.toString(a));
		int nor = 2 ; // no of Rotations
		for ( int i=0; i<nor; i++ ) 
		{
			int fE = a[0] ; // get First Element
			for(int j=0 ; j<a.length-1; j++ ) 
			{
				a[j]= a[j+1];
			}
			a[a.length-1]=fE ; // put first element at last position
		}
		System.out.println("Output: "+"Array after " + nor + " rotations " + Arrays.toString(a));
	}

}


package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
import java.util.Stack;
public class STO0027_0_ReverseEachWordOfString 
{
	/*
	 * Input: reverse me without split 
	 * Output: esrever em tuohtiw tilps
	 */
	public static void main(String[] args) 
	{
		String str = "reverse me without split";
		System.out.println("Input: "+str);
		Stack st=new Stack<Character>();
		System.out.print("Output: ");
		for (int i = 0; i < str.length(); ++i) 
		{
			if (str.charAt(i) != ' ')
				st.push(str.charAt(i));
			else {
				while (st.empty() == false) 
				{
					System.out.print(st.pop());
				}
				System.out.print(" ");
			}
		}
		while (st.empty() == false) 
		{
			System.out.print(st.pop());
		}
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
public class STO0028_0_ReverseStringWithOutReverseDigitsAndSpecialCharacters 
{
	/*
	 * Input: My n@me is 12Rahul 
	 * Output: yM em@n si 12luhaR 
	 * Only charcters should be Character, special characters and numbers should be displayed as it is.
	 */
	public static void main(String[] args) 
	{
		String str = "My n@me is 12Rahul";
		System.out.println("Input: "+str);
		String result="";
		String[] py = str.split(" ");
		int counter=0;
		for(int i=0;i<py.length;i++) 
		{
			String tem = py[i];
			for(int gg = tem.length()-1; gg>=0; gg--) 
			{
				if(!Character.isDigit(tem.charAt(counter))) 
				{
					result = result + tem.charAt(gg+counter);
				}
				else
				{
					result = result + tem.charAt(counter);
					counter++;
				}
			}
			result = result+ " ";
			counter=0;
		}
		System.out.println("Output: "+result);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class STO0028_1_ReverseStringWithOutReverseDigitsAndSpecialCharacters 
{
	/*
	 * Input String // My n@me is 12Rahul 
	 * Output String // yM em@n si 12luhaR 
	 * Only charcters should be Character, special characters and numbers should be displayed as it is.
	 */
	public static void main(String[] args) 
	{
		String str = "My n@me is 12Rahul";
		System.out.println("Input: "+str);
		String resultString = Stream.of(str.split(" ")).map(String::toCharArray).map(STO0028_1_ReverseStringWithOutReverseDigitsAndSpecialCharacters::reverse)
				.collect(Collectors.joining(" "));
		System.out.println("Output: "+resultString);
	}
	public static String reverse ( char str [ ] )
	{
		int left = 0 , right = str.length - 1 ;
		while ( left< right ) 
		{
			// Ignore numbers characters
			if ( Character.isDigit ( str [left]))
				left ++ ;
			else if ( Character.isDigit ( str [right]))
				right-- ;
			else {
				char tmp = str [ left ] ;
				str [ left ] = str [ right ] ;
				str [ right ] = tmp ;
				left ++ ;
				right-- ;
			}
		}
		return new String ( str ) ;
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
public class STO0029_0_ReverseSentence 
{
	/*
	 * Input - Hi I am Naveen I need and answer 
	 * Output - answer and deen I Naveen ma I Hi
	 */
	public static void main(String[] args) 
	{
		String str = "Hi I am Naveen I need and answer";
		System.out.println("Input: "+str);
		String[] sp=getPattern(str);
		System.out.print("Output: ");
		// print Array
		for(int j=sp.length-1; j>=0; j--) 
		{
			System.out.print(sp[j] + " ");
		}
	}
	private static String[] getPattern(String revStr)
	{
		String[] splitStr = revStr.split(" ");
		for ( int j = splitStr.length-3; j>=0 ; j=j-3)
		{
			String temp=splitStr[j];
			StringBuilder sb = new StringBuilder(temp);
			splitStr[j] = sb.reverse().toString();
		}
		return splitStr ;
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
public class STO0029_1_ReverseSentence 
{
	/*
	 * Input - Hi I am Naveen I need and answer 
	 * Output - answer and deen I Naveen ma I Hi
	 */
	public static void main(String[] args) 
	{
		String input = "Hi I am Naveen i need and answer";
		System.out.println("Input: "+input);
		String[] inputArr=input.split(" ");
		String outputStr = "" ;
		int j = 0 ;
		for (int i=inputArr.length-1; i>=0 ; i-- ) 
		{
			++ j ;
			String indexedStr = "";
			if (j%3==0)
			{
				for (int k=inputArr[i].length()-1 ; k>=0 ; k--) 
				{
					indexedStr = indexedStr + inputArr[i].charAt(k);
				}
			}
			else 
			{
				indexedStr=inputArr[i];
			}
			outputStr = outputStr + " " + indexedStr;
		}
		System.out.println("Output: "+outputStr.trim());
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
public class STO0030_0_ReverseAfterSplit 
{
	/*
	 * Input :Hello world,welcome to my world,my world 
	 * Output:world Hello ,world my to welcome ,world my  
	 * my Condition: without using predefined function
	 */
	public static void main(String[] args) 
	{
		String str1 = "Hello world,welcome to my world,my world";
		System.out.println("Input: "+str1);
		String arr[] = str1.split(",");
		String res = "";
		for(int i=0;i<arr.length;i++) 
		{
			String[] de = arr[i].split(" ");
			for(int j=de.length-1;j>=0;j--) 
			{
				res = res + de[j] + " ";
			}
			res = res + ",";
		}
		res = res.substring(0,res.length()-1);
		System.out.println("Output: "+res);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
public class STO0030_1_ReverseAfterSplit 
{
	/*
	 * Input :Hello world,welcome to my world,my world 
	 * Output:world hello ,world my to welcome ,world 
	 * my Condition: without using predefined function
	 */
	public static void main(String[] args) 
	{
		//inbuilt function split();
		String input = "Hello world,welcome to my world,my world" ;
		String output = "";

		//inbuilt function1
		String[] str_array= input.split(",");
		int len1= str_array.length;

		//System.out.println("Level 1 array length "+len1);
		System.out.println("Input String:  "+input);
		for (String s : str_array)
		{
			//System.out.println("Level words "+s);
			String[] sub_str_array = s.split(" ") ;
			int len2= sub_str_array.length;

			//System.out.println("Level 2 array length "+len2);
			if(len2>1)
			{
				String gap=" ";
				int c=0;
				for (int i=len2; i>0; i-- )
				{
					if (i==len2)
					{
						//System.out.println("Level 2 Reverse words "+sub_str_array[i-1]);
						output=output+sub_str_array[i-1];
					}
					else
					{
						output=output+gap+sub_str_array[i-1];
					}
					c++;
				}
			}
			//if1 end
			//add , after each string except for the last one in each loop
			if(s==str_array[len1-1])
			{}
			else
				output= output+",";
		} //End of 1st for loop
		System.out.println("Output String: "+output);
	} //main function
	//class end
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
public class STO0030_2_ReverseAfterSplit 
{
	/**
	 * Write Java code for
	 * String input = "I am Rajesh, currently attending, interview with, abc systems";
	 * String output= "Rajesb am I, attending currently, with interview, systems abc";
	 * 
	 */
	public static void main(String[] args) 
	{
		String str= "I am Rajesh, currently attending, interview with, abc systems";
		String[] strArray=str.split(",");
		String reverse="";
		
		for(int i=0;i<strArray.length;i++)
		{
			String[] s2=strArray[i].split(" ");
			reverse=reverse+reverse(s2)+",";
  		}
		System.out.println("Inpur: "+str);
		System.out.println("Output: "+reverse);
	}

	private static String reverse(String[] str) 
	{
		String reverse=" ";
		for(int i=str.length-1;i>=0;i--)
		{
			reverse=reverse+str[i]+" ";
		}
		return reverse;
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0031_0_HighestAsciiValueCharacter 
{
	/*
	 * Input string s ="amZgxY" 
	 * Print character who have highest ASCII value.
	 */
	public static void main(String[] args) 
	{
		String str = "amZgxY";
		System.out.println("Inout: "+str);
		System.out.println("Output: "+test(str));
	}
	public static char test ( String str ) 
	{
		int greatestVal = 0 ;
		int len = str.length();
		for (int i = 0 ; i<len; i++ )
		{
			int currentVal = (int)str.charAt(i);
			if (currentVal>greatestVal)
			{
				greatestVal=currentVal ;
			}
		}
		char greatestChar = (char)(greatestVal);
		return greatestChar ;
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0031_1_HighestAsciiValueCharacter 
{
	/*
	 * Input string s ="amZgxY" 
	 * Print character who have highest ASCII value.
	 */
	public static void main(String[] args) 
	{
		String str = "amZgxY";
		System.out.println("Input: "+str);
		int currentmax = 0 ;
		for (Character c : str.toCharArray()) 
		{
			if ((int)c>currentmax)
				currentmax = (int)c;
		}
		System.out.println ("Output: "+(char)currentmax);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Collections;
import java.util.stream.Collectors;
public class STO0031_2_HighestAsciiValueCharacter 
{
	/*
	 * Input string s ="amZgxY" 
	 * Print character who have highest ASCII value.
	 */
	public static void main(String[] args) 
	{
		String str = "amZgxY";
		System.out.println("Input: "+str);

		// Using Stream
		char c = (char)str.chars().max().getAsInt();
		System.out.println ("Output Using Stream: "+ c ) ;


		// using for each loop
		int max = 0 ;
		for (char char_val : str.toCharArray())
			if ( char_val > max )
				max = char_val ;
		System.out.println ("Output Using For Each Loop: "+(char)max);


		// Using Collections class
		char c1 = (char)Collections.max(str.chars().boxed().collect(Collectors.toList())).intValue();
		System.out.println("Output Using Collection Class: "+c1);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
public class STO0032_0_ReverseOnlyDigitsOfAString 
{
	/*
	 * Input = “GDP in 2016 has fallen from 6.8% to 4.5%” 
	 * Output = “GDP in 6102 has fallen from 8.6% to 5.4%” 
	 * Only reverse the numbers of a string.
	 */
	public static void main(String[] args) 
	{
		String s="GDP in 2016 has fallen from 6.8% to 4.5%";
		System.out.println("Input: "+s);
		StringBuffer rev=new StringBuffer();
		StringBuffer number=new StringBuffer();
		int length=s.length();
		for(int i=0;i<length;i++) {
			Character c=s.charAt(i);
			if(c.isDigit(c) || c.equals('.')) 
			{
				number.append(c);
			}
			else if(!number.isEmpty()) 
			{
				String rev1="";
				for(int j=number.length()-1;j>=0;j--) 
				{
					rev1=rev1+number.charAt(j);
				}
				rev.append(rev1+c);
				number.delete(0, number.length());
			}
			else 
			{
				rev.append(c);
			}
		}
		System.out.print("Output: "+rev);
	}
}


package com.softwaretestingo.sto000collectedpgms.interviewprograms;
public class STO0035_0_InterviewPrograms 
{
	/*
	 * Input - Ramakant 
	 * Output - R1a1m1a2k1a3n1t1 
	 * I have to take input string and in output will print no of occurance after each character
	 */
	public static void main(String[] args) 
	{
		String name = "Ramakant";
		System.out.println("Input: "+name);
		String text = "";
		for (int i = 0; i < name.length(); i++) 
		{
			char[] ch = name.toCharArray();
			text = text + ch[i] + ((name.substring(0, i).length())-(name.substring(0, i).replace(String.valueOf(ch[i]),"").length())+1);
		}
		System.out.println("Output: "+text);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.others;
import java.util.Stack;
public class STO0036_0_CheckForBalancedBrackets 
{
	// Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.
	// Example: 
	// Input: exp = “[()]{}{[()()]()}” 
	// Output: Balanced
	// {},[],{]
	// Input: exp = “[(])” 
	// Output: Not Balanced
	public static void main(String[] args) 
	{
		String equ = "[()]{}{[()()]()}";
		System.out.println("Input: "+equ);
		Stack<Character> stack = new Stack<>();
		for (int i =0 ; i< equ.length() ; i++) 
		{
			if (equ.charAt(i) == '{' || equ.charAt(i) == '[' || equ.charAt(i) == '(') 
			{
				stack.push(equ.charAt(i));
			}
			else if (!stack.isEmpty() && ( (equ.charAt(i) == ']' && stack.peek() == '[') || (equ.charAt(i) == '}' && stack.peek() == '{') || (equ.charAt(i) == ')' && stack.peek() == '(')))
			{
				stack.pop();
			}
			else 
			{
				stack.push(equ.charAt(i));
			}
		}
		if (stack.empty())
		{
			//System.out.println(stack.toString());
			System.out.println("Output: "+"Balanced");
		}
		else 
		{
			//System.out.println(stack.toString());
			System.out.println("Output: "+"Not Balanced");
		}
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.others;
import java.util.HashMap;
import java.util.LinkedList;
public class STO0036_1_CheckForBalancedBrackets 
{
	// Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.
	// Example: 
	// Input: exp = “[()]{}{[()()]()}” 
	// Output: Balanced
	// {},[],{]
	// Input: exp = “[(])” 
	// Output: Not Balanced

	static HashMap<String, String> bracketDetails=new HashMap<String, String>();
	public static void main(String[] args) 
	{
		storeBracketStartAndEnd();
		String testString = "[{()}](){()}";
		System.out.println("Input: "+testString);
		boolean status = true ;
		LinkedList<String> l1 = new LinkedList<String>();
		testString = testString.replaceAll("[^\\(\\{\\[\\)\\}\\]]", "");
		for ( int i = 0 ; i < testString.length(); i++ )
		{
			String element = String.valueOf(testString.charAt(i));
			if (element.equalsIgnoreCase("(")||element.equalsIgnoreCase("{")||element.equalsIgnoreCase("["))
			{
				l1.addFirst (bracketDetails.get(element));
			}
			else 
			{
				if (! element.equalsIgnoreCase(l1.getFirst())) 
				{
					status = false;
					break;
				} 
				else 
				{
					l1.removeFirst();
				}
			}

		}
		if (status) 
		{
			System.out.println("Output: "+"Balanced");
		} 
		else 
		{
			System.out.println("Output: "+"Not Balanced");
		}
	}
	public static void storeBracketStartAndEnd() 
	{
		bracketDetails.put("(",")");
		bracketDetails.put("{","}");
		bracketDetails.put("[","]");
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Stack;
public class STO0022_0_RemoveAdjacentDuplicates 
{
	/**
	 * Input string : weelccoommee hhoommeee 
	 * Output string : welcome home
	 */
	public static void main(String[] args) 
	{
		String s = "weelccoommee hhoommeee";
		System.out.println("Input: "+s);
		Stack<Character> st = new Stack<>();
		st.push(s.charAt(0));
		for (int i = 1; i<s.length(); i++ ) 
		{
			if (s.charAt(i-1) != s.charAt(i))
				st.push(s.charAt(i));
		}
		System.out.print("Output: ");
		for ( Character c : st )
			System.out.print(c) ;
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.HashSet;
import java.util.Set;
public class STO0022_1_RemoveAllDuplicates 
{
	/**
	 * Original String : softwaretestingo
	 * After removing the duplicates : softwareing
	 */
	public static void main(String[] args) 
	{
		String orignalString = "softwaretestingo";
		StringBuilder builder = new StringBuilder();

		Set<Character> set = new HashSet<>();
		char[] chars = orignalString.toCharArray();

		for (char ch : chars) 
		{
			if (set.add(ch)) 
			{
				builder.append(ch);
			}
		}
		System.out.println("Original String : " + orignalString);
		System.out.println("After removing the duplicates : " + builder.toString());
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0040_0_ReplaceLastTwoSpecialCharacterWithDots 
{
	/*
	 * Input string : Aut@oma#tion@# 
	 * Output: Aut@oma#tion.. 
	 * Input maybe any string, but only the last alphanumeric character should be removed
	 */
	public static void main(String[] args) 
	{
		String s = "Aut@oma#tion@#";
		System.out.println("Input: "+s);
		String [ ] newstring = s.split("");
		int count = 0 ;
		String last = "";
		for ( int i = s.length()-1; i>=0;i--)
		{
			if (!newstring[i].matches("[a-zA-Z]"))
			{
				count++;
				last=last+".";
			}
			else
			{
				break;
			}
		}
		System.out.print("Output: "+s.substring(0, s.length()-count)+last);	
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0041_0_LetterFollowedByNumberInOriginalOrder 
{
	/*
	 * String input= AB2C99423A 
	 * String output =A2B9C9A423
	 */
	public static void main(String[] args) 
	{
		String s = "AB2C99423A";
		System.out.println("Input: "+s);
		char[] cArr = s.toCharArray();
		char resultArr[] = new char [cArr.length*2];
		int evenCount = 0 ;
		int oddcount = 1 ;
		for ( int i=0 ; i<s.length(); i++ )
		{
			if ( Character.isAlphabetic(cArr[i]))
			{
				resultArr [evenCount] = cArr[i];
				evenCount = evenCount+2;
			} 
			else if(!Character.isAlphabetic(cArr[i]))
			{
				resultArr [oddcount]= cArr[i];
				oddcount = oddcount+2 ;
			}
		}
		System.out.print("Output: ");
		System.out.print(resultArr);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0041_1_LetterFollowedByNumberInOriginalOrder 
{
	/*
	 * String input= AB2C99423A 
	 * String output =A2B9C9A423
	 */
	public static void main(String[] args) 
	{
		String inpu = "AB2C99423A";
		System.out.println("Input: "+inpu);
		String charac = "";
		String intege = "";
		String result="";
		for(int i=0;i<inpu.length();i++) 
		{
			if(Character.isLetter(inpu.charAt(i))) 
			{
				charac = charac + inpu.charAt(i);
			}
			else if(Character.isDigit(inpu.charAt(i))) 
			{
				intege = intege + inpu.charAt(i);
			}
		}
		int index1=0, index2=0;
		for(int i=0;i<inpu.length();i++) 
		{
			if(i%2==0 && charac.length()>index1) 
			{
				result = result + charac.charAt(index1);
				index1++;
			}
			else 
			{
				if(intege.length()>index2)
				{
					result = result + intege.charAt(index2);
					index2++;
				}
			}
		}
		System.out.println("Output: "+result);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Arrays;
public class STO0042_0_SplitStringByCapitalLetterAndAddSpace 
{
	/*
	 * Input =“abCdefGHijkl”; 
	 * Output: “ab Cdef G Hijkl”
	 */
	public static void main(String[] args) 
	{
		String st = "abCdefGHijkl";
		System.out.println("Input: "+st);
		String[] r = st.split("(?=\\p{Upper})");
		System.out.print("Output: ");
		Arrays.stream(r).forEach(System.out::println);
	}
}


package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0010_1_ReplaceSpecificCharIncrementally 
{
	/**
	 * Input: tomorrow 
	 * Output: t#m##rr###w
	 */
	public static void main(String[] args) 
	{
		String input = "tomorrow";
        char target = 'o';

        int hashCount = 1;

        // Traverse each character manually
        for (int i = 0; i < input.length(); i++) 
        {
            char ch = input.charAt(i);

            if (ch == target) 
            {
                // Print incremental #
                for (int j = 0; j < hashCount; j++) 
                {
                    System.out.print("#");
                }
                hashCount++;
            }
            else
            {
                System.out.print(ch);
            }
        }
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class STO0046_0_SumOfDigitsOfString 
{
	/*
	 * 1. Find Sum of numbers in given strings. 
	 * Input : "Welcome[21], Java1How are you78" 
	 * OutPut : 100 [21+1+78]
	 * 
	 * 2. Find Sum of digits in given strings. 
	 * Input : "Welcome[21], Java1How are you78" 
	 * OutPut : 19 [2+1+1+7+8]
	 */
	public static void main(String[] args) 
	{
		STO0046_0_SumOfDigitsOfString main = new STO0046_0_SumOfDigitsOfString();
		String testData = "Welcome[21], Java1How are you78";
		System.out.println("Input: "+testData);
		List<Integer> integers = main.getIntegers(testData);
		System.out.println("Sum of numbers : " + integers.stream().reduce(0, (n1, n2) -> n1 + n2));
		System.out.println("Sum of digits of numbers : " + integers.stream().filter(num->num>0).map(num -> main.sumOfDigits(num)).reduce(0, (n1, n2) -> n1 + n2));
	}

	private Integer sumOfDigits(Integer number)
	{
		int sum = 0;
		while (number > 0)
		{
			sum += number % 10;
			number = number / 10;
		}
		return sum;
	}


	private List<Integer> getIntegers(String testData) 
	{
		return Arrays.asList(testData.split(" ")).stream().map(word -> getNumber(word)).collect(Collectors.toList());
	}

	private Integer getNumber(String data) 
	{
		String num = "";
		try 
		{
			for (Character ch : data.toCharArray())
			{
				if (Character.isDigit(ch)) num += String.valueOf(ch);
			}
		} 
		catch (Exception ex) 
		{
			return 0;
		}
		return num.length() > 0 ? Integer.parseInt(num) : 0;
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
import java.util.HashMap;
import java.util.Map;
public class STO0026_3_SortStringAccordingToWordLength 
{
	/*
	 * input="1222bbbbcccaaaammmmm" 
	 * output="1222cccbbbbaaaammmmm"
	 * 
	 * We need to sort the string base on character size
	 */
	public static void main(String[] args) 
	{
		String str="1222bbbbcccaaaammmmm";
		System.out.println("Input: "+str);
		System.out.println("Output: "+sortFreq(str));
	}
	public static String sortFreq(String str) 
	{
		StringBuilder sb = new StringBuilder();

		Map<Character, Integer> hm = new HashMap<>();
		for (Character c : str.toCharArray())
		{
			hm.put(c, hm.getOrDefault(c, 0) + 1);
		}
		//System.out.println("frequency map of the String is " + hm);

		hm.entrySet().stream()
						.sorted(Map.Entry. <Character, Integer>comparingByValue())
						.forEach(a -> {Character key = a.getKey();
		int value = a.getValue();
		for (int i = 0; i < value; i++) {
			sb.append(key);
		}
		});
		//System.out.println(sb);

		return sb.toString();
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class STO0026_4_SortStringAccordingToWordLength 
{
	/*
	 * String input="1222bbbbcccaaaammmmm" 
	 * String output="1222cccbbbbaaaammmmm"
	 * 
	 * We need to sort the string base on character size
	 */
	public static void main(String[] args) 
	{
		String input = "1222cccbbbbaaaammmmmmm";
		System.out.println("Input: "+input);
		Map<String, Integer> outputMap = new HashMap<>();
		for (String letter : input.split("")) 
		{
			outputMap.compute(letter, (k,v)->v==null?1:v+1);
		}
		//System.out.println("Output: "+outputMap);
		Map<Integer, List<String>> inversed =
					outputMap
					.entrySet()
					.stream().collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
					inversed.values().forEach(list->list.sort(null));
		System.out.print("Output: ");
					new TreeMap<>(inversed).forEach((k,v)->v.forEach(letter-> System.out.print(letter.repeat(k))));
	}
}


package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0049_0_FirstLeastFrequentCharacterInString 
{
	/* wap to find the first non repeating character. */
	public static void main(String[] args) 
	{
		String s="minimum";
		System.out.println("Input: "+s);
		int distinct=0;

		for(int i=0;i<s.length();i++)
		{
			for(int j=0;j<s.length();j++)
			{
				if(s.charAt(i)==s.charAt(j))
				{
					distinct++;
				}
			}
			if(distinct==1)
			{
				System.out.println("Output: "+s.charAt(i)+"--"+distinct+"\n");
				break;
			}
			String d=String.valueOf(s.charAt(i)).trim();
			s.replaceAll(d,"");
			distinct=0;
		}
	}
}

package com.softwaretestingo.javapgms;
public class STO0003_PhoneNumberValidator 
{
	/**
	 * Author: SoftwareTestingo Admin
	 * Blog: www.softwaretestingo.com
	 * URL: https://www.softwaretestingo.com/core-java-tutorial/
	 * 
	 * Problem Statement: Phone Number Validation Test
	 * 
	 */
	public static void main(String[] args) 
	{
		System.out.println("Phone number 1234567890 validation result: "+validatePhoneNumber("1234567890"));
		System.out.println("Phone number 123-456-7890 validation result: "+validatePhoneNumber("123-456-7890"));
		System.out.println("Phone number 123-456-7890 x1234 validation result: "+validatePhoneNumber("123-456-7890 x1234"));
		System.out.println("Phone number 123-456-7890 ext1234 validation result: "+validatePhoneNumber("123-456-7890 ext1234"));
		System.out.println("Phone number (123)-456-7890 validation result: "+validatePhoneNumber("(123)-456-7890"));
		System.out.println("Phone number 123.456.7890 validation result: "+validatePhoneNumber("123.456.7890"));
		System.out.println("Phone number 123 456 7890 validation result: "+validatePhoneNumber("123 456 7890"));
	}

	private static boolean validatePhoneNumber(String phoneNo) 
	{
		//validate phone numbers of format "1234567890"
		if (phoneNo.matches("\\d{10}")) return true;
		//validating phone number with -, . or spaces
		else if(phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) return true;
		//validating phone number with extension length from 3 to 5
		else if(phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}")) return true;
		//validating phone number where area code is in braces ()
		else if(phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")) return true;
		//return false if nothing matches the input
		else return false;
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class STO0051_0_PrintInDescendingOrderAsPerOccurance 
{
	/*
	 * Input: tomorrow 
	 * Output: ooorrtmw
	 */
	public static void main(String[] args) 
	{
		String input = "tomorrow";
		System.out.println("Input: "+input);
		Map<Character, Integer> map = StringManipulation(input);
		// sort and print
		List<Map.Entry<Character, Integer>> toSort = new ArrayList<>(map.entrySet());
		toSort.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
		System.out.print("Output: ");
		for ( Map.Entry<Character, Integer> x : toSort ) 
		{
			int count = x.getValue();
			while ( count > 0 ) 
			{
				System.out.print ( x.getKey ( ) ) ;
				count-- ;
			}
		}
	}
	private static Map<Character, Integer> StringManipulation(String input) 
	{
		Map<Character, Integer> map=new LinkedHashMap<>();
		for(char ch : input.toCharArray())
			if(map.containsKey(ch))
				map.put(ch, map.get(ch)+1);
			else
				map.put(ch, 1);
		return map;
	}
}


package com.softwaretestingo.sto000collectedpgms.interviewprograms.numbers;
import java.util.Arrays;
import java.util.stream.IntStream;
public class STO0053_0_SumOfDigitsUntilSumIsSingleDigit
{
	/*
	 * Given an integer num, repeatedly add all its digits until the result has only
	 * one digit, and return it.
	 * 
	 * Example 1:
	 * Input: num = 38
	 * Output: 2
	 * 
	 * Explanation: The process is
	 * 38 --> 3 + 8 --> 11
	 * 11 --> 1 + 1 --> 2 
	 * Since 2 has only one digit, return it.
	 * Example 2:
	 * Input: num = 0
	 * Output: 0
	 */

	public static void main(String[] args) 
	{
		String input1 = "38";
		String input2 = "1485631";
		String input3 = "0";
		System.out.println("Input: "+input1+": "+"Output: " +add(input1));
		System.out.println("Input: "+input2+": "+"Output: " +add(input2));
		System.out.println("Input: "+input3+": "+"Output: " +add(input3));
	}
	public static int add(String input) 
	{
		int[] array = Arrays.asList(input.split("")).stream().mapToInt(Integer::parseInt).toArray();
		int sum = IntStream.of(array).sum();
		if (sum / 10 == 0)
		{
			return sum;
		} 
		else 
		{
			return add(String.valueOf(sum));
		}
	}
}



package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0056_0_SwitchCaseOfCharacters 
{
	public static void main(String[] args) 
	{
		String s="Automation Testing";
		System.out.println("Input: "+s);
		char[] ch=s.toCharArray();

		StringBuffer sb= new StringBuffer(s);

		for (int i = 0; i < ch.length; i++) 
		{

			if(Character.isLowerCase(s.charAt(i)))
			{
				sb.setCharAt(i, Character.toUpperCase(s.charAt(i)));
			}
			else if(Character.isUpperCase(s.charAt(i)))
			{
				sb.setCharAt(i, Character.toLowerCase(s.charAt(i)));
			}
		}
		System.out.println("Output: " + sb);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class STO0057_0_PrintCharacterAndFrequency 
{
	public static void main(String[] args) 
	{
		String name="Monojjonon";
		System.out.println("Input: "+name);
		char []ch=name.toCharArray();
		Map<Character,Integer > bmap = new HashMap<Character, Integer>();
		Map<Character, Integer> sortedMap = new LinkedHashMap<>();
		List<Integer> list = new ArrayList<>();

		for (char c : ch) 
		{
			if(bmap.containsKey(c)) 
			{
				bmap.put(c, bmap.get(c)+1);
			}
			else
			{
				bmap.put(c, 1);
			}
		}

		System.out.println("Character occurrence in a string- " + bmap);

		Integer minValue=Collections.min(bmap.values());
		Integer maxValue=Collections.max(bmap.values());

		System.out.println("Min Value : " + minValue + " Max Value : " + maxValue);


		for (Entry<Character, Integer> entry : bmap.entrySet()) 
		{
			list.add(entry.getValue());
		}
		Collections.sort(list);

		for (Integer num : list) 
		{
			for (Entry<Character, Integer> entry : bmap.entrySet()) 
			{
				if(entry.getValue().equals(num))
				{
					sortedMap.put(entry.getKey(), num);
				}
			}
		}
		System.out.println("Ascending order values - " + sortedMap);
	}
}





package com.softwaretestingo.sto000collectedpgms.interviewprograms;
public class STO0068_0_MoveSpecialCharacterToEnd 
{	
	public static void main(String[] args) 
	{	
		/* "I a#m S@ou$%^ra@v";
		 *  I am Sourav#@$%^@ */
		
		String s="!I a#m S@ou$%^ra@v";
		System.out.println("Input: "+s);
		String spl=s.replaceAll("[a-zA-z0-9 ]+","");
		String spl1=s.replaceAll("[$&+^,:;=?@#|'<>*()%!]+","");
		//System.out.println(spl);
		System.out.println("Output: "+spl1+spl);	
	}
}


package com.softwaretestingo.sto000collectedpgms.interviewprograms.reverse;
public class STO0029_2_ReverseSentence 
{
	public static void main(String[] args) 
	{
		String s="Welcome to Software Testing Blog", rev="";
		System.out.println("Input: "+s);
		String []sWord=s.split(" ");

		for (int i = sWord.length-1; i >=0; i--) 
		{
			rev=rev+sWord[i]+ " ";
		}
		System.out.println("Output: "+rev);
	}
}



package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
public class STO0026_2_SortStringAccordingToWordLength 
{
	public static void main(String[] args) 
	{
		String str="this interview is for CBA";
		System.out.println("Input: "+str);
		String temp;
		String []sw=str.split(" ");

		for(int i=0; i<sw.length;i++)
		{
			for(int j=i+1; j<sw.length; j++)
			{
				if(sw[i].length()> sw[j].length())
				{
					temp= sw[i]; 
					sw[i]=sw[j]; 
					sw[j]=temp; 
				}
			}
		}
		System.out.print("Output: ");
		for (int i = 0; i < sw.length; i++) 
		{
			System.out.print(sw[i]+ " ");
		}
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0075_0_ExtractDigitsFromString 
{
	public static void main(String[] args) 
	{
		String s ="Mono1j2";
		System.out.println("Input: "+s);
		char ch[]=s.toCharArray();

		StringBuilder sb = new StringBuilder();
		for(char ch1: ch)
		{
			if(Character.isDigit(ch1))
			{
				sb.append(ch1);
			}
		}
		System.out.println("Output: "+sb);
	}
}
//Output- 12

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0076_0_CountTotalNumberOfDigitsInaString 
{	
	public static void main(String[] args) 
	{	
		String s="%i a#m m@o$noj346";
		System.out.println("Input: "+s);
		int digits=0;
		
		for(int i=0;i<s.length();i++)
		{
			if(s.charAt(i) >= 48 && s.charAt(i) <= 57)
			{
				digits++;
			}
		}
		System.out.println("Number of digits (Output): " + digits);		
	}
}



package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class STO0059_0_RemoveKthCharacterCountFromString 
{
	/**
	 * Enter the String: softwaretestingo
	 * Enter the Occurance Character Number For Remove : 2
	 * After Removing The Characters Having More then 2 Times:-  fwaring      
	 */
	public static void main(String[] args) throws IOException 
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("Enter the String: ");
		String str=br.readLine();

		// remove characters occurring more than once
		System.out.print("Enter the Occurance Character Number For Remove : ");
		int k = Integer.parseInt(br.readLine());

        // ASCII frequency
        int[] freq = new int[256]; 

        // 1) Count frequency
        for (int i = 0; i < str.length(); i++) 
        {
            char ch = str.charAt(i);
            freq[ch]++;
        }

        // 2) Print characters whose frequency < k (preserve order)
        for (int i = 0; i < str.length(); i++) 
        {
            char ch = str.charAt(i);
            if (freq[ch] < k)
            {
                System.out.print(ch);
            }
        }
	}
}






package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0087_0_FindLongestPalindromicSubstringFromString 
{
	static int findLongSubstr(String str)
	{
		// Get length of input String
		int n = str.length();

		// All subStrings of length 1 are palindromes
		int maxLength = 1, start = 0;

		// Nested loop to mark start and end index
		for (int i = 0; i < str.length(); i++) 
		{
			for (int j = i; j < str.length(); j++) 
			{
				int flag = 1;

				// Check palindrome
				for (int k = 0; k < (j - i + 1) / 2; k++)
					if (str.charAt(i + k)!= str.charAt(j-k))
						flag = 0;

				// Palindrome
				if (flag != 0 && (j - i + 1) > maxLength) {
					start = i;
					maxLength = j - i + 1;
				}
			}
		}

		System.out.print("Longest palindrome substring is: ");
		printSubStr(str, start, start + maxLength - 1);

		// Return length of LPS
		return maxLength;
	}

	// Function to print a subString str[low..high]
	static void printSubStr(String str, int low, int high)
	{
		for (int i = low; i <= high; ++i)
			System.out.print(str.charAt(i));
	}
	public static void main(String[] args)
	{
		String str = "abcdcbe";
		System.out.println("Input: "+str);
		System.out.print("\nLength is: "+ findLongSubstr(str));
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0090_0_PrintWordWithFrequency 
{
	//Java Program to Count repeated words in String
	public static void main(String[] args) 
	{
		String input="Welcome to Java Session Session Session";  
		System.out.println("Input: "+input);
		String[] words=input.split(" ");
		int wrc=1;

		for(int i=0;i<words.length;i++)   
		{
			for(int j=i+1;j<words.length;j++)
			{

				if(words[i].equals(words[j]))
				{
					wrc=wrc+1; 
					words[j]="0";
				}
			}
			if(words[i]!="0")
				System.out.println(words[i]+"- "+wrc);
			wrc=1;
		}  
	}
}









package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class STO0001_4_SecondMaxCharFrequency 
{
	/**
	 * How to find 2nd largest duplicate character from given String using map? Ex:
	 * 
	 * Second Large Character Value From String abbcccddddcc is:  Character d And Count is: 4
	 * Second Large Character Value From String annnyrggrrrrrrr is:  Character n And Count is: 3
	 */
	//If you do not want to use entrySet then u can use this logics
	

	public static Map<Character,Integer> solution(String str) 
	{
		Object ch=null;
		Map<Character,Integer> map = new HashMap<>();
		char[] charArray = str.toCharArray();
		for(int i =0; i<charArray.length; i++)
		{
			if(map.containsKey(charArray[i]))
			{
				int count=map.get(charArray[i]);
				map.put(charArray[i],count + 1);           
			}
			else 
			{
				map.put(charArray[i],1);
			}
		}
		int largest = -1 ;
		int secondLarge = -1 ;

		for(Entry<Character,Integer> m : map.entrySet()) 
		{
			if(m.getValue()>largest ) 
			{
				secondLarge=largest ;
				ch=m.getKey();
				largest = m.getValue();
			} 
			else if(m.getValue()<largest && m.getValue()>secondLarge) 
			{
				secondLarge = m.getValue();
				ch=m.getKey();
			}
		}
		System.out.println("Second Large Character Value From String " + str +" is: "+" Character "+ch +" And Count is: "+secondLarge);
		return map;
	}
	public static void main(String[] args) 
	{
		String str="abbcccddddcc";
		String str1="annnyrggrrrrrrr";
		STO0001_4_SecondMaxCharFrequency.solution(str);
		STO0001_4_SecondMaxCharFrequency.solution(str1);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
import java.util.Arrays;
public class STO0015_0_ProductExceptSelf 
{
	/**
	 * Write a java program to given array arr [ 1,2,3,4 ] to multiple the number 
	 * and ignore one for next ignore another one  number and continue 
	 * same so  we will get out put [ 24,12,8,6 ] 
	 * Input: [1, 2, 3, 4]
	 * Output: 24 12 8 6 
	 */

	//This Questions Asked in Cigniti technologies
	void multipleValue(int arr[], int n) 
	{
		// If Only 1 Element is passed
		if (n == 1) 
		{
			System.out.print(0);
			return;
		}
		int i, temp = 1;

		/* Allocate memory for the product array */
		int prod[] = new int[n];

		/* Initialize the product array as 1 */
		for (int j = 0; j < n; j++)
			prod[j] = 1;

		/* In this loop, temp variable contains product of
           elements on left side excluding arr[i] */
		for (i = 0; i < n; i++) 
		{
			prod[i] = temp;
			temp *= arr[i];
		}

		/* Initialize temp to 1 for product on right side */
		temp = 1;

		/* In this loop, temp variable contains product of
           elements on right side excluding arr[i] */
		for (i = n - 1; i >= 0; i--) 
		{
			prod[i] *= temp;
			temp *= arr[i];
		}

		/* print the constructed prod array */
		for (i = 0; i < n; i++)
			System.out.print(prod[i] + " ");

		return;
	}

	public static void main(String[] args) 
	{
		STO0015_0_ProductExceptSelf pa = new STO0015_0_ProductExceptSelf();
		int arr[] = { 1,2,3,4 };
		int n = arr.length;
		System.out.println("Input: "+Arrays.toString(arr));
		System.out.print("Output: ");
		pa.multipleValue(arr, n);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0046_0_CountVowelsInString 
{
	/**
	 * Input: SoftwareTestingo
	 * Total no of vowels in string are: 6
	 * 
	 */
	public static void main(String[] args) 
	{
		String str = "SoftwareTestingo";
		System.out.println("Input: "+str);
		str = str.toLowerCase();
		int count = 0;

		for (int i = 0; i < str.length(); i++) 
		{
			// check if char[i] is vowel
			if (str.charAt(i) == 'a' || str.charAt(i) == 'e'
					|| str.charAt(i) == 'i'
					|| str.charAt(i) == 'o'
					|| str.charAt(i) == 'u') {
				// count increments if there is vowel in
				// char[i]
				count++;
			}
		}

		// display total count of vowels in string
		System.out.println("Total no of vowels in string are: " + count);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.numbers;
import java.util.Scanner;
public class STO0004_0_ReverseNumber 
{	
	/**
	 * Enter a number 12345
	 * Input:12345
	 * Output: 54321
	 * 
	 */
	public static void main(String[] args) 
	{
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter a number ");
		int num=sc.nextInt();
		System.out.println("Input:"+num);
		int rev=0;
		
		while(num!=0)
		{
			rev=rev*10+num%10;
			num=num/10;
		}
		System.out.println("Output: "+rev);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0047_0_MaskAndFormatNumber
{
	/**
	 * Input: 5450595638154862
	 * After Masking Output: 545059******4862
	 * Modified Output: 5450-59**-****-4862
	 * 
	 */
	public static void main(String[] args) 
	{
		String input = "5450595638154862";
		String output = maskCreditCard(input);
		String formattedOutput = formatCreditCard(output);
		System.out.println("Input: " + input);
		System.out.println("After Masking Output: " + output);
		System.out.println("Modified Output: " + formattedOutput);
	}

	public static String maskCreditCard(String creditCardNumber) 
	{
		// Check if the credit card number is valid
		if (creditCardNumber == null || creditCardNumber.length() < 16) 
		{
			return "Invalid credit card number";
		}

		// Get the length of the credit card number
		int length = creditCardNumber.length();

		// Replace middle digits with asterisks
		StringBuilder maskedNumber = new StringBuilder();
		for (int i = 0; i < length; i++) 
		{
			if (i >= 6 && i <= 11) {
				// Check if the digit is in the middle range
				maskedNumber.append('*');
			} 
			else 
			{
				maskedNumber.append(creditCardNumber.charAt(i));
			}
		}
		return maskedNumber.toString();
	}

	public static String formatCreditCard(String creditCardNumber) 
	{
		// Check if the credit card number is valid
		if (creditCardNumber == null || creditCardNumber.length() != 16) 
		{
			return "Invalid credit card number";
		}

		// Format the credit card number
		StringBuilder formattedNumber = new StringBuilder();
		for (int i = 0; i < creditCardNumber.length(); i++) 
		{
			if (i == 4 || i == 8 || i == 12) 
			{
				formattedNumber.append('-');
			}
			formattedNumber.append(creditCardNumber.charAt(i));
		}
		return formattedNumber.toString();
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Scanner;
public class STO0048_0_NameShortForm 
{
	/**
	 * Enter the Name : softwaretestingo blog
	 * Short Form: s.blog
	 * 
	 */
	public static void main(String[] args) 
	{
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter the Name : ");
		String name = sc.nextLine();
		String word = "";
		System.out.print("Short Form: ");
		for (int i = 0; i < name.length(); i++) 
		{
			char ch = name.charAt(i);
			if (ch != ' ') 
			{
				word = word + ch;
			} 
			else 
			{
				System.out.print(word.charAt(0) + ".");
				word = "";
			}
		}
		System.out.print(word);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class STO0001_0_RemoveSecondMax 
{
	//Program Remove the second highest element from the HashMap
	/**
	 * Original Map: {Thirty=30, Twenty=20, FourTwenty=420, one Twenty=120, Ten=10}
	 * Sorted Map: {Ten=10, Twenty=20, Thirty=30, one Twenty=120, FourTwenty=420}
	 * After Removing Second Max Number: {Ten=10, Twenty=20, Thirty=30, FourTwenty=420}
	 * 
	 */
	public static void main(String[] args) 
	{
		Map<String, Integer> map = new HashMap<>();
		map.put("Thirty", 30);
		map.put("Ten", 10);
		map.put("Twenty", 20);
		map.put("FourTwenty", 420);
		map.put("one Twenty", 120);
		
		// print the map
		System.out.println("Original Map: "+map);
		
		//sorting
		LinkedHashMap<String, Integer> smap = map.entrySet().stream().sorted((t1,t2)->t1.getValue().compareTo(t2.getValue())).
		collect(Collectors.toMap(Map.Entry::getKey ,Map.Entry::getValue,(t1,t2)->t1,LinkedHashMap::new));
		System.out.println("Sorted Map: "+smap);
		
		int size = smap.size();
		//System.out.println(size);
		
		int max = Collections.max(smap.values()); int SecondMax = 0;
		for (int value : smap.values())
		{
			if (value > max)
				{
					SecondMax = max; max = value;
				}
			else if (value > SecondMax && value != max)
				{
					SecondMax = value;
				}
		}
		//System.out.println(SecondMax);
		Integer Value = SecondMax;
		
		for(Entry<String, Integer> entry: smap.entrySet())
		{
				if(entry.getValue() == Value) 
				{
					//System.out.println("The key of the: " + Value + " is " + entry.getKey());
					smap.remove(entry.getKey());
					break;
				}
		}
		System.out.println("After Removing Second Max Number: "+smap); 
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
public class STO0027_0_SumOfNumbersInString 
{
	/**
	 * Write a program that calculate the sum of all numbers present in alphanumeric
	 * string in sentence.
	 * 
	 * Input: "1a b23c de45f" 
	 * Output: 69 (1 + 23 + 45)
	 */
	public static void main(String[] args) 
	{
		String str = "1a b23cd e45f";
		System.out.println("Input: "+str);
		int sum = 0;

		String number = "";
		for (int i = 0; i <=str.length()-1; i++) 
		{
			if (Character.isDigit(str.charAt(i))) 
			{
				number += str.charAt(i);
			} 
			else if (!number.isEmpty()) 
			{
				sum += Integer.parseInt(number);
				number = "";
			}
		}
		System.out.println("Sum Of All Numbers: "+sum);
	}
}
package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class STO0027_1_SumOfNumbersInString 
{
	/**
	 * Write a program that calculate the sum of all numbers present in alphanumeric
	 * string in sentence.
	 * 
	 * Input: "1a b23c de45f" 
	 * Output: 69 (1 + 23 + 45)
	 */
	public static void main(String[] args) 
	{
		String str = "1a b23cd e45f";
		System.out.println("Input: "+str);
		int sum = 0;
		String pattern = "\\d+";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(str);
		while (m.find()) 
		{
			sum = sum + Integer.parseInt(m.group());
		}
		System.out.println("Output: "+sum);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.Arrays;
public class STO0049_0_SortLowerUpperDigits 
{
	/**
	 * Input: aBcA1bC2
	 * Output: abcABC12
	 * 
	 */
	public static void main(String[] args) 
	{
		String str="aBcA1bC2";
		System.out.println("Input: "+str);
		System.out.println("Output: "+ modifyString(str));
	}

	public static String modifyString(String s) 
	{
		String d = "", l = "", u = "", result = "";
		for (int i = 0; i < s.length(); i++) 
		{
			if (Character.isDigit(s.charAt(i))) 
			{
				d = d + "" + s.charAt(i);

			}
			if (Character.isLowerCase(s.charAt(i))) 
			{
				l = l + "" + s.charAt(i);
			}
			if (Character.isUpperCase(s.charAt(i))) 
			{
				u = u + "" + s.charAt(i);
			}

		}
		return result += sortString(l) + "" + sortString(u) + "" + sortString(d);

	}

	public static String sortString(String s) 
	{
		char[] temp = s.toCharArray();
		Arrays.sort(temp);
		return new String(temp);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.strings;
import java.util.ArrayList;
import java.util.List;
public class STO0060_0_SplitStringIntoCharsAndNumbers 
{
	/**
	 * Author: SoftwareTestingo 
	 * Admin Blog: www.softwaretestingo.com Problem
	 * Statement: 
	 * 
	 * Input Value: ab2c4d45ef234
	 * Integers: 2,4,45,234
	 * Characters: ab,c,d,ef
	 * 
	 * URL: https://www.softwaretestingo.com/core-java-tutorial/
	 * 
	 * @param args
	 */
	public static void main(String[] args) 
	{
		String input = "ab2c4d45ef234";
        System.out.println("Input Value: " + input);

        String numTemp = "";
        String charTemp = "";
        String numResult = "";
        String charResult = "";

        for (int i = 0; i < input.length(); i++) 
        {
            char ch = input.charAt(i);

            if (Character.isDigit(ch)) 
            {
                // Save accumulated letters before starting number
                if (!charTemp.isEmpty()) 
                {
                    if (!charResult.isEmpty()) 
                    {
                        charResult = charResult + "," + charTemp;
                    } 
                    else 
                    {
                        charResult = charTemp;
                    }
                    charTemp = "";
                }
                numTemp = numTemp + ch; // Keep building number

            } 
            else if (Character.isLetter(ch)) 
            {
                // Save accumulated digits before starting letters
                if (!numTemp.isEmpty()) 
                {
                    if (!numResult.isEmpty()) 
                    {
                        numResult = numResult + "," + numTemp;
                    } 
                    else 
                    {
                        numResult = numTemp;
                    }
                    numTemp = "";
                }
                charTemp = charTemp + ch; // Keep building word
            }
        }

        // Handle last number if string ends with digits
        if (!numTemp.isEmpty()) 
        {
            if (!numResult.isEmpty()) 
            {
                numResult = numResult + "," + numTemp;
            } 
            else 
            {
                numResult = numTemp;
            }
        }

        // Handle last characters if string ends with letters
        if (!charTemp.isEmpty()) 
        {
            if (!charResult.isEmpty()) 
            {
                charResult = charResult + "," + charTemp;
            } 
            else 
            {
                charResult = charTemp;
            }
        }

        System.out.println("Integers: " + numResult);
        System.out.println("Characters: " + charResult);
	}
}




package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
import java.util.Arrays;
public class STO0018_0_FindMissingRepeating 
{
	/**
	 * Input: [7, 3, 4, 5, 5, 6, 2]
	 * The repeating number is 5
	 * The missing number is 1
	 */
	static void printTwoElements(int[] arr, int n)
    {
        int[] temp = new int[n]; // Creating temp array of size n
        
        // with initial values as 0.
        int repeatingNumber = -1;
        int missingNumber = -1;
 
        for (int i = 0; i < n; i++) 
        {
            temp[arr[i] - 1]++;
            if (temp[arr[i] - 1] > 1) 
            {
                repeatingNumber = arr[i];
            }
        }
        for (int i = 0; i < n; i++) 
        {
            if (temp[i] == 0) 
            {
                missingNumber = i + 1;
                break;
            }
        }
 
        System.out.println("The repeating number is " + repeatingNumber);
        System.out.println("The missing number is " + missingNumber);
    }

	public static void main(String[] args) 
	{
		int[] arr = { 7, 3, 4, 5, 5, 6, 2 };
		System.out.println("Input: "+Arrays.toString(arr));
        int n = arr.length;
        printTwoElements(arr, n);
	}
}

package com.softwaretestingo.sto000collectedpgms.interviewprograms.array;
import java.util.Arrays;
public class STO0019_0_FindMissingBetweenArrays 
{
	/**
	 * 1. Missing number in array1 & array2 is: 3
	 * 2. Missing number in array1 & array2 is: 10
	 * 
	 */
	private static int missingNumber(int[] arr1, int arr2[]) 
	{
		 
        int missingNumber = arr1[0];
        for (int index = 1; index < arr1.length; index++) 
        {
            missingNumber ^= arr1[index];
        }
 
        for (int index = 0; index < arr2.length; index++) 
        {
            missingNumber ^= arr2[index];
        }
        return missingNumber;
    }
	public static void main(String[] args) 
	{
		int array1[] = { 1, 2, 3, 4, 5 };
        int array2[] = { 1, 2, 4, 5 };
 
        String sArr1 = Arrays.toString(array1);
        String sArr2 = Arrays.toString(array2);
 
        System.out.printf("1. Missing number in array1 & array2 is:", sArr1, sArr2);
        int missingNumber = missingNumber(array1, array2);
        System.out.printf(" %d", missingNumber);
 
        array1 = new int[] { 10, 20, 30, 40 };
        array2 = new int[] { 20, 30, 40,  };
 
        sArr1 = Arrays.toString(array1);
        sArr2 = Arrays.toString(array2);
 
        System.out.printf("\n2. Missing number in array1 & array2 is:", sArr1, sArr2);
        missingNumber = missingNumber(array1, array2);
        System.out.printf(" %d", missingNumber);
	}
}

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

1 thought on “Top 70 Java Program Interview Questions”

Leave a Comment