How To Learn Test Automation From Zero

Manual testers that want to move to test automation should do this gradually by learning one automation skill at a time.

The process of learning test automation is similar with climbing a staircase, one stair at a time.

Each next skill should be just a bit more complex that the previous one.




Many testers don't know how to move from manual testing to test automation.

They don't know either what skills are needed for test automation.

Or how these skills should be learned and in what order.



Where can inspiration be found on how to learn test automation?


Sometimes, inspiration comes from unexpected places.


I have been reading lately Stephen King's book, "On Writing" where he explains the secrets of his creative writing.

Success did not come for him either easy or fast.

Over the years, his works were rejected hundreds of times by the editors of the magazines where he was trying to publish.

Most people, when facing repeated rejections, think of quitting and doing something else, something where they can do better.

Not Stephen King.

Every time he got a rejection note, the note was placed on a nail attached to a wall from his bedroom. The nail and the notes on it were the proof that his writing skills are not good yet and in need of more honing and improvement. 

In time, the number of rejection notes increased so much so nail was replaced by a spike with plenty of additional space for the coming rejections.



And he persevered and wrote more.

Initially, he targeted the 1960 version of blogs.

When his novels were accepted there, he moved to writing for second tier magazines and then for the first tier magazines.

Finally, he published his first novel Carrie after 10 years of writing.

To summarize, Stephen Kings's writing process was supported by 3 main activities:
  • lots of practice; he wrote for 10 years before publishing his first novel
  • driven by honest feedback; the number of rejection notes from the wall's spike showed the true value of his writing
  • challenge himself just barely above his current skill level; as soon as his writings were accepted by a publication, he started writing immediately for better publications, challenging his skills this way

So what can we use from Stephen King's story for test automation?

The last activity was the one that caught my attention: 
challenge himself just barely above his current skill level

I wasn't sure why it stuck in me, why I could not forget about it.

My first intuition was that it may be related to the way that I was approaching learning about testing.

The way I was learning and still do consisted in
  • learning some aspect of testing
  • keeping at it until having a good understanding
  • starting learning another skill that was close to previous one but a bit more difficult

For example, after learning HTML to understand how web pages are build, I continued with CSS (Cascade Style Sheets) on how styling information is getting added to the HTML elements.

And then continued with JavaScript on how dynamic effects come into play in web pages.


Isn't this the same as 
Challenge Yourself  Just Beyond Your Current Skill Level?


How can these ideas be applied for learning test automation?

What skills does someone need to start from zero in automated testing?

How does one get started in automation testing?





Going from manual testing to test automation is similar to walking on a staircase.

At the bottom of the staircase, you have manual testing.

Test automation is at the top of the staircase.

So you start walking, one step at a time:

                                                Test Automation (basic skills)

                                             Learn Page Object Model

                                         Learn Object Oriented Programming in Java
                                      Learn the WebDriver framework

                                 Learn JUNIT                                                            
  
                            Learn the Java basics
                                
                        Learn Eclipse

                     Learn how to create XPATH locators

                 Use browser plugins (Firebug, Firepath, FireCookie)                     

             Learn HTML and CSS
                
         Read how the HTTP protocol works, get and post requests

     Understand how browsers work
            
Manual Testing



A few words below on each stair.




Understand how browsers work

Let's take a specific type of test automation: 
web test automation using Java as the programming language and the Selenium WebDriver framework

Since test automation is all about writing code that interacts with the elements of a site through a browser, it is useful to understand more about
  • the components of a browser
  • the settings that control a browser
  • how cookies works
  • how browser sessions work
  • browser DOM; this is an internal browser structure created from the HTML and CSS code; as soon as a new HTML element is added to the browser DOM, it is displayed on the page in the browser


Read about how the HTTP protocol works

Each page displayed by a browser is part of a website hosted on a web server.

For every page change that happens in the browser, there is communication between the browser and the web server.

This communication happens over the HTTP protocol.

Understanding how HTTP works is useful for test automation as web pages can be requested in a few different ways (get, post requests).


While learning about HTTP, look also into
  • URL parameters
  • parameter coding and decoding  

Learn HTML 

All websites are built using HTML.

In test automation, we interact with elements of a web page and in order to do this, it is important to understand how these elements are created.

Basic HTML knowledge is useful for test automation:
  • common HTML elements: buttons, text boxes, lists, links, etc
  • HTML tags
  • HTML attributes

After going through HTML theory, reading about CSS clarifies how style sheets are added to HTML code so that the end result is good looking web pages.



Use browser plugins (Firebug, Firepath, Chrome Inspector)




The browser plugins are helpful for providing access to information about 
  • HTML source of a page: The HTML source of a page can be viewed through the View Page Source option of any browser; a browser plugin like FireBug shows the same information in an easy to understand tree-like format
  • cookies; some of the browser plugins such as FireBug not only show the cookie information but allow modifying the cookies' values
  • information about the page load; all components of a page are presented, their size, content type and loading time

Learn how to create XPATH locators

Before a test automation script can interact with a web page element, it needs a way of finding the element on the page.

XPATH provides a flexible way of creating locator expressions for finding web page elements.


Learn Eclipse

Test automation is all about writing code in a programming language that interacts with a site in the browser through a test automation framework.

The code development is being done in an application called IDE (integrated development environment).

The IDE used most of the time for Java projects is Eclipse.

Before creating projects in Eclipse, learning about the Eclipse main functionalities is a good idea.


 Learn Java basics

Test automation is 100% programming in a language.

In our case, the language is Java.

So you need to learn the Java language basics such as
  • basic data types (integer, boolean, string)
  • create variables
  • data type operators
  • boolean operators
  • if/else statement
  • switch statement
  • for statement
  • while statement
  • arrays 
  • lists
  • other classes from the Java API

Learn JUNIT

JUNIT is a unit testing framework that is typically being used by developers for creating unit tests that validate the code correctness.

For test automation, JUNIT provides a way of creating independent test scripts.

Some of the fundamental JUNIT concepts for test automation are
  • test scripts
  • assertions
  • annotations
  • test suites

Learn the Selenium WebDriver framework

The test automation scripts interact with elements of a website through the test automation framework, Selenium WebDriver.

Selenium WebDriver framework has lots of classes specialized in 
  • managing the browser (WebDriver class)
  • interacting with common HTML elements (WebElement class)
  • interacting with lists and dropdown lists (Select class)
  • finding elements (WebDriverWait class)
  • using element locators (By class)

Learn Object Oriented Programming in Java

The next level of Java programming is related to the object oriented concepts.

You need to learn about
  • class inheritance
  • polymorphism
  • abstract classes
  • interfaces

All these high level programming concepts will allow you to take your test automation scripts to the next level with the help of ................ Page Object Model



Learn Page Object Model

While learning test automation, your test scripts include WebDriver API commands.

This is ok while learning but these types of scripts are difficult to maintain on the long run.

The WebDriver API commands need to be removed then from the test scripts.

The Page Object Model, together with the Object Oriented Concepts, will help you create your own classes that correspond to site pages.

This way, the WebDriver API commands will be included in the Page Object classes and the test scripts use the Page objects.



Start Practicing Your New Test Automation Skills

Learning about test automation is very important but the automation practice is essential.

Start working on your projects as soon as possible.

Create your first test automation project and continue from there.



Is this the end of the learning?

Do you know test automation at this point?

You reached the basic level of test automation and the end of the first staircase.

The next staircase is waiting for you ................

Tutorial - How To Create Your First Selenium WebDriver Project In 10 Easy Lessons

The best way of getting started with test automation using Selenium WebDriver and Java is through practice.

This test automation tutorial shows you how to create your first Selenium WebDriver project.

You will learn through practice about
  • phases of a test automation project
  • how to set up your test automation environment
  • how to convert a regression test case into an automated test case
  • how to create locators for all web elements that the test scripts need to interact with
  • how to write the test automation code using the Selenium WebDriver framework
  • how to create JUNIT test scripts and use JUNIT assertions
  • how to run test scripts in different browsers
  • how to synchronize the test scripts with the website
  • how to use By variables for locators (NEW)
  • share the browser between test scripts (NEW)

