SlideShare ist ein Scribd-Unternehmen logo
1 von 41
1
1. Given an integer "532341", output should be reverse of integer.
Ans:
public classReverseNumber {
public static void main(String[] args) {
int num = 1234,reversed = 0;
while(num != 0) {
int digit= num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + reversed);
}
}
2. Given two words, check if they are anagramof each other or not.
public static void main(String[] args) throws ParseException {
String s1="anagram";
String s2="margana";
int lettersS1[] = new int[Character.MAX_VALUE];
int lettersS2[] = new int[Character.MAX_VALUE];
if(s1.length()!=s2.length())
System.out.print("No");
else {
for(inti = 0; i<s1.length() ;++i) {
lettersS1[s1.toLowerCase().charAt(i)]++;
lettersS2[s2.toLowerCase().charAt(i)]++;
}
boolean anag= true;
for(inti = 0;i<lettersS1.length&&anag;++i) {
if(lettersS1[i] != lettersS2[i]) {
anag= false;
}
}
if(anag) {
System.out.print("Anagram");
} else {
System.out.print("No anagram");
}
}
}
2
3. Palindromejava
class PalindromeExample{
public static void main(String args[]){
intr,sum=0,temp;
intn=454;//It is the number variableto be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindromenumber ");
else
System.out.println("not palindrome");
Q 4 :Palindromeword
public class palindrom {
public static void main(String args[])
{
String name2 = "", name = "naman";
int i;
// char name2;
for(i=name.length()-1;i>-1;i--)
name2=name2+name.charAt(i);
System.out.println(name2);
if(name.equals(name2))
{
System.out.println("palindrome");
}
else
{
System.out.println("no");
}
}
}
5. Given two strings A = "My name is Praneta"and B = "name is", output should be a new stringthat has all words
of A that are not present in "B". Output : "My Praneta"
package examples;
class StringSubString {
public static void main(String[] args) {
String oldStr = "My Name is Archana";
String delStr = "Name is ";
String newStr;
newStr = oldStr.replace(delStr, "");
System.out.println(oldStr);
3
System.out.println(newStr);
}
}
6. Given an integer number n, for multiples of three print “Fizz” for the multiples of fiveprint “Buzz”. For numbers
which are multiples of both three and fiveprint “FizzBuzz”.
public class FizzBuzz {
public static void main(String[] args) {
for (inti = 1; i < 101; i++) {
// Set this to true when one of the special conditions ismet.
boolean printed = false;
if (i % 3 == 0) {
// When i is divisibleby 3, then print"Fizz"
printed = true;
System.out.print("Fizz");
} else if (i % 5 == 0) {
// When i is not divisibleby 3 but is divisibleby 5, then print"Buzz"
printed = true;
System.out.print("Buzz");
}
}
}
}
7. binary search programin java
1. class BinarySearchExample{
2. public static void binarySearch(intarr[],intfirst,intlast,intkey){
3. int mid = (first+ last)/2;
4. while( first<= last){
5. if ( arr[mid] < key ){
6. first= mid + 1;
7. }else if ( arr[mid] == key ){
8. System.out.println("Element is found atindex: " + mid);
9. break;
10. }else{
11. last= mid - 1;
12. }
13. mid = (first+ last)/2;
14. }
15. if ( first> last){
16. System.out.println("Element is not found!");
17. }
18. }
19. public static void main(String args[]){
20. int arr[] = {10,20,30,40,50};
21. int key = 30;
22. int last=arr.length-1;
23. binarySearch(arr,0,last,key);
24. }
25. }
26. Element is found at index: 2
4
8.Given a string,find the second most frequent character in it.
// Java Program to find the second
// most frequent character in each string
public class GFG
{
static final intNO_OF_CHARS = 256;
// finds the second most frequently occurring
// char
static char getSecondMostFreq(String str)
{
// count number of occurrences of every
// character.
int[] count = new int[NO_OF_CHARS];
int i;
for (i=0; i< str.length(); i++)
(count[str.charAt(i)])++;
// Traverse through the count[] and find
// second highest element.
int first= 0, second = 0;
for (i = 0; i < NO_OF_CHARS; i++)
{
/* If current element is smaller than
firstthen update both firstand second */
if (count[i] > count[first])
{
second = first;
first= i;
}
/* If count[i] is in between firstand
second then update second */
else if (count[i] > count[second] &&
count[i] != count[first])
second = i;
}
return (char)second;
}
// Driver programto test above function
public static void main(Stringargs[])
{
String str = "geeksforgeeks";
char res = getSecondMostFreq(str);
if (res != '0')
System.out.println("Second most frequent char"+
" is " + res);
else
System.out.println("No second most frequent"+
5
"character");
}
}
9.There aretwo sorted arrays.Firstoneis of sizem+n containingonly m elements. Another one is of size n and
contains n elements. Merge these two arrays into the firstarray of sizem+n such that the output is sorted.
class MergeArrays
{
/* Function to move m elements at the end of array mPlusN[] */
void moveToEnd(int mPlusN[], int size)
{
int i,j = size- 1;
for (i = size- 1; i >= 0; i--)
{
if (mPlusN[i] != -1)
{
mPlusN[j] = mPlusN[i];
j--;
}
}
}
/* Merges array N[] of sizen into array mPlusN[]
of sizem+n*/
void merge(int mPlusN[], intN[], int m, intn)
{
int i = n;
/* Current index of i/p part of mPlusN[]*/
int j = 0;
/* Current index of N[]*/
int k = 0;
while(k < (m + n))
{
if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n))
{
mPlusN[k] = mPlusN[i];
k++;
i++;
}
{
mPlusN[k] = N[j];
k++;
j++;
}
}
}
/* Utility that prints out an array on a line*/
void printArray(intarr[],intsize)
6
{
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
public static void main(String[] args)
{
MergeArrays mergearray = new MergeArrays();
/* Initializearrays */
int mPlusN[] = {2, 8, -1, -1, -1, 13, -1, 15, 20};
int N[] = {5, 7, 9, 25};
int n = N.length;
int m = mPlusN.length - n;
/*Move the m elements at the end of mPlusN*/
mergearray.moveToEnd(mPlusN, m + n);
/*Merge N[] into mPlusN[] */
mergearray.merge(mPlusN, N, m, n);
/* Printthe resultantmPlusN */
mergearray.printArray(mPlusN,m + n);
}
}
Output: 2 5 7 8 9 13 15 20 25
10. Given an array,and count n, rotate the array n times. Eg {1,2,3,4,5} and n = 2, output should be {3,4,5,1,2}
class leftrotate
{
static void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
{
int j, temp;
temp = arr[0];
for (j = 0; j < n - 1; j++)
arr[j] = arr[j + 1];
arr[j] = temp;
}
for (int k = 0; k < n; k++)
System.out.print(arr[k] + " ");
}
public static void main(String[] args)
{
7
int arr[] = {1, 2, 3, 4, 5, 6, 7};
leftRotate(arr, 2, 7);
}}
Output :
3 4 5 6 7 1 2
11. Given an array of 0s,1s and 2s, arrangearray in increasingorder so that firstelements are 0s,then 1s and 2s.
// Java program to sortan array of 0, 1 and 2
import java.io.*;
class countzot{
// Sort the inputarray,the array is assumed to
// have values in {0, 1, 2}
static void sort012(inta[],intarr_size)
{
int lo = 0;
int hi = arr_size- 1;
int mid = 0,temp=0;
while(mid <= hi)
{
switch (a[mid])
{
case0:
{
temp = a[lo];
a[lo] = a[mid];
a[mid] = temp;
lo++;
mid++;
break;
}
case1:
mid++;
break;
case2:
{
temp = a[mid];
a[mid] = a[hi];
a[hi] = temp;
hi--;
break;
}
}
}
}
/* Utility function to print array arr[] */
static void printArray(intarr[],intarr_size)
{
int i;
for (i = 0; i < arr_size;i++)
System.out.print(arr[i]+" ");
8
System.out.println("");
}
/*Driver function to check for above functions*/
public static void main (String[] args)
{
int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
int arr_size= arr.length;
sort012(arr,arr_size);
System.out.println("Array after seggregation ");
printArray(arr,arr_size);
}
}
Output:
array after segregation 0 0 0 0 0 1 1 1 1 1 2 2
12. Programto count occurrence of a given character in a string
// JAVA programto count occurrences
// of a character
class GFG
{
// Method that return count of the given
// character in the string
public static intcount(Strings,char c)
{
int res = 0;
for (inti=0; i<s.length(); i++)
{
// checkingcharacter in string
if (s.charAt(i) == c)
res++;
}
return res;
}
// Driver method
public static void main(Stringargs[])
{
String str= "geeksforgeeks";
char c = 'e';
System.out.println(count(str, c));
}
}
Output: 4
Q 13 factorial of no.
9
Ans:
1. class FactorialExample{
2. public static void main(String args[]){
3. int i,fact=1;
4. int number=5;
5. for(i=1;i<=number;i++){
6. fact=fact*i;
7. }
8. System.out.println("Factorial of "+number+" is: "+fact);
9. }
10. }
Q14 Fibonacci series
Ans:
1. class FibonacciExample1{
2. public static void main(String args[])
3. {
4. int n1=0,n2=1,n3,i,count=10;
5. System.out.print(n1+" "+n2);//printing 0 and 1
6.
7. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
8. {
9. n3=n1+n2;
10. System.out.print(" "+n3);
11. n1=n2;
12. n2=n3;
13. }
14.
15. }}
Q15 Prime Number
Ans:
1. class PrimeExample{
2. public static void main(String args[]){
3. int i,m=0,flag=0;
4. int n=17;//it is the number to be checked
5. m=n/2;
10
6. for(i=2;i<=m;i++){
7. if(n%i==0){
8. System.out.println("Number is not prime");
9. flag=1;
10. break;
11. }
12. }
13. if(flag==0)
14. System.out.println("Number is prime");
15. }
16. }
Q16 Bubble sort
Ans:
1. public class BubbleSortExample {
2. static void bubbleSort(int[] arr) {
3. int n = arr.length;
4. int temp = 0;
5. for(int i=0; i < n; i++){
6. for(int j=1; j < (n-i); j++){
7. if(arr[j-1] > arr[j]){
8. //swap elements
9. temp = arr[j-1];
10. arr[j-1] = arr[j];
11. arr[j] = temp;
12. }
13.
14. }
15. }
16.
17. }
18. public static void main(String[] args) {
19. int arr[] ={3,60,35,2,45,320,5};
20.
21. System.out.println("Array Before Bubble Sort");
22. for(int i=0; i < arr.length; i++){
23. System.out.print(arr[i] + " ");
24. }
25. System.out.println();
26.
27. bubbleSort(arr);//sorting array elements using bubble sort
28.
29. System.out.println("Array After Bubble Sort");
30. for(int i=0; i < arr.length; i++){
11
31. System.out.print(arr[i] + " ");
32. }
33.
34. }
35. }
Q:17// Java program to illustrate to find a substring
// in the string.
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which a substring
// is to be searched.
String str = "GeeksforGeeks is a computer science portal";
// Returns index of first occurrence of substring
int firstIndex = str.indexOf("Geeks");
System.out.println("First occurrence of char Geeks"+
" is found at : " + firstIndex);
// Returns index of last occurrence
int lastIndex = str.lastIndexOf("Geeks");
System.out.println("Last occurrence of char Geeks is"+
" found at : " + lastIndex);
// Index of the first occurrence
// after the specified index if found.
int first_in = str.indexOf("Geeks", 10);
System.out.println("First occurrence of char Geeks"+
" after index 10 : " + first_in);
int last_in = str.lastIndexOf("Geeks", 20);
System.out.println("Last occurrence of char Geeks " +
"after index 20 is : " + last_in);
}
}
Q 18:
Java program to illustrate how to find a substring
// in the string using contains
import java.io.*;
import java.lang.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which substring
// to be searched.
12
String test = "software";
CharSequence seq = "soft";
boolean bool = test.contains(seq);
System.out.println("Found soft?: " + bool);
// it returns true substring if found.
boolean seqFound = test.contains("war");
System.out.println("Found war? " + seqFound);
// it returns true substring if found otherwise
// return false.
boolean sqFound = test.contains("wr");
System.out.println("Found wr?: " + sqFound);
}
}
Output:
Found soft?: true
Found war? true
Found wr?: false
Question: // Java program to illustrate to find a character
// in the string.
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// This is a string in which a character
// to be searched.
String str = "GeeksforGeeks is a computer science portal";
// Returns index of first occurrence of character.
int firstIndex = str.indexOf('s');
System.out.println("First occurrence of char 's'" +
" is found at : " + firstIndex);
// Returns index of last occurrence specified character.
int lastIndex = str.lastIndexOf('s');
System.out.println("Last occurrence of char 's' is" +
" found at : " + lastIndex);
// Index of the first occurrence of specified char
// after the specified index if found.
int first_in = str.indexOf('s', 10);
System.out.println("First occurrence of char 's'" +
" after index 10 : " + first_in);
int last_in = str.lastIndexOf('s', 20);
13
System.out.println("Last occurrence of char 's'" +
" after index 20 is : " + last_in);
// gives ASCII value of character at location 20
int char_at = str.charAt(20);
System.out.println("Character at location 20: " +
char_at);
// throws StringIndexOutOfBoundsException
// char_at = str.charAt(50);
}
}
Q20 Reverse a string
Ans :
// Java program to Reverse a String by converting string to characters one
// by one
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString
{
public static void main(String[] args)
{
String input = "GeeksForGeeks";
// convert String to character array
// by using toCharArray
char[] try1 = input.toCharArray();
for (int i = try1.length-1; i>=0; i--)
System.out.print(try1[i]);’’’
}
}
Output:
skeeGrofskeeG
Q21 duplicate character in string
How do you count the number of occurrencesof each character in a string?
import java.util.HashMap;
import java.util.Set;
class DuplicateCharactersInString
{
static void duplicateCharCount(String inputString)
{
14
//Creating a HashMap containing char as key and it's occurrences as
value
HashMap<Character, Integer> charCountMap = new HashMap<Character,
Integer>();
//Converting given string to char array
char[] strArray = inputString.toCharArray();
//checking each char of strArray
for (char c : strArray)
{
if(charCountMap.containsKey(c))
{
//If char is present in charCountMap, incrementing it's count
by 1
charCountMap.put(c, charCountMap.get(c)+1);
}
else
{
//If char is not present in charCountMap,
//putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
//Getting a Set containing all keys of charCountMap
Set<Character> charsInString = charCountMap.keySet();
System.out.println("Duplicate Characters In "+inputString);
//Iterating through Set 'charsInString'
for (Character ch : charsInString)
{
if(charCountMap.get(ch) > 1)
{
//If any char has a count of more than 1, printing it's count
System.out.println(ch +" : "+ charCountMap.get(ch));
}
}
}
public static void main(String[] args)
{
duplicateCharCount("JavaJ2EE");
15
duplicateCharCount("Fresh Fish");
duplicateCharCount("Better Butter");
}
}
22.Write a java program to remove all white spaces from a string.?
class RemoveWhiteSpaces
{
public static void main(String[] args)
{
String str = " Core Java jsp servlets jdbc struts hibernate
spring ";
//1. Using replaceAll() Method
String strWithoutSpace = str.replaceAll("s", "");
System.out.println(strWithoutSpace); //Output :
CoreJavajspservletsjdbcstrutshibernatespring
}
}
Q 23 Write a java program to check whethertwo stringsare anagram or not? USING HASHMAP
public class AnagramProgram
{
static void isAnagram(String s1, String s2)
{
//Removing white spaces from s1 and s2 and converting case to lower case
String copyOfs1 = s1.replaceAll("s", "").toLowerCase();
String copyOfs2 = s2.replaceAll("s", "").toLowerCase();
//Initially setting status as true
boolean status = true;
if(copyOfs1.length() != copyOfs2.length())
{//Setting status as false if copyOfs1 and copyOfs2 doesn't have same
length
status = false;}
else
16
{
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < copyOfs1.length(); i++)
{
//Getting char from copyOfs1
char charAsKey = copyOfs1.charAt(i);
//Initializing char count to 0
int charCountAsValue = 0;
//Checking whether map contains this char
if(map.containsKey(charAsKey))
{
//If contains, retrieving it's count
charCountAsValue = map.get(charAsKey);
}
//Putting char and it's count to map with pre-incrementing
char count
map.put(charAsKey, ++charCountAsValue);
//Getting char from copyOfs2
charAsKey = copyOfs2.charAt(i);
17
//Initializing char count to 0
charCountAsValue = 0;
//Checking whether map contains this char
if(map.containsKey(charAsKey))
{
//If contains, retrieving it's count
charCountAsValue = map.get(charAsKey);
}
//Putting char and it's count to map with pre-decrementing
char count
map.put(charAsKey, --charCountAsValue);
}
//Checking each character and it's count
for (int value : map.values())
{
if(value != 0)
{
//If character count is not equal to 0, then setting
status as false
status = false;
}
}
18
}
//Output
if(status)
{
System.out.println(s1+" and "+s2+" are anagrams");
}
else
{
System.out.println(s1+" and "+s2+" are not anagrams");
}
}
public static void main(String[] args)
{
isAnagram("Mother In Law", "Hitler Woman");}
}}
Output :
Mother In Law and Hitler Woman are anagrams
24. Write a java program to reverse a given string with preserving the position of spaces?
public class MainClass
{
static void reverseString(String inputString)
{
//Converting inputString to char array 'inputStringArray'
char[] inputStringArray = inputString.toCharArray();
//Defining a new char array 'resultArray' with same size as
inputStringArray
char[] resultArray = new char[inputStringArray.length];
19
//First for loop :
//For every space in the 'inputStringArray',
//we insert spaces in the 'resultArray' at the corresponding
positions
for (int i = 0; i < inputStringArray.length; i++)
{
if (inputStringArray[i] == ' ')
{
resultArray[i] = ' ';
}
}
//Initializing 'j' with length of resultArray
int j = resultArray.length-1;
//Second for loop :
//we copy every non-space character of inputStringArray
//from first to last at 'j' position of resultArray
for (int i = 0; i < inputStringArray.length; i++)
{
if (inputStringArray[i] != ' ')
{
//If resultArray already has space at index j then
decrementing 'j'
if(resultArray[j] == ' ')
{
j--;
}
resultArray[j] = inputStringArray[i];
j--;
}
}
System.out.println(inputString+" ---> "+String.valueOf(resultArray));
}
public static void main(String[] args)
{
reverseString("I Am Not String");
reverseString("JAVA JSP ANDROID");
reverseString("1 22 333 4444 55555");
}
}
20
Output :
I Am Not String —> g ni rtS toNmAI
JAVA JSP ANDROID —> DIOR DNA PSJAVAJ
1 22 333 4444 55555 —> 5 55 554 4443 33221
25.How do you convert string to integer and integer to string in java?
public class StringToInteger
{
public static void main(String[] args)
{
String s = "2015";
int i = Integer.parseInt(s);
System.out.println(i); //Output : 2015
}
}
26.Write a code to prove that strings are immutable in java?
public class StringExamples
{
public static void main(String[] args)
{
String s1 = "JAVA";
String s2 = "JAVA";
System.out.println(s1 == s2); //Output : true
s1 = s1 + "J2EE";
System.out.println(s1 == s2); //Output : false
}
}
27.is new String() also immutable?
public class StringExamples
{
public static void main(String[] args)
{
String s1 = new String("JAVA");
System.out.println(s1); //Output : JAVA
s1.concat("J2EE");
System.out.println(s1); //Output : JAVA
21
}
}
28 Write a code to checkwhether one string is a rotation of another?
public class MainClass
{
public static void main(String[] args)
{
String s1 = "JavaJ2eeStrutsHibernate";
String s2 = "StrutsHibernateJavaJ2ee";
//Step 1
if(s1.length() != s2.length())
{
System.out.println("s2 is not rotated version of s1");
}
else
{
//Step 2
String s3 = s1 + s1;
//Step 3
if(s3.contains(s2))
{
System.out.println("s2 is a rotated version of s1");
}
else
{
System.out.println("s2 is not rotated version of s1");
}
}
}
}
29.Write a java program to reverse eachword ofa givenstring?
Splitthe given inputString intowordsusingsplit() method. Thentake eachindividual word,reverse it
and appendto reverseString. FinallyprintreverseString.Below image shows code snippetof the same.
22
public class ReverseEachWord
{
static void reverseEachWordOfString(String inputString)
{
String[] words = inputString.split(" ");
String reverseString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
reverseString = reverseString + reverseWord + " ";
}
System.out.println(inputString);
System.out.println(reverseString);
System.out.println("-------------------------");
}
public static void main(String[] args)
{
reverseEachWordOfString("Java Concept Of The Day");
}
}
Output :
Java Concept Of The Day
avaJ tpecnoC fO ehT yaD
————————-
23
// Java program to print all distint elements in a given array
import java.io.*;
class GFG {
static void printDistinct(int arr[], int n)
{
// Pick all elements one by one
for (int i = 0; i < n; i++)
{
// Check if the picked element
// is already printed
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier,
// then print it
if (i == j)
System.out.print( arr[i] + " ");
}
}
// Driver program
public static void main (String[] args)
{
int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int n = arr.length;
printDistinct(arr, n);
}
}
// JAVA Code for Find Second largest
// element in an array
class GFG {
/* Function to print the second largest
elements */
public static void print2largest(int arr[],
int arr_size)
{
int i, first, second;
/* There should be atleast two elements */
if (arr_size < 2)
{
System.out.print(" Invalid Input ");
return;
}
first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size ; i++)
{
/* If current element is smaller than
24
first then update both first and second */
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == Integer.MIN_VALUE)
System.out.print("There is no second largest"+
" elementn");
else
System.out.print("The second largest element"+
" is "+ second);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {12, 35, 1, 10, 34, 1};
int n = arr.length;
print2largest(arr, n);
}
}
Q: /* Function to print first smallest and second smallest
elements */
static void print2Smallest(int arr[])
{
int first, second, arr_size = arr.length;
/* There should be atleast two elements */
if (arr_size < 2)
{
System.out.println(" Invalid Input ");
return;
}
first = second = Integer.MAX_VALUE;
for (int i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if (arr[i] < first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second
25
then update second */
else if (arr[i] < second && arr[i] != first)
second = arr[i];
}
if (second == Integer.MAX_VALUE)
System.out.println("There is no second" +
"smallest element");
else
System.out.println("The smallest element is " +
first + " and second Smallest" +
" element is " + second);
}
/* Driver program to test above functions */
public static void main (String[] args)
{
int arr[] = {12, 13, 1, 10, 34, 1};
print2Smallest(arr);
}
}
Q: // Java code to find largest three elements
// in an array
class PrintLargest
{
/* Function to print three largest elements */
static void print2largest(int arr[], int arr_size)
{
int i, first, second, third;
/* There should be atleast two elements */
if (arr_size < 3)
{
System.out.print(" Invalid Input ");
return;
}
third = first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than
first*/
if (arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second)
{
third = second;
26
second = arr[i];
}
else if (arr[i] > third)
third = arr[i];
}
System.out.println("Three largest elements are " +
first + " " + second + " " + third);
}
/* Driver program to test above function*/
public static void main (String[] args)
{
int arr[] = {12, 13, 1, 10, 34, 1};
int n = arr.length;
print2largest(arr, n);
}
}
-------------------------Theory-----------------------------------
4. Various HTTP codes like2xx,3xx, 4xx, 5xx
i)200 OK, 201 Created, 202 Accepted ,203 Non-Authoritative Information
204 No Content, 205 Reset Content,206 Partial Content ,207 Multi-Status,208 Already Reported ,226 IM Used
ii)300 MultipleChoices,301 Moved Permanently,302 Found,303 See Other 304 Not Modified,305 Use Proxy,306
Switch Proxy,307 Temporary Redirect ,308 Permanent Redirect
iii) 400 Bad Request,401 Unauthorized (RFC 7235),
402 Payment Required,403 Forbidden,404 Not Found,405 Method Not Allowed,406 Not Acceptable,407 Proxy
Authentication Required (RFC 7235),408 Request Timeout,409 Conflict,,410 Gone
iv) 500 Internal Server Error,501 Not Implemented,502 Bad Gateway,503 Service Unavailable,504 Gateway
Timeout,505 HTTP Version Not Supported,506 VariantAlso Negotiates ,507 InsufficientStorage508 Loop Detected
,510 Not Extended ,511 Network Authentication Required
5.How to run failed test cases programmatically.UsingTestNG Selenium
-------------------JAVA Theory---------------------------------------------------------------------------------------------------------------------
1. What is class and objectin Java?
Classisa template ora blueprintthatdefinesthe state andbehaviorof the objectsitsupport.
Objectshave state andbehaviorasdescribed byitsclass. Objectisan instance of a class.
The difference betweenaclassandan objectisthat class iscreatedwhenthe program iscreatedbut
the objectsare createdat the run time.
classcName
{
consistsof variablesandmethods
}
27
classc1 = newclass();
where c1 is the object
2. What is inheritance andtypesof inheritance?
A classacquiringpropertiesof anotherclassisknownasinheritance.
A classthat acquiresthe propertiesisknownassubclasswhere asa classwhose propertiesare being
acquiredisknownas superclass.
Subclasscan inheritonlyinstance membersof superclass.
There are 4 typesof inheritance.
a. Simple Inheritance :Where one classinheritsfromanotherclass.
b. MultiLevel Inheritance: Where once classis a subclassof a classand a superclassof another
class
c. Multiple Inheritance :Where aclass inheritsfrommore thanone superclass.Javadoesnot
supportMultiple Inheritance
d. Hierarchical Inheritance :A classhavingmore than one subclassisknownashierarchical
inheritance.
Eg. ClassC
{Voidtest1(){SOP(“test1”);}}
ClassD extendsC
{Voidtest2(){SOP(“test2”);}}
ClassRun
{PSVM()
{D d1=newD();
d1.test1();
d1.test2();}}
OUTPUT: test1test2
3. What is methodoverriding?
Methodoverridingmeansoverridingthe functionalityof amethodinitssubclass.If a subclasshas a
methodwithsame name andsame parametersas itssuperclassbutthe implementationis different,itis
knownas overridingthe method.
It isusedin runtime polymorphism
It isusedto change the implementationof the methodinitssubclass.
To do methodoverriding,the followingare necessary:
a. Havingan Is-A relationship
b. Methodmust have same name as itsparentclass
c. Methodmust have same parameterasits parentclass
Example :
28
ClassA
{
Int a;
Voidprint()
{
System.out.println(“thisprintsaline”);
}
}
ClassB extendsA
{
Voidprint()
{
System.out.println(“thisismethod overriding”);
}
}
4. What is methodoverloading?
MethodoverloadingisaconceptinJava where twoor more methodsina classcan have same name but
the methodsignature orargumentsneedtobe different.The overloadedmethodsare bindedbythe
JVMat compile time itself.
5. Difference betweenmethodoverloadingandmethodoverriding?
a. In Methodoverloading,twoormore methodshave same name withinthe classwhile in
overriding,the subclasscanhave methodwithsame name.
b. The argumentsinoverloadinghave tobe different,where asinoverriding;the argumentsor
signature issame.
c. Methodoverloadinghappensatcompile time whereasmethodoverridinghappensatruntime.
6. What is abstract class?Explainitsfeatures.
Definingamethodwithonlymethoddeclarationisknownasabstractmethod.
The abstract methoddoesn’tspecifyabodyandit mustbe declaredusingthe ‘abstract’keyword.A
classdeclaredusing‘abstract’keywordisknownasabstract class.It can have onlyabstract methods,
only concrete methods,orbothabstract and concrete methods.
If any class hasan abstract method,itis compulsorytodefine the classasabstract.
We cannotcreate an instance of abstractclass.Hence the instance membersof abstractclasscannotbe
referred.
The subclassof abstract classalso must be abstract until andunlessitimplementsall the abstract
methodof the inheritedsuperclass.
Abstractmethodsare usedto specifymandatorybehaviorinsubclass.Subclassmustimplement
abstract methodsotherwisetheyneedtobe declaredasabstract as well.
29
We can achieve generalizationbyusingabstractclass.Definingcommonbehaviorforsubclassesis
knownas generalization.
7. What is interface?Howdoesitdifferfromabstractclass?
An interface isacollectionof abstractmethods.A classimplementsaninterface therebyinheritingthe
abstract methodsof the interface.
An interface onlyhasabstractmethodswhile anabstractclasscan have abstract as well asconcrete
methods.
We cannotinstantiate aninterface,while we candoso withabstractclass.
An interface doesnothave anyconstructors.
An interface cannotbe extendedby aclass,it can onlybe implemented.
An interface canextendmultiple interfaces.
Classcan extendonlyone class;however,interfacescanimplementmultipleinterfaces.
8. What is typecastinginJava.Explaindatatype castingandclasstypecasting.
Castingone type of informationtoanothertype of informationisknownastype casting.There are two
typesof typecasting:
a. Datatype casting
b. Classtype casting
In datatype casting,we can cast data type to another. There are two typesof data type casting:
Narrowing
Widening
Whena lowerdatatype iscastedto a higherdatatype,itisknownas widening.
A compilercanimplicitlydowidening.
Ex an intcan be typecastedintodoubleimplicitlybycompiler.
Whena higherdatatye iscastedintoa lowerdatatype,itisknownasnarrowing.Itneedstobe done
explicitly.
Ex double iscastedtoint.
Castingone classtype to anotherisknownas class type casting.
A classcastingis possible onlyif the classesare havingIs-A relationship.
There are twotypesof casting:
a. Upcasting
b. Downcasting
30
Castingsubclassobjecttosuperclasstype isknownasupcasting.Subclassobjectbehavesassuperclass.
It will notshowthe propertiesof subclass.
Castingsuperclasstype tosubclasstype isknownasdowncasting.Downcastingispossibleonlyif the
objectisupcasted.
Q:singletoninselenium:
public class WebDriverSingleton {
public static WebDriver driver;
public static WebDriver getInstance() {
if (driver == null) {
driver = new FirefoxWebDriver();
}
return driver;
}
}
10. What ispolymorphism?Explainhowtoachieve polymorphismwithexample.
An objectshowingdifferentbehavioratdifferentstagesof itslifecycleisknownaspolymorphism.
There are twotypesof polymorphism:
Compile time polymorphism:Whenthe methoddeclarationisbindedtomethoddefinitionbycompiler,
it isknownas compile time polymorphism.
Whenthe methoddeclarationisbindedtomethoddefinitionatthe time of objectcreationbyJVMat
runtime,itisknownas runtime polymorphism.
To achieve polymorphism,three thingsare needed:
Inheritance
MethodOverriding
Up Casting
Example :
Interface Demo
{
Voiddisp();
Voidprint();
}
ClassSample implementsdemo
{
Voiddisp()
{
Sop (“inside disp”);
}
31
Voidprint()
{
Sop(“insideprint”);
}
}
PublicclassMClass
{
Psvm
{
Demod;
D = newsample();
d.disp();
d.print();
}
}
11. What isabstractionand howto achieve it?
Abstractionisthe processof hidingthe implementationof classfromitsusage.
It definesthe functionalityof the objectbutdoesnotdefineinwhichclassthe implementationisdone.
To achieve abstractionwe needtodothe following:
a. Generalize the behaviorof the classesinaninterface.
b. Implementthe behaviorinthe subclass
c. Create a ref variable of interface anduse itto create objectsof subclass
By usingabstraction,we achieve loosecouplingbetweenimplementationandusage.
Loose couplingwill have three layers:
a. ImplementationLayer - where the objectbehaviorisdefined
b. ObjectcreationLayer– where the objectIscreated
c. Objectutilization –where the behaviorof objectusedwithoutknowingthe objectcreated
12. What isencapsulation?
Encapsulationisthe processof binding the memberstoitsclassor interface.
Memberscannotbe accessedwithoutusingclassname orinterface name.The membersof aclasscan
be restrictedupto 4 levels:
a. Private
b. Package
c. Protected
d. Public
In Private level,the memberscanbe accessed withinaclass.The private membershave the lowest
visibility
32
Package level memberscanbe accessedacrossany classin the package.It cannotbe accessedfrom
outside the package
Protectedlevelmembershave the visibilitytill package level howevertheycanbe accessedfromoutside
usinginheritance.
Publicmemberscanbe accessedfromanywhere.Ithasmore visibilitythananyotheraccessspecifier.
13. Can a constructor be declaredasprivate?
Yes.To protect itfrom beingsubclassed.Noclass can extenditbecause thentheycannotcall super();
Also, tohave a control oninstantiationof anobjectof the class.
14. Differencebetweenpackage level andprotectedlevelaccessspecifier?
Package level hasvisibility uptopackage and noone from outside itcanaccess it.Protectedmembers
have visibility uptopackage level butcanbe accessedfromoutside usinginheritance.
15. Explainthe featuresof Stringclassandwhatis immutable?
Newoperatorisnot requiredto create an objectof Stringclass.Whenthe stringis declaredusing
double quotesJVMcreatesanobject.
In Java,there isno datatype tostore stringsinsteaditprovidesaclassbythe name String tohandle a set
of characters
Stringclassis a memberof java.langpackage
In String,objectscanbe createdusingtwo ways:
a. Usingnewoperator
b. Usingdouble quotes(““ ) ;
Stringclassis a final class,itcannot have subclasses
It isan immutable class.Anyobjectwhose valuecannotbe changedaftercreationisknownas
immutable.
Once we assigna value toa stringobject,we cannotreassignit.If we try to reassignit,it will notmodify
the objectbut create a newone.
16. What isan array inJava? Explaintypesof array.
An array isa collectionof similartypesof elementswhereeachelementisstoredcontinuouslyinthe
memory.
Theyare referredthroughitsindex.Index rangesfrom0to length-1
There are twotypesof arrays:
a. Primitive
b. Reference
33
Array of primitive type storesthe primitive datatypeswhile arrayof reference type isusedtostore
objectsof the class.An array of reference type will alwayshave addressof the objects.
If we declare anarray of objectclass,itcan holdany type of java objectinit.
It has followinglimitation:
a. Size isrestricted/limited
b. Array isusedto store onlysimilartypesof elements
c. Array lengthwill notreturnthe exactnumberof elementsstoredinarraybutwill returnthe
total memoryinitialized.
17. What iscollectionAPI?Whyisitused?
Collectionsare usedtostore anytype of data objects.The size of collectionsgrowsdynamicallyatthe
run time.
Collectionsreturnsthe exactnumberof objectsstoredinitandnot the memoryallocated.
Each elementstoredincollectionare castedintoobjecttype. Whenwe retrieve objectfromcollection,
it still isinobjecttype andwe needtodowncastit to use the features.
3 types: set,queue,list
18. Explainfeaturesof list,queue,set.
a. List : It storesanytypesof elements
a. Elementsare all indexed
b. Referselementsbyusingindex
c. Duplicate andnull elementsare allowed
b. Queue : It isalsoa type of collectionandstoresanytypesof elements
Elementsare storedwithoutindex
TheyfollowFIFO
Duplicatesare allowedbutnull isnotallowed
Java haspriorityqueue where peekmethodisusedtoretrievethe header while poll methodis
usedto retrieve andremove the headerelement
c. Set: Itstoresany typesof elements
Elementsare notindexed
Duplicatesare notallowed
Null isallowed
Elementsare retrievedusingIterator
19. What ismap? How isit differentfromothercollections?
Elementsare storedinkeyvalue pair
Keycan be any object
Value canbe anyobject
Keyshouldbe unique
Keyismappedto value andisusedas an index.
20. What isa linkedlist?Explainitsfeatures.
34
The linkedlistclassimplementsthe listinterface.Ithastwoconstructorsone isthe defaultone which
buildsanemptylinkedlist.
It acts both as a listas well asqueue
LinkedList()
Secondisa linkedlistthatisinitializedwiththe elementsof collectionc
LinkedList(Collectionc)
LinkedListhasvariousmethodslike add,remove,poll,peek,getfirst,getlast,etc
21. Differencebetweensetandqueue andlist?
Null :List, Set
Duplicates:List,Queue
Index :List
In queue(),elementsare retrievedusingpeekorpoll method,whileinsetelementsare retrievedusing
iterator
22. What isiterator?Explainitsbehaviorandwhenitshouldbe used?
We needtocreate an iteratorobjectto accessset elements.
It has 3 methods:
Next() – getsthe nextelementinset
hasNext() –checksif nextelementexistsornot
remove() - removesthe currentelement
23. What isexception?Whentouse exceptioninjava?
An exceptionisanerror which occursduringruntime of program that disruptsthe normal flow of the
program.
An exceptioncanbe due to variousof reasonslike incorrectuserinput, file notfound,etc.
There are twotypesof exceptions:
a. Checkedexception:These kindsorexceptionsare checkedatcompile time bycompiler.The
compilerforcesustohandle the exceptionoritmustspecifythe exceptionusingthrows
keyword.
b. Uncheckedexception: Uncheckedexceptionsare the onesthatare notcheckedat compile
time sowe are not forcedto handle orspecifythe exception
In java,undererrorand runtime exceptions,theyare uncheckedexceptionsrestall are checked
exceptions.
24. What isspecificexceptionandgenericexceptionhandler?Whenshouldwe use both?
Base class of exceptionhierarchydoesnotprovide anyspecificinformationaboutthe error.Thatiswhy
Exceptionclasshasmanysubclasseslike IOExceptionetc.We shouldalwaysthrow specificexceptionsso
that the callerwill knowthe rootcause of the error andalsodebuggingbecomeseasy.
35
Whenwe are unsure if anyexceptionsmightoccur,inthatcase we coulduse genericexceptions.
25. What ischeckedand uncheckedexception?
a. Checkedexception:Thesekindsof exceptionsare checkedatcompile time bycompiler. The
compilerforcesustohandle the exceptionoritmustspecifythe exceptionusingthrows
keyword.
b. Uncheckedexception: Uncheckedexceptionsare the onesthatare notcheckedat compile
time sowe are not forcedto handle orspecifythe exception
26. Differencebetweenthrow,throwsandthrowable.
Throwable isthe superclassforerrorsandexceptionswhile throw andthrowsare keywords.
Throwsis a postmethodmodifierwhichspecifieswhichkindof exceptionsmaybe thrownbythe
method.
Throw isusedto throwan exceptionandrequiresasingle argumentwhichisaninstance of Throwable
or its subclass.
27. What isstream?Explaintypesof stream.
Streamsrepresentaninputsource andan outputdestinationinJava.A streamcan be defined asa
sequence of data.There are two typesof streams:
a. Inputstream
b. Outputstream.
Inputstreamis usedtoread the data fromthe source while the outputstreamisusedtowrite the data
to the destination.The outputstreamwritestothe destinationat one characterat a time.
29. Differencebetweenstaticandinstance objects?
Staticmembersare not a part of object;however, instance variablesare partof object.
Staticmembershave onlysingle copyof theminthe memory,howeverinstance variablescanhave
multiple copiesof theminthe memory.
To use the instance variable,we needtocreate areference of anobject.
30. What isprimitive variable andreference variable?
In java,there are two typesof variables,namelyprimitive variable andreference variable.
Primitive variablesare usedtostore primitive dataandisdeclaredusingdatatype.
Reference variable are declaredusingclassorinterface name.Itisusedto store an objectof a class.
31. What isa constructor?Why isit required?
36
Constructorsare usedtocreate an instance of the class.OR constructoris a bitof code that allowsusto
create an objectof the class.
There are twotypesof constructorsi.e.defaultconstructorandparameterizedconstructor.
Defaultconstructorsdonot have anyargumentswhile parameterizedconstructorscanhave one or
more than one argument.
If there is noconstructor definedinaclass,the compilercallsthe defaultconstructorimplicitly.
32. What isa defaultconstructorandwhen isitcreated?
In absence of the constructorsthat a programmerexplicitlycreates,the compilerimplicitlycreatesa
defaultconstructorwithzeroparametersandinitializesall the instance variablestodefaultvalues.
33. What isconstructor overloading?
Constructoroverloadingallowsustohave more than one constructorina classwithdifferent
arguments.
Once we explicitlyprovideconstructortoa class,compilerwill notadddefaultconstructortothe class.
34. What isuse of ‘this’keyword inJava?
Withinaninstance methodora constructor,thiskeywordpointstothe currentobjectbeingcalled.
OR
It isa reference variable thatpointstothe currentobject.
35. Why doesJavanot supportmultiple inheritances?
a. Subclass constructorcannot have more thanone super();
b. The objectclass memberscannotbe inheritedintothe subclassinmore thanone pathwith
differentdefinitionssince itwill create ambiguity.Itisalsoknownasdiamondproblem.
36. What isthe difference betweenthisandsuper?
Thisis usedtoreferto the current object,while superisusedtocall the constructor of superclass.
Superiscalledimplicitlyif itisnotcodedbyprogrammerwhile itisnot the case withthis().
37. What isconstructor chaining?Whenithappens?
Callinganotherconstructorof same classfrom anotherconstructoriscalledconstructorchaining.We
use this() toachieve constructorchaining.
38. Differencebetweenmethodsandconstructors?
37
40. Thiskeyword
Thisis a keywordusedtoaccessnon-staticmembersof the class.
Thisis alsousedto call otherconstructorsof the same class.
Call to Thismust be the firststatementinsidethe constructor.
Eg. ClassBox
{
Int width;
Stringcolour;
Box(intw,Stringc)
{width=w;
Colour=c;}
Box(intw)
{this(w)
Colour=c}
}
Voidprint()
{
SOP(w);
SOP(c);
}
Classrun
{PSVM()
{
Box b1=new Box(4);
B1.print();
Box b2=new Box(10,”green”);
B1.print();
}
}
OUTPUT: 4 Null 10 green
--------------------------------------------------------------------------------------------------------------------------------------------------------
Q. SQL : Inner join query
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Difference between drop, truncate and delete
–> DELETE:
1. Removes Some or All rows froma table,WHERE clause can be used.Canbe rolledback
38
> TRUNCATE:
1. Removes All rowsfroma table,Nowhere clause canbe used.,cannotbe rolledback
DROP
Commandremovesatable fromthe database.All the tables'rows,indexesandprivilegeswill alsobe
removed.NoDML triggerswill be fired.The operationcannotbe rolledback.
1. Create test data for checkout page of a ecommerce website. (Vlocity)
2. Create a test plan for whatsapp group (Amazon)
3. Create test data for a zomato likeapp where top 3 restaurants arelisted in the 5 km vicinity.Filters arefood
type and pincodeand GPS Coordinates (Amazon)
4. Explainingmostdifficulttestingrelated problem that occurred in your projectand how did you solveit.
(Groupon)
Q Rest assured advantages:
Rest-Assured isaJavabasedDSL (DomainSpecificLanguage) whichismostcommonlyusedtotestout
REST basedservices.Rest-Assuredpresentsagreatadvantage because itsupportsmultiple HTTP
requestsandcan validate and/orverifythe responsesof these requests.Thesemultiple requestsinclude
GET, POST,PUT, DELETE, PATCH,OPTIONSandHEAD methods.Giventhatitsupportsthese various
requests,italsoallowsforthemtobe constructedwithmultipleparameters,headers,andtheir
respective body,aswell asvalidatingresponse’sstatuscode,headers,cookiesandresponse time.
https://gorillalogic.com/blog/automation-testing-part-2-api-testing-rest-assured/
Hashmap Factorisation
Q:Types of authentication in api testing : OAuth2.0, OAuth1.0, Q:PUT vs. POST in REST We use Modify
HeaderValue (HTTPHeaders) ,tool usedModifyHeaderValue,headername iv-user,headervalue
archanasingh What isAuthenticationandHow doesAuthenticationworksinRESTWebServices
Q:Authentication
Authentication is a process to prove that you are the person who you intend to be.
http://toolsqa.com/rest-assured/authentication-authorization-rest-webservices/ Filehandling..2 file..fetch value
Q:static import in java
Static import. Static import is a feature introducedinthe Javaprogramminglanguage thatallows
members(fieldsandmethods) definedinaclassas public static to be usedin Java code;without
specifyingthe classinwhichthe fieldisdefined.Thisfeature wasintroducedintothe language inversion
5.0.
Q:What is a Wrapper class
39
As we are not able to use Primitive Data Types as objects directly in Java Programming
language, we can use Wrapper Class to wrap the Primitive Data Types into objects. Hence
Wrapper Classes are used, to wrap the primitive type into an object, so that we can use the
Primitive Data Type as an object.
Wrappermethods
The solutiontothisproblemliesinusingwrappermethodsforthe standardSeleniummethods.So
insteadof doingthiseverytime Ineedtoperforma click:
?
(new WebDriverWait(driver,
10)).until(ExpectedConditions.elementToBeClickable(By.id("loginButton")));
driver.findElement(By.id("loginButton")).click();
I have created a wrapper method click() in a MyElements class that looks like this:
?
public static void click(WebDriver driver, By by) {
(new WebDriverWait(driver,
10)).until(ExpectedConditions.elementToBeClickable(by));
driver.findElement(by).click();
}
Of course, the 10 second timeout is arbitrary and it’s better to replace this with some constant
value. Now, every time I want to perform a click in my test I can simply call:
?
MyElements.click(driver, By.id("loginButton");
which automatically performs a WebDriverWait, resulting in much stabler, better readable and
maintainable scripts.
Ex:
Extending your wrapper methods: error handling
Using wrapper methods for Selenium calls has the additional benefit of making error handling
much more generic as well. For example, if you often encounter a
StaleElementReferenceException (which those of you writing tests for responsive and dynamic
web applications might be all too familiar with), you can simply handle this in your wrapper
method and be done with it once and for all:
40
?
public static void click(WebDriver driver, By by) {
try {
(new WebDriverWait(driver,
10)).until(ExpectedConditions.elementToBeClickable(by));
driver.findElement(by).click();
catch (StaleElementReferenceException sere) {
// simply retry finding the element in the refreshed DOM
driver.findElement(by).click();
}
}
Q: How to clonean object in java
The clone() methodof Objectclassis usedto clone an object.The java.lang.Cloneable interface mustbe
implementedbythe classwhose objectclone we wantto create.If we don'timplementCloneable
interface, clone() methodgeneratesCloneNotSupportedException.The clone()methodisdefinedinthe
Objectclass.
Q: Unboxing and Autoboxing in java
Comparable vs Comparator in Java
Java provides two interfaces to sort objects using data members of the class:
1. Comparable
2. Comparator
Using Comparable Interface
A comparable object is capable of comparing itself with another object. The class itself must
implements the java.lang.Comparable interface to compare its instances.
Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list
of Movies based on year of release. We can implement the Comparable interface with the Movie
class, and we override the method compareTo() of Comparable interface.
8.3 2015
Now, suppose we want sort movies by their rating and names also. When we make a collection
element comparable(by having it implement Comparable), we get only one chance to implement
the compareTo() method. The solution is using Comparator.
41
Using Comparator
Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate
class. We create multiple separate classes (that implement Comparator) to compare by different
members.
Collections class has a second sort() method and it takes Comparator. The sort() method invokes
the compare() to sort objects.
To compare movies by Rating, we need to do 3 things :
1. Create a class thatimplementsComparator(andthusthe compare() methodthatdoesthe work
previouslydonebycompareTo()).
2. Make an instance of the Comparatorclass.
3. Call the overloadedsort() method,givingitboththe listandthe instance of the class that
implementsComparator.
 Comparable ismeantfor objectswithnatural orderingwhichmeansthe objectitself mustknow
how it is to be ordered. For example Roll Numbers of students. Whereas, Comparator interface
sorting is done through a separate class.
 Logically, Comparable interface compares “this” reference with the object specified and
Comparator in Java compares two different class objects provided.
 If any class implementsComparable interface inJavathen collectionof that objecteitherListor
Array can be sortedautomaticallybyusingCollections.sort() orArrays.sort() methodandobjects
will be sorted based on there natural order defined by CompareTo method.
To summarize, if sorting of objects needs to be based on natural order then use Comparable
whereas if you sorting needs to be done on attributes of different objects, then use Comparator
in Java.

Weitere ähnliche Inhalte

Was ist angesagt?

Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]Baruch Sadogursky
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsBaruch Sadogursky
 
Pj01 4-operators and control flow
Pj01 4-operators and control flowPj01 4-operators and control flow
Pj01 4-operators and control flowSasidharaRaoMarrapu
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Sunil Kumar Gunasekaran
 
Java Puzzle
Java PuzzleJava Puzzle
Java PuzzleSFilipp
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 

Was ist angesagt? (19)

Java puzzles
Java puzzlesJava puzzles
Java puzzles
 
Ann
AnnAnn
Ann
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
Studyx1
Studyx1Studyx1
Studyx1
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
PythonOOP
PythonOOPPythonOOP
PythonOOP
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Pj01 4-operators and control flow
Pj01 4-operators and control flowPj01 4-operators and control flow
Pj01 4-operators and control flow
 
Java Puzzlers
Java PuzzlersJava Puzzlers
Java Puzzlers
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
Java file
Java fileJava file
Java file
 
Java Puzzle
Java PuzzleJava Puzzle
Java Puzzle
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 

Ähnlich wie QA Auotmation Java programs,theory

JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfRohitkumarYadav80
 
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfeyewatchsystems
 
FileName EX06_1java Programmer import ja.pdf
FileName EX06_1java Programmer  import ja.pdfFileName EX06_1java Programmer  import ja.pdf
FileName EX06_1java Programmer import ja.pdfactocomputer
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...MaruMengesha
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginnersishan0019
 
Example of JAVA Program
Example of JAVA ProgramExample of JAVA Program
Example of JAVA ProgramTrenton Asbury
 
Refer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdfRefer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdfarishmarketing21
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdfICADCMLTPC
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdfanupamfootwear
 
81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programsAbhishek Jena
 

Ähnlich wie QA Auotmation Java programs,theory (20)

JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
 
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
 
FileName EX06_1java Programmer import ja.pdf
FileName EX06_1java Programmer  import ja.pdfFileName EX06_1java Programmer  import ja.pdf
FileName EX06_1java Programmer import ja.pdf
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Java file
Java fileJava file
Java file
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
C programs
C programsC programs
C programs
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Vcs16
Vcs16Vcs16
Vcs16
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Example of JAVA Program
Example of JAVA ProgramExample of JAVA Program
Example of JAVA Program
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
Java programs
Java programsJava programs
Java programs
 
Refer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdfRefer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdf
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs81818088 isc-class-xii-computer-science-project-java-programs
81818088 isc-class-xii-computer-science-project-java-programs
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 

Kürzlich hochgeladen (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 

QA Auotmation Java programs,theory

  • 1. 1 1. Given an integer "532341", output should be reverse of integer. Ans: public classReverseNumber { public static void main(String[] args) { int num = 1234,reversed = 0; while(num != 0) { int digit= num % 10; reversed = reversed * 10 + digit; num /= 10; } System.out.println("Reversed Number: " + reversed); } } 2. Given two words, check if they are anagramof each other or not. public static void main(String[] args) throws ParseException { String s1="anagram"; String s2="margana"; int lettersS1[] = new int[Character.MAX_VALUE]; int lettersS2[] = new int[Character.MAX_VALUE]; if(s1.length()!=s2.length()) System.out.print("No"); else { for(inti = 0; i<s1.length() ;++i) { lettersS1[s1.toLowerCase().charAt(i)]++; lettersS2[s2.toLowerCase().charAt(i)]++; } boolean anag= true; for(inti = 0;i<lettersS1.length&&anag;++i) { if(lettersS1[i] != lettersS2[i]) { anag= false; } } if(anag) { System.out.print("Anagram"); } else { System.out.print("No anagram"); } } }
  • 2. 2 3. Palindromejava class PalindromeExample{ public static void main(String args[]){ intr,sum=0,temp; intn=454;//It is the number variableto be checked for palindrome temp=n; while(n>0){ r=n%10; //getting remainder sum=(sum*10)+r; n=n/10; } if(temp==sum) System.out.println("palindromenumber "); else System.out.println("not palindrome"); Q 4 :Palindromeword public class palindrom { public static void main(String args[]) { String name2 = "", name = "naman"; int i; // char name2; for(i=name.length()-1;i>-1;i--) name2=name2+name.charAt(i); System.out.println(name2); if(name.equals(name2)) { System.out.println("palindrome"); } else { System.out.println("no"); } } } 5. Given two strings A = "My name is Praneta"and B = "name is", output should be a new stringthat has all words of A that are not present in "B". Output : "My Praneta" package examples; class StringSubString { public static void main(String[] args) { String oldStr = "My Name is Archana"; String delStr = "Name is "; String newStr; newStr = oldStr.replace(delStr, ""); System.out.println(oldStr);
  • 3. 3 System.out.println(newStr); } } 6. Given an integer number n, for multiples of three print “Fizz” for the multiples of fiveprint “Buzz”. For numbers which are multiples of both three and fiveprint “FizzBuzz”. public class FizzBuzz { public static void main(String[] args) { for (inti = 1; i < 101; i++) { // Set this to true when one of the special conditions ismet. boolean printed = false; if (i % 3 == 0) { // When i is divisibleby 3, then print"Fizz" printed = true; System.out.print("Fizz"); } else if (i % 5 == 0) { // When i is not divisibleby 3 but is divisibleby 5, then print"Buzz" printed = true; System.out.print("Buzz"); } } } } 7. binary search programin java 1. class BinarySearchExample{ 2. public static void binarySearch(intarr[],intfirst,intlast,intkey){ 3. int mid = (first+ last)/2; 4. while( first<= last){ 5. if ( arr[mid] < key ){ 6. first= mid + 1; 7. }else if ( arr[mid] == key ){ 8. System.out.println("Element is found atindex: " + mid); 9. break; 10. }else{ 11. last= mid - 1; 12. } 13. mid = (first+ last)/2; 14. } 15. if ( first> last){ 16. System.out.println("Element is not found!"); 17. } 18. } 19. public static void main(String args[]){ 20. int arr[] = {10,20,30,40,50}; 21. int key = 30; 22. int last=arr.length-1; 23. binarySearch(arr,0,last,key); 24. } 25. } 26. Element is found at index: 2
  • 4. 4 8.Given a string,find the second most frequent character in it. // Java Program to find the second // most frequent character in each string public class GFG { static final intNO_OF_CHARS = 256; // finds the second most frequently occurring // char static char getSecondMostFreq(String str) { // count number of occurrences of every // character. int[] count = new int[NO_OF_CHARS]; int i; for (i=0; i< str.length(); i++) (count[str.charAt(i)])++; // Traverse through the count[] and find // second highest element. int first= 0, second = 0; for (i = 0; i < NO_OF_CHARS; i++) { /* If current element is smaller than firstthen update both firstand second */ if (count[i] > count[first]) { second = first; first= i; } /* If count[i] is in between firstand second then update second */ else if (count[i] > count[second] && count[i] != count[first]) second = i; } return (char)second; } // Driver programto test above function public static void main(Stringargs[]) { String str = "geeksforgeeks"; char res = getSecondMostFreq(str); if (res != '0') System.out.println("Second most frequent char"+ " is " + res); else System.out.println("No second most frequent"+
  • 5. 5 "character"); } } 9.There aretwo sorted arrays.Firstoneis of sizem+n containingonly m elements. Another one is of size n and contains n elements. Merge these two arrays into the firstarray of sizem+n such that the output is sorted. class MergeArrays { /* Function to move m elements at the end of array mPlusN[] */ void moveToEnd(int mPlusN[], int size) { int i,j = size- 1; for (i = size- 1; i >= 0; i--) { if (mPlusN[i] != -1) { mPlusN[j] = mPlusN[i]; j--; } } } /* Merges array N[] of sizen into array mPlusN[] of sizem+n*/ void merge(int mPlusN[], intN[], int m, intn) { int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; while(k < (m + n)) { if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n)) { mPlusN[k] = mPlusN[i]; k++; i++; } { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line*/ void printArray(intarr[],intsize)
  • 6. 6 { int i; for (i = 0; i < size; i++) System.out.print(arr[i] + " "); System.out.println(""); } public static void main(String[] args) { MergeArrays mergearray = new MergeArrays(); /* Initializearrays */ int mPlusN[] = {2, 8, -1, -1, -1, 13, -1, 15, 20}; int N[] = {5, 7, 9, 25}; int n = N.length; int m = mPlusN.length - n; /*Move the m elements at the end of mPlusN*/ mergearray.moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ mergearray.merge(mPlusN, N, m, n); /* Printthe resultantmPlusN */ mergearray.printArray(mPlusN,m + n); } } Output: 2 5 7 8 9 13 15 20 25 10. Given an array,and count n, rotate the array n times. Eg {1,2,3,4,5} and n = 2, output should be {3,4,5,1,2} class leftrotate { static void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) { int j, temp; temp = arr[0]; for (j = 0; j < n - 1; j++) arr[j] = arr[j + 1]; arr[j] = temp; } for (int k = 0; k < n; k++) System.out.print(arr[k] + " "); } public static void main(String[] args) {
  • 7. 7 int arr[] = {1, 2, 3, 4, 5, 6, 7}; leftRotate(arr, 2, 7); }} Output : 3 4 5 6 7 1 2 11. Given an array of 0s,1s and 2s, arrangearray in increasingorder so that firstelements are 0s,then 1s and 2s. // Java program to sortan array of 0, 1 and 2 import java.io.*; class countzot{ // Sort the inputarray,the array is assumed to // have values in {0, 1, 2} static void sort012(inta[],intarr_size) { int lo = 0; int hi = arr_size- 1; int mid = 0,temp=0; while(mid <= hi) { switch (a[mid]) { case0: { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; break; } case1: mid++; break; case2: { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; break; } } } } /* Utility function to print array arr[] */ static void printArray(intarr[],intarr_size) { int i; for (i = 0; i < arr_size;i++) System.out.print(arr[i]+" ");
  • 8. 8 System.out.println(""); } /*Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size= arr.length; sort012(arr,arr_size); System.out.println("Array after seggregation "); printArray(arr,arr_size); } } Output: array after segregation 0 0 0 0 0 1 1 1 1 1 2 2 12. Programto count occurrence of a given character in a string // JAVA programto count occurrences // of a character class GFG { // Method that return count of the given // character in the string public static intcount(Strings,char c) { int res = 0; for (inti=0; i<s.length(); i++) { // checkingcharacter in string if (s.charAt(i) == c) res++; } return res; } // Driver method public static void main(Stringargs[]) { String str= "geeksforgeeks"; char c = 'e'; System.out.println(count(str, c)); } } Output: 4 Q 13 factorial of no.
  • 9. 9 Ans: 1. class FactorialExample{ 2. public static void main(String args[]){ 3. int i,fact=1; 4. int number=5; 5. for(i=1;i<=number;i++){ 6. fact=fact*i; 7. } 8. System.out.println("Factorial of "+number+" is: "+fact); 9. } 10. } Q14 Fibonacci series Ans: 1. class FibonacciExample1{ 2. public static void main(String args[]) 3. { 4. int n1=0,n2=1,n3,i,count=10; 5. System.out.print(n1+" "+n2);//printing 0 and 1 6. 7. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed 8. { 9. n3=n1+n2; 10. System.out.print(" "+n3); 11. n1=n2; 12. n2=n3; 13. } 14. 15. }} Q15 Prime Number Ans: 1. class PrimeExample{ 2. public static void main(String args[]){ 3. int i,m=0,flag=0; 4. int n=17;//it is the number to be checked 5. m=n/2;
  • 10. 10 6. for(i=2;i<=m;i++){ 7. if(n%i==0){ 8. System.out.println("Number is not prime"); 9. flag=1; 10. break; 11. } 12. } 13. if(flag==0) 14. System.out.println("Number is prime"); 15. } 16. } Q16 Bubble sort Ans: 1. public class BubbleSortExample { 2. static void bubbleSort(int[] arr) { 3. int n = arr.length; 4. int temp = 0; 5. for(int i=0; i < n; i++){ 6. for(int j=1; j < (n-i); j++){ 7. if(arr[j-1] > arr[j]){ 8. //swap elements 9. temp = arr[j-1]; 10. arr[j-1] = arr[j]; 11. arr[j] = temp; 12. } 13. 14. } 15. } 16. 17. } 18. public static void main(String[] args) { 19. int arr[] ={3,60,35,2,45,320,5}; 20. 21. System.out.println("Array Before Bubble Sort"); 22. for(int i=0; i < arr.length; i++){ 23. System.out.print(arr[i] + " "); 24. } 25. System.out.println(); 26. 27. bubbleSort(arr);//sorting array elements using bubble sort 28. 29. System.out.println("Array After Bubble Sort"); 30. for(int i=0; i < arr.length; i++){
  • 11. 11 31. System.out.print(arr[i] + " "); 32. } 33. 34. } 35. } Q:17// Java program to illustrate to find a substring // in the string. import java.io.*; class GFG { public static void main (String[] args) { // This is a string in which a substring // is to be searched. String str = "GeeksforGeeks is a computer science portal"; // Returns index of first occurrence of substring int firstIndex = str.indexOf("Geeks"); System.out.println("First occurrence of char Geeks"+ " is found at : " + firstIndex); // Returns index of last occurrence int lastIndex = str.lastIndexOf("Geeks"); System.out.println("Last occurrence of char Geeks is"+ " found at : " + lastIndex); // Index of the first occurrence // after the specified index if found. int first_in = str.indexOf("Geeks", 10); System.out.println("First occurrence of char Geeks"+ " after index 10 : " + first_in); int last_in = str.lastIndexOf("Geeks", 20); System.out.println("Last occurrence of char Geeks " + "after index 20 is : " + last_in); } } Q 18: Java program to illustrate how to find a substring // in the string using contains import java.io.*; import java.lang.*; class GFG { public static void main (String[] args) { // This is a string in which substring // to be searched.
  • 12. 12 String test = "software"; CharSequence seq = "soft"; boolean bool = test.contains(seq); System.out.println("Found soft?: " + bool); // it returns true substring if found. boolean seqFound = test.contains("war"); System.out.println("Found war? " + seqFound); // it returns true substring if found otherwise // return false. boolean sqFound = test.contains("wr"); System.out.println("Found wr?: " + sqFound); } } Output: Found soft?: true Found war? true Found wr?: false Question: // Java program to illustrate to find a character // in the string. import java.io.*; class GFG { public static void main (String[] args) { // This is a string in which a character // to be searched. String str = "GeeksforGeeks is a computer science portal"; // Returns index of first occurrence of character. int firstIndex = str.indexOf('s'); System.out.println("First occurrence of char 's'" + " is found at : " + firstIndex); // Returns index of last occurrence specified character. int lastIndex = str.lastIndexOf('s'); System.out.println("Last occurrence of char 's' is" + " found at : " + lastIndex); // Index of the first occurrence of specified char // after the specified index if found. int first_in = str.indexOf('s', 10); System.out.println("First occurrence of char 's'" + " after index 10 : " + first_in); int last_in = str.lastIndexOf('s', 20);
  • 13. 13 System.out.println("Last occurrence of char 's'" + " after index 20 is : " + last_in); // gives ASCII value of character at location 20 int char_at = str.charAt(20); System.out.println("Character at location 20: " + char_at); // throws StringIndexOutOfBoundsException // char_at = str.charAt(50); } } Q20 Reverse a string Ans : // Java program to Reverse a String by converting string to characters one // by one import java.lang.*; import java.io.*; import java.util.*; // Class of ReverseString class ReverseString { public static void main(String[] args) { String input = "GeeksForGeeks"; // convert String to character array // by using toCharArray char[] try1 = input.toCharArray(); for (int i = try1.length-1; i>=0; i--) System.out.print(try1[i]);’’’ } } Output: skeeGrofskeeG Q21 duplicate character in string How do you count the number of occurrencesof each character in a string? import java.util.HashMap; import java.util.Set; class DuplicateCharactersInString { static void duplicateCharCount(String inputString) {
  • 14. 14 //Creating a HashMap containing char as key and it's occurrences as value HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>(); //Converting given string to char array char[] strArray = inputString.toCharArray(); //checking each char of strArray for (char c : strArray) { if(charCountMap.containsKey(c)) { //If char is present in charCountMap, incrementing it's count by 1 charCountMap.put(c, charCountMap.get(c)+1); } else { //If char is not present in charCountMap, //putting this char to charCountMap with 1 as it's value charCountMap.put(c, 1); } } //Getting a Set containing all keys of charCountMap Set<Character> charsInString = charCountMap.keySet(); System.out.println("Duplicate Characters In "+inputString); //Iterating through Set 'charsInString' for (Character ch : charsInString) { if(charCountMap.get(ch) > 1) { //If any char has a count of more than 1, printing it's count System.out.println(ch +" : "+ charCountMap.get(ch)); } } } public static void main(String[] args) { duplicateCharCount("JavaJ2EE");
  • 15. 15 duplicateCharCount("Fresh Fish"); duplicateCharCount("Better Butter"); } } 22.Write a java program to remove all white spaces from a string.? class RemoveWhiteSpaces { public static void main(String[] args) { String str = " Core Java jsp servlets jdbc struts hibernate spring "; //1. Using replaceAll() Method String strWithoutSpace = str.replaceAll("s", ""); System.out.println(strWithoutSpace); //Output : CoreJavajspservletsjdbcstrutshibernatespring } } Q 23 Write a java program to check whethertwo stringsare anagram or not? USING HASHMAP public class AnagramProgram { static void isAnagram(String s1, String s2) { //Removing white spaces from s1 and s2 and converting case to lower case String copyOfs1 = s1.replaceAll("s", "").toLowerCase(); String copyOfs2 = s2.replaceAll("s", "").toLowerCase(); //Initially setting status as true boolean status = true; if(copyOfs1.length() != copyOfs2.length()) {//Setting status as false if copyOfs1 and copyOfs2 doesn't have same length status = false;} else
  • 16. 16 { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < copyOfs1.length(); i++) { //Getting char from copyOfs1 char charAsKey = copyOfs1.charAt(i); //Initializing char count to 0 int charCountAsValue = 0; //Checking whether map contains this char if(map.containsKey(charAsKey)) { //If contains, retrieving it's count charCountAsValue = map.get(charAsKey); } //Putting char and it's count to map with pre-incrementing char count map.put(charAsKey, ++charCountAsValue); //Getting char from copyOfs2 charAsKey = copyOfs2.charAt(i);
  • 17. 17 //Initializing char count to 0 charCountAsValue = 0; //Checking whether map contains this char if(map.containsKey(charAsKey)) { //If contains, retrieving it's count charCountAsValue = map.get(charAsKey); } //Putting char and it's count to map with pre-decrementing char count map.put(charAsKey, --charCountAsValue); } //Checking each character and it's count for (int value : map.values()) { if(value != 0) { //If character count is not equal to 0, then setting status as false status = false; } }
  • 18. 18 } //Output if(status) { System.out.println(s1+" and "+s2+" are anagrams"); } else { System.out.println(s1+" and "+s2+" are not anagrams"); } } public static void main(String[] args) { isAnagram("Mother In Law", "Hitler Woman");} }} Output : Mother In Law and Hitler Woman are anagrams 24. Write a java program to reverse a given string with preserving the position of spaces? public class MainClass { static void reverseString(String inputString) { //Converting inputString to char array 'inputStringArray' char[] inputStringArray = inputString.toCharArray(); //Defining a new char array 'resultArray' with same size as inputStringArray char[] resultArray = new char[inputStringArray.length];
  • 19. 19 //First for loop : //For every space in the 'inputStringArray', //we insert spaces in the 'resultArray' at the corresponding positions for (int i = 0; i < inputStringArray.length; i++) { if (inputStringArray[i] == ' ') { resultArray[i] = ' '; } } //Initializing 'j' with length of resultArray int j = resultArray.length-1; //Second for loop : //we copy every non-space character of inputStringArray //from first to last at 'j' position of resultArray for (int i = 0; i < inputStringArray.length; i++) { if (inputStringArray[i] != ' ') { //If resultArray already has space at index j then decrementing 'j' if(resultArray[j] == ' ') { j--; } resultArray[j] = inputStringArray[i]; j--; } } System.out.println(inputString+" ---> "+String.valueOf(resultArray)); } public static void main(String[] args) { reverseString("I Am Not String"); reverseString("JAVA JSP ANDROID"); reverseString("1 22 333 4444 55555"); } }
  • 20. 20 Output : I Am Not String —> g ni rtS toNmAI JAVA JSP ANDROID —> DIOR DNA PSJAVAJ 1 22 333 4444 55555 —> 5 55 554 4443 33221 25.How do you convert string to integer and integer to string in java? public class StringToInteger { public static void main(String[] args) { String s = "2015"; int i = Integer.parseInt(s); System.out.println(i); //Output : 2015 } } 26.Write a code to prove that strings are immutable in java? public class StringExamples { public static void main(String[] args) { String s1 = "JAVA"; String s2 = "JAVA"; System.out.println(s1 == s2); //Output : true s1 = s1 + "J2EE"; System.out.println(s1 == s2); //Output : false } } 27.is new String() also immutable? public class StringExamples { public static void main(String[] args) { String s1 = new String("JAVA"); System.out.println(s1); //Output : JAVA s1.concat("J2EE"); System.out.println(s1); //Output : JAVA
  • 21. 21 } } 28 Write a code to checkwhether one string is a rotation of another? public class MainClass { public static void main(String[] args) { String s1 = "JavaJ2eeStrutsHibernate"; String s2 = "StrutsHibernateJavaJ2ee"; //Step 1 if(s1.length() != s2.length()) { System.out.println("s2 is not rotated version of s1"); } else { //Step 2 String s3 = s1 + s1; //Step 3 if(s3.contains(s2)) { System.out.println("s2 is a rotated version of s1"); } else { System.out.println("s2 is not rotated version of s1"); } } } } 29.Write a java program to reverse eachword ofa givenstring? Splitthe given inputString intowordsusingsplit() method. Thentake eachindividual word,reverse it and appendto reverseString. FinallyprintreverseString.Below image shows code snippetof the same.
  • 22. 22 public class ReverseEachWord { static void reverseEachWordOfString(String inputString) { String[] words = inputString.split(" "); String reverseString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String reverseWord = ""; for (int j = word.length()-1; j >= 0; j--) { reverseWord = reverseWord + word.charAt(j); } reverseString = reverseString + reverseWord + " "; } System.out.println(inputString); System.out.println(reverseString); System.out.println("-------------------------"); } public static void main(String[] args) { reverseEachWordOfString("Java Concept Of The Day"); } } Output : Java Concept Of The Day avaJ tpecnoC fO ehT yaD ————————-
  • 23. 23 // Java program to print all distint elements in a given array import java.io.*; class GFG { static void printDistinct(int arr[], int n) { // Pick all elements one by one for (int i = 0; i < n; i++) { // Check if the picked element // is already printed int j; for (j = 0; j < i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, // then print it if (i == j) System.out.print( arr[i] + " "); } } // Driver program public static void main (String[] args) { int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}; int n = arr.length; printDistinct(arr, n); } } // JAVA Code for Find Second largest // element in an array class GFG { /* Function to print the second largest elements */ public static void print2largest(int arr[], int arr_size) { int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { System.out.print(" Invalid Input "); return; } first = second = Integer.MIN_VALUE; for (i = 0; i < arr_size ; i++) { /* If current element is smaller than
  • 24. 24 first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } if (second == Integer.MIN_VALUE) System.out.print("There is no second largest"+ " elementn"); else System.out.print("The second largest element"+ " is "+ second); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {12, 35, 1, 10, 34, 1}; int n = arr.length; print2largest(arr, n); } } Q: /* Function to print first smallest and second smallest elements */ static void print2Smallest(int arr[]) { int first, second, arr_size = arr.length; /* There should be atleast two elements */ if (arr_size < 2) { System.out.println(" Invalid Input "); return; } first = second = Integer.MAX_VALUE; for (int i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second
  • 25. 25 then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == Integer.MAX_VALUE) System.out.println("There is no second" + "smallest element"); else System.out.println("The smallest element is " + first + " and second Smallest" + " element is " + second); } /* Driver program to test above functions */ public static void main (String[] args) { int arr[] = {12, 13, 1, 10, 34, 1}; print2Smallest(arr); } } Q: // Java code to find largest three elements // in an array class PrintLargest { /* Function to print three largest elements */ static void print2largest(int arr[], int arr_size) { int i, first, second, third; /* There should be atleast two elements */ if (arr_size < 3) { System.out.print(" Invalid Input "); return; } third = first = second = Integer.MIN_VALUE; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first*/ if (arr[i] > first) { third = second; second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) { third = second;
  • 26. 26 second = arr[i]; } else if (arr[i] > third) third = arr[i]; } System.out.println("Three largest elements are " + first + " " + second + " " + third); } /* Driver program to test above function*/ public static void main (String[] args) { int arr[] = {12, 13, 1, 10, 34, 1}; int n = arr.length; print2largest(arr, n); } } -------------------------Theory----------------------------------- 4. Various HTTP codes like2xx,3xx, 4xx, 5xx i)200 OK, 201 Created, 202 Accepted ,203 Non-Authoritative Information 204 No Content, 205 Reset Content,206 Partial Content ,207 Multi-Status,208 Already Reported ,226 IM Used ii)300 MultipleChoices,301 Moved Permanently,302 Found,303 See Other 304 Not Modified,305 Use Proxy,306 Switch Proxy,307 Temporary Redirect ,308 Permanent Redirect iii) 400 Bad Request,401 Unauthorized (RFC 7235), 402 Payment Required,403 Forbidden,404 Not Found,405 Method Not Allowed,406 Not Acceptable,407 Proxy Authentication Required (RFC 7235),408 Request Timeout,409 Conflict,,410 Gone iv) 500 Internal Server Error,501 Not Implemented,502 Bad Gateway,503 Service Unavailable,504 Gateway Timeout,505 HTTP Version Not Supported,506 VariantAlso Negotiates ,507 InsufficientStorage508 Loop Detected ,510 Not Extended ,511 Network Authentication Required 5.How to run failed test cases programmatically.UsingTestNG Selenium -------------------JAVA Theory--------------------------------------------------------------------------------------------------------------------- 1. What is class and objectin Java? Classisa template ora blueprintthatdefinesthe state andbehaviorof the objectsitsupport. Objectshave state andbehaviorasdescribed byitsclass. Objectisan instance of a class. The difference betweenaclassandan objectisthat class iscreatedwhenthe program iscreatedbut the objectsare createdat the run time. classcName { consistsof variablesandmethods }
  • 27. 27 classc1 = newclass(); where c1 is the object 2. What is inheritance andtypesof inheritance? A classacquiringpropertiesof anotherclassisknownasinheritance. A classthat acquiresthe propertiesisknownassubclasswhere asa classwhose propertiesare being acquiredisknownas superclass. Subclasscan inheritonlyinstance membersof superclass. There are 4 typesof inheritance. a. Simple Inheritance :Where one classinheritsfromanotherclass. b. MultiLevel Inheritance: Where once classis a subclassof a classand a superclassof another class c. Multiple Inheritance :Where aclass inheritsfrommore thanone superclass.Javadoesnot supportMultiple Inheritance d. Hierarchical Inheritance :A classhavingmore than one subclassisknownashierarchical inheritance. Eg. ClassC {Voidtest1(){SOP(“test1”);}} ClassD extendsC {Voidtest2(){SOP(“test2”);}} ClassRun {PSVM() {D d1=newD(); d1.test1(); d1.test2();}} OUTPUT: test1test2 3. What is methodoverriding? Methodoverridingmeansoverridingthe functionalityof amethodinitssubclass.If a subclasshas a methodwithsame name andsame parametersas itssuperclassbutthe implementationis different,itis knownas overridingthe method. It isusedin runtime polymorphism It isusedto change the implementationof the methodinitssubclass. To do methodoverriding,the followingare necessary: a. Havingan Is-A relationship b. Methodmust have same name as itsparentclass c. Methodmust have same parameterasits parentclass Example :
  • 28. 28 ClassA { Int a; Voidprint() { System.out.println(“thisprintsaline”); } } ClassB extendsA { Voidprint() { System.out.println(“thisismethod overriding”); } } 4. What is methodoverloading? MethodoverloadingisaconceptinJava where twoor more methodsina classcan have same name but the methodsignature orargumentsneedtobe different.The overloadedmethodsare bindedbythe JVMat compile time itself. 5. Difference betweenmethodoverloadingandmethodoverriding? a. In Methodoverloading,twoormore methodshave same name withinthe classwhile in overriding,the subclasscanhave methodwithsame name. b. The argumentsinoverloadinghave tobe different,where asinoverriding;the argumentsor signature issame. c. Methodoverloadinghappensatcompile time whereasmethodoverridinghappensatruntime. 6. What is abstract class?Explainitsfeatures. Definingamethodwithonlymethoddeclarationisknownasabstractmethod. The abstract methoddoesn’tspecifyabodyandit mustbe declaredusingthe ‘abstract’keyword.A classdeclaredusing‘abstract’keywordisknownasabstract class.It can have onlyabstract methods, only concrete methods,orbothabstract and concrete methods. If any class hasan abstract method,itis compulsorytodefine the classasabstract. We cannotcreate an instance of abstractclass.Hence the instance membersof abstractclasscannotbe referred. The subclassof abstract classalso must be abstract until andunlessitimplementsall the abstract methodof the inheritedsuperclass. Abstractmethodsare usedto specifymandatorybehaviorinsubclass.Subclassmustimplement abstract methodsotherwisetheyneedtobe declaredasabstract as well.
  • 29. 29 We can achieve generalizationbyusingabstractclass.Definingcommonbehaviorforsubclassesis knownas generalization. 7. What is interface?Howdoesitdifferfromabstractclass? An interface isacollectionof abstractmethods.A classimplementsaninterface therebyinheritingthe abstract methodsof the interface. An interface onlyhasabstractmethodswhile anabstractclasscan have abstract as well asconcrete methods. We cannotinstantiate aninterface,while we candoso withabstractclass. An interface doesnothave anyconstructors. An interface cannotbe extendedby aclass,it can onlybe implemented. An interface canextendmultiple interfaces. Classcan extendonlyone class;however,interfacescanimplementmultipleinterfaces. 8. What is typecastinginJava.Explaindatatype castingandclasstypecasting. Castingone type of informationtoanothertype of informationisknownastype casting.There are two typesof typecasting: a. Datatype casting b. Classtype casting In datatype casting,we can cast data type to another. There are two typesof data type casting: Narrowing Widening Whena lowerdatatype iscastedto a higherdatatype,itisknownas widening. A compilercanimplicitlydowidening. Ex an intcan be typecastedintodoubleimplicitlybycompiler. Whena higherdatatye iscastedintoa lowerdatatype,itisknownasnarrowing.Itneedstobe done explicitly. Ex double iscastedtoint. Castingone classtype to anotherisknownas class type casting. A classcastingis possible onlyif the classesare havingIs-A relationship. There are twotypesof casting: a. Upcasting b. Downcasting
  • 30. 30 Castingsubclassobjecttosuperclasstype isknownasupcasting.Subclassobjectbehavesassuperclass. It will notshowthe propertiesof subclass. Castingsuperclasstype tosubclasstype isknownasdowncasting.Downcastingispossibleonlyif the objectisupcasted. Q:singletoninselenium: public class WebDriverSingleton { public static WebDriver driver; public static WebDriver getInstance() { if (driver == null) { driver = new FirefoxWebDriver(); } return driver; } } 10. What ispolymorphism?Explainhowtoachieve polymorphismwithexample. An objectshowingdifferentbehavioratdifferentstagesof itslifecycleisknownaspolymorphism. There are twotypesof polymorphism: Compile time polymorphism:Whenthe methoddeclarationisbindedtomethoddefinitionbycompiler, it isknownas compile time polymorphism. Whenthe methoddeclarationisbindedtomethoddefinitionatthe time of objectcreationbyJVMat runtime,itisknownas runtime polymorphism. To achieve polymorphism,three thingsare needed: Inheritance MethodOverriding Up Casting Example : Interface Demo { Voiddisp(); Voidprint(); } ClassSample implementsdemo { Voiddisp() { Sop (“inside disp”); }
  • 31. 31 Voidprint() { Sop(“insideprint”); } } PublicclassMClass { Psvm { Demod; D = newsample(); d.disp(); d.print(); } } 11. What isabstractionand howto achieve it? Abstractionisthe processof hidingthe implementationof classfromitsusage. It definesthe functionalityof the objectbutdoesnotdefineinwhichclassthe implementationisdone. To achieve abstractionwe needtodothe following: a. Generalize the behaviorof the classesinaninterface. b. Implementthe behaviorinthe subclass c. Create a ref variable of interface anduse itto create objectsof subclass By usingabstraction,we achieve loosecouplingbetweenimplementationandusage. Loose couplingwill have three layers: a. ImplementationLayer - where the objectbehaviorisdefined b. ObjectcreationLayer– where the objectIscreated c. Objectutilization –where the behaviorof objectusedwithoutknowingthe objectcreated 12. What isencapsulation? Encapsulationisthe processof binding the memberstoitsclassor interface. Memberscannotbe accessedwithoutusingclassname orinterface name.The membersof aclasscan be restrictedupto 4 levels: a. Private b. Package c. Protected d. Public In Private level,the memberscanbe accessed withinaclass.The private membershave the lowest visibility
  • 32. 32 Package level memberscanbe accessedacrossany classin the package.It cannotbe accessedfrom outside the package Protectedlevelmembershave the visibilitytill package level howevertheycanbe accessedfromoutside usinginheritance. Publicmemberscanbe accessedfromanywhere.Ithasmore visibilitythananyotheraccessspecifier. 13. Can a constructor be declaredasprivate? Yes.To protect itfrom beingsubclassed.Noclass can extenditbecause thentheycannotcall super(); Also, tohave a control oninstantiationof anobjectof the class. 14. Differencebetweenpackage level andprotectedlevelaccessspecifier? Package level hasvisibility uptopackage and noone from outside itcanaccess it.Protectedmembers have visibility uptopackage level butcanbe accessedfromoutside usinginheritance. 15. Explainthe featuresof Stringclassandwhatis immutable? Newoperatorisnot requiredto create an objectof Stringclass.Whenthe stringis declaredusing double quotesJVMcreatesanobject. In Java,there isno datatype tostore stringsinsteaditprovidesaclassbythe name String tohandle a set of characters Stringclassis a memberof java.langpackage In String,objectscanbe createdusingtwo ways: a. Usingnewoperator b. Usingdouble quotes(““ ) ; Stringclassis a final class,itcannot have subclasses It isan immutable class.Anyobjectwhose valuecannotbe changedaftercreationisknownas immutable. Once we assigna value toa stringobject,we cannotreassignit.If we try to reassignit,it will notmodify the objectbut create a newone. 16. What isan array inJava? Explaintypesof array. An array isa collectionof similartypesof elementswhereeachelementisstoredcontinuouslyinthe memory. Theyare referredthroughitsindex.Index rangesfrom0to length-1 There are twotypesof arrays: a. Primitive b. Reference
  • 33. 33 Array of primitive type storesthe primitive datatypeswhile arrayof reference type isusedtostore objectsof the class.An array of reference type will alwayshave addressof the objects. If we declare anarray of objectclass,itcan holdany type of java objectinit. It has followinglimitation: a. Size isrestricted/limited b. Array isusedto store onlysimilartypesof elements c. Array lengthwill notreturnthe exactnumberof elementsstoredinarraybutwill returnthe total memoryinitialized. 17. What iscollectionAPI?Whyisitused? Collectionsare usedtostore anytype of data objects.The size of collectionsgrowsdynamicallyatthe run time. Collectionsreturnsthe exactnumberof objectsstoredinitandnot the memoryallocated. Each elementstoredincollectionare castedintoobjecttype. Whenwe retrieve objectfromcollection, it still isinobjecttype andwe needtodowncastit to use the features. 3 types: set,queue,list 18. Explainfeaturesof list,queue,set. a. List : It storesanytypesof elements a. Elementsare all indexed b. Referselementsbyusingindex c. Duplicate andnull elementsare allowed b. Queue : It isalsoa type of collectionandstoresanytypesof elements Elementsare storedwithoutindex TheyfollowFIFO Duplicatesare allowedbutnull isnotallowed Java haspriorityqueue where peekmethodisusedtoretrievethe header while poll methodis usedto retrieve andremove the headerelement c. Set: Itstoresany typesof elements Elementsare notindexed Duplicatesare notallowed Null isallowed Elementsare retrievedusingIterator 19. What ismap? How isit differentfromothercollections? Elementsare storedinkeyvalue pair Keycan be any object Value canbe anyobject Keyshouldbe unique Keyismappedto value andisusedas an index. 20. What isa linkedlist?Explainitsfeatures.
  • 34. 34 The linkedlistclassimplementsthe listinterface.Ithastwoconstructorsone isthe defaultone which buildsanemptylinkedlist. It acts both as a listas well asqueue LinkedList() Secondisa linkedlistthatisinitializedwiththe elementsof collectionc LinkedList(Collectionc) LinkedListhasvariousmethodslike add,remove,poll,peek,getfirst,getlast,etc 21. Differencebetweensetandqueue andlist? Null :List, Set Duplicates:List,Queue Index :List In queue(),elementsare retrievedusingpeekorpoll method,whileinsetelementsare retrievedusing iterator 22. What isiterator?Explainitsbehaviorandwhenitshouldbe used? We needtocreate an iteratorobjectto accessset elements. It has 3 methods: Next() – getsthe nextelementinset hasNext() –checksif nextelementexistsornot remove() - removesthe currentelement 23. What isexception?Whentouse exceptioninjava? An exceptionisanerror which occursduringruntime of program that disruptsthe normal flow of the program. An exceptioncanbe due to variousof reasonslike incorrectuserinput, file notfound,etc. There are twotypesof exceptions: a. Checkedexception:These kindsorexceptionsare checkedatcompile time bycompiler.The compilerforcesustohandle the exceptionoritmustspecifythe exceptionusingthrows keyword. b. Uncheckedexception: Uncheckedexceptionsare the onesthatare notcheckedat compile time sowe are not forcedto handle orspecifythe exception In java,undererrorand runtime exceptions,theyare uncheckedexceptionsrestall are checked exceptions. 24. What isspecificexceptionandgenericexceptionhandler?Whenshouldwe use both? Base class of exceptionhierarchydoesnotprovide anyspecificinformationaboutthe error.Thatiswhy Exceptionclasshasmanysubclasseslike IOExceptionetc.We shouldalwaysthrow specificexceptionsso that the callerwill knowthe rootcause of the error andalsodebuggingbecomeseasy.
  • 35. 35 Whenwe are unsure if anyexceptionsmightoccur,inthatcase we coulduse genericexceptions. 25. What ischeckedand uncheckedexception? a. Checkedexception:Thesekindsof exceptionsare checkedatcompile time bycompiler. The compilerforcesustohandle the exceptionoritmustspecifythe exceptionusingthrows keyword. b. Uncheckedexception: Uncheckedexceptionsare the onesthatare notcheckedat compile time sowe are not forcedto handle orspecifythe exception 26. Differencebetweenthrow,throwsandthrowable. Throwable isthe superclassforerrorsandexceptionswhile throw andthrowsare keywords. Throwsis a postmethodmodifierwhichspecifieswhichkindof exceptionsmaybe thrownbythe method. Throw isusedto throwan exceptionandrequiresasingle argumentwhichisaninstance of Throwable or its subclass. 27. What isstream?Explaintypesof stream. Streamsrepresentaninputsource andan outputdestinationinJava.A streamcan be defined asa sequence of data.There are two typesof streams: a. Inputstream b. Outputstream. Inputstreamis usedtoread the data fromthe source while the outputstreamisusedtowrite the data to the destination.The outputstreamwritestothe destinationat one characterat a time. 29. Differencebetweenstaticandinstance objects? Staticmembersare not a part of object;however, instance variablesare partof object. Staticmembershave onlysingle copyof theminthe memory,howeverinstance variablescanhave multiple copiesof theminthe memory. To use the instance variable,we needtocreate areference of anobject. 30. What isprimitive variable andreference variable? In java,there are two typesof variables,namelyprimitive variable andreference variable. Primitive variablesare usedtostore primitive dataandisdeclaredusingdatatype. Reference variable are declaredusingclassorinterface name.Itisusedto store an objectof a class. 31. What isa constructor?Why isit required?
  • 36. 36 Constructorsare usedtocreate an instance of the class.OR constructoris a bitof code that allowsusto create an objectof the class. There are twotypesof constructorsi.e.defaultconstructorandparameterizedconstructor. Defaultconstructorsdonot have anyargumentswhile parameterizedconstructorscanhave one or more than one argument. If there is noconstructor definedinaclass,the compilercallsthe defaultconstructorimplicitly. 32. What isa defaultconstructorandwhen isitcreated? In absence of the constructorsthat a programmerexplicitlycreates,the compilerimplicitlycreatesa defaultconstructorwithzeroparametersandinitializesall the instance variablestodefaultvalues. 33. What isconstructor overloading? Constructoroverloadingallowsustohave more than one constructorina classwithdifferent arguments. Once we explicitlyprovideconstructortoa class,compilerwill notadddefaultconstructortothe class. 34. What isuse of ‘this’keyword inJava? Withinaninstance methodora constructor,thiskeywordpointstothe currentobjectbeingcalled. OR It isa reference variable thatpointstothe currentobject. 35. Why doesJavanot supportmultiple inheritances? a. Subclass constructorcannot have more thanone super(); b. The objectclass memberscannotbe inheritedintothe subclassinmore thanone pathwith differentdefinitionssince itwill create ambiguity.Itisalsoknownasdiamondproblem. 36. What isthe difference betweenthisandsuper? Thisis usedtoreferto the current object,while superisusedtocall the constructor of superclass. Superiscalledimplicitlyif itisnotcodedbyprogrammerwhile itisnot the case withthis(). 37. What isconstructor chaining?Whenithappens? Callinganotherconstructorof same classfrom anotherconstructoriscalledconstructorchaining.We use this() toachieve constructorchaining. 38. Differencebetweenmethodsandconstructors?
  • 37. 37 40. Thiskeyword Thisis a keywordusedtoaccessnon-staticmembersof the class. Thisis alsousedto call otherconstructorsof the same class. Call to Thismust be the firststatementinsidethe constructor. Eg. ClassBox { Int width; Stringcolour; Box(intw,Stringc) {width=w; Colour=c;} Box(intw) {this(w) Colour=c} } Voidprint() { SOP(w); SOP(c); } Classrun {PSVM() { Box b1=new Box(4); B1.print(); Box b2=new Box(10,”green”); B1.print(); } } OUTPUT: 4 Null 10 green -------------------------------------------------------------------------------------------------------------------------------------------------------- Q. SQL : Inner join query SELECT table1.column1, table2.column2... FROM table1 INNER JOIN table2 ON table1.common_field = table2.common_field; Difference between drop, truncate and delete –> DELETE: 1. Removes Some or All rows froma table,WHERE clause can be used.Canbe rolledback
  • 38. 38 > TRUNCATE: 1. Removes All rowsfroma table,Nowhere clause canbe used.,cannotbe rolledback DROP Commandremovesatable fromthe database.All the tables'rows,indexesandprivilegeswill alsobe removed.NoDML triggerswill be fired.The operationcannotbe rolledback. 1. Create test data for checkout page of a ecommerce website. (Vlocity) 2. Create a test plan for whatsapp group (Amazon) 3. Create test data for a zomato likeapp where top 3 restaurants arelisted in the 5 km vicinity.Filters arefood type and pincodeand GPS Coordinates (Amazon) 4. Explainingmostdifficulttestingrelated problem that occurred in your projectand how did you solveit. (Groupon) Q Rest assured advantages: Rest-Assured isaJavabasedDSL (DomainSpecificLanguage) whichismostcommonlyusedtotestout REST basedservices.Rest-Assuredpresentsagreatadvantage because itsupportsmultiple HTTP requestsandcan validate and/orverifythe responsesof these requests.Thesemultiple requestsinclude GET, POST,PUT, DELETE, PATCH,OPTIONSandHEAD methods.Giventhatitsupportsthese various requests,italsoallowsforthemtobe constructedwithmultipleparameters,headers,andtheir respective body,aswell asvalidatingresponse’sstatuscode,headers,cookiesandresponse time. https://gorillalogic.com/blog/automation-testing-part-2-api-testing-rest-assured/ Hashmap Factorisation Q:Types of authentication in api testing : OAuth2.0, OAuth1.0, Q:PUT vs. POST in REST We use Modify HeaderValue (HTTPHeaders) ,tool usedModifyHeaderValue,headername iv-user,headervalue archanasingh What isAuthenticationandHow doesAuthenticationworksinRESTWebServices Q:Authentication Authentication is a process to prove that you are the person who you intend to be. http://toolsqa.com/rest-assured/authentication-authorization-rest-webservices/ Filehandling..2 file..fetch value Q:static import in java Static import. Static import is a feature introducedinthe Javaprogramminglanguage thatallows members(fieldsandmethods) definedinaclassas public static to be usedin Java code;without specifyingthe classinwhichthe fieldisdefined.Thisfeature wasintroducedintothe language inversion 5.0. Q:What is a Wrapper class
  • 39. 39 As we are not able to use Primitive Data Types as objects directly in Java Programming language, we can use Wrapper Class to wrap the Primitive Data Types into objects. Hence Wrapper Classes are used, to wrap the primitive type into an object, so that we can use the Primitive Data Type as an object. Wrappermethods The solutiontothisproblemliesinusingwrappermethodsforthe standardSeleniummethods.So insteadof doingthiseverytime Ineedtoperforma click: ? (new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(By.id("loginButton"))); driver.findElement(By.id("loginButton")).click(); I have created a wrapper method click() in a MyElements class that looks like this: ? public static void click(WebDriver driver, By by) { (new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(by)); driver.findElement(by).click(); } Of course, the 10 second timeout is arbitrary and it’s better to replace this with some constant value. Now, every time I want to perform a click in my test I can simply call: ? MyElements.click(driver, By.id("loginButton"); which automatically performs a WebDriverWait, resulting in much stabler, better readable and maintainable scripts. Ex: Extending your wrapper methods: error handling Using wrapper methods for Selenium calls has the additional benefit of making error handling much more generic as well. For example, if you often encounter a StaleElementReferenceException (which those of you writing tests for responsive and dynamic web applications might be all too familiar with), you can simply handle this in your wrapper method and be done with it once and for all:
  • 40. 40 ? public static void click(WebDriver driver, By by) { try { (new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(by)); driver.findElement(by).click(); catch (StaleElementReferenceException sere) { // simply retry finding the element in the refreshed DOM driver.findElement(by).click(); } } Q: How to clonean object in java The clone() methodof Objectclassis usedto clone an object.The java.lang.Cloneable interface mustbe implementedbythe classwhose objectclone we wantto create.If we don'timplementCloneable interface, clone() methodgeneratesCloneNotSupportedException.The clone()methodisdefinedinthe Objectclass. Q: Unboxing and Autoboxing in java Comparable vs Comparator in Java Java provides two interfaces to sort objects using data members of the class: 1. Comparable 2. Comparator Using Comparable Interface A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release. We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface. 8.3 2015 Now, suppose we want sort movies by their rating and names also. When we make a collection element comparable(by having it implement Comparable), we get only one chance to implement the compareTo() method. The solution is using Comparator.
  • 41. 41 Using Comparator Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members. Collections class has a second sort() method and it takes Comparator. The sort() method invokes the compare() to sort objects. To compare movies by Rating, we need to do 3 things : 1. Create a class thatimplementsComparator(andthusthe compare() methodthatdoesthe work previouslydonebycompareTo()). 2. Make an instance of the Comparatorclass. 3. Call the overloadedsort() method,givingitboththe listandthe instance of the class that implementsComparator.  Comparable ismeantfor objectswithnatural orderingwhichmeansthe objectitself mustknow how it is to be ordered. For example Roll Numbers of students. Whereas, Comparator interface sorting is done through a separate class.  Logically, Comparable interface compares “this” reference with the object specified and Comparator in Java compares two different class objects provided.  If any class implementsComparable interface inJavathen collectionof that objecteitherListor Array can be sortedautomaticallybyusingCollections.sort() orArrays.sort() methodandobjects will be sorted based on there natural order defined by CompareTo method. To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.