0% found this document useful (0 votes)
18 views

Dsa Problem Solving

The document contains a collection of frequently asked Java programs for Quality Assurance, covering various topics such as number manipulation, string operations, and array handling. It includes code examples for tasks like swapping numbers, checking for Armstrong numbers, generating Fibonacci series, and determining prime numbers. Additionally, it addresses string manipulation techniques, such as reversing strings and removing duplicates, along with methods for counting occurrences of words and characters.

Uploaded by

shagunrastogi80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
18 views

Dsa Problem Solving

The document contains a collection of frequently asked Java programs for Quality Assurance, covering various topics such as number manipulation, string operations, and array handling. It includes code examples for tasks like swapping numbers, checking for Armstrong numbers, generating Fibonacci series, and determining prime numbers. Additionally, it addresses string manipulation techniques, such as reversing strings and removing duplicates, along with methods for counting occurrences of words and characters.

Uploaded by

shagunrastogi80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
Frequently Asked Java Programs for QA Top 10 numbers Questions 1. Swap two numbers Input: a= 100, b= 200; public static void main(String[] args) { int a = 100, b = 200; System.out.printin(“After swapping, a=" + a+" and b="+b); 1/1. Swapping using three Variables int temp = a; eB b=temp; System.out printin(“After swapping, a=" + a+" and b= 1/ 2. Using Two Variables +b); azatb; b=a-b; az=a-b; System.out printin(“After swapping, a=" +a +" and b =" +b); 1/3. Swapping a and b using XOR a=ab; b=a%b; a=ab; System.out printin("After swapping, a="+a+" and b="+b); 2. Armstrong number Armstrong number is a number that is equal to the sum of cubes of its digits. Input: 153 , Output: Yes 153 is an Armstrong number. => (1*1*1) + (5°5*5) + (3*3*3) = 153 public static void main(Stringl} args) { int sum = 0, res, temp; int num = 153;/ It is the number to check Armstrong temp = num; while (num > 0) { res = num % 10; num = num / 10; sum = sum + (res * res * res); if (temp == sum) System. out printin(temp + " is armstrong number"); else System.out.printin(temp + " is Not armstrong number"); } 3. Fibonacci Series — In Fibonacci series, next number is the sum of previous two numbers Input = First 10 Numbers Output = 0, 1, 1, 2, 3,5, 8, 13, 21, 34, 55 etc, The first two numbers of Fibonacci series are O and 1. public static void main(Stringl] args) { int num1 ), num2 , num=10; for (int i = 0; i <= num; i+#) System.out.print(num + int num3 = num2 + num1;// Swap num = num2; num2 = num; 4. Reverse a numbers and Number is Palindrome or Not. Input = 12321 Output =12321 public static void main(String[] args) { int num = 12321; 1/1, Reverse a Number Using the While Loop reversed number int rev = 0; int temp = num; int rem; // remainder while (num > 0) { rem = num % 10; rev = (rev * 10) + rem; num = num / 10; } System.out printin(’Reversed Number is " + rev); I \erity number is palindrome or not if (rev == temp) { System.out.printin(“palindrome number "); }else { System.out.printin(“not palindrome"); } uf 5. Factorial Number Factorial Program in Java: Factorial of n is the product of all positive descending integers. Input = Output = 5*4*3*2*1 = 120 public static void main(String{] args) { Scanner sc = new Scanner(System in); System.out.printin("Enter number which you want for Factorial: "); int num = sc.nextint(; 1; 1 <= num; i++) { = fact *i; System.out printin(’Factorial of" + num +" is" + fact); 6. OddEvenNumbers Input = 11 Output = Given number is odd number public static void main(String[] args) { 1/1, Using Brute Forcew Approach ‘Scanner sc = new Scanner(System in); System. out printin("Enter Number: int num = sc.nextint(); if (num % 2 == 0)// Brute Forcew Approach 4 System.out.printin(’Given is even number’); yelse { System.out.printin(’Given number is odd number"); 7. Prime Number Prime number is a number that is greater than 1 and divided by 1 or itself only. Input = 31, Output = The number is prime. Public static void main(String(] args) { if (um <= 1){ System.out printin("The number is not prim return; for (int i = 2; i <= flim / 2; i++) { if (hum % i == 0) count++; y if (count > 1) { System.out.printin("The number is not prime"); yelse { System.out printin("The number is prime"); } 8. Largest number from 3 number! given list public static void main(String|] args) { 1/ TODO Auto-generated method stub 1/1. By using if else condition int num = 7, num2 = 9, nume = 10; if( numa >= num2 && num1 >= num3) System.out.printin(num1 + " is the largest number.”); else if (num2 >= num1 && num2 >= num3) System. out.printin(num2 + " is the largest number."); else System. out.printin(nums + " is the largest number."); 1/2. Using Collections. max() method and ArrayList, ArrayList x = new ArrayList<>(); x.add(12); x.add(22); x.add(54); ‘System.out.printin(Collections.max(x)+ " is the largest number."); } 9, Sum of Digits ‘Sum of all given numbers. Input = 987 Output = 24 public static void main(Stringl] args) { int n = 987; int sum = 0; while (n != 0) { sum = sum +n % 10; n=n/10; } System.out printin("Using While:- " + sum); } 10.Count digits in an integer number Input = 29845315, Output = 8 public static void main(Stringl] args) { // TODO Auto-generated method stub long num = 29845315; int count = 0, num2 = 298453; 1/1. by using while loop while (num != 0) { num = num / 10; count++; } System.out.printin("Number of digits : " + count); 1/ 2. Converting given number to string solution to count digits in an integer String result = Integer.toString(num2); // calculate the size of string System. out printin(+result.length()); } Top 15 String Questions 1. Reverse a string Input = mama ‘Output = mama public static void main(String[] args) { String str = "mama", String s2=""; 1/1, by using the charAt() method for (inti = str.length() - 1; i >= 0; i+) { $2 = s2 + str.charAt(i);// extracts each character and store in string } System.out.printin("Reversed word: " + $2); 11 below is code to check weather given string is Palindrome or not if (str.equalsignoreCase(s2)) { ‘System.out.printin("String is Palindrome"); yelse { System.out.printin(’String is not Palindrome"); } } 112, Using built in reverse() method of the StringBuilder class: String input = "Welcome To Jave Learning"; StringBuilder input1 = new StringBuilder(); inputl.append(input); // append a string into StringBuilder input1 input1.reverse(); System.out.printin(input1); 113. Using StringBuffer: String strText = "Java Learning” I conversion from String object to StringBuffer StringBuffer sbr = new StringBuffer(strText); sbr.reverse(); System.out.printin(sbr); 2. Remove space form given string Input String = “hello java Learning” Output String = “hellojavaLearning” public static void main(Stringl] args) { System.out printin("Enter String "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); System.out.printin(“Original String- " + input); input = input.replaceAll("\s", System.out.printin("Final String- 3. Finding Common Elements in Arrays Input array1 = { 4, 2, 3, 1, 6}; array2 ={6, 7,84} Output = 1/ By using the for loop Integer{] arrayl = { 4, 2, 3, 1, 6}: Integer{] array2 = { 6, 7, 8, 4}; List commonElements = new ArrayList<>(); for (int i = 0; i < array1.length; i++) { for (int j = 0; j < array2.length; j++) { if (arrayifi) == array2f) { commonElements.add(array1 i); th System.out printin("Common Elements for given two array List is:" + commonElements); 1/ by using ArrayList with retainAll method ArrayList list = new ArrayList<>(Arrays.asList(array1)); ArrayList list2 = new ArrayList<>(Arrays.asList(array2)); list1.retainAll(list2); System.out.printin("Common Elements:" + list); 1/ By using Java Stream Stringf] array3 = { "Java", "JavaScript’, "C", "C++" }; Stringl] array = { "Python, "C#", "Java", "C++" }; ArrayList list3 = new ArrayList<>(Arrays.asList(array3)); ArrayList list = new ArrayList<>(Arrays.asList(aray4)); List commonElementsi = list3.stream(filter(list4::contains).collect(Collectors.toList(); System.out printin(commonElements1); yy} 4. Find first and last element of ArrayList in java Input = array = { 4, 2, 3, 1, 6}; Output = First is:4, Last is: 6 ArrayList list = new ArrayList(5); II find first element int first = list.get(0);//First Element I find last element int last = list.get(list.sizeQ) - 1);/ast Element 5, Second Largest and Second Smallest Numbers: 1/ Code to find second largest and second smallest numbers in an array int] arrayList = { 4, 2, 3, 1,0, 6,12,15,20 }; int num=arrayList.length; Arrays.sort(arrayList); System.out printin("Second Largest element is “+arrayList[num-2)); //Display Second Smallest System.out printin("Second Smallest element is “+arrayList[1)); 6. How to sort an Array without using inbuilt method? Input = array(] = { 10, 5, 20, 63, 12, 57, 88, 60 }; Output = 5 10 12 20 57 60 63 88 int temp, size; int array(] = { 10, 5, 20, 63, 12, 57, 88, 60 }: size = array.length; for (int i= 0; i< size; i++) { for (intj = i+ 1; j arraytil) { temp = arrayfi); array(i] = arraylj: array(j] = temp; ; i < array.length; i++) { System. out.printin("Array sorted: " + array[i)); } 11 Print 3rd Largest number from an Array System.out.printin( "Third largest number is:: " + array{size - 3]); System.out.printin(tssts+#svesassreneseen: II sort array using the Arrays.sort method Arrays.sort(array); System.out.printin("sorted array-" + Arrays.toString(array)); int thirdMaxNum=array[size-3); System.out printIn("Third highest array" +thirdMaxNum ); 7. Counting number of occurrences of given word in a string using Java? String = "Java is a programming language. Java is widely used in software Testing"; Input = "Java’, Output = 2 public static void main(Stringl] args) { String string = "Java is a programming language. Java is widely used in software Testing”; String[] words = string.toLowerCase().split(’ "); String word = "java int occurrences = 0; for (int i = 0; i < words. length; i++) if (wordsfi].equals(word)) occurrences++; System. out printin(accurrences); 8. Find each word occurrence from given string in string java Input = “Alice is girl and Bob is boy"; Output = {Bob=1, Alice=1, and=1, is=2, girl=1, boy=1} public static void main(Stringl] args) { String str = "Alice is girl and Bob is boy"; MapéString, Integer> hashMap = new HashMap<>(); Stringl] words = str.split(”"); for (String word : words) { if (hashMap.containskey(word)) hashMap.put(word, hashMap.get(word) + 1); else hashMap.put(word, 1); System. out printin(hashMap 9. Reverse the entire sentence Input = “India is country My" Output = "My country is India” public static void main(Stringl} args) { String sti] = "India is country My’ split(* "; String ans = ""; for (int i = str.length - 1; 1 ans = ans + str{i] +"; System.out printin(ans.substring(0, ans.length( - 1)); } 10. count the occurrences of each character? Input = "This is an example"; Output = public static void main(String{] args) { String str = "This is an example"; HashMap count = new HashMap(); J/- convert string to character array charf] arr = str.toCharArray(); // traverse every character and count the Occurrences for (char c : art) { //filter out white spaces if(c!=") if (ount.containsKey(c)) { 1/ if character already traversed, increment it count.put(c, count.get(c) + Jelse { 1/ if character not traversed, add it to hashmap count.put(c, 1); } } } // traverse the map and print the number of occurences of a character for (Map.Entry entry : count.entrySet()) { System.out.print( entry.getKey() +" = " + entry.getValue()+", 11, Removing Duplicates from an Array J/using for loop Stringl] strArray = {'abc", “def, 1/1. Using Brute Force Method for (int i = 0; i < strArray.length: { for (int j = i+1; j < strArray.length; j++) { if( (strArrayfi}==(strArray[j))) ) { System.out.printin("Brute Force Method : Duplicate Element is : “+strArrayli); wy 7/ using Hashset HashSet hs = new HashSetsString>(); for (String arrayElement : strArray) be”, “"mno" i+) { if(ths.add(arrayElement)) {System.out.printin("HashSet :Duplicate Element is } 12. Reverse each word in a sentence Input = “reverse each word in a string’; Output = “esrever hcae drow ni a gnirts" public static void main(Stringl] args) { String str = “reverse each word in a string’; String words] = str.split("\s String reverseWord ="; for (String w : words) { StringBuilder sb = new StringBuilder(w); sb.reverse(); reverseWord = reverseWord + sb.toString() + ""; i) System.out printin(reverseWord.trimQ); } 13. String Anagrams: Determine if two strings are anagrams of each other Input = String str = "Army"; String str2 = "Mary"; Output = army and mary are anagram. public static void main(Stringl] args) { String str = "Army" String str2 = "Mary"; strl = str1.toLowerCase(); str2 = str2.toLowerCase(); 1/ check if length is same if (str.length() == str2.length()) { JI convert strings to char array charf] charArray1 = str1.toCharArray(); charf] charArray2 = str2.toCharArray(); J/ sort the char array Arrays.sort(charArray1); Arrays.sort(charArray2); lit sorted char arrays are same, then the string is anagram boolean result = Arrays.equals(charArray1, charArray2); if (result) { System.out.printin(str1 +" and" + str2 +" are anagram. yelse { System.out.printin(stri +" and" + str2 +" are not anagram."); } yelse { System.out.printin(str1 +" and" + str2 +" are not anagram."); i} 14, How to print duplicate characters from the string? Input = “apple is fruit"; Output = pi public static void main(Stringl] args) { String str = “apple is fruit’; char[] carray = str.toCharArray(); System.out.printin("The string is:" + str); System.out.print("Duplicate Characters in above string are: for (int i = 0; i < str.length(); i++) { for (int j =i + 1; | < str.length(; j++) { if (carray{i] == carrayf)) { System.out.print(carray[i] + ""); break; 15, Find and print the largest element in an array. W Initialize array int{] arr = new int{] { 25, 11, 7, 75, 56 }; 1/ Initialize max with first element of array int max = arr{0}; 1/ Loop through the array for (int i = 0; i < arrlength; i++) { 1/ Compare elements of array with max if (arrfi] > max) max = arti; System.out printin(’Largest element present in given array: " + max 16. Java program to split an alphanumeric digit without using split method Input = "Welcome234T0567Java89Programming0@#!""; Output = WelcomeToJavaProgramming 234567890 @# public static void main(String[] args) { String str = "Welcome234T0567Java89Programming0@: StringBuffer alpha = new StringBuffer(), num = new StringButfer(), special = new StringBuffer); for (int i = 0; i < str.length(); i++) { if (Character isDigit(str.charAt()))) num.append(str.charAt('); else if (Character.isAlphabetic(str.charAt(i))) alpha.append(str.charAt(i)); else special.append(str.charAt(i)); } System.out printin(alpha); System.out.printin(num); System.out printin(special);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy