One of the oldest trick question from programming interview is, How do you swap two integers without using temp variable? This was first asked to me on a C, C++ interview and then several times on various Java interviews. Beauty of this question lies both on trick to think about how you can swap two numbers with out third variable, but also problems associated with each approach. If a programmer can think about integer overflow and consider that in its solution then it creates a very good impression in the eye of interviewers. Ok, so let's come to the point, suppose you have tow integers i = 10 and j = 20, how will you swap them without using any variable so that j = 10 and i = 20? Though this is journal problem and solution work more or less in every other programming language, you need to do this using Java programming constructs. You can swap numbers by performing some mathematical operations e.g. addition and subtraction and multiplication and division, but they face problem of integer overflow. There is a neat trick of swapping number using XOR bitwise operator which proves to be ultimate solution. We will explore and understand each of these three solutions in detail here, and if you are hungry for more programming questions and solutions, you can always take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions, one of the best book to prepare for programming job interviews.
Read more »
Search
Thursday, August 13, 2015
Wednesday, August 12, 2015
How To Handle SSL Certificate Error In IE Browser For Selenium WebDriver Test
Earlier we learnt how to handle SSL certificate error by creating custom profile In selenium WebDriver test when you run It In Firefox browser as described In THIS POST. IE browser do not have any such feature to create and run test In custom profile. So you need to do something different for IE browser to resolve certificate related error when you run WebDriver test.
As you know, we can resolve error "Enable protected mode for all zones" as described In THIS POST and Set IE browser Zoom Level To 100% Error as described In previous post. Now let's see how to resolved SSL certificate error In IE browser for selenium WebDriver test.
When you see SSL certificate error In IE browser, Your screen will looks like bellow.
There Is one option link with text "Continue to this website (not recommended)." If somehow we can click on this link then original site page will be loaded and our test script can go further for execution. If you view link In HTML mode using F12 then you will realize that link has ID called "overridelink". We can click on that link using driver.navigate() method with Javascript as bellow.
//To click on "Continue to this website (not recommended)." link to load original website.
driver.navigate().to("javascript:document.getElementById('overridelink').click()");This solution Is worked for me In many website's tests. Full example demonstration Is as bellow.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class SSLErrorInIE {
public static void main(String[] args) {
// Set path of IEDriverServer.exe
// Note : IEDriverServer.exe should be In D: drive.
System.setProperty("webdriver.ie.driver", "D://IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("URL of SSL error site");
//To click on "Continue to this website (not recommended)." link to load original website.
driver.navigate().to("javascript:document.getElementById('overridelink').click()");
}
}This way we can resolve SSL certificate error In IE browser. View THIS ARTICLE to know how to handle SSL cretificate error in google chrome browser.
Sunday, August 9, 2015
What Is An Abstract Class In Java?
What Is An Abstract Class?
If you will go to attend an interview for selenium WebDriver with java , 90% Interviewer will ask you this question. Your answer should be like this : An abstract class is a class that is declared with abstract keyword. If class contains any abstract method then you must have to declare your class as abstract class. Also abstract classes can be subclassed, but they cannot be instantiated. That means you can not create object of abstract class. It may or may not have abstract methods. it can have concrete methods too so that it does not provide 100% abstraction.
Earlier we learnt interface in THIS POST. It is 100% abstraction. View THIS POST to know difference between abstract class and interface.
Bellow given class has abstract method so it is declared as abstract class.
//abstract class
public abstract class Animal {
//concrete method
public void eat(String food) {
// do something with food....
}
// abstract method
public abstract void makeNoise();
}Let's try to understand abstract class and abstract methods in detail.
What Is Abstraction in Java?
Abstraction is process of hiding implementation details from user. User can use only functionality but can not see how it is implemented. Example : Calling a friend is best example of abstraction. Here you can talk with each other but you don't know about internal implementation of your phone and it's network using which you can talk. It is called abstraction.
What Is Abstract Method?
If any method is declared with abstract keyword then it is called abstract method. Abstract method can not have a body. Actual implementation of abstract method will be done by it's child class. If any class extends abstract class then that subclass must have to implement all the abstract methods declared by it's super class(abstract class).
Example of abstract class with simple and concrete methods is as bellow.
Animal.javapackage abstraction;
//abstract class
public abstract class Animal {
// concrete method. Sub class can use it if needed.
public void eat(String food) {
// do something with food....
}
// concrete method. Sub class can use it if needed.
public static void sleep(int hours) {
// do something with sleep....
}
// abstract method. Sub classes must have to implement it if extend this class.
public abstract void makeNoise();
}Bellow given classes are sub classes of Animal class so both of them have implemented abstract method of Animal abstract class. But they do not need to implement concrete methods of super class. They can declare and implement their own concrete methods independently.
Dog.java
package abstraction;
public class Dog {
// abstract method of super class is implemented in sub class.
public void makeNoise() {
System.out.println("Bark! Bark!");
}
// Concrete method
public void payingBall() {
System.out.println("Dog is playing with ball");
}
}Cow.java
package abstraction;
public class Cow extends Animal {
// abstract method of super class is implemented in sub class.
public void makeNoise() {
System.out.println("Moo! Moo!");
}
// Concrete method
public void milking() {
System.out.println("Cow is milking");
}
}When And Why To Use Abstract Class?
If you see at above example, Abstract class is not only template for it's child classes but it has it's own functionality too. Like eat(String food), sleep(int hours). Both these methods are concrete but child class can use them if required.
You can use abstract class as parent class for sub classes
- When you expect to implement same method in all sub classes with different implementation detail.
- When you expect to implement methods in super class(abstract class) which can be used by its sub classes if needed.
- When you expect to implement independent method in sub class which do not have any relation or use with its super class.
Points to Remember About Abstract Class
- If class is declared with abstract keyword then it is called abstract class.
- If class has abstract method, you must have to declare class as abstract class.
- In abstract class, You can only declare abstract methods but you can not define abstract methods.
- Sub classes of abstract class must have to implement all abstract methods of super abstract class.
- You can not instantiate(Can not create object of) abstract class.
- Abstract classes can have concrete methods, constructors and Member variables too.
Tuesday, August 4, 2015
How To Find Broken Links/Images From Page Using Selenium WebDriver Example
If you remember, Earlier we learnt how to extract all links from page In THIS POST. Extracting all links from page Is not useful If you don't know all the links are working fine or some of them are broken links or supposing there are few broken Images links. How to find these broken links or broken Images from page using selenium WebDriver? This Is part of testing In which you need to
check status of links/Images -> 1) Link URLs are opening targeted page 2) Images display properly on page or not. If links are Incorrect then It will not work.Finding each and every link from page and verifying It manually will take lots of your time. You will find many broken link checker tools online. You can perform same task using selenium WebDriver. Lets see example on finding broken links from single page.
In bellow given example, First of all I have calculated total number of links on page. Then extracted all links one by one and check Its response code by calling getResponseCode function. I have used apache Interface HttpResponse to get the response code of URL. If It Is 200, that means link URL Is not broken and working fine. But If response code Is 404 or 505 that means link or Image IS broken.
In bellow given example, I have used test page where one link and Img URL Is broken to show you practically how It will differentiate those links from valid links. Execute bellow given selenium WebDriver test example In your eclipse and verify result In console. Console result will show you status of link URL If It Is broken or not.
package Testing_Pack;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class BrokenlinksTest {
public static void main(String[] args) throws IOException {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/09/testing.html");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Find total No of links on page and print In console.
List<WebElement> total_links = driver.findElements(By.tagName("a"));
System.out.println("Total Number of links found on page = " + total_links.size());
//for loop to open all links one by one to check response code.
boolean isValid = false;
for (int i = 0; i < total_links.size(); i++) {
String url = total_links.get(i).getAttribute("href");
if (url != null) {
//Call getResponseCode function for each URL to check response code.
isValid = getResponseCode(url);
//Print message based on value of isValid which Is returned by getResponseCode function.
if (isValid) {
System.out.println("Valid Link:" + url);
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
} else {
System.out.println("Broken Link ------> " + url);
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
}
} else {
//If <a> tag do not contain href attribute and value then print this message
System.out.println("String null");
System.out.println("----------XXXX-----------XXXX----------XXXX-----------XXXX----------");
System.out.println();
continue;
}
}
driver.close();
}
//Function to get response code of link URL.
//Link URL Is valid If found response code = 200.
//Link URL Is Invalid If found response code = 404 or 505.
public static boolean getResponseCode(String chkurl) {
boolean validResponse = false;
try {
//Get response code of URL
HttpResponse urlresp = new DefaultHttpClient().execute(new HttpGet(chkurl));
int resp_Code = urlresp.getStatusLine().getStatusCode();
System.out.println("Response Code Is : "+resp_Code);
if ((resp_Code == 404) || (resp_Code == 505)) {
validResponse = false;
} else {
validResponse = true;
}
} catch (Exception e) {
}
return validResponse;
}
}Console output for above example execution will looks like bellow.
This way you can find broken links or Images from any page using selenium WebDriver.
<< PREVIOUS || NEXT >>
How to load data from CSV file in Java - Example
You can load data from a CSV file in Java program by using BufferedReader class from java.io package. You can read the file line by line and convert each line into an object representing that data. Actually there are couple of ways to read or parse CSV file in Java e.g. you can use a third party library like Apache commons CSV or you can use Scanner class, but in this example we will use traditional way of loading CSV file using BufferedReader.
Read more »
Sunday, August 2, 2015
How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
Problem : You are getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory in your Java program, which uses logging framework to log messages into log file. It could be direct dependency or indirect dependency due to any framework e.g. Spring, Hibernate or any open source library like jackson or any other JSON parsing library.
Read more »
What Is Polymorphism In Java OOP?
We learnt about Encapsulation In previous post. Polymorphism Is another OOP fundamental concept. Interviewer can also ask you about Polymorphism In java then you must be aware about It.
What Is Polymorphism?
Polymorphism Is made from two Greek words -> "polys" and "morphē". polys means "many, much" and morphē means "form, shape". Polymorphism means "many form or many shapes". In normal words, Polymorphism Is the ability by which, We can create reference variables or functions which behaves differently in different programmatic context.
Simple example of polymorphism Is cat makes sound "meow" and dog makes sound "woof". Thus, sound of makeSound() function will depends on the type of animal.There are two types of polymorphisms as bellow.
1) Compile time polymorphism
Compile time polymorphism Is also known as static binding or method overloading. Static polymorphism Is achieved through method overloading. Method overloading means there are several methods with same name In same class but with different types/order/number of parameters. In this situation, Java knows compile time which method needs to Invoke based on Its signature and so It Is known as compile time polymorphism.
Let's understand It with very basic example as bellow.
StaticPolymorph.java
package oopbasics;
public class StaticPolymorph {
//Method 1
public int sum(int x, int y) {
return x + y;
}
//Method 2
public int sum(int x, int y, int z) {
return x + y + z;
}
//Method 3
public int sum(double x, int y) {
return (int) x + y;
}
//Method 4
public int sum(int x, double y) {
return x + (int) y;
}
}Above class has total four methods overloaded with same name sum. Now lets access all of them using different parameters and types as bellow.
ExcStaticPolymorph.java
package oopbasics;
public class ExcStaticPolymorph {
public static void main(String[] args) {
StaticPolymorph poly = new StaticPolymorph();
// Call Method 1
System.out.println(poly.sum(1, 7));
// Call Method 2
System.out.println(poly.sum(4, 2, 1));
// Call Method 3
System.out.println(poly.sum(2.5, 3));
// Call Method 4
System.out.println(poly.sum(4, 3.7));
}
}Output :
8
7
5
7Above class will access sum method from StaticPolymorph.java class based on number of parameters and Its type.
2) Run time polymorphism
Run time polymorphism Is also known as dynamic binding or method overriding. You can get method overriding when you use Inheritance In your program. In this situation, Java knows run time which method needs to Invoke. Let's understand It using very simple example of parent class Animal.java and Its child class Dog.java as bellow.
Animal.java
package oopbasics;
public class Animal {
public void makeNoise() {
System.out.println("Some sound of animal.");
}
}Dog.java
package oopbasics;
class Dog extends Animal {
public void makeNoise() {
System.out.println("Woof");
}
}Both above class has method with same name makeNoise(). Animal.java Is parent class and Dog.java Is Its child class. Now lets access both methods as bellow.
ExcAnimalAndDog.java
package oopbasics;
public class ExcAnimalAndDog {
public static void main(String[] args) {
Animal a1 = new Animal();
// Call makeNoise() from Animal class
a1.makeNoise();
Animal a2 = new Dog();
// Call makeNoise() from Dog class
a2.makeNoise();
}
}Output :
Some sound of animal.
WoofThis Is run time polymorphism In java. You can use multiple children class In above example. Next post will explain you abstract class in java.
Subscribe to:
Posts (Atom)