All these in just 10 easy lessons!

The work needed for each lesson takes about 30 minutes to complete.

To make this test automation course even more useful for you, you can email me about any issues that you are running into while working on your project.



More than 500 testers took this course so far.



Unfortunately, the course is no longer free.

You can still attend it for just USD 7.

Less than $1 per lesson.

If you are interested, please use the following link for the USD 7 transfer:

PayPal.Me/AlexandruSiminiuc


I will email you the course link as soon as the transfer is complete.

Alex

How to read test automation script parameters from a CSV file

If your test automation scripts are using parameters, the parameters values can be stored in a CSV file.

A CSV parser is needed for reading the content of the file and providing the data to the test automation script.

One of the parsers that can be used is OPEN CSV

First, download the Open CSV jar file:




Then, a
dd this jar file to the project in Eclipse:
  • right click on the project name
  • select Properties
  • select Java Build Path
  • select the Libraries tab
  • click the Add External Jars button
  • browse to the folder where the Open CSV Jar file is saved
  • select the jar file
  • click OK to save the changes





Display the Package Explorer view in Eclipse by going to:


Menu --> Window --> Show View --> Package Explorer

Expand the project in Package Explorer, expand Referenced Libraries and then expand the open CSV jar:



Expand the com.opencsv package.


The package includes multiple classes such as 
  • CSVParser
  • CSVReader
  • CSVWriter
  • CSVIterator


We will use CSVReader for reading the content of a text file.

Expand the CSVReader class and take a look at the methods:



For the purpose of reading the content of the text file, we need:

CSVReader(Reader) constructor
The constructor will create the csv file object.

readAll() method
This method will read the file content and provide it as a list of String arrays.

close()
This method will close the csv reader object.



The text file includes multiple lines of text.

Each line has multiple values separated by -:

keyword-sortorder-resultnumber
java-author-10
oracle-date-20
microsoft-title-15



How does the code looks like?


import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import com.opencsv.CSVReader;

public class Class1 {

 public static void main(String[] args) throws IOException {

  String filePath = "c:\\temp\\parameters.txt";

  CSVReader csvSource;
  List<String[]> allLines;  
  
  FileReader fileReader = new FileReader(filePath);

  csvSource = new CSVReader(fileReader);
  allLines = csvSource.readAll();

  for (int lineNo = 0; lineNo < allLines.size(); lineNo++) {
    String[] currentLineArray = allLines.get(lineNumber);
    String currentLine = currentLineArray[0];
    String[] values = currentLine.split("-");

    for (int index = 0; index < values.length; index++)
      System.out.println(values[index]);

  }
 }
}



Lets see how we can apply this code to a WebDriver script.

The following script is very simple:
  • it opens a site (http://www.vpl.ca)
  • executes a keyword search (for the Java keyword)
  • checks that the url of the results page is correct


The parameter to be added to the script corresponds to the Java keyword.

After adding the parameter, we will be able to run the script for all keyword values stored in the text file.


@Test
public void testPage() throws InterruptedException { 

  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.vpl.ca");

  WebElement searchField;
  searchField = driver.findElement(
           By.xpath("//input[@id='globalQuery']"));

  searchField.click();
  searchField.sendKeys("java");

  WebElement searchButton;
  searchButton = driver.findElement(
          By.xpath("//input[@class='search_button']"));

  searchButton.click();

  Thread.sleep(5000);
  String resultsPageUrl = "t=keyword";
  assertTrue("this is not the results page", 
             driver.getCurrentUrl().indexOf(resultsPageUrl) >= 0);

  driver.quit(); 
} 


The test script updated with parameters is below.



import static org.junit.Assert.*;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.opencsv.CSVReader;

@RunWith(value = Parameterized.class)
public class tests {
 
  private String stringValue;
 
  public tests(String stringValue) {
     this.stringValue = stringValue;
  }
     
    @Parameters
    public static Collection< object > data() throws IOException {
  
      /*
       * if the values of the parameters are not read from a file,
       * the data array is created this way.

            Object[][] data = 
               {
                  {"java-author-10"},
                  {"oracle-date-20"},
                  {"microsoft-title-15"}
               };
     
       * if the values of the parameters are read from a file,
       * the data array needs to be populated from the file
     */
  
     String filePath = "c:\\temp\\parameters.txt";
  
     CSVReader csvSource;
     List< string > allLines; 
             
     csvSource = new CSVReader(new FileReader(filePath));
     allLines = csvSource.readAll();
     csvSource.close();
  
     Object[][] data = new Object[allLines.size()][];
  
     for (int lineNumber = 0; lineNumber < allLines.size(); lineNumber++) 
         data[lineNumber] = allLines.get(lineNumber);             
      
     return Arrays.asList(data);       
  }
  
  @Test
  public void testPage() throws InterruptedException {

     String[] values = stringValue.split("-");
     String keyword = values[0];
  
     WebDriver driver;
     driver = new FirefoxDriver();
   
     driver.get("http://www.vpl.ca");
   
     WebElement searchField;
     searchField = driver.findElement(
                By.xpath("//input[@id='globalQuery']"));
   
     searchField.click();
     searchField.sendKeys(keyword);
   
     WebElement searchButton;
     searchButton = driver.findElement(
                By.xpath("//input[@class='search_button']"));   

     searchButton.click();
   
     Thread.sleep(5000);
   
     String resultsPageUrl = "t=keyword";
     assertTrue("this is not the results page", 
                driver.getCurrentUrl().indexOf(resultsPageUrl) >= 0);
   
     driver.quit();
                 
  }
}

How to get a test automation job without experience

There is high demand today on the job market for manual testers with test automation skills.

But the paradox is that there are few qualified testers available.




Why is this?

One reason may be that manual testers are not learning programming and test automation due to their concern that it is not possible to get an automation job without work experience.

This article tells you how to get a test automation job without having work experience.

It is based on my personal experience and on the reason for creating this blog.

test-able.blogspot.ca was created in 2011.

I was then a full time employee (last time working a full time job) for a major online Canadian company.

The job started 8 years before so I felt ready for new challenges and projects.

For that company, I created the testing department, hired the testers, implemented the testing processes and tools. The testing team went from 2 testers in the beginning to 14 testers when I left. In summary, I added the testing team to the software development department.

I thought that I knew my job very well.





But in the same time, I was a bit anxious and wondering if I would be capable of performing well for other employers.

So, to get control of my job change anxiety, I pushed the pedal a little bit on self training and looked into things that I did not know yet like:

- exploratory testing

Good books such as the "Exploratory Software Testing" by James Whittaker and "Lessons Learned In Software Testing" by James Bach taught me what exploratory testing is and how it is done.

- mobile testing

"Tap Into Mobile Application Testing" by Jonathan Kohl has been of great help here.

After the learning phase, I practiced both mobile and exploratory testing for about 2 years in more than 800 projects with uTest.com with great results.

- test automation

The first test automation tool that I worked with was Quick Test Professional (QTP).

My employer at that time purchased the full suite of Mercury Quality Assurance tools which included Quality Center, Load Runner and QTP.

Even after learning the new skills, something was still missing.

I was looking for a way of making public who I was from a professional point of view.

I was also searching for something that will make me different and more interesting for recruiters than the other testers.




I always considered that having a work portfolio is the best instrument of getting more work.

After seeing the quality work produced already, new clients have the confidence of giving you more work.

But what portfolio did I have at that time?

What could I show about "Alex the tester" to a recruiter or a company interested in hiring me?

After reading James Bach's advice to new testers that they should blog about testing, I created the blog.





Initially, the blog had 1 purpose only: to expose more information to public about my testing experience, knowledge and skills.

What I do, what I learn, what I read, what is interesting for me, what testing problems I am struggling with.

My thought was that exposing lots of information about my testing on the blog will help me find other jobs.

And it did.


It really did.

Recruiters and companies interested in hiring me were able now to not only see my resume but also read my blog and find there evidence about my testing skills.

After a while, the purpose of the blog changed.




I started being more interested in test automation so I thought that the blog can become the repository or portfolio of my test automation experiences.

Everyone interested in hiring me was able to read the blog and based on the information found there decide if 


  • I have the required skills
  • I have the proper mindset when it comes to testing
  • I did relevant work in the past
  • I am a good candidate for the interview


The blog became a way of providing proof that I can do test automation through the published articles, code samples, articles published on other blogs, etc.

I am talking about my blog but what does this have to do with the article's topic?

So going back, how can anyone get a test automation job without having any automation experience?

This is one of questions that I am getting from people that want to learn test automation.

They think that learning test automation is good and useful.

But, in the same time, they don't have the confidence that companies will hire them due to the lack of practical experience.

So this concern holds them back and in many cases they postpone the test automation learning until later.

Learning test automation is obviously not easy for manual testers.

It includes learning a programming language, a test automation framework and unit testing.

It takes time, focus and perseverance.

So let's assume that you took a test automation course or learned all these things by yourself.

What do you do now?





How do you get a test automation job without experience?

There are a few things that I did with this blog that you can do as well.

They will help a lot with getting your desired automation position:


1. create your own blog and dedicate it to learning and practicing test automation

Choose a name for the blog that is related to test automation:

Example:
test-automation-practice.blogspot.ca
learn-and-practice-test-automation.blogspot.com

You can create the blog in minutes for free using Blogspot or Wordpress.

Or any other blogging platform that you like.

You can even build your own site.

2. write on the blog for recruiters and companies

Everything that you write on the blog should have one purpose only:
to convince other people that you know test automation and can write code for it.

When writing for the blog, try writing less articles but with more content instead of more and shorter articles.

Try writing more about what you learn and do and less about general topics such as what test automation is and how it works.

IT recruiters are interested in finding you a job in test automation.

Learning about test automation in general is not so important for them.

3. keep the blog focused on test automation

The blog becomes less effective if you mix test automation articles with articles on other topics.

If you want to blog on other topics, consider creating a separate blog.

4. while learning test automation, start writing articles about


  • new things that you learned; write about new programming concepts, about new test automation framework components, about unit testing, about other skills like xpath and css selectors
  • post samples of code that you wrote, lots of samples
  • obstacles for your learning and their solutions
  • questions that you have about test automation

5. as soon as your automation knowledge gets better, start working on a project that automates the functional testing for a well known site

Choose a well known site first.

Select a few functional scenarios that the users of the site are going through.

If you select a site that has an ecommerce component, avoid automating scenarios related to user login and shopping cart.

Start writing the test scripts for the selected user scenarios.





6. keep improving the test scripts for the selected site while your knowledge gets better

As soon as you learn things like explicit waits, implement them in your scripts.

After learning how to create your own classes using the page object model, change your scripts for these new concepts.

Refactor the code of the scripts to make the scripts easier to understand, easier to modify and shorter.

7. create a public repository on GitHub.com and publish there your code from time to time

Give access to the public to the code.

Share the GitHub repository link on your blog.




8. keep learning about programming and test automation and keep improving your code

One of your goals is to use the blog to convince recruiters and companies that you know programming and test automation.

The IT recruiters do not know how to evaluate if your automation code is good or not.

But your potential employer can do that.

So work hard on creating the best code that you can.

9. start connecting on LinkedIn with IT recruiters

You are building the blog for recruiters and potential employers so you need to link with them.

10. from time to time, add links of articles from your blog to your LinkedIn profile

You can also publish articles on LinkedIn.

All your connections including IT recruiters will get your test automation updates.

11. update your LinkedIn profile with your new programming and test automation skills

12. keep learning and keep blogging

13. add the blog link to your resume

How do all these help you finding a test automation job?

The blog and your GitHub code repository will be the proof that 


  • you do know programming
  • you do know test automation
  • you can write good test automation code


The blog and the GitHub code repository become your test automation experience.

There are more benefits to having a testing blog.

First, your technical writing will improve a lot by creating articles for the blog.

Second, writing about test automation will make you think more about what you learned.

In order to explain other people about test automation, you will have to have everything clear in your head first and this will just strengthen your knowledge.


You can apply at this point in confidence to test automation jobs since you have everything that it is required

- skills

- experience

- proof

Good Luck with the job search!

How to create classes and objects in Java

The focus of this blog is test automation for manual testers.

Test automation is not only about the Selenium WebDriver framework but also about a programming language (Java in our case) and unit testing (JUNIT).

Actually, the most important test automation skill is Java programming

This article is about how classes and objects are created in Java.

The code that follows is about working with triangles.

Any triangle has 3 sides.

For a triangle, one of the measures is the perimeter which is calculated by summing the values of the triangle sides.

The easiest way of calculating a triangle perimeter is

public class mainTriangle {
public static void main(String[] args) {

int x = 3, y = 4, z = 5;

int perimeter = x + y + z;

System.out.println("perimeter value = " + perimeter);

}
}

The code declares 3 numeric variables (using the int data type), one for each triangle side. It assigns a value to each side.

It then declares a numeric variable for the perimeter and it assigns to it the sum of the sides variables.

The last line displays the perimeter value to the console. If you run this code in Eclipse, the result is




Let's assume now that we want to do the same thing for one more triangle. The code changes just a bit:

public class mainTriangle 

public static void main(String[] args)

int x1 = 3, y1 = 4, z1 = 5;

int perimeter1 = x1 + y1 + z1;

System.out.println("perimeter1 value = " + perimeter1);;

int x2 = 6, y2 = 7, z2 = 8;

int perimeter2 = x2 + y2 + z2;

System.out.println("perimeter2 value = " + perimeter2);

}


The result of executing the code is:

perimeter1 value = 12
perimeter2 value = 18




The problems with this code are that

  • it is not clear that x1, y1, z1 (and x2, y2, z2) are the sides of a triangle
  • the code is repeated twice for calculating the perimeter for both triangles

To correct these deficiencies, we will create a class that describes a triangle.

A class is simply a container that defines the data and behaviors of a triangle:

public class Triangle{

int side1;
int side2;
int side3;

public Triangle(int x, int y, int z)

{
side1 = x;
side2 = y;
side3 = z;
}
}

What are all these things?

Lets take them one by one:

  • Triangle is the name of the class 
  • The class content is included between { }
  • side1, side2, side3 are called class members:
  1. The class members store information about the class. 
  2. In our case, the class members will store the triangle side values. 
  • public Triangle(int x, int y, int z) is called the class constructor:
  1. When an object for the class is created, the class constructor is executed first. 
  2. The class constructor can have parameters (x, y, z). 
  3. It stores the parameter values in the class members so that they can be used at a later time 
  4. The constructor provides the way of supplying information about specific triangle objects and storing it inside of the object.

Each class has objects that are concrete instances of the class.

An object is created as follows:


Triangle triangle1 = new Triangle(3, 4, 5);

Triangle triangle2 = new Triangle(7, 8, 9);



The code for creating the triangle1 object does the following:

  • the class contructor gets the following values for the x, y, z parameters: 3, 4, 5
  • the constructor stores the parameter values in the class members: side1, side2, side3
  • the values for class members for the triangle1 object are 3, 4, 5

So, our code becomes



public class mainTriangle { 


public static void main(String[] args) {

Triangle triangle1 = new Triangle(3, 4, 5);

Triangle triangle2 = new Triangle(7, 8, 9);

}



Executing the code will show no results.

We have added so far definitions of the data that any triangle has (members for the triangle sides).

We need to add now definitions for the behavior of the Triangle class.



Lets add a method to the class.

A method is a way of implementing a behavior that the class objects have.

The method will do something very simple.

It will get the value of one of the sides and return it.

public class Triangle{

int side1;
int side2;
int side3;

public Triangle(int x, int y, int z)

{
    side1 = x;
    side2 = y;
    side3 = z;
}

public int getSide1()
{
    return side1;
}

}


The method has the following components:

  • getSide1() is the method name
  • the code of the method is included in {}
  • the method returns a numeric value (int)
  • the method will get the value of the side1 class member and provide it (return side1;)
Similar methods can be implemented for the other 2 sides:


public class Triangle{

int side1;
int side2;
int side3;

public Triangle(int x, int y, int z)

{
    side1 = x;
    side2 = y;
    side3 = z;
}

public int getSide1()
{
    return side1;
}

public int getSide2()
{
    return side2;
}

public int getSide3()
{
    return side3;
}

}


We can add more code to our application:

public class mainTriangle {

public static void main(String[] args) {


Triangle triangle1 = new Triangle(3, 4, 5);
Triangle triangle2 = new Triangle(7, 8, 9);


System.out.println("side1 = " + triangle1.getSide1());
System.out.println("side2 = " + triangle1.getSide2());
System.out.println("side3 = " + triangle1.getSide3());

}


The result of executing the code is

side1 = 3
side2 = 4
side3 = 5

We can also calculate the perimeter of triangle1:

public class mainTriangle {

public static void main(String[] args) {


Triangle triangle1 = new Triangle(3, 4, 5);
Triangle triangle2 = new Triangle(7, 8, 9);



int perimeter = triangle1.getSide1() + triangle1.getSide2() + triangle1.getSide3();
System.out.println("perimeter = " + perimeter);


}


The result of executing the code is

side1 = 3
side2 = 4
side3 = 5
perimeter = 12




It is very nice and interesting that you can create classes and objects.

But how is this code better than the original one?

It seems that more code is needed when using classes and objects!

For the perimeter calculation, we can create a new method inside of the Triangle class:

public class Triangle{

int side1;
int side2;
int side3;

public Triangle(int x, int y, int z)

{
    side1 = x;
    side2 = y;
    side3 = z;
}

public int getSide1()
{
    return side1;
}

public int getSide2()
{
    return side2;
}

public int getSide3()
{
    return side3;
}

public int getPerimeter()
{
    return side1 + side2 + side3;
}

}

The getPerimeter() method works as follows:

- it gets the values of the side1, side2, side3 members
- it adds them up
- it returns the value of the sum

With the new method, the code gets simpler:

public class mainTriangle {

public static void main(String[] args) {

Triangle triangle1 = new Triangle(3, 4, 5);
Triangle triangle2 = new Triangle(7, 8, 9);

System.out.println("perimeter = " + triangle1.getPerimeter());

}


I did not use a variable to store the result of getPerimeter and then display its value.

Instead, I display directly the getPerimeter value.

If the perimeter of the second triangle is needed, just one more line is added:

public class mainTriangle {

public static void main(String[] args) {

Triangle triangle1 = new Triangle(3, 4, 5);
Triangle triangle2 = new Triangle(7, 8, 9);

System.out.println("perimeter1 = " + triangle1.getPerimeter());
System.out.println("perimeter2 = " + triangle2.getPerimeter()); 


}

}


I am hoping that the advantages of creating classes and objects start becoming obvious:

- it is clear in the final code that 3, 4, 5 are side values of a triangle

- the Triangle class defines how the triangle perimeter is calculated; this is done only once and then used by any of the objects of the class; imagine that the we need not one line of code for calculating the perimeter but 5 lines

- there is no code duplication any longer

I hope that this short example showed that programming can be learned and it is not as difficult as you may think.


How about some exercises using your new knowledge? :)

1. Create a rectangle class with methods for calculating the rectangle perimeter and area

2. Add a method to the Triangle class that checks if the triangle is scalene (all sides are different), isosceles (2 sides are equal) or equilateral (all sides are equal)?


If you liked this article and want to provide feedback or want to submit your solutions to the exercises, please use the comments section.