1. Framework
a. General Data Driven Framework
b. Testing Web Driver Data Driven Framework
2. JAVA
3. Sample Programs on Java
4. Interview Questions on Java
5. Selenium RC
6. TestNG and JUnit
7. Web Driver.
8. Sample Programs on Selenium
9. Interview Question on Selenium
Framework
General Data Driven Framework &
TestNG WebDriver Data Driven
Framework Aim or Goals of Framework:
¾ Tests With Multiple Suite
¾ Run Selective Test Suite
¾ Run Selected Test Cases
¾ Generate Logs
¾ Repeat a test case – Parameterize
¾ Execute Test cases with multiple sets of data
¾ Run complete Project in Console or command line
¾ BAT file for execution through ANT
¾
Generate Html Reports using TestNG
Prepare Test Suites - TestSuite.xlsx
Prepare Test Cases and Test data xls for Test Suites. One xls file per test
suite
Introduce Runmodes
Make eclipse Java project
make package- suiteA
make package- suiteB
make package- suiteC
make package- logs
make package- util
make package- base,
in base create initialize function and declare global variables like xls files
with path.
make package- config, create OR.properties and config.properties
make package- xls
Put xls files in xls
Prepare config.properties and OR.properties
Make TestUtil.java in util package
Prepare function to check Runmode of a Test Case in Test Suite -
isTestCaseRunnable
Prepare function to return test data for a test case in two dim array -
getData
Make TestBase.java
Prepare initialize function to initialize the logs,
Make TestSuiteBase.java class in each test Suite package
Prepare all test classes in all suites
Prepare testng.xml and individual suite xmls
Batch run and check empty project
Implement @BeforeSuite and @BeforeTest functions in Project to check
Runmode of Suite and Test
Batch run and check empty project
Implement @dataprovider Functions in all test classes - PARAMETRIZING
THE TEST CASES
Implement build.xml and run project through command prompt
Make a .bat file to run the frameworkDouble clicking on bat file your will
or complete script will execute and generate the reports and logs.
Framework is Class Room Training
JAVA
INDEX of JAVA
1. Introduction to Java 1.1. History
1.2. Java Virtual machine
1.3. Java Runtime Environment vs. Java Development Kit 1.4. Characteristics of Java
1.5. Development Process with Java 1.6. Classpath
2. Installation of Java 3. Your first Java program
3.1. Write source code
3.2. Compile and run your Java program 3.3. Using the classpath
4. Integrated Development Environment
5. Your first graphical user interface application (GUI) 6. Statements
6.1. Boolean Operations 6.2. Switch Statement 7. Working with Strings 8. Type Conversion
8.1. Conversion to String
8.2. Conversion from String to Number 8.3. Double to int
8.4. SQL Date conversions 9. Cheat Sheets
9.1. Working with classes
10. Thank you
11. Questions and Discussion 12. Links and Literature
1. Introduction to Java
1.1. History
Java is a programming language created by James Gosling from Sun Microsystems in 1991. The first publicly available version of Java (Java 1.0) was released in 1995. Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
From the Java programming language the Java platform evolved. The Java platform allows that the program code is written in other languages than the Java programming language and still runs on the Java virtual machine.
1.2. Java Virtual machine
The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.
The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into so-called bytecode. The Java virtual machine interprets this bytecode and executes the Java program.
1.3. Java Runtime Environment vs. Java Development Kit
Java comes in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK).
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java
programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.
1.4. Characteristics of Java
The target of Java is to write a program once and then run this program on multiple operating systems.
Java has the following properties:
• Platform independent: Java programs use the Java virtual machine as
abstraction and do not access the operating system directly. This makes Java programs highly portable. A Java program which is standard complaint and follows certain rules can run unmodified on all supported platforms, e.g. Windows or Linux.
• Object-orientated programming language: Except the primitive data types, all elements in Java are objects.
• Strongly-typed programming language: Java is strongly-typed, e.g. the types of the used variables must be pre-defined and conversion to other objects is relatively strict, e.g. must be done in most cases by the programmer.
•
• Interpreted and compiled language: Java source code is transferred into the bytecode format which does not depend on the target platform. These
bytecode instructions will be interpreted by the Java Virtual machine (JVM).
• The JVM contains a so called Hotspot-Compiler which translates performance critical bytecode instructions into native code instructions.
• Automatic memory management: Java manages the memory allocation and de-allocation for creating new objects. The program does not have direct access to the memory. The so-called garbage collector deletes automatically objects to which no active pointer exists.
The Java syntax is similar to C++. Java is case sensitive, e.g. the variables myValue and myvalue will be treated as different variables.
1.5. Development Process with Java
The programmer writes Java source code in a text editor which supports plain text. Normally the programmer uses an Integrated Development Environment (IDE) for programming. An IDE supports the programmer in the task of writing code, e.g. it provides auto-formating of the source code, highlighting of the important keywords, etc.
At some point the programmer (or the IDE) calls the Java compiler (javac). The Java compiler creates the bytecode instructions. . These instructions are stored in .class files and can be executed by the Java Virtual Machine.
1.6. Classpath
The classpath defines where the Java compiler and Java runtime look for .class files to load. This instructions can be used in the Java program.
For example if you want to use an external Java library you have to add this library to your classpath to use it in your program.
2
.Installation of Java
Java might already be installed on your machine. You can test this by opening a
console (if you are using Windows: Win+R, enter cmd and press Enter) and by typing in the following command:
java -version
If Java is correctly installed, you should see some information about your Java
installation. If the command line returns the information that the program could not be found, you have to install Java. The central website for installing Java is the following URL:
http://java.com
If you have problems installing Java on your system, search via Google for How to install JDK on YOUR_OS. This should result in helpful links. Replace YOUR_OS with your operating system, e.g. Windows, Mac OS X, etc.
3. Your first Java program
3.1. Write source code
The following Java program is developed under Microsoft Windows. The process on other operating system should be similar but is not covered in this description.
Select a new directory which will contain your Java code. I will use the c:\temp\java which will be called javadir in the following description.
Open a text editor which supports plain text, e.g. Notepad under Windows and write the following source code. You can start Notepad via Start → Run → Notepad and by pressing enter.
// A small Java program
public class HelloWorld {
public static void main(String[] args) { System.out.println("Hello World"); }
Save the source code in your javadir directory with the HelloWorld.java filename. The name of a Java source file must always equals the class name (within the source code) and end with the .java extension. In this example the filename must be HelloWorld.java because the class is called HelloWorld.
3.2. Compile and run your Java program
Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to the javadir directory with the command cd javadir, for example in my case cd
c:\temp\java. Use the command dir to see that the source file is in the directory. javac testjava.java
Check the content of the directory with the command "dir". The directory contains now a file "testjava.class". If you see this file you have successfully compiled your first Java source code into bytecode.
By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d compiler flag.
Run -> cmd. Switch to the directory jardir. To run your program type in the command line: java testjava
The system should write "learning selenium" on the command line.
3.3. Using the classpath
You can use the classpath to run the program from another place in your directory. Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to any directory you want. Type:
If you are not in the directory in which the compiled class is stored then the system should result an error message Exception in thread "main"
java.lang.NoClassDefFoundError: test/TestClass
To use the class type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the " learning selenium " output.
java -classpath "mydirectory" learning selenium
4. Integrated Development Environment
The previous chapter explained how to create and compile a Java program on the command line. A Java Integrated Development Environment (IDE) provides lots of ease of use functionality for creating java programs. There are other very powerful IDE's available, for example the Eclipse IDE. .
In the following I will say "Create a Java project SomeName". This will refer to creating an Eclipse Java project. If you are using a different IDE please follow the required steps in this IDE.
4.1. To Install Java:
1. Go to google and type “download JDK”
2. Now select your OS compatibility (32bit or 64bit) 3. Install in your system.
4.2. To Configure Eclipse IDE:
1. Go to google and type “download Eclipse” 2. Now select your OS compatibility (32bit or 64bit) 3. Save in your system and open folder and send shortcut to desktop
Click on short cut it displays like below:
Now click on workbench link.
5. Your first graphical user interface application (GUI)
Introduction of Eclipse and eclipse GUI.
Now open eclipse short cut from the desktop as above explained. It’ll displays like below screenshot.
Using
Step 1
1. Go toEclipse c
:
o file mencreate a
u ÆNewÆsnew Jav
select Javava proje
a Projectect :
Step
Type Pro
2:
Step
• Now • Go to3:
click on pr o file menu roject folde u or click bu er and selec utton and s ct src folde select pack er kageStep
• Type
4:
Creat
Step
Select pte Class
5:
package folds:
Step
1. Type 2. Selec 3. Click6:
e class Nam ct public st k on finish bme, Ex: Basi tatic void m button. cPrograms, main check , spaces it box won’t alloww.
It disp
6. Statements
The following describes certain aspects of the software.
6.1. Boolean Operations
Use == to compare two primitives or to see if two references refers to the same object. Use the equals() method to see if two different objects are equal.
&& and || are both Short Circuit Methods which means that they terminate once the result of an evaluation is already clear. Example (true || ....) is always true while (false && ...) always false is. Usage:
(var !=null && var.method1()..) ensures that var is not null before doing the real check.
Table 1. Boolean
Operations Description
== Is equal, in case of objects the system checks if the reference variable point to the same object, is will not compare the
Operations Description
content of the objects! && And
!= is not equal, similar to the "==" a.equals(b) Checks if string a equals b
a.equalsIgnoreCase(b) Checks if string a equals b while ignoring lower cases If (value ? false : true)
{} Return true if value is not true. Negotiation
6.2. Switch Statement
The switch statement can be used to handle several alternatives if they are based on the same constant value.
switch (expression) { case constant1: command;
break; // Will prevent that the other cases or also executed
case constant2: command; break; ... default: } Example: switch (cat.getLevel()) {
case 0: return true; case 1: if (cat.getLevel() == 1) { if (cat.getName().equalsIgnoreCase(req.getCategory())) { return true; } } case 2: if (cat.getName().equalsIgnoreCase(req.getSubCategory())) { return true; } }
7. Working with Strings
The following lists the most common string operations Table 2. .
Command Description
text1.equals("Testing"); return true if text1 is equal to "Testing". The test is case sensitive.
text1.equalsIgnoreCase("Testing");
return true if text1 is equal to "Testing". The test is not case sensitive. For example it would also be true for "testing"
StringBuffer str1 = new StringBuffer(); Define a new String with a variable length. str.charat(1); Return the character at position 1. (Strings
starting with 0)
str.substring(1); Removes the first characters.
str.substring(1, 5); Gets the substring from the second to the fifths character.
str.indexOf(String) Find / Search for String Returns the index of the first occurrence of the specified string.
Command Description
str.lastIndexOf(String)
Returns the index of the last occurrence of the specified string. StringBuffer does not support this method. Hence first convert the StringBuffer to String via method toString. str.endsWith(String) Returns true if str ends with String
str.startsWith(String) Returns true if str starts with String
str.trim() Removes spaces
str.replace(str1,str2) Replaces all occurrences of str1 by str2 str.concat(str1); Concatenates str1 at the end of str. str.toLowerCase() str.toUpperCase() Converts string to lower- or uppercase str1 + str2 Concatenate str1 and str2
String[] zeug = myString.split("-"); String[] zeug = myString.split("\\.");
Spits myString at / into Strings. Attention: the split string is a regular expression, so if you using special characters which have a meaning in regular expressions you need to quote them. In the second example the . is used and must be quoted by two backslashes.
8. Type Conversion
If you use variables of different types Java requires for certain types an explicit conversion. The following gives examples for this conversion.
8.1. Conversion to String
Use the following to convert from other types to Strings
// Convert from int to String
String s1 = String.valueOf (10); // "10" String s2 = // Convert from double to String
// Convert from boolean to String
String s3 = String.valueOf (1 < 2); // "true" // Convert from date to String
String s4 = String.valueOf (new Date()); // "Tue Jun 03 14:40:38 CEST 2003"
8.2. Conversion from String to Number
// Conversion from String to int
int i = Integer.parseInt(String);
// Conversion from float to int
float f = Float.parseFloat(String);
// Conversion from double to int
double d = Double.parseDouble(String);
The conversion from string to number is independent from the Locale settings, e.g. it is always using the English notification for number. In this notification a correct number format is "8.20". The German number "8,20" would result in an error. To convert from a German number you have to use the NumberFormat class. The challenges is that if the value is for example 98.00 then the NumberFormat class would create a Long which cannot be casted to Double. Hence the following complex conversion class.
private Double convertStringToDouble(String s) { Locale l = new Locale("de", "DE");
Locale.setDefault(l);
NumberFormat nf = NumberFormat.getInstance(); Double result = 0.0;
try {
result = Double.parseDouble(String.valueOf(nf.parse(s))); } else {
result = (Double) nf.parse(new String(s)); }
} catch (ClassNotFoundException e1) { e1.printStackTrace();
} catch (ParseException e1) { e1.printStackTrace(); }
return result; }
8.3. Double to int
int i = (int) double;
9. Cheat Sheets
The following can be used as a reference for certain task which you have to do.
9.1. Working with classes
While programming Java you have to create several classes, methods, instance variables. The following uses the package test.
Table 3.
What to do How to do it
Create a new class called MyNewClass.
package test;
public class MyNewClass { }
Create a new attribute (instance variable) "var1" in
What to do How to do it
public class MyNewClass { private String var1; }
Create a Constructor for "MyNewClass which has a String parameter and assigns the value of it to the "var1" instance variable.
package test;
public class MyNewClass { private String var1; public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; } }
Create a new method "doSomeThing" in class which do not return a value and has no parameters
package test;
public class MyNewClass { private String var1; public MyNewClass(String para1) {
var1 = para1;
// or this.var1= para1;
}
public void doSomeThing() { }
}
Create a new method "doSomeThing2" in class which do not return a value and has two parameters, a int and a Person
package test;
public class MyNewClass { private String var1; public MyNewClass(String para1) {
var1 = para1;
// or this.var1= para1;
What to do How to do it
public void doSomeThing() { }
public void doSomeThing2(int a, Person person) {
} }
Create a new method "doSomeThing2" in class which do return an int value and has three parameters, two Strings and a Person
package test;
public class MyNewClass { private String var1; public MyNewClass(String para1) {
var1 = para1;
// or this.var1= para1;
}
public void doSomeThing() { }
public void doSomeThing2(int a, Person person) {
}
public int
doSomeThing3(String a, String b, Person person) {
return 5; // Any value will do for this example
} } Create a class "MyOtherClass" with two instance
variables. One will store a String, the other will store a Dog. Create getter and setter for these variables.
package test;
What to do How to do it
String myvalue; Dog dog;
public String getMyvalue() { return myvalue;
}
public void setMyvalue(String myvalue) {
this.myvalue = myvalue; }
public Dog getDog() { return dog;
}
public void setDog(Dog dog) { this.dog = dog;
} }
9.2. Working with local variable
A local variable must always be declared in a method.
Table 4.
What to do How to do it
Declare a (local) variable of type string. String variable1; Declare a (local) variable of type string and assign
"Test" to it. String variable2 = "Test"; Declare a (local) variable of type Person Person person;
Declare a (local) variable of type Person, create a
new Object and assign the variable to this object. Person person = new Person(); Declare a array of type String String array[];
Declare a array of type Person and create an array
for this variable which can hold 5 Persons. Person array[]= new Person[5]; Assign 5 to the int variable var1 (which was
already declared); var1 = 5; Assign the existing variable pers2 to the exiting
variable pers1; pers1 = pers2; Declare a ArrayList variable which can hold
objects of type Person ArrayList<Person> persons; Create a new ArrayList with objects of type
Person and assign it to the existing variable persons
persons = new ArrayList<Person>();
Declare a ArrayList variable which can hold objects of type Person and create a new Object for it.
ArrayList<Person> persons = new ArrayList<Person>();
Java basic program- Program-1:
package Pack1;
public class JavaBasic_Commands {
public static void main(String[]args){
System.out.println("learning selenium");
int a=10; //32bit it can store the numeric values
int b=11,c=12;
long l=67; //64 bit it can store the numeric values
double d=45.6; //it can any decimal values
double d1=35;
System.out.println(a+d);
char c1='j'; //it can strore a single char
String str="selenium";
System.out.println(str);
}
}
Out put:
learning selenium
55.6
selenium
Program-2:
package Pack1;
public class String_functions {
public static void main (String[]args){
String str="learning"; //it can store no.of chars
or group of words,
String str1="the rain have been started";
System.out.println(str+"===="+str1);
int length=str1.length();
System.out.println(length);
//String[] test=str1.split(" ");
}
}
Out put:
learning====the rain have been started
26
For loops Program-3:
package Pack1;
public class For_Loops {
//int i=5;
for(int i=5;i>=0;i‐‐){ //initialization,
condition, incremental or decremental
System.out.print(i);
}
}
}
Out put:
5
4
3
2
1
0
If conditions programs-4:
package Pack1;
public class If_Conditions {
public static void main (String[]args){
/*int a=120, b=25;
if(a>b){
System.out.println("a is the greatest value=
"+a);
}else{
System.out.println("b is the greatest value=
"+b); //type syso+contl+spacebar
}
*/
//< > + ‐ / % &
int a=14, b=13, c=45;
if(a>b && a>c){
System.out.println("a is the greatest value= "+a);
}else if(b>c){
System.out.println("b is the greatest value=
"+b);
}else{
System.out.println("c is the greatest value=
"+c);
}
}
}
Output:
c is the greatest value= 45
While loop - programs-5:
package Pack1;
public class While_Loop {
public static void main(String[] args) {
int i=1; //initializtion
while(i<=5){ //condition
System.out.println(i);
i++; //incremental or decremental
}
}
}
Out put:
1
2
3
4
5
Simple Date program - programs-6:
import java.util.*; public class DateDemo {
Date dNow = new Date();
System.out.println("Current Date: " + dNow);
} }
Out put:
Current Date: Tue Apr 23 14:15:54 IST 2013Find Smallest Number and Largest Number in an array:
Program-7:
public class FindLargestSmallestNumber { public static void main(String[] args) { int numbers[] = new int[]{32,43,53,54,32,65,63,98,111,23,21}; int smallest = numbers[0]; int largetst = numbers[0]; for(int i=1; i< numbers.length; i++){ if(numbers[i] > largetst) largetst = numbers[i]; else if (numbers[i] < smallest) smallest = numbers[i]; } System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); } }Out put:
Largest Number is : 111 Smallest Number is : 21
Factorial Print for number - Program-8:
public class Example1 { public static void main(String[] args) { int numbers[]=new int[]{2,3,5,1,8,6,9,25,‐5}; int smallest=numbers[0]; int largest=numbers[0]; for(int i=1;i<numbers.length;i++){ if(numbers[i]>largest) largest=numbers[i]; else if(numbers[i]<smallest) smallest=numbers[i]; } System.out.println("largest number= "+largest); System.out.println("smallest number= "+smallest); } }Out put:
Enter a Factorial Number = 25 2076180480Matrix print
- Program-9:
public class MatricsPrint {public static void main(String[] args) {
for(int i=1;i<=9;i=i+3){ for(int j=i;j<i+3;j++){
System.out.print(j+" ");
} } }
Out put:
1 2 3 4 5 6 7 8 9Rev_Num_Print
- Program-10:
public class Rev_Num_Print { public static void main(String[] args) { int n, reverse=0; System.out.println("Enter a number"); Scanner in= new Scanner(System.in); n= in.nextInt(); while (n!=0){ reverse= reverse * 10; reverse= reverse + n%10; n=n/10; //System.out.println(reverse); } System.out.println(reverse); } }Out put:
Enter a number 12345 54321Reverse sentence
- Program-11:
public class Reverse_sentance {
String x="Bittu going to delhi"; String temp[]=x.split(" "); for(int i=0;i<temp.length;i++){ String k=temp[i]; for(int j=k.length()‐1;j>=0;j‐‐){ System.out.print(k.charAt(j)); } System.out.print(" "); } } }
Out put:
uttiB gniog ot ihled
SumTotal - Program-11:
public class SumTotal { public static void main(String[] args) { int x[]=new int []{2,3,5,23,25,12}; int sum=0; for(int i=0;i<x.length;i++){ sum=sum+x[i]; } System.out.println(sum); } }Out put:70
Java Important Interview Questions:
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An
Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q:What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that
class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Q:What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a
of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
Q:State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class
must be public too)
private : Private variables or methods may be used only by an instance of the same
class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all
subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private
or protected).It means that it is visible to all within a particular package. TOP
Q:What is an abstract class?
A: Abstract class must be extended/subclassed (to be useful). It serves as a template.
A class that is abstract may not be instantiated (ie, you may not call its
constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
Q:What is static in java?
A: Static means one per class, not one for each object no matter how many instance
of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
Q:What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final
method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
Q:What if the main method is declared as private?
A: The program compiles properly but at runtime it will give "Main method not public."
message.
Q:What if the static modifier is removed from the signature of the main method? A: Program compiles. But at runtime throws an error "NoSuchMethodError".
Q:What if I write static public void instead of public static void? A: Program compiles and runs properly.
Q:What if I do not provide the String array as the argument to the method? A: Program compiles but throws a runtime error "NoSuchMethodError".
Q:What is the first argument of the String array in main method?
A: The String array is empty. It does not have any element. This is unlike C/C++ where
the first element by default is the program name.
Q:If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
A: It is empty. But not null.
Q:How can one prove that the array is not null but empty using one line of code? A: Print args.length. It will print 0. That means it is empty. But if it would have been
null then it would have thrown a NullPointerException on attempting to print args.length.
A: Yes it is possible. While starting the application we mention the class name to be
run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
Q:Can I have multiple main methods in the same class?
A: No the program fails to compile. The compiler says that the main method is already
defined in the class.
Q:Do I need to import java.lang package any time? Why ? A: No. It is by default loaded internally by the JVM.
Q:Can I import same package/class twice? Will the JVM load the package twice at runtime?
A: One can import the same package or same class multiple times. Neither compiler
nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
Q:What are Checked and UnChecked Exception?
A: A checked exception is some subclass of Exception (or Exception itself), excluding
class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by
java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg,
StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
Q: What is Overriding?
A: When a class defines a method using the same name, return type, and arguments
as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass.
Methods may be overridden to be more public, not more private.
Q:What are different types of inner classes?
A: Nested top-level classes, Member classes, Local classes, Anonymous classes Nested top-level classes- If you declare a class within a class and specify the
static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.
Member classes - Member inner classes are just like other member methods and
member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.
Local classes - Local classes are like local variables, specific to a block of code.
Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level
further. As anonymous classes have no name, you cannot provide a constructor.
Q: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
A: Yes the imports are checked for the semantic validity at compile time. The code
containing above line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD location: package io import java.io.ABCD;
Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will
import classes in the package MyTest only. It will not import any class in any of it's subpackage.
Q: What is the difference between declaring a variable and defining a variable? A: In declaration we just mention the type of the variable and it's name. We do not
initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
Q:Can a top level class be private or protected?
A: No. A top level class can not be private or protected. It can have either "public" or
no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the
"modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
Q: What type of parameter passing does Java support? A: In Java the arguments are always passed by value. Q: Objects are passed by value or by reference?
A: Java only supports pass by value. With objects, the object reference itself is
passed by value and so both the original reference and parameter copy both refer to the same object.
A: Externalizable is an interface which contains two methods readExternal and
writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
Oops Interview Questions:
1. What are the principle concepts of OOPS?
There are four principle concepts upon which object oriented design and programming rest. They are:
• Abstraction
• Polymorphism
• Inheritance
• Encapsulation
(i.e. easily remembered as A-PIE).
2. What is Abstraction?
Abstraction refers to the act of representing essential features without including the background details or explanations.
2. What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from
directly altering or accessing the properties or methods of the encapsulated object.
• Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside
view, where the behavior of the abstraction is implemented.
• Abstraction solves the problem in the design side while Encapsulation is the
Implementation.
• Encapsulation is the deliverables of Abstraction. Encapsulation barely talks
about grouping up your abstraction to suit the developer needs.
4. What is Inheritance?
• Inheritance is the process by which objects of one class acquire the properties of objects of another class.
• A class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass.
• Inheritance is done by using the keyword extends.
• The two most common reasons to use inheritance are:
o To promote code reuse o To use polymorphism
5. What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations."
Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name.
• In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
• In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
7. Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading.
Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in
three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
8.What is runtime polymorphism or dynamic method dispatch?
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
10.What is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.
11.What is method overloading?
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
Note:
• Overloaded methods MUST change the argument list
• Overloaded methods CAN change the return type
• Overloaded methods CAN change the access modifier
• Overloaded methods CAN declare new or broader checked exceptions
• A method can be overloaded in the same class or in a subclass
12.What is method overriding?
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of
overriding is the ability to define behavior that’s specific to a particular subclass type.
• The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
• You cannot override a method marked final
• You cannot override a method marked static
13.What are the differences between method overloading and method overriding?
Overloaded Method Overridden Method
Arguments Must change Must not change
Return type Can change Can’t change except for
covariant returns
Exceptions Can change Can reduce or eliminate. Must
not throw new or broader checked exceptions
Access Can change Must not make more restrictive
(can be less restrictive)
Invocation Reference type determines which overloaded version is selected. Happens at compile time.
Object type determines which method is selected. Happens at runtime.
14.Can overloaded methods be override too?
Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.
15.Is it possible to override the main method?
NO, because main is a static method. A static method can't be overridden in Java.
16.How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.
// From subclass
super.overriddenMethod();
17.What is super?
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
Note:
• You can only go back one level.
• In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.
31.What is Constructor?
• A constructor is a special method whose task is to initialize the object of its class.
• It is special because its name is the same as the class name.
• They do not have return types, not even void and therefore they cannot return values.
• They cannot be inherited, though a derived class can call the base class constructor.
• Constructor is invoked whenever an object of its associated class is created.
32.How does the Java default constructor be provided?
If a class defined by the code does not have any constructor, compiler will
automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.
33.Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class constructor.
34.What are the differences between Contructors and Methods?
Constructors Methods
Modifiers Cannot be abstract, final, native, static, or synchronized
Can be abstract, final, native, static, or synchronized
Return Type No return type, not even void void or a valid return type
Name Same name as the class (first letter is capitalized by
convention) -- usually a noun
Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action
this Refers to another constructor in the same class. If used, it must be the first line of the
constructor
Refers to an instance of the owning class. Cannot be used by static methods.
super Calls the constructor of the parent class. If used, must be the first line of the constructor
Calls an overridden method in the parent class
Inheritance Constructors are not inherited Methods are inherited
35.How are this() and super() used with constructors?
• Constructors use this to refer to another constructor in the same class with a different parameter list.
• Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will
complain.
Class Methods Instance Methods
Class methods are methods which are declared as static. The method can be called without creating an instance of the class
Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes.
Class methods can only operate on class members and not on instance members as class methods are unaware of instance members.
Instance methods of the class can also not be called from within a class method unless they are being called on an
instance of that class. Class methods are methods which are
declared as static. The method can be called without creating an instance of the class.
Instance methods are not declared as static.
37.How are this() and super() used with constructors?
• Constructors use this to refer to another constructor in the same class with a different parameter list.
• Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will
complain.
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..
39.What are Access Specifiers available in Java?
Java offers four access specifiers, listed below in decreasing accessibility:
• Public- public classes, methods, and fields can be accessed from everywhere.
• Protected- protected methods and fields can only be accessed within the same
class to which the methods and fields belong, within its subclasses, and within classes of the same package.
• Default(no specifier)- If you do not set access to specific level, then such a
class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
• Private- private methods and fields can only be accessed within the same class
to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
Situation public protected default private
Accessible to class
from same package? yes yes yes no Accessible to class
from different package? yes no, unless it is a subclass no no
The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.
• final Classes- A final class cannot have subclasses.
• final Variables- A final variable cannot be changed once it is initialized.
• final Methods- A final method cannot be overridden by subclasses.
41.What are the uses of final method?
There are two reasons for marking a method as final:
• Disallowing subclasses to change the meaning of the method.
• Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.
42.What is static block?
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.
43.What are static variables?
Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically
initialized with a default value. The default value depends on the data type of the variables.
44.What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
45.What are static methods?
Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a
particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:
• A static method can only call other static methods.
• A static method must only access static data.
• A static method cannot reference to the current object using keywords super or this.
Selenium
• To eliminate the errors or defects and improve the quality of application
2. Why defects occur?
¾ Hard coding
¾ While integrating the modules ¾ Lack of documentation
¾ Miscommunication ¾ Time pressure
¾ Dynamically changing requirements
3. What is automation Testing?
It is a process of implementing particular work automatically by using a machine, to reduce the need of human work in the production of goods and services...
4. What is meant by Automation in software testing?
It is a process of testing an application(executing the tests, comparing expected and actual results under some controlled conditions and generating the reports)
automatically by using a 'Tool' to reduce the need of human effort. This tool may be Selenium / QTP / RFT / SilkTest /sahi/watir etc…
5. Why you choose selenium?
¾ Selenium is a open source tool
¾ It can Automate any Web Application ¾ It is a perfect tool for Browser Automation ¾ In the market very demand Automation Tool ¾ Around 60-70% companies are using selenium ¾ In future it may be 90%
¾ Once we prepare the code in the windows platform we can run in any OS, platform independent.
¾ We can integrate with No. of tools and languages
6. Types of Automation Tools
¾ Functional Automation Tools: QTP, Winrunner, Silktest, Selenium, Sahi, watir etc.
¾ Performance Tools: LoadRunner, RFT, SOAP etc.
¾ Management tools: Test Director, Quality center, Testlink, Rally etc. ¾ Bugtracking tools: Jira, Bagzilla
¾ Build Tools: ANT and Rake
7. What is Selenium?
¾ Selenium is Functional Automation tool
¾ Selenium is Browser or Web based Automation Tool
¾ Selenium is suite of tools, SeleniumIDE, RC, WebDriver, Grid
¾ It can record or automate any web application but it can’t support for client or desktop application.
¾ It can support many languages java, C#, Ruby, python ¾ Data driven is possible
¾ User can enhance script in any following language JAVA, C#, PHP, Ruby, Python
¾ Selenium is a Functional Testing Tool can be used for Regression testing of Web applications in a variety of browsers and platforms
¾ Selenium was developed by ThoughtWorks, now takeover by sauce labs. ¾ It's an Open Source Tool
1. What to Automate or Not to Automate?
Is automation always advantageous? When should one decide to automate test cases? It is not always advantageous to automate test cases. There are times when manual testing may be more appropriate. For instance, if the application’s user interface will change considerably in the near future, then any automation would need to be
rewritten. Also, sometimes there simply is not enough time to build test automation. For the short term, manual testing may be more effective. If an application has a very tight deadline, there is currently no test automation available, and it’s imperative that the testing get done within that time frame, then manual testing is the best solution. However, automation has specific advantages for improving the long-term efficiency of a software team’s testing processes.
Test automation supports:
• Frequent regression testing
• Rapid feedback to developers during the development process • Virtually unlimited iterations of test case execution
• Customized reporting of application defects
• Support for Agile and eXtreme development methodologies • Disciplined documentation of test cases
5. Test Automation for Web Applications?
Many, perhaps most, software applications today are written as web-based applications to be run in an Internet browser. The effectiveness of testing these applications varies widely among companies and organizations. In an era of
continuously improving software processes, such as eXtreme programming (XP) and Agile, it can be argued that disciplined testing and quality assurance practices are still underdeveloped in many organizations. Software testing is often conducted
manually. At times, this is effective; however there are alternatives to manual testing that many organizations are unaware of, or lack the skills to perform. Utilizing these alternatives would in most cases greatly improve the efficiency of their software development by adding efficiencies to their testing. Test automation is often the answer. Test automation means using a tool to run repeatable tests against the target application whenever necessary.
3. Introducing Selenium
Selenium is a robust set of tools that supports rapid development of test automation for web-based applications. Selenium provides a rich set of testing functions
specifically geared to the needs of testing of a web application. These operations are highly flexible, allowing many options for locating UI elements and comparing
expected test results against actual application behavior. One of Selenium’s key features is the support for executing one’s tests on multiple browser platforms.
4. Selenium Components
Selenium is composed of three major tools. Each one has a specific role in aiding the development of web application test automation.
4.1 Selenium-IDE
Selenium-IDE is the Integrated Development Environment for building Selenium test cases. It operates as a Firefox add-on and provides an easy-to-use interface for developing and running individual test cases or entire test suites. Selenium-IDE has a recording feature, which will keep account of user actions as they are performed and store them as a reusable script to play back. It also has a context menu (right-click) integrated with the Firefox browser, which allows the user to pick from a list of assertions and verifications for the selected location. Selenium-IDE also offers full editing of test cases for more precision and control. Although Selenium-IDE is a
Firefox only add-on, tests created in it can also be run against other browsers by using Selenium-RC and specifying the name of the test suite on the command line.
4.2 Selenium-RC (Remote Control)
Selenium-RC allows the test automation developer to use a programming language for maximum flexibility and extensibility in developing test logic. For instance, if the application under test returns a result set, and if the automated test program needs to run tests on each element in the result set, the programming language’s iteration support can be used to iterate through the result set, calling Selenium commands to run tests on each item.
Selenium-RC provides an API (Application Programming Interface) and library for each of its supported languages: HTML, Java, C#, Perl, PHP, Python, and Ruby. This ability to use Selenium-RC with a highlevel programming language to develop test cases also allows the automated testing to be integrated with a project’s automated build environment.
4.3 Selenium-Grid
Selenium-Grid allows the Selenium-RC solution to scale for large test suites or test suites that must be run in multiple environments. With Selenium-Grid, multiple instances of Selenium-RC are running on various operating system and browser
configurations. Each of these when launching register with a hub. When tests are sent to the hub they are then redirected to an available Selenium-RC, which will launch the browser and run the test. This allows for running tests in parallel, with the entire test suite theoretically taking only as long to run as the longest individual test.
Selenium 1.0 and Selenium-RC.
This is the old, support platform for Selenium 1.0. It should still apply to the Selenium 2.0 release of Selenium-RC.
Browser Selenium IDE Selenium 1 (RC) Operating
Systems
Firefox 3 Record and playback tests Start browser, run
tests Windows, Linux, Mac Firefox 2 Record and playback tests Start browser, run
tests Windows, Linux, Mac IE 8 Test execution only via
Selenium RC* Start browser, run tests Windows, Linux, Mac IE 7 Test execution only via
Selenium RC* Start browser, run tests Windows IE 6 Test execution only via