Constructor in 5 mins

Q. What is constructor.

Constructor is a special member function which has same name as class name and called whenever the object of that class is created.

Q. What are the properties of constructor 

Constructor has following properties:

  • Constructor has same name as class name.
  • It is used for initializing variables of class.
  • It is called whenever object of class is created.
  • It does not have return type, not even void.
  • It can have parameters.

Q. How many types of Constructors are there.

  • Default Constructor       –>  public Message()
  • No-arg Constructor       –>  public Message()
  • Parametrized Constructor     –>  public Message(String str)
  • Copy Constructor                                

Q. What are rules for writing Constructor:

  • Constructor(s) of a class must has same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static and Synchronized.
  • Access modifiers can be used in constructor declaration to control its access 
  • It can have parameters
  • It should not contain return type.
  • It can have throws clause: we can throw exception from constructor.


Q. What happens if you keep a return type for a constructor?

It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name

Q. How to invoke constructor.

        Message m= new Message();


Q. What is the difference between constructors and other regular methods?


Constructor
Regular method
Constructors must have the same name as the class name and cannot return a value .
public class Message {

    private String msg;   
   
//constructor
   
public Message() {}

//parameterize constructor
   
public Message(String str){
        this
.msg=str;
    }
}
The constructors are called only once per creation of an object.
Regular methods can have any name and can be
 called any number of times.
public class Message {
   
//Method
   
public String getMsg() {
    
System.out.println(“hello method”);
       
return “TestMethod”;
    }
}
regular methods can be called many times.



Q. What happens if you do not provide a constructor?
If you do not include a constructor, the Java compiler will create a default constructor in the byte code with an empty argument. This default constructor is equivalent to the explicit constructor.
public Message() {}.
If a class includes one or more explicit constructors like

     //Non-parameterize or NO-ARG constructor
    public Message() {}

    //parameterize constructor
    public Message(String str){
        this.msg=str;
    }

Then java compiler does not create the default constructor public Message() {}.

Q. How a no – argument constructor is different from default Constructor?

By default compiler creates a default constructor with no formal parameters and no throws clause.

And If you have added your own constructor (no matter whether it’s without parameters or with parameters) the compiler will not add the default constructor in this case.

Q. What is Constructor Chaining ?

Constructor Chaining is calling another constructor from one constructor.

Q. How you call one constructor from another? 
By using this() syntax.

package com.thread;

public class Message {

    // parameterize constructor
    public Message(String str) {
        System.out.println(str);
        System.out.println("String constructor");
    }

    // parameterize constructor
    public Message(Integer number) {
        // calling another constructor
        this("Calling String constructor");
        System.out.println("Integer constructor");
    }

    public static void main(String[] args) {
        Message m2 = new Message(3);
        Message m3 = new Message("Test");

        System.out.println(m2);
        System.out.println(m3);
    }

}

//Output
String constructor
Integer constructor
Test
String constructor

Q. How to call the superclass constructor?
You can use the keyword Super to invoke the super class’s constructor.


super("Your Text");


Q. Can we declare constructor as private?

Yes we can declare constructor as private.

Q. How to write  parameterize constructor? 

package com.thread;

public class Message {

    private String msg;
    private Integer number;

    // constructor
    public Message() {
        System.out.println("Empty constructor");
    }

    // parameterize constructor
    public Message(String str) {
        System.out.println("String constructor");
        this.msg = str;
    }

    // parameterize constructor
    public Message(Integer number) {
        System.out.println("Integer constructor");
        this.number = number;
    }

    public static void main(String[] args) {
        Message m1 = new Message();
        Message m2 = new Message(3);
        Message m3 = new Message("Test");

        System.out.println(m1);
        System.out.println(m2);
        System.out.println(m3);
    }

}
Output:
Empty constructor
Integer constructor
String constructor

135 total views, no views today

Run main thread before child thread.

As we all know in multi threading we cant guarantee the order of execution of threads .So in this example i will show you how to make sure one method calls after another.

To implement this we are going to use JOIN() concept of multi threading.


Join() : The join method allows one thread to wait for the completion of another. 

 MyThread1 t1 = new MyThread1();


if t1 is a Thread object whose thread is currently executing.
t1.join(); causes the current thread to pause execution until t1 thread terminates.

So to execute main thread before child thread it should call join method on main thread and hence child thread has to wait until competing of main thread.

Ruuner class: 

package com.thread;

public class ThreadRun {

//Main Thread
public static void main(String args[]) {
//Main thread reference
MyThread1.
mainThread= Thread.currentThread();
  //Thread T-1
MyThread1 t1 = new MyThread1();
t1.setName("t1");
t1.start();

//Main thread logic
for (int i = 0; i < 5; i++) {
System.out.println("Main Thread");
}
}

}
Child Thread class:

package com.thread;

public class MyThread1 extends Thread {
 //static thread to access in other class
static Thread mainThread;

public void run() {

try {
  // Child thread wait here until main completed
mainThread.
join();
}
catch (InterruptedException e1) {
e1.
printStackTrace();
}

//Thread -1 logic
for (int i = 0; i < 5; i++) {
System.
out.println("child Thread -1 " + Thread.currentThread().getName());
try {
Thread.
sleep(1000);
}
catch (Exception e) {
System.
out.println(e);
}
}
}
}

Output:
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1

117 total views, no views today

Join on multiple threads in java

Join() : If a thread (name it T1) calls the join method on another Thread named T2, then T1 waits for T2 to complete its execution before it continues from that point.

below is the example of thread join .


Thread 1:
package com.thread;

public class MyThread1 extends Thread {

 public void run() {

  //Thread T-2 
  MyThread2 t2 = new MyThread2();
  t2.setName("t2");
  //T2 started
  t2.start();

  try {
   //Thread T-1 wait till Thread T-2 get completed
   t2.join();
   
  } catch (InterruptedException e1) {
   e1.printStackTrace();
  }

  //Thread -1  logic
  for (int i = 0; i < 5; i++) {
   System.out.println("child Thread -1 " + Thread.currentThread().getName());
   try {
    Thread.sleep(1000);
   } catch (Exception e) {
    System.out.println(e);
   }
  }
 }
}
Thread 2:

package com.thread;

public class MyThread2 extends Thread {

 public void run() {
  
  //Thread -2 logic
  for (int i = 0; i < 5; i++) {
   System.out.println("child Thread -2 " + Thread.currentThread().getName());
   try {
    Thread.sleep(1000);
   } catch (Exception e) {
    System.out.println(e);
   }
  }
 }
}
Thread runner class:
package com.thread;

public class ThreadRun {

 //Main Thread
 public static void main(String args[]) {
  
  //Thread T-1
  MyThread1 t1 = new MyThread1();
  t1.setName("t1");
  
  try {
   //start thread T-1
   t1.start();
   //Main thread wait for T1 to complete
   t1.join();
   
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  
  //Main thread logic
  for (int i = 0; i < 5; i++) {
   System.out.println("Main Thread");
  }
 }

}
Output:
child Thread -2 t2
child Thread -2 t2
child Thread -2 t2
child Thread -2 t2
child Thread -2 t2
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread

145 total views, no views today

First Cucumber+java+maven project.

Prerequisite: following should be installed:
  • Java
  • Eclipse
  • Maven
  • maven-eclipse-plugin
  • Cucumber-eclipse-plugin

Step 1) Lets create a new project in eclipse by following steps:

Click on new –> Other –> Maven –> Maven Project — > Next

Step 2) Now click on Simple project and keep the default workspace location.

Step 3) Provide details as Artifact id, Group id, name and description. and click on Finish.

Step 4) This should create a basic maven project. 

Create packages as shown in the below snapshot and create new files in the project.


























Feature file:


Feature:  Adding numbers with a Calculator
  In order to not learn math
  As someone who is bad at math
  I want to be able to add numbers using a Calculator
  
  Scenario:  Add two positive numbers
    Given I have a Calculator
    When I add 1 and 1
    Then the sum should be 2
    
  Scenario:  Add a positive and negative number
    Given I have a Calculator
    When I add 1 and -1
    Then the sum should be 0
    
  Scenario:  Add two negative numbers
    Given I have a Calculator
    When I add -1 and -1
    Then the sum should be -2




Runner.java:

@CucumberOptions
(
features = "src/test/resources/featurefile/caclculator.feature",
glue = {"com.steps"},
plugin = {"pretty", "com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"},
tags={"~@ignore"} 
)

This class responsible for reading the features file 
Feature -- link of feature file
Glue Tag -- This holds the package containing steps
Plugin -- any report plugin you want to add.
Tags -- if you want to test specific tags methods like @functional @regression


package com.feature;

import org.junit.AfterClass;
import org.junit.runner.RunWith;

import com.cucumber.listener.Reporter;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(value = Cucumber.class)
@CucumberOptions
(features = "src/test/resources/featurefile/caclculator.feature",
glue = {"com.steps"},
plugin = {"pretty", "com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"},
tags={"~@ignore"} 
)
public class Runnner {

    @AfterClass
    public static void writeExtentReport() {
        Reporter.setSystemInfo("Machine", "Windows 7:-" + "64 Bit");
        Reporter.setSystemInfo("Maven", "3.5.2");
        Reporter.setSystemInfo("Java Version", "1.8.0_151");
    }
}



CalculatorSteps.java :



package com.steps;

import static org.junit.Assert.assertEquals;

import com.feature.Calculator;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;


public class CalculatorSteps {

 private Calculator calculator;

 private int actualSum;
        //  ^ - denotes start of string in feature file given statement
 //  $ - denotes end of string in feature file given statement

 @Given("^I have a Calculator$")
 public void intializeCalculator() {
  this.calculator = new Calculator();
 }
        //  ^ - denotes start of string in feature file when statement
 //  $ - denotes end of string in feature file when statement
        //  (-?\d)  denotes the parameter in number format

 @When("^I add (-?\d) and (-?\d)$")
 public void whenIAddTwoNumbers(int firstNumber, int secondNumber) {
  this.actualSum = this.calculator.add(firstNumber, secondNumber);
 }

 @Then("^the sum should be (-?\d)$")
 public void thenTheSumShouldBe(int expectedSum) {
  assertEquals("The expected sum does not equal the actual sum", expectedSum, this.actualSum);
 }
}
Calcuator.java:

This class is our main class which we need to test using our feature file.This contains our logical code generally.

package com.feature;

public class Calculator {

 public int add(int firstNumber, int secondNumber) {
  return firstNumber + secondNumber;
 }
}
Pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.practise</groupId>
 <artifactId>cucumber</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <description> </description>
 <properties>
  <cucumber.version>0.3.2</cucumber.version>
  <file.encoding>UTF-8</file.encoding>
  <java.version>1.8</java.version>
 </properties>
 <build>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
     <encoding>${file.encoding}</encoding>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>2.5.6</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
   <scope>test</scope>
  </dependency>
  
  
  <!-- Cucummber dependencies -->
  
  <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.5</version>
        </dependency>
        
         <!-- https://mvnrepository.com/artifact/com.vimalselvam/cucumber-extentsreport -->
        <dependency>
            <groupId>com.vimalselvam</groupId>
            <artifactId>cucumber-extentsreport</artifactId>
            <version>3.0.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->
        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>3.1.2</version>
        </dependency>
  
 </dependencies>

</project>

As  you addded all these class and files now time to run the application

open class Runner and rightclick ->run as –>Junit test

You will see this on screen with all passing test cases.

Flow diagram of cucumber test.

117 total views, no views today

First Selenium program using Maven+Java


This is basic example to use Webdriver, Maven with Java.


We need Tools:


1.Eclipse – IDE to Build our applications

Download and install Eclipse. I choose Eclipse IDE 
you can choose IDE of you choice.



2.Maven – We need maven to get all our dependencies automatically, which also allows users to reuse same jars across multiple projects

Download and install maven.
Eclipse does not have integrated Maven support out of the box. To add the support, I am going to use Maven Integration (m2e).


Steps to create program


Step 1:  First create a new Maven project. 

In Eclipse: File -> New -> Other  -> Maven -> Maven project

  • Click: Next, Next, Next
  • Type in field Group Id: com.demo.yourCompanyName
  • Type in field Artifact Id: yourProjectName
  • Click: Finish


Step 2 Edit pom.xml

Eclipse should detect the pom.xml changes automatically, build the project and download required dependencies.

After the build is finished, there should be selenium*.jar files under Maven Dependencies under the Project Explorer panel.

POM.XML

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.yourCompanyName</groupId>
<artifactId>Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>


Step 3:

Create a new test class
Right-click over package com.yourcompany.yourclientprojectname 

under src/test/java and select New -> Class

Type in ClassName: OpenFirefox

Java Code:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class OpenFirefox {

public static void main(String[] args)

{

System.out.println("Start");

System.setProperty("webdriver.gecko.driver", "Path to gekco driver\geckodriver.exe");

WebDriver driver = new FirefoxDriver();

driver.get("https://www.google.co.in/");

System.out.println("End");
}
}


Step 4 :


Right click on class RunAs –>java application.

Your firefox browser will open with given URL “https://www.google.co.in/

140 total views, no views today