String interview Questions
What is String in java?
- Generally, string is a sequence of characters. But in java,string is an object that represents a sequence of characters.
The java.lang.String class is used to create string object.
- Java String comparesion?
- There are three ways to compare string in java:
- By equals() method
- By == operator
- By compareTo() method
- compareTo() uses unicode based comparision on decimal value.
public class CompareToExample2{
public static void main(String args[]){
String s1="hello"; // h decimal value 104
String s2="";
String s3="me";
System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s3));
}
}
Output:- 5
-2
--*****************************************************************************************************************
1- Armstrong Number
import java.util.*;
public class armstrongNumber{
public void checkArmstrongNumber(int n){
int c=0,a,temp;
//int n=100 ;//It is the number to check armstrong
temp=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(temp==c)
System.out.println(temp+" is a armstrong number");
else
System.out.println(temp+" is not a armstrong number");
}
public static void main(String[] args) {
armstrongNumber arm= new armstrongNumber();
arm.checkArmstrongNumber(103);
}
}
-------------------------------------------------------------------------------------------
2- Fibonacci Series
import java.util.*;
public class fabonnacciSeries{
public void getFabonnacciSeries(int maxLimit){
int i, n1=0,n2=1,n3=0,temp;
System.out.println("Fabonnacci Series for given numbers "+ maxLimit);
System.out.print(n1 +" "+ n2);
for (i=2; i<=maxLimit; ++i){
n3=n1 + n2;
System.out.print(" "+ n3);
n1=n2;
n2=n3;
}
}
public static void main(String[] args) {
fabonnacciSeries fab= new fabonnacciSeries();
Scanner scan= new Scanner(System.in);
System.out.println("Enter number to get Fabonnacci Series : ");
int limit = scan.nextInt();
fab.getFabonnacciSeries(limit);
}
}
----------------------------------------------------------------------------------------
3- Factorial Number
import java.util.*;
public class factorialNumber{
public void getfactorialNumber(int maxLimit){
int i, fact=1;
for (i=1; i <= maxLimit; i++){
fact = fact*i;
}
System.out.println("Factorial of "+maxLimit+" is: "+fact);
}
public static void main(String[] args) {
factorialNumber fact= new factorialNumber();
Scanner scan= new Scanner(System.in);
System.out.print("Enter number to get Factotial : ");
int limit = scan .nextInt();
fact.getfactorialNumber(limit);
}
}
Using recursion:
class FactorialExample2{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int i,fact=1;
int number=4;//It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}
----------------------------------------------------------------------------------------
4- Prime Number (1 to maxLimit)
// get prime no between two limit like 1 to 100
import java.util.*;
public class primeNoCheck{
// function to check number is prime b/w 2 limit
public void getPrimeNoWithLimit(int minLimit,int maxLimit){
int i,j;
System.out.println("All prime number between "+minLimit+" to "+maxLimit+" is : ");
for (i=minLimit; i<=maxLimit; i++){
boolean isPrime=true;
for(j=2; j<i; j++){
if(i%j==0){
isPrime=false;
break;
}
}
if(isPrime){System.out.print(i+" ");}
}
System.out.println("\n ");
}
// function to check no is prime or not
public boolean isPrimeNumber(int number){
for(int i = 2; i<= number/2; i++){
if (number%i==0){
return false;
}
}
return true;
}
public static void main(String [] arg){
Scanner scan1 = new Scanner(System.in);
System.out.println("Enter minlimit : ");
int minlimit= scan1.nextInt();
System.out.println("Enter maxlimit : ");
int maxlimit= scan1.nextInt();
primeNoCheck p= new primeNoCheck();
p.getPrimeNoWithLimit(minlimit,maxlimit);
System.out.println(" Is "+maxlimit +" is prime ?: "+ p.isPrimeNumber(maxlimit));
}
}
----------------------------------------------------------------------------------------
5- Palindrome Number
import java.io.*;
import java.util.*;
public class palindromeNumber{
public static void main(String arg[]) throws Exception {
int num =1234543201;
int number = num;
int revNum = 0;
int temp=0;
while(number> 0){
temp = number % 10;
number = number / 10;
revNum = revNum * 10 + temp;
}
if(num == revNum)
System.out.println(num + " is a palindrome number");
else
System.out.println(num + " is not a palindrome number");
}
}
Q: Palindrome check string is palindrome or not using Stack?
import java.util.*;
public class palindrome {
public void palindromeStringBuffer(String str){
StringBuffer strBuff = new StringBuffer(str);
StringBuffer strBuffRev = new StringBuffer(str);
strBuffRev.reverse();
int str2Len =strBuffRev.length();
System.out.println("Rev String Is : "+strBuffRev+ " and length is : "+str2Len);
if(strBuff.toString().equals(strBuffRev.toString())){System.out.println("Enter String is palindrome");}
else{System.out.println("Enter String is not palindrome"); }
}
public void palindromeStack(String str){
Stack stack = new Stack();
for(int i=0; i< str.length(); i++){
stack.push(str.charAt(i));
}
String revStr="";
while(!stack.isEmpty()){
revStr=revStr+stack.pop();
}
System.out.println("Rev String Is : "+revStr+ " and length is : "+revStr.length());
if(str.equals(revStr)){System.out.println("Enter String is palindrome");}
else{System.out.println("Enter String is not palindrome"); }
}
//Using for loop/While loop and String function charAt
public void palindromeCheck(String str){
String revStr="";
int len=str.length();
for(int i = len - 1 ; i >= 0 ; i--){
revStr = revStr + str.charAt(i);}
System.out.println("Rev String Is : "+revStr+ " and length is : "+revStr.length());
if(str.equals(revStr)){System.out.println("Enter String is palindrome");}
else{System.out.println("Enter String is not palindrome"); }
}
public static void main(String []arg){
System.out.println("Enter String or Number to check palindrome: ");
Scanner scan = new Scanner(System.in);
String inputString = scan.nextLine();
int len =inputString.length();
System.out.println("Input String Is : "+inputString+ " and length is : "+len);
palindrome pa= new palindrome();
System.out.println("\nPalindrome check using String Buffer");
pa.palindromeStringBuffer(inputString);
System.out.println("\nPalindrome check using Stack");
pa.palindromeStack(inputString);
System.out.println("\nPalindrome check. using String Function charAt() ..\n");
pa.palindromeCheck(inputString);
}
}
----------------------------------------------------------------------------------------
Java String Interview Questions:
String Function in Java Example:
A) Java String charAt:
-The java string charAt() method returns a char value at the given index number. The index number starts from 0.
-Syntex: public char charAt(int index)
String name="javatpoint";
char ch=name.charAt(4);
output: t
B) Java String compareTo:
-The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0.
s1.compareTo(s2));
s1 > s2 => positive number
s1 < s2 => negative number
s1 == s2 => 0
C) Java String concat():
-The java string concat() method combines specified string at the end of this string. It returns combined string. It is like appending another string.
String s1="java string";
s1.concat("is immutable");
o/p: java string is immutable
D) Java String contains():
-The java string contains() method searches the sequence of characters in this string. It returns true if sequence of char values are found in this string otherwise returns false.
-public boolean contains(CharSequence sequence)
String name="what do you know about me";
System.out.println(name.contains("do you know")); // true
System.out.println(name.contains("about")); // true
System.out.println(name.contains("hello")); // false
E) Java String endsWith():
-The java string endsWith() method checks if this string ends with given suffix. It returns true if this string ends with given suffix else returns false.
-public boolean endsWith(String suffix)
String s1="java by javatpoint";
System.out.println(s1.endsWith("t")); //true
System.out.println(s1.endsWith("point")); //true
System.out.println(s1.endsWith("point0")); //false
F) Java String startsWith():
-The java string startsWith() method checks if this string starts with given prefix. It returns true if this string starts with given prefix else returns false.
-public boolean startsWith(String prefix)
G) Java String equals():
-The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.
-The String equals() method overrides the equals() method of Object class.
str1.equals(str2);
H) Java String format():
-The java string format() method returns the formatted string by given locale, format and arguments.
-If you don't specify the locale in String.format() method, it uses default locale by calling Locale.getDefault() method.
-The format() method of java language is like sprintf() function in c language and printf() method of java language.
-public static String format(String format, Object... args)
and,
-public static String format(Locale locale, String format, Object... args)
String name="sonoo";
String sf1=String.format("name is %s",name); // name is sonoo
String sf2=String.format("value is %f",32.33434); //value is 32.334340
String sf3=String.format("value is %32.12f",32.33434);// value is 32.334340000000 returns 12 char fractional part filling with 0
I) Java String getBytes():
-The java string getBytes() method returns the byte array of the string. In other words, it returns sequence of bytes.
-public byte[] getBytes()
-public byte[] getBytes(Charset charset)
-public byte[] getBytes(String charsetName)throws UnsupportedEncodingException
String s1="ABCDEFG";
byte[] barr=s1.getBytes();
for(int i=0;i<barr.length;i++){
System.out.println(barr[i]);
}
o/p: print 65 66 67 68 69 70 71
J) Java String indexOf():
-The java string indexOf() method returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.
-int indexOf(int ch) returns index position for the given char value
-int indexOf(int ch, int fromIndex) returns index position for the given char value and from index
-int indexOf(String substring) returns index position for the given substring
-int indexOf(String substring, int fromIndex) returns index position for the given substring and from index
String s1="this is index of example";
int index1=s1.indexOf("is"); //returns the index of is substring
int index2=s1.indexOf("index");//returns the index of index substring
System.out.println(index1+" "+index2); //2 8
//passing substring with from index
int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index
System.out.println(index3); //5 i.e. the index of another is
//passing char value
int index4=s1.indexOf('s');//returns the index of s char value
System.out.println(index4); //3
K) Java String intern():
-The java string intern() method returns the interned string. It returns the canonical representation of string.
-It can be used to return string from pool memory, if it is created by new keyword.
String s1=new String("hello");
String s2="hello";
String s3=s1.intern();//returns string from pool, now it will be same as s2
System.out.println(s1==s2);//false because reference is different
System.out.println(s2==s3);//true because reference is same
L) Java String isEmpty():
-The java string isEmpty() method checks if this string is empty. It returns true, if length of string is 0 otherwise false.
-The isEmpty() method of String class is included in java string since JDK 1.6.
str.isEmpty();
M) Java String join():
-The java string join() method returns a string joined with given delimiter. In string join method, delimiter is copied for each elements.
-In case of null element, "null" is added. The join() method is included in java string since JDK 1.8.
-public static String join(CharSequence delimiter, CharSequence... elements)
and
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
String joinString1=String.join("-","welcome","to","javatpoint"); // welcome-to-javatpoint
N) Java String lastIndexOf():
-The java string lastIndexOf() method returns last index of the given character value or substring. If it is not found, it returns -1. The index counter starts from zero.
String s1="this is index of example";//there are 2 's' characters in this sentence
int index1=s1.lastIndexOf('s');//returns last index of 's' char value
o/p: 6
O) length():
-The java string length() method length of the string. It returns count of total number of characters. The length of java string is same as the unicode code units of the string.
P) Java String replace():
-The java string replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence.
String s1="javatpoint is a very good website";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
o/p: jevetpoint is e very good website
-Java String replace(CharSequence target, CharSequence replacement) method example
String s1="my name is khan my name is java";
String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"
Q) Java String replaceAll():
-The java string replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.
-public String replaceAll(String regex, String replacement)
example same as replace
-Java String replaceAll()
example: remove white spaces
String s1="My name is Khan. My name is Bob. My name is Sonoo.";
String replaceString=s1.replaceAll("\\s",""); // MynameisKhan.MynameisBob.MynameisSonoo.
qs: replace all special char wih space:
String str="/-+!@#$%^&());:[]{}'\' |wetyk 678dfg LPOI";
String result = str.replaceAll("[^\\dA-Za-z ]", "").replaceAll("\\s", "+");
\d: capture digits
\D: represents any non-digit character
\s: whitespace
\S: non-whitespace character
\w: alphanumeric letters and digits
\W: non-alphanumeric character (such as punctuation)
\b: which matches the boundary between a word and a non-word character
\w+\b: capturing entire words
^: not seletcted (skip char using regex)
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(abc|def) Matches abc or def
R) Java String split():
-The java string split() method splits this string against given regular expression and returns a char array.
-public String split(String regex)
and,
public String split(String regex, int limit)
String s1="java string split method by javatpoint";
String[] words=s1.split("\\s");//splits the string based on string
for(String w:words){ //using java foreach loop to print elements of string array
System.out.println(w);
}
// print all word with new line
for(String w:s1.split("\\s",2)){
System.out.println(w);
}
o/p: java
string split method by javatpoint
-String str = "jan-feb-march";
String[] temp;
String delimeter = "-";
temp = str.split(delimeter);
for(int i =0; i < temp.length ; i++){
System.out.println(temp[i]);
} //o/p: jan feb march with new line
S) Java String substring():
-The java string substring() method returns a part of the string.
-public String substring(int startIndex) and public String substring(int startIndex, int endIndex)
String s1="javatpoint";
System.out.println(s1.substring(2,4));//returns va
System.out.println(s1.substring(2));//returns vatpoint
T) Java String toCharArray():
-The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
-public char[] toCharArray()
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
}
// o/p: hello
U) Java String trim():
-The java string trim() method eliminates leading and trailing spaces. The unicode value of space character is '\u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.
-
String s1=" hello string ";
System.out.println(s1+"javatpoint");//without trim() // ' hello string javatpoint'
System.out.println(s1.trim()+"javatpoint");//with trim() // 'hello stringjavatpoint'
V) Java String valueOf():
-The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.
-public static String valueOf(boolean b)
-public static String valueOf(char c)
-public static String valueOf(char[] c)
-public static String valueOf(int i)
-public static String valueOf(long l)
-public static String valueOf(float f)
-public static String valueOf(double d)
-public static String valueOf(Object o)
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
//o/p: 3010
--**************************
/**
* Java Program to parse String to Enum in Java with examples.
*/
public class EnumTest {
private enum LOAN {
HOME_LOAN {
@Override
public String toString() {
return "Always look for cheaper Home loan";
}
},
AUTO_LOAN {
@Override
public String toString() {
return "Cheaper Auto Loan is better";
}
},
PEROSNAL_LOAN{
@Override
public String toString() {
return "Personal loan is not cheaper any more";
}
}
}
public static void main(String[] args) {
// Exmaple of Converting String to Enum in Java
LOAN homeLoan = LOAN.valueOf("HOME_LOAN");
System.out.println(homeLoan);
LOAN autoLoan = LOAN.valueOf("AUTO_LOAN");
System.out.println(autoLoan);
LOAN personalLoan = LOAN.valueOf("PEROSNAL_LOAN");
System.out.println(personalLoan);
}
}
Output:
Always look for cheaper Home loan
Cheaper Auto Loan is better
Personal loan is not cheaper anymore
Read more: http://javarevisited.blogspot.com/2011/12/convert-enum-string-java-example.html#ixzz48ZJjWAbz
--*********************************************************************************************************************************************
0- difference b/w a==b,a.equals(b),a.compareTo(b),compare(a, b)?
a==b:
== object reference equality (whether they are the same object)
== handles null strings fine.
a.equals(b):
value equality (whether they are logically "equal").
null string will cause an exception.
a.compareTo(b):
Comparable interface.
Compares values and returns an int which tells if the values compare less than, equal, or greater than.
This is implemented as part of the Comparable interface,
compare(a, b):
Comparator interface.
Compares values of two objects. This is implemented as part of the Comparator interface,
work with sort() method.
1- how can compare string? Use "==" or use equals()?
http://www.leepoint.net/data/expressions/22compareobjects.html
a) == handles null strings fine, but .equals() from a null string will cause an exception:
String nullString1 = null;
String nullString2 = null;
nullString1 == nullString2; // Evaluates to true
nullString1.equals(nullString2); // Throws an Exception
b) == tests for object reference equality (whether they are the same object). & .equals() tests for value equality (whether they are logically "equal").
String a="Test";
String b="Test";
if(a==b) //--- true
String a="test";
String b=new String("test");
if (a==b) //--- false
--------------------------------------
While .equals() always compares value of String so it gives true in both cases
String a="Test";
String b="Test";
if(a.equals(b)) ===> true
String a="test";
String b=new String("test");
if(a.equals(b)) ===> true
So using .equals() is awalys better.
// These two have the same value
new String("test").equals("test") ==> true
// ... but they are not the same object
new String("test") == "test" ==> false
// ... neither are these
new String("test") == new String("test") ==> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" ==> true
// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st" ==> true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false
// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
You almost always want to useObjects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.
2- why is char[] preferred over String for security sensitive information? or What is the biggest difference between a String and a Character Array in Java?
Strings are immutable, which means once they are created, they will stay unchanged until Garbage Collector kicks in. With an array, you can explicitly change its elements. In this way, security sensitive information(e.g. password) will not be present anywhere in the system.
Immutability of Strings:-
Strings in Java are immutable(i.e. once created we can not change its value) and it also uses the String Pool concept for reusability purpose, hence we are left with no option to clear it from the memory until GC clears it from the memory. Because of this there are great chances that the object created will remain in the memory for a long duration and we can’t even change its value. So anyone having access to the memory dump can easily retrieve the exact password from the memory. For this we can also use the encryption techniques so that if someone access then he will get the encrypted copy of the password.
But with character array you can yourself wipe out the data from the array and there would be no traces of password into the memory.
Accidental printing to logs:-
Along with the memory dump protection storing passwords in Strings also prevent accidental logging of password in Text files, consoles, monitors and other insecure places. But in the same scenario char array is not gonna print a value same as when we use toString() method.
public class PasswordSecurityExample {
public static void main(String[] args) {
String password = "password";
char[] password2;
System.out.println("Printing String -> " + password);
password2 = password.toCharArray();
System.out.println("Printing Char Array -> " + password2);
}
}
Recommendation by Java itself:-
Java itself recommends the use of Char Array instead of Strings. It is clear from the JPasswordField of javax.swing as the method public String getText() which returns String is Deprecated from Java 2 and is replaced by public char[] getPassword() which returns Char Array.
3- Can we use string for switch statement?
Yes to version 7. From JDK 7, we can use string as switch condition. Before version 6, we can not use string as switch condition.
//in java 7 only!
switch (str.toLowerCase()) {
case "a":
value = 1;
break;
case "b":
value = 2;
break;
}
4.1- How can convert string to int in Java?
int i = Integer.parseInt("10");
4.2- How can convert int to string in java?
-using Integer.toString(int):
int number = -782;
String numberAsString = Integer.toString(number);
-using String.valueOf(int):
String numberAsString = String.valueOf(-782);
-using new Integer(int).toString():
String numberAsString = new Integer(-782).toString();
-using String.format():
public static String format(String format, Object... args)
String numberAsString = String.format ("%d", -782);
-using StringBuffer or StringBuilder:
StringBuffer is a class that is used to concatenate multiple values into a String. StringBuilder works similarly but not thread safe like StringBuffer.
String numberAsString = new StringBuffer().append(-782).toString();
String numberAsString = new StringBuilder().append(-782).toString();
-using DecimalFormat:
The class java.text.DecimalFormat is a class that formats a number to a String representation following a certain pattern.
Example:
int number = 12345;
DecimalFormat decimalFormat = new DecimalFormat("#");
String numberAsString = decimalFormat.format(number);
System.out.println(numberAsString);
Output:- 12345
int number = 12345;
DecimalFormat decimalFormat = new DecimalFormat("#,##0");
String numberAsString = decimalFormat.format(number);
System.out.println(numberAsString);
Output:- 12,345
5- How to split a string with white space characters?
-Single whitespace:
public class TestConsole {
public static void main(String[] args) {
String sampleString = "Apple Banana Carrot";
String[] animals = sampleString.split(" ");
int animalIndex = 1;
for (String animal : animals) {
System.out.println(animalIndex + ". " + animal);
animalIndex++;
}
}
}
-Multiple White Space:
String str = myString.split("\\s+");
example:
String string = "1-50 of 500+";
String[] stringArray = string.split("\\s+");
for (String str : stringArray) {
System.out.println(str);
}
-other split in java
-split by , (coma)
syntax: public String[] split(String regex)
public static void main(String[] args) {
String sampleString = "Cat,Dog,Elephant";
String[] animals = sampleString.split(",");
System.out.println("The number of animals is: " + animals.length);
for (String animal : animals) {
System.out.println(animal);
}
}
Output: The number of animals is: 3
Cat
Dog
Elephant
-using limit:
syntex: public String[] split(String regex, int limit)
-String[] shapes = "Circle,Square,Rectangle,Hexagon".split(",", 2);
its equals to String[] shapes = {"Circle", "Square,Rectangle,Hexagon"}; its split before 2nd string in String Array
-String[] shapes = "Circle,Square,Rectangle,Hexagon".split(",", 3);
its equals to String[] shapes = {"Circle", "Square", "Rectangle,Hexagon"}; its split before 3nd string starting from String Array
-if we use number 10 more then array element then
String[] shapes = "Circle,Square,Rectangle,Hexagon".split(",", 10);
its equals to : equals to String[] shapes = {"Circle", "Square", "Rectangle", "Hexagon"};
-Regular expression
-String[] items = "abc123def456ghi789".split("\\d+");
This is equivalent to: String[] items = {"abc", "def", "ghi"};
-String[] items = "123abc456def789".split("[a-zA-Z]+");
The equivalent to: String[] items = {"123", "456", "789"};
-Using "\\."
String[] items = "A.B.C".split("\\."); Is equivalent to String[] items = {"A", "B", "C"};
-Using "\\|"
String[] items = "A|B|C".split("\\|"); Is also equivalent to String[] items = {"A", "B", "C"};
-Empty Strings:
-Prefix - when the String starts with the delimiter, the first element becomes empty String.
String[] items = ",A,B,C".split(","); I s equivalent to String[] items = { "", "A", "B", "C" };
-Middle - each additional occurence of the delimiter in the middle of the String will result to a corresponding empty String
String[] items = ",A,B,,,C".split(","); I s equivalent to String[] items = { "", "A", "B", "", "", "C" };
-Suffix - all occurence of the delimiter at the end of the String will be ignored.
String[] items = "A,B,C,,,,,,,,,,".split(","); I s equivalent to String[] items = { "A", "B", "C" };
-However, we can force split to count all extra delimiters at the end of the String by passing -1 as limit:
String[] items = "A,B,C,,,".split(",", -1); I s equivalent to String[] items = { "A", "B", "C", "", "", "" };
6- What substring() method does?
This method is use to create new string using an v existing string
syntax;
public String substring(int beginIndex) or public String substring(int beginIndex, int endIndex)
import java.io.*;
public class Test{
public static void main(String args[]){
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.substring(11) );
System.out.print("Return Value :" );
System.out.println(Str.substring(11, 15) );
}
}
Output:
Return Value :Tutorialspoint.com
Return Value :Tuto
7- String vs StringBuilder vs StringBuffer?
-Java.lang.StringBuffer Class
-String Buffer is:
A string buffer is like a String, but can be modified.
It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
They are safe for use by multiple threads.
Every string buffer has a capacity.
-Java StringBuffer Replace Example:-
StringBuffer sb = new StringBuffer("Hello World");
System.out.println("Original Text : " + sb);
sb.replace(0,5,"Hi");
System.out.println("Replaced Text : " + sb);
Output: Original Text : Hello World Replaced Text : Hi World
8- How to repeat a string?
- using new String:
String str = "abc123";
String repeated = new String(new char[3]).replace("\0", str);
- using repeat():
String str = "abc123";
String repeated = str.repeate(3);
output: abc123abc123abc123
9- How to convert string to date?
import java.io.*;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class StringToDate {
public static void main(String[] args) throws Exception {
String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
}
}
10- How to count # of occurrences of a character in a string?
String Str = new String("Welcome to Tutorialspoint.com! here you can find anything regarding Iterview");
int noOfOccurence = 0;
for (int i =0; i<Str.length();i++){
if(Str.charAt(i)=='i'){
noOfOccurence++;
}
}
System.out.println("No OF Occurence of 'i' is : "+noOfOccurence);
11- Write a method to check if input String is Palindrome?
12- Write a method that remove given charater from String?
public void wordOccurenceRemoveFromString(String Str,char chRemove) throws Exception,IOException {
System.out.println("Orignal String is : "+ Str );
int noOfOccurence = 0;
StringBuilder sb = new StringBuilder();
for (int i =0; i<Str.length();i++){
char ch= Str.charAt(i);
if(ch==chRemove){
continue;
}
sb.append(ch);
}
System.out.println("After remove i from string : "+sb.toString());
}
- 2nd option to remove char from given string (use above function to execute this code)
String word="";
for (int i = 0; i < Str.length(); i++){
if (Str.charAt(i) != chRemove){
word += Str.charAt(i);
}
}
System.out.println("After remove i from string : "+word);
13- How can we make String upper case or lower case?
-UpperCase
str.toUppeCase();
- LowerCase
str.toLowerCase();
14- What is string subScquence method?
- public CharSequence subSequence(int beginIndex,int endIndex) // its begin with 0 to n index
Returns a new character sequence that is a subsequence of this sequence. An invocation of this method of the form
str.subSequence(begin, end)
behaves in exactly the same way as the invocation
str.substring(begin, end)
-Example: String str1="If the memstores in a region are this size or";
str1.subSequence(0,6);
-output: 'If the'
-- str.substring(4, 14) == str.subSequence(4, 14) return false
-- str.substring(4, 14).equals(str.subSequence(4, 14)) return true
15- How to compare two String in java program?
1-By equals() method
2-By = = operator
3-By compareTo() method
-use equals()
String x = "JUNK"; String y = "junk";
if (x.equals(y)) output: Not Equals
-use equalIgnoreCase()
if (x.equalsIgnoreCase(y)) output: Equals
-use compareTo() to get char size wise
str1.compareTo(str2)
String str1 = "Hello World";
String str2 = "hello World";
String str3 = "hello world";
String str4 = new String("Hello World");
Object objStr = str1;
System.out.println( str1.compareTo(str2) ); //-32
System.out.println( str1.compareToIgnoreCase(str2)); //0
System.out.println( str1.compareTo(objStr.toString())); //0
System.out.println(str1.equals(str2)); //false
System.out.println(str1.equals(str3)); //false
System.out.println(str1.equals(str4)); //true
System.out.println(str1.equalsIgnoreCase(str3)); //true
System.out.println(str1==str2); //false
System.out.println(str1==str3); // false
System.out.println(str1==str4); // false because both string have diff object
16- How can get string present in given String in Java?
- Using contains() function:-
public class JavaStringSearch {
public static void main(String[] args) throws Exception {
String str1="If the memstores in a region are this size or";
String str2="in a";
if(str1.toLowerCase().contains(str2.toLowerCase())){
System.out.println("string found");
}else {
System.out.println("string not found");
}
}
}
- Using matches() function:-
String str="If the memstores in a region are this size or";
-matched any string in another string:
str.matches("(?i).*in.*"); // ina is a sub string text to search
-matched any string in string startwith :
str.matches("(?i)If.*");; // If is a sub string text to search
-matched any string in string endwith :
str.matches("(?i).*or"); // ina is a sub string text to search
-Using indexOf() function:
String str="If the memstores in a region are this size or";
if(str.indexOf("the") > -1){
System.out.println("string found");
}
17-How to reverse a String?
-using StringBuffer reverse()
String string="abcdef";
String reverse = new StringBuffer(string).reverse().toString();
18-How to trim spaces in the given string in java?
- String str = " Junk ";
System.out.println(str.trim());
-Output: Junk
19-How to compare StringBuffer object to String object in java?
-The below example shows how to compare StringBuffer object with String object. String object provides contentEquals() method to compare content with a StringBuffer object.
String c = "We are comparing the content with a StringBuffer content";
StringBuffer sb = new StringBuffer("We are comparing the content with a StringBuffer content");
c.contentEquals(sb); // equals
20- Searching last occurance of word?
-String strOrig = "Hello world ,Hello Reader";
int lastIndex = strOrig.lastIndexOf("Hello");
if(lastIndex > 1)
System.out.println(lastIndex); // 13
21- Search word in a String?
--String strOrig = "Hello world ,Hello Reader";
int index = strOrig.indexOf("Hello");
if(index > 1)
System.out.println(index); // found at 0 index
22- How to match regions in strings ?
-String first_str = "Welcome to Microsoft";
String second_str = "I work with Microsoft";
boolean match = first_str.regionMatches(11, second_str, 12, 9);
System.out.println("first_str[11 -19] == " + "second_str[12 - 21]:-"+ match);
// return true
23- Get System time in miliseconds?
-long Time = System.currentTimeMillis();
23(a) Swap no without 3rd variable?
num1= num1+num2;
num2= num1-num2;
num1= num1-num2;
System.out.println("After Swapping using add and substract ");
System.out.println("Value of number1 is :" + num1);
System.out.println("Value of number2 is :" +num2);
//or using division and multiplication.
num1= num1*num2;
num2= num1/num2;
num1= num1/num2;
System.out.println("After Swapping using div & multiplication");
System.out.println("Value of number1 is :" + num1);
System.out.println("Value of number2 is :" +num2);
num1= num1^num2;
num2= num1^num2;
num1= num1^num2;
System.out.println("After Swapping using bitwise operator");
System.out.println("Value of number1 is :" + num1);
System.out.println("Value of number2 is :" +num2);
23(b)Swap no with 3rd variable?
int x,y,temp;
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
temp = x;
x = y;
y = temp;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);
24- Reverse arraylist in java?
import java.util.ArrayList;
import java.util.Collections;
ArrayList listOfInts = new ArrayList<>();
listOfInts.add("1"); listOfInts.add("2"); listOfInts.add("3"); listOfInts.add("4"); listOfInts.add("5");
System.out.println("Before Reversing : " + listOfInts);
Collections.reverse(listOfInts);
System.out.println("After Reversing : " + listOfInts);
25- How can compare two array in java?
-syntex: for 1D array
Arrays.equals(1st[], 2nd[]);
-String[] cities = new String[]{"London", "Paris", "NewYork", "HongKong", "Tokyo"};
String[] metros = new String[]{"London", "Paris", "NewYork", "HongKong", "Tokyo"};
System.out.println(Arrays.equals(cities, capitals));
output: return true
-syntex: for multi D array
Arrays.deepEquals(1st[], 2nd[]);
int[][] a1 = { {2,4}, {4,6}, {8,10} };
int[][] a2 = { {12,14}, {14,16}, {18,20} };
int[][] a3 = { {2,4}, {4, 6}, {8,10} };
boolean result = Arrays.deepEquals(a1, a2);
System.out.println(result); // false
boolean result = Arrays.deepEquals(a1, a3);
System.out.println(result); // true
26- Difference between Array vs ArrayList in Java?
-Main difference between Array vs ArrayList in Java is static nature of Array and dynamic nature of ArrayList.
1) First and Major difference between Array and ArrayList in Java is that Array is a fixed length data structure while ArrayList is a variable length Collection class. You can not change length of Array once created in Java but ArrayList re-size itself when gets full depending upon capacity and load factor.
2) ArrayList is slower than Array:
Since ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.
3) Another difference between Array and ArrayList in Java is that you can not use Generics along with Array, as Array instance knows about what kind of type it can hold and throws ArrayStoreException, if you try to store type which is not convertible into type of Array. ArrayList allows you to use Generics to ensure type-safety.
4) calculate length:
array uses length function to get array length while ArrayList uses size() funtion.
String[] cities = new String[]{"London", "Paris", "NewYork", "HongKong", "Tokyo"};
Array :-cities.length
ArrayList :-cities.size()
5) One more major difference between ArrayList and Array is that, you can not store primitives in ArrayList, it can only contain Objects. While Array can contain both primitives and Objects in Java. Though Autoboxing of Java 5 may give you an impression of storing primitives in ArrayList, it actually automatically converts primitives to Object. e.g.
ArrayList integerList = new ArrayList();
integerList.add(1); //here we are not storing primitive in ArrayList, instead autoboxing will convert int primitive to Integer object
6) Java provides add() method to insert element into ArrayList and you can simply use assignment operator to store element into Array e.g. In order to store Object to specified position use
Object[] objArray = new Object[10];
objArray[1] = new Object();
7) One more difference on Array vs ArrayList is that you can create instance of ArrayList without specifying size, Java will create Array List with default size but its mandatory to provide size of Array while creating either directly or indirectly by initializing Array while creating it. By the way you can also initialize ArrayList while creating it.
Array & ArrayList Initialization:
String[] coolStringArray = new String[]{"Java" , "Scala" , "Groovy"};
System.out.println(" Array : " + Arrays.toString(coolStringArray));
List notSoCoolStringList = new ArrayList();
notSoCoolStringList.add("Java");
notSoCoolStringList.add("Scala");
notSoCoolStringList.add("Groovy");
System.err.println(" List : " + notSoCoolStringList);
//Now here is simple Java tips to create and initialize List in one line
List coolStringList = Arrays.asList("Java", "Scala", "Groovy");
System.err.println(" List created and initialized at same line : " + coolStringList);
In Java, every variable has a type declared in the source code. There are two kinds of types: reference types and primitive types. Reference types are references to objects. Primitive types directly contain values. There are 8 primitive types:
byte
short
int
long
char
float
double
boolean
--***********************************************************************************************************************************
Selenium:
1- Fundamental difference b/w how Selenium RC and WebDriver works?
2- What is JSON wire protocol? Why it is used?
3- What is same origin policy in selenium?
4- how o simulae CTRL+ALT+DELETE key stroke in selenium?
4.1- how can selec all on page?
driver.findElement(By.xpath("//body")).sendKeys(Keys.chord(Keys.CONTROL, "a"));
5- How to click on hidden link?
5.1 How to check value of hidden link in selenium?
String script = "return document.getElementById('code').getAttribute('value');";
String value1 = ((JavascriptExecutor) driver).executeScript(script).toString();
System.out.println(value1);
6- There are ten different options listed in a Combo box say OPT1, OPT2,......, OPT10 and a Submit button. Write code to select OPT1,OPT2 and OPT10 using Control key and hit Submit button?
7- Write a code so that browser session can take a screenshot of the webpage?
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Test(enabled=true)
public void takeScreenShotPrintScreen() throws InterruptedException, IOException {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("full.png"));
}
8- Write a selenium code to take a screenshot of the webpage on test failure?
//Taking ScreenShot ONLY for Failed Tests
package com.pack.listeners;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.pack.sample.TestBase;
public class TestListener implements ITestListener {
WebDriver driver=null;
String filePath = "D:\\SCREENSHOTS";
@Override
public void onTestFailure(ITestResult result) {
System.out.println("***** Error "+result.getName()+" test has failed *****");
String methodName=result.getName().toString().trim();
takeScreenShot(methodName);
}
public void takeScreenShot(String methodName) {
//get the driver
driver=TestBase.getDriver();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with test method name
try {
FileUtils.copyFile(scrFile, new File(filePath+methodName+".png"));
System.out.println("***Placed screen shot in "+filePath+" ***");
} catch (IOException e) {
e.printStackTrace();
}
}
public void onFinish(ITestContext context) {}
public void onTestStart(ITestResult result) {}
public void onTestSuccess(ITestResult result) {}
public void onTestSkipped(ITestResult result) { }
public void onTestFailedButWithinSuccessPercentage(ITestResult result) { }
public void onStart(ITestContext context) { }
}
and add lis
9.1) What is WebDriver Browser Commands?
Method: A Java method is a collection of statements that are grouped together to perform an operation.
Method Name: To access any method of any class, we need to create an object of class and then all the public methods will appear for the object.
Parameter: It is an argument which is passed to a method as a parameter to perform some operation. Every argument must passed with the same data type. For e.g. get(String arg0) : void. This is asking for a String type argument.
Return Type: Method can returns a value or returning nothing (void). If the void is mentioned after the method, it means the method is returning no value. And if it is returning any value, then it must display the type of the value for e.g. getTitle() : String.
Now it would be very easy to understand the WebDriver commands in the below chapter. The very first thing you like to do with Selenium is to Opening a new browser, Perform few tasks and Closing the browser. Below are the numbers of commands you can apply on the Selenium opened browser.
-Get Command
get(String arg0) : void – This method Load a new web page in the current browser window. Accepts String as a parameter and returns nothing.
Command – driver.get(appUrl);
Where appUrl is the website address to load. It is best to use a fully qualified URL.
driver.get("http://www.google.com");
//Or can be written as
String URL = "http://www.DemoQA.com";
driver.get(URL);
-Get Title Command
getTitle() : String – This method fetches the Title of the current page. Accepts nothing as a parameter and returns a String value.
Command – driver.getTitle();
As the return type is String value, the output must be stored in String object/variable.
driver.getTitle();
//Or can be used as
String Title = driver.getTitle();
-Get Current URL Command
getCurrentUrl() : String – This method fetches the string representing the Current URL which is opened in the browser. Accepts nothing as a parameter and returns a String value.
Command – driver.getCurrentTitle();
As the return type is String value, the output must be stored in String object/variable.
driver.getCurrentUrl();
//Or can be written as
String CurrentUrl = driver.getCurrentUrl();
-Get Page Source Command
getPageSource() : String – This method returns the Source Code of the page. Accepts nothing as a parameter and returns a String value.
Command – driver.getPageSource();
As the return type is String value, the output must be stored in String object/variable.
driver.getPageSource();
//Or can be written as
String PageSource = driver.getPageSource();
-Close Command
close() : void – This method Close only the current window the WebDriver is currently controlling. Accepts nothing as a parameter and returns nothing.
Command – driver.close();
Quit the browser if it’s the last window currently open.
driver.close();
-Quit Command
quit() : void – This method Closes all windows opened by the WebDriver. Accepts nothing as a parameter and returns nothing.
Command – driver.quit();
Close every associated window.
driver.quit();
-Navigate Command:
-Goto Url command:
driver.navigate().to("URL");
-Goto Url Back command:
driver.navigate().back();
-Goto Url Forward command:
driver.navigate().forward();
-Goto Page Referesh command:
driver.navigate().referesh();
-Example;
package automationFramework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebDriverCommands {
public static void main(String[] args) {
// Create a new instance of the FireFox driver
WebDriver driver = new FirefoxDriver();
// Storing the Application Url in the String variable
String url = "http://www.store.demoqa.com";
//Launch the ToolsQA WebSite
driver.get(url);
// Storing Title name in the String variable
String title = driver.getTitle();
// Storing Title length in the Int variable
int titleLength = driver.getTitle().length();
// Printing Title & Title length in the Console window
System.out.println("Title of the page is : " + title);
System.out.println("Length of the title is : "+ titleLength);
// Storing URL in String variable
String actualUrl = driver.getCurrentUrl();
if (actualUrl.equals(url)){
System.out.println("Verification Successful - The correct Url is opened.");
}else{
System.out.println("Verification Failed - An incorrect Url is opened.");
//In case of Fail, you like to print the actual and expected URL for the record purpose
System.out.println("Actual URL is : " + actualUrl);
System.out.println("Expected URL is : " + url);
}
// Storing Page Source in String variable
String pageSource = driver.getPageSource();
// Storing Page Source length in Int variable
int pageSourceLength = pageSource.length();
// Printing length of the Page Source on console
System.out.println("Total length of the Pgae Source is : " + pageSourceLength);
//Closing browser
driver.close();
}
}
9.2) WebElement Commands?
-What is WebElement?
-WebElement represents an HTML element. HTML documents are made up by HTML elements. HTML elements are written with a start tag, with an end tag, with the content in between: content
The HTML element is everything from the start tag to the end tag:
My first HTML paragraph.
-http://20tvni1sjxyh352kld2lslvc.wpengine.netdna-cdn.com/wp-content/gallery/selenium-basics/WebElementCommands_01.png
-Clear Command
clear( ) : void – If this element is a text entry element, this will clear the value. This method accepts nothing as a parameter and returns nothing.
Command – element.clear();
-SendKeys Command
sendKeys(CharSequence… keysToSend ) : void – This simulate typing into an element, which may set its value. This method accepts CharSequence as a parameter and returns nothing.
Command – element.sendKeys(“text”);
-Click Command
click( ) : void – This simulates the clicking of any element. Accepts nothing as a parameter and returns nothing.
Command – element.click();
Note: Most of the time we click on the links and it causes a new page to load, this method will attempt to wait until the page has loaded properly before handing over the execution to next statement. But If click() causes a new page to be loaded via an event or is done by sending a native event for example through javascript, then the method will not wait for it to be loaded.
There are some preconditions for an element to be clicked. The element must be Visible and it must have a Height and Width greater than 0.
-IsDisplayed Command
isDisplayed( ) : boolean – This method determines if an element is currently being displayed or not. This accepts nothing as a parameter but returns boolean value(true/false).
Command – element.isDisplayed();
WebElement element = driver.findElement(By.id("UserName"));
boolean status = element.isDisplayed();
//Or can be written as
boolean staus = driver.findElement(By.id("UserName")).isDisplayed();
Note: Do not confuse this method with element present on the page or not. This will return true if the element is present on the page and throw a NoSuchElementFound exception if the element is not present on the page. This refers the property of the element, sometimes the element is present on the page but the property of the element is set to hidden, in that case this will return false, as the element is present in the DOM but not visible to us.
-IsEnabled Command
isEnabled( ) : boolean – This determines if the element currently is Enabled or not? This accepts nothing as a parameter but returns boolean value(true/false).
Command – element.isEnabled();
This will generally return true for everything but I am sure you must have noticed many disabled input elements in the web pages.
WebElement element = driver.findElement(By.id("UserName"));
boolean status = element.isEnabled();
//Or can be written as
boolean staus = driver.findElement(By.id("UserName")).isEnabled();
//Or can be used as
WebElement element = driver.findElement(By.id("userName"));
boolean status = element.isEnabled();
// Check that if the Text field is enabled, if yes enter value
if(status){
element.sendKeys("ToolsQA");
}
-IsSelected Command
isSelected( ) : boolean – Determine whether or not this element is selected or not. This accepts nothing as a parameter but returns boolean value(true/false).
Command – element.isSelected();
This operation only applies to input elements such as Checkboxes, Select Options and Radio Buttons. This returns True if the element is currently selected or checked, false otherwise.
WebElement element = driver.findElement(By.id("Sex-Male"));
boolean status = element.isSelected();
//Or can be written as
boolean staus = driver.findElement(By.id("Sex-Male")).isSelected();
-Submit Command
submit( ) : void– This method works well/better than the click() if the current element is a form, or an element within a form. This accepts nothing as a parameter and returns nothing.
Command – element.submit();
If this causes the current page to change, then this method will wait until the new page is loaded.
driver.findElement(By.id("SubmitButton")).submit();
-GetText Command
getText( ) : String– This method will fetch the visible (i.e. not hidden by CSS) innerText of the element. This accepts nothing as a parameter but returns a String value.
Command – element.submit();
This returns an innerText of the element, including sub-elements, without any leading or trailing whitespace.
WebElement element = driver.findElement(By.xpath("anyLink"));
String linkText = element.getText();
-getTagName Command
getTagName( ) : String– This method gets the tag name of this element. This accepts nothing as a parameter and returns a String value.
Command – element.getTagName();
This does not return the value of the name attribute but return the tag for e.g. “input“ for the element .
WebElement element = driver.findElement(By.id("SubmitButton"));
String tagName = element.getTagName();
//Or can be written as
String tagName = driver.findElement(By.id("SubmitButton")).getTagName();
-getCssValue Command
getCssvalue( ) : String– This method Fetch CSS property value of the give element. This accepts nothing as a parameter and returns a String value.
Command – element.getCssValue();
Color values should be returned as rgba strings, so, for example if the “background-color” property is set as “green” in the HTML source, the returned value will be “rgba(0, 255, 0, 1)”.
-getAttribute Command
getAttribute(String Name) : String– This method gets the value of the given attribute of the element. This accepts the String as a parameter and returns a String value.
Command – element.getAttribute();
Attributes are Ids, Name, Class extra and using this method you can get the value of the attributes of any given element.
WebElement element = driver.findElement(By.id("SubmitButton"));
String attValue = element.getAttribute("id"); //This will return "SubmitButton"
-getSize Command
getSize( ) : Dimension – This method fetch the width and height of the rendered element. This accepts nothing as a parameter but returns the Dimension object.
Command – element.getSize();
This returns the size of the element on the page.
WebElement element = driver.findElement(By.id("SubmitButton"));
Dimension dimensions = element.getSize();
System.out.println(“Height :” + dimensions.height + ”Width : "+ dimensions.width);
-getLocation Command
getLocation( ) : Point – This method locate the location of the element on the page. This accepts nothing as a parameter but returns the Point object.
Command – element.getLocation();
This returns the Point object, from which we can get X and Y coordinates of specific element.
WebElement element = driver.findElement(By.id("SubmitButton"));
Point point = element.getLocation();
System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y);
10) Difference between navigation and get method in selenium webdriver?
- Basically both methods are used for same purpose, And the purpose is to navigate a URL(a web page)
- Get method :
Here when this method is called its navigates to the webpage(yoursfriends.com) if the page is containing the js files or Ajax of flash file so it would hold the process till then the page is loaded completely then the another action is performed. like
Step 1. driver.get();
Step 2. element.click();
Here, till then the page is completely loaded click is not to be performed.
- Navigate method:
Navigate method is also used to navigate a url we can navigate to any URL by this method like : driver.navigate.to(“URL”); But here is the benefit that we can go back and forward in the browser history like:
driver.navigate.to(“URL”);
driver.navigate().forward();
driver.navigate().back();
driver.navigate().refresh();
11) In Selenium WebDriver, how do you select an item from a drop-down menu?
-We can select an item from the drop-down menu by Value, by Index or by Visible Text.
WebElement cars = driver.findElement(By.id("cars"));
Select car = new Select(cars)
//select by value
car.selectByValue("vo"); //this will select Volvo from drop-down
//select by index
car.selectByIndex(2); //this will select Saab
//select by visible text
car.selectByVisibleText("Audi") //this will select Audi
12) What is the difference between implicit wait and explicit wait in selenium webdriver?
- Selenium Webdriver introduces the concept of waits for AJAX based applications. There are two waiting methods, implicit wait and explicit wait.
- Implicit wait:
- driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
When an implicit wait is implemented in tests, if WebDriver cannot find an element in the Document Object Model (DOM), it will wait for a defined amount of time for the element to appear in the DOM. In other terms, an implicit wait polls the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available.
Implicit waits can slow down your tests, because once set, the implicit wait is set for the life of the WebDriver object’s instance. This means that when an application responds normally, it will still wait for each element to appear in the DOM which increases the overall execution time.
Another downside is if for example you set the waiting limit to be 5 seconds and the elements appears in the DOM in 6 seconds, your tests will fail because you told it to wait a maximum of 5 seconds.
- Explicit wait:
- Explicit waits are better than implicit wait. Unlike an implicit wait, you can write custom code or conditions for wait before proceeding further in the code.
An explicit wait can be used where synchronization is needed, for example the page is loaded but we are still waiting for a call to complete and an element to appear.
Selenium WebDriver provides WebDriverWait and ExpectedCondition classes for implementing an explicit wait. The ExpectedCondition class provides a set of predefined conditions to wait before proceeding further in the code.
An example of an explicit wait is:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.titleContains("selenium"));
Implicit wait time is applied to all elements in your script and Explicit wait time is applied only for particular specified element.
13) Describe Selenium Explicit Waits Example?
WebDriver Waits Examples
We can use WebDriverWait class in many different cases. When ever we need to perform any operation on element, we can use webdriver wait to check if the element is Present or visible or enabled or disabled or Clickable etc.
We will look into different examples for all the above scenarios:
- isElementPresent:
Below is the syntax to check for the element presence using WebDriverWait. Here we need to pass locator and wait time as the parameters to the below method. Here it is checking that an element is present on the DOM of a page or not. That does not necessarily mean that the element is visible. ExpectedConditions will return true once the element is found in the DOM.
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
We should use presenceOfElementLocated when we don't care about the element visible or not, we just need to know if it's on the page.
We can also use the below syntax which is used to check if the element is present or not. We can return true ONLY when the size of elements is greater than Zero. That mean there exists atleast one element.
WebElement element = driver.findElements(By.cssSelector(""));
element.size()>0;
- isElementClickable
Below is the syntax for checking an element is visible and enabled such that we can click on the element. We need to pass wait time and the locator as parameters.
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.elementToBeClickable(locator));
- isElementVisible
Below is the syntax to check if the element is present on the DOM of a page and visible. Visibility means that the element is not just displayed but also should also has a height and width that is greater than 0.
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
We can also use the below to check the element to be visible by WebElement.
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait..until(ExpectedConditions.visibilityOf(element));
We can also use the below to check all elements present on the web page are visible. We need to pass list of WebElements.
List linkElements = driver.findelements(By.cssSelector('#linkhello'));
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait..until(ExpectedConditions.visibilityOfAllElements(linkElements));
- isElementInVisible
Below is the syntax which is used for checking that an element is either invisible or not present on the DOM.
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
- isElementEnabled
Below is the syntax which is used to check if the element is enabled or not
WebElement element = driver.findElement(By.id(""));
element.isEnabled();
- isElementDisplayed
Below is the syntax which is used to check if the element is displayed or not. It returns false when the element is not present in DOM.
WebElement element = driver.findElement(By.id(""));
element.isDisplayed();
Wait for invisibility of element
Below is the syntax which is used to check for the Invisibility of element with text
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by));
Wait for invisibility of element with Text
Below is the syntax which is used for checking that an element with text is either invisible or not present on the DOM.
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by, strText));
12) HOW TO UPLOAD FILE USING JAVA ROBOT CLASS AND SELENIUM WEBDRIVER?
package com.helloselenium.selenium.test;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class UploadFileUsingJavaRobot{
public static void setClipboardData(String string) {
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
public static void main(String[] args) {
String filepath = "path of the file to upload";
setClipboardData(filepath);
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.helloselenium.com/2015/03/how-to-upload-file-using-java-robot.html");
WebElement fileInput = driver.findElement(By.name("uploadFileInput"));
fileInput.click();
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (AWTException e) {
e.printStackTrace();
}
driver.quit();
}
}
Q00) - Find the max consecutive repitative chracter in following string ''
