Java Interview Questions
Interview Questions
Java:-
1. Method Overriding.
2. Method overloading.
3. Wrapper Class.
SQL:-
1 create the table and perform left outer join, right outer join.
2.Difference between left and right outer join.
C:-
1. Define Pointer with an example.
2.write a code to print the address of a pointer variable.
3.Code to print the value of a pointer variable.
4.Difference between call by value and call by reference.
5.Write a program to delete the third element in an array.
One question about certificate which I mentioned in the resume that how you think it is your achievement.
Q)- What is Blank Final in Java?
- A blank final variable in Java is a final variable that is not initialized during declaration. Below is a simple example of blank final.
// A simple blank final example
final int i;
i = 30;
- How are values assigned to blank final members of objects?
Values must be assigned in constructor.
// A sample Java program to demonstrate use and
// working of blank final
class Test
{
// We can initialize here, but if we initialize here, then all objects get the same value. So we use blank final
final int i;
Test(int x) {
// Since we have initialized above, we must initialize i in constructor.If we remove this line, we get compiler error.
i = x;
}
}
// Driver Code
class Main{
public static void main(String args[])
{
Test t1 = new Test(10);
System.out.println(t1.i);
Test t2 = new Test(20);
System.out.println(t2.i);
}
}
Output: 10
20
If we have more than one constructors or overloaded constructor in class, then blank final variable must be initialized in all of them. However constructor chaining can be used to initialize the blank final variable.
// A Java program to demonstrate that we can
// use constructor chaining to initialize
// final members
class Test
{
final public int i;
Test(int val) { this.i = val; }
Test()
{
// Calling Test(int val)
this(10);
}
public static void main(String[] args)
{
Test t1 = new Test();
System.out.println(t1.i);
Test t2 = new Test(20);
System.out.println(t2.i);
}
}
Run on IDE
Output:
10
20
Q)- Here are few important difference between static and dynamic binding?
1) Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.
2) private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.
3) Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding.
4) Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Here is an example which will help you to understand both static and dynamic binding in Java.
Static Binding Example in Java
public class StaticBindingTest
{
public static void main(String args[])
{
Collection c = new HashSet();
StaticBindingTest et = new StaticBindingTest();
et.sort(c);
}
//overloaded method takes Collection argument
public Collection sort(Collection c)
{
System.out.println("Inside Collection sort method");
return c;
}
//another overloaded method which takes HashSet argument which is sub class
public Collection sort(HashSet hs)
{
System.out.println("Inside HashSet sort method");
return hs;
}
}
Output: Inside Collection sort method
Example of Dynamic Binding in Java
public class DynamicBindingTest
{
public static void main(String args[])
{
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle
{
public void start()
{
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle
{
@Override
public void start()
{
System.out.println("Inside start method of Car");
}
}
Output: Inside start method of Car
Q)- What is the use of making constructor private in a class? (Singleton Class)
- https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
- Some reasons where you may need private constructor:
- The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
- A utility class, that only contains static methods.
- Java Singleton Class Example Using Private Constructor
We can make constructor as private. So that We can not create an object outside of the class.
This property is useful to create singleton class in java.
Singleton pattern helps us to keep only one instance of a class at any time.
The purpose of singleton is to control object creation by keeping private constructor.
Java Singleton Sample Code
Code:
package com.myjava.constructors;
public class MySingleTon {
private static MySingleTon myObj;
/**
* Create private constructor
*/
private MySingleTon(){
}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
public void getSomeThing(){
// do something here
System.out.println("I am here....");
}
public static void main(String a[]){
MySingleTon st = MySingleTon.getInstance();
st.getSomeThing();
}
}
Q)- Differene b/w throw & throws Keyword:-
No. throw throws
1) Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception.
2) Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
Ex. void method(){ throw new ArithmeticException("sorry"); } public void method() throws IOException,SQLException.
Q)- Differene b/w this & Super Keyword:-
- There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
Usage of java this keyword- Here is given the 6 usage of java this keyword.
1- this can be used to refer current class instance variable.
2- this can be used to invoke current class method (implicitly)
3- this() can be used to invoke current class constructor.
4- this can be passed as an argument in the method call.
5- this can be passed as argument in the constructor call.
6- this can be used to return the current class instance from the method.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Output:
0 null 0.0
0 null 0.0
Note:- In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
- Then use this keyword
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
Output:
111,"ankit",5000
112,"sumit",6000
Note:- If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
Output:
111,"ankit",5000
112,"sumit",6000
Q)- Difference Between Abstract Class and Interface in Java?
-
Q)- Difference between singleton class and static class?
-
NEFT-CITIN18XXX6-LOOKSMART INDIA PVT LTD-/ I
NEFT-CITIN18XX1-LOOKSMART INDIA PVT LTD-/ I
What is Security Testing: Complete Tutorial
What is Security?
Security is set of measures to protect an application against unforeseen actions that cause it to stop functioning or being exploited. Unforeseen actions can be either intentional or unintentional.
What is Security testing?
Security Testing is a variant of Software Testing which ensures, that system and applications in an organization, are free from any loopholes that may cause a big loss. Security testing of any system is about finding all possible loopholes and weaknesses of the system which might result into a loss of information at the hands of the employees or outsiders of the Organization.
What is Security Testing: Complete Tutorial
The goal of security testing is to identify the threats in the system and measure its potential vulnerabilities. It also helps in detecting all possible security risks in the system and help developers in fixing these problems through coding.
Types of Security Testing:
There are seven main types of security testing as per Open Source Security Testing methodology manual. They are explained as follows:
Vulnerability Scanning:
This is done through automated software to scan a system against known vulnerability signatures.
Security Scanning:
It involves identifying network and system weaknesses, and later provides solutions for reducing these risks. This scanning can be performed for both Manual and Automated scanning.
Penetration testing:
This kind of testing simulates an attack from a malicious hacker. This testing involves analysis of a particular system to check for potential vulnerabilities to an external hacking attempt.
Risk Assessment:
This testing involves analysis of security risks observed in the organization. Risks are classified as Low, Medium and High. This testing recommends controls and measures to reduce the risk.
Security Auditing:
This is an internal inspection of Applications and Operating systems for security flaws. Audit can also be done via line by line inspection of code
Ethical hacking:
It's hacking an Organization Software systems. Unlike malicious hackers ,who steal for their own gains , the intent is to expose security flaws in the system.
Posture Assessment:
This combines Security scanning, Ethical Hacking and Risk Assessments to show an overall security posture of an organization.
- Integration of security processes with the SDLC:
It is always agreed, that cost will be more ,if we postpone security testing after software implementation phase or after deployment. So, it is necessary to involve security testing in SDLC life cycle in the earlier phases.
Let's look into the corresponding Security processes to be adopted for every phase in SDLC
SDLC Phases Security Processes
Requirements Security analysis for requirements and check abuse/misuse cases
Design Security risks analysis for designing. Development of Test Plan including security tests
Coding and Unit Testing Static and Dynamic Testing and Security White Box Testing
Integration Testing Black Box Testing
System Testing Black Box Testing and Vulnerability scanning
Implementation Penetration Testing, Vulnerability Scanning
Support Impact analysis of Patches
- Test plan should include
Security related test cases or scenarios
Test Data related to security testing
Test Tools required for security testing
Analysis on various tests outputs from different security tools
- Sample Test Scenarios for Security Testing:
Sample Test scenarios to give you a glimpse of security test cases -
Password should be in encrypted format
Application or System should not allow invalid users
Check cookies and session time for application
For financial sites, Browser back button should not work.
- Methodologies
In security testing, different methodologies are followed, and they are as follows:
Tiger Box: This hacking is usually done on a laptop which has a collection of OSs and hacking tools. This testing helps penetration testers and security testers to conduct vulnerabilities assessment and attacks.
Black Box: Tester is authorized to do testing on everything about the network topology and the technology.
Grey Box: Partial information is given to the tester about the system, and it is a hybrid of white and black box models.
http://toolsqa.com/selenium-webdriver/testng-annotations-groups-depends/
TestNG Groups Anotation:-
-
@Test (groups = { "Car" })
public void Car1() {
System.out.println("Batch Car - Test car 1");
}
@Test (groups = { "Car" })
public void Car2() {
System.out.println("Batch Car - Test car 2");
}
@Test (groups = { "Scooter" })
public void Scooter1() {
System.out.println("Batch Scooter - Test scooter 1");
}
@Test (groups = { "Scooter" })
public void Scooter2() {
System.out.println("Batch Scooter - Test scooter 2");
}
@Test (groups = { "Car", "Sedan Car" })
public void Sedan1() {
System.out.println("Batch Sedan Car - Test sedan 1");
}
XML file:-
Dependent Test:-
-
@Test (dependsOnMethods = { "OpenBrowser" })
public void SignIn() {
System.out.println("This will execute second (SignIn)");
}
@Test
public void OpenBrowser() {
System.out.println("This will execute first (Open Browser)");
}
@Test (dependsOnMethods = { "SignIn" })
public void LogOut() {
System.out.println("This will execute third (Log Out)");
}
Priority Test:-
- @Test(priority = 0)
Disable Test:-
- @Test(enabled=false)
- @Test(priority = 3, enabled = false)
Parallel Tests:-
-
Parallel Classes:-
-
Parallel Methods:-
-
Retry Failed Tests in TestNG:-
- TestNG have org.testng.IRetryAnalyzer interface to retry failure test.
public interface IRetryAnalyzer {
/**
* Returns true if the test method has to be retried, false otherwise.
*
* @param result The result of the test method that just ran.
* @return true if the test method has to be retried, false otherwise.
*/
public boolean retry(ITestResult result);
}
- Create new class RetryAnalyzer & implemnents IRetryAnalyzer interface
- package Tests;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class RetryAnalyzer implements IRetryAnalyzer {
int counter = 0;
int retryLimit = 4;
@Override
public boolean retry(ITestResult result) {
if(counter < retryLimit){
counter++;
return true;
}
return false;
}
}
- Lets see how we can use it, there are two ways to include retry analyser in your tests
1) By specifying retryAnalyzer value in the @Test annotation
2) By adding Retry analyser during run time by implementing on the of the Listener interfaces
- 1)-
import org.testng.Assert;
import org.testng.annotations.Test;
public class Test001 {
@Test(retryAnalyzer = Tests.RetryAnalyzer.class)
public void Test1()
{
Assert.assertEquals(false, true);
}
@Test
public void Test2()
{
Assert.assertEquals(false, true);
}
}
TestNG Listeners:-->
- As far as testing concern only few can be used effectively such as :
- ISuiteListener: It has two method in it onStart() & onFinish(). Whenever a class implements this listener, TestNG guarantees the end-user that it will invoke the methods onStart() and onFinish() before and after running a TestNG Suite. So before TestNG picks up your suite for execution, it first makes a call to onStart() method and runs whatever has been scripted in this method. In a similar way, it again makes a call to onFinish() method after a suite has been run.
- ITestListener: The working of this listener is also exactly the same as ISuiteListerner but the only difference is that it makes the call before and after the Test not the Suite. It has seven methods in it.
- onFinish(): Invoked after all the tests have run and all their Configuration methods have been called.
- onStart(): Invoked after the test class is instantiated and before any configuration method is called.
- onTestFailedButWithinSuccessPercentage(ITestResult result): Invoked each time a method fails but has been annotated with successPercentage and this failure still keeps it within the success percentage requested.
- onTestFailure(ITestResult result): Invoked each time a test fails.
- onTestSkipped(ITestResult result): Invoked each time a test is skipped
- onTestStart(ITestResult result): Invoked each time before a test will be invoked.
- onTestSuccess(ITestResult result): Invoked each time a test succeeds.
- IInvokedMethodListener: The working of this listener is also exactly the same as ISuiteListerner & ITestListerner and the only difference is that it makes the call before and after every Method. It has only two methods in it.
- afterInvocattion(): Invoke after each method
- beforeInvocation(): Invoke before each method
Steps to add listeners in Selenium:
1) create Listerner Class & implements Interface like ISuiteListener,ITestListener or more as per needs
2) Create another class to impliment it & import TestNG Listener to your test class.
- @Listeners(PackageName.ListenerClassName)
- // For e.g. @Listeners(utility.Listener.class)
3) Add Listener tag in TestNG xml file in suite tag not in test tag:
//
- Step 1:-
package utility;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.Reporter;
public class Listener implements ITestListener, ISuiteListener, IInvokedMethodListener {
// This belongs to ISuiteListener and will execute before the Suite start
@Override
public void onStart(ISuite arg0) {
Reporter.log("About to begin executing Suite " + arg0.getName(), true);
}
// This belongs to ISuiteListener and will execute, once the Suite is finished
@Override
public void onFinish(ISuite arg0) {
Reporter.log("About to end executing Suite " + arg0.getName(), true);
}
// This belongs to ITestListener and will execute before starting of Test set/batch
public void onStart(ITestContext arg0) {
Reporter.log("About to begin executing Test " + arg0.getName(), true);
}
// This belongs to ITestListener and will execute, once the Test set/batch is finished
public void onFinish(ITestContext arg0) {
Reporter.log("Completed executing test " + arg0.getName(), true);
}
// This belongs to ITestListener and will execute only when the test is pass
public void onTestSuccess(ITestResult arg0) {
// This is calling the printTestResults method
printTestResults(arg0);
}
// This belongs to ITestListener and will execute only on the event of fail test
public void onTestFailure(ITestResult arg0) {
// This is calling the printTestResults method
printTestResults(arg0);
}
// This belongs to ITestListener and will execute before the main test start (@Test)
public void onTestStart(ITestResult arg0) {
System.out.println("The execution of the main test starts now");
}
// This belongs to ITestListener and will execute only if any of the main test(@Test) get skipped
public void onTestSkipped(ITestResult arg0) {
printTestResults(arg0);
}
// This is just a piece of shit, ignore this
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
}
// This is the method which will be executed in case of test pass or fail
// This will provide the information on the test
private void printTestResults(ITestResult result) {
Reporter.log("Test Method resides in " + result.getTestClass().getName(), true);
if (result.getParameters().length != 0) {
String params = null;
for (Object parameter : result.getParameters()) {
params += parameter.toString() + ",";
}
Reporter.log("Test Method had the following parameters : " + params, true);
}
String status = null;
switch (result.getStatus()) {
case ITestResult.SUCCESS:
status = "Pass";
break;
case ITestResult.FAILURE:
status = "Failed";
break;
case ITestResult.SKIP:
status = "Skipped";
}
Reporter.log("Test Status: " + status, true);
}
// This belongs to IInvokedMethodListener and will execute before every method including @Before @After @Test
public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1) {
String textMsg = "About to begin executing following method : " + returnMethodName(arg0.getTestMethod());
Reporter.log(textMsg, true);
}
// This belongs to IInvokedMethodListener and will execute after every method including @Before @After @Test
public void afterInvocation(IInvokedMethod arg0, ITestResult arg1) {
String textMsg = "Completed executing following method : " + returnMethodName(arg0.getTestMethod());
Reporter.log(textMsg, true);
}
// This will return method names to the calling function
private String returnMethodName(ITestNGMethod method) {
return method.getRealClass().getSimpleName() + "." + method.getMethodName();
}
}
TestNG Reporter Logs:-
- import org.apache.log4j.Logger;
- import org.apache.log4j.xml.DOMConfigurator;
- import utility.logs;
private static Logger Log = Logger.getLogger(Log.class.getName());
@Test
public static void test() {
DOMConfigurator.configure("log4j.xml");
driver = new FirefoxDriver();
Log.info("New driver instantiated");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Log.info("Implicit wait applied on the driver for 10 seconds");
driver.get("http://www.store.demoqa.com");
Log.info("Web application launched");
// Our first step is complete, so we produce a main event log here for our reports.
Reporter.log("Application Lauched successfully | ");
driver.findElement(By.xpath(".//*[@id='account']/a")).click();
Log.info("Click action performed on My Account link");
driver.findElement(By.id("log")).sendKeys("testuser_1");
Log.info("Username entered in the Username text box");
driver.findElement(By.id("pwd")).sendKeys("Test@123");
Log.info("Password entered in the Password text box");
driver.findElement(By.id("login")).click();
Log.info("Click action performed on Submit button");
// Here we are done with our Second main event
Reporter.log("Sign In Successful | " );
driver.findElement(By.id("account_logout"));
Log.info("Click action performed on Log out link");
driver.quit();
Log.info("Browser closed");
// This is the third main event
Reporter.log("User is Logged out and Application is closed | ");
}
