Posted: March 21st, 2012 | Author: Christopher Vigliotti | Filed under: Java | No Comments »
If you happen to be thumbing through the Sun Certified Java Associate Study Guide (why not!) and are having issues with Exercise 2.1 then help yourself to the answer. The goals of Exercise 2.1 are to create an ArrayList of floats, iterate through the list and printing out the values when they meet a certain condition. I know that this is Java 101 stuff here, but the key for me to complete this exercise was to realize that I could declare floats to numeric values that contained decimals easily by adding an f immediately after the number.
float requiredFishLength = 28.0; |
This code throws an error
float requiredFishLength = 28.0f; |
Just add f-bomb!
Lastly, here’s my solution for Exercise 2-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| float requiredFishLength = 28.0f;
ArrayList<Float> fishLengthList = new ArrayList<Float>();
fishLengthList.add(10.0f);
fishLengthList.add(15.5f);
fishLengthList.add(18.0f);
fishLengthList.add(29.5f);
fishLengthList.add(45.5f);
for(float fishLength: fishLengthList){
if(fishLength > requiredFishLength){
System.out.println(fishLength);
}
} |
I got 99 problems but the syntax ain’t one!
Posted: February 16th, 2012 | Author: Christopher Vigliotti | Filed under: Java, O-O | No Comments »
Hark! It’s the second installment of my “Java-licious Java Primer” series. The series was created for folks that are new to software development (experienced code-heads and vulcans may want to skip this one). In this post we’ll be focusing on “properties”.
Arguments
Methods may require arguments in order to function. Arguments are the values that you pass into a method. Lets compare these two examples…
1
2
3
| public static void displayYourName(){
System.out.println("John Jacob Jingleheimer-Schmidt");
} |
Example 1a – a method that does not require any arguments
We can determine that the above method does not require any arguments because the arguments are not defined in the parenthesis “()” on line 1.
1
2
3
| public static void displayYourName(String yourName){
System.out.println(yourName);
} |
Example 1b – a method that requires one argument
Check out the code inside of the parenthesis “()” on line 1. “String yourName” means that the method expects you to pass in a string when calling this method. The method will refer to this string as “yourName”.
Remember that methods may (or may not) require arguments.
Returned Values
Additionally methods may return values. Lets compare these two examples…
1
2
3
| public static void displayYourName(){
System.out.println("John Jacob Jingleheimer-Schmidt");
} |
Example 2a – a method that does not return a value
1
2
3
| public static String getYourName(){
return "John Jacob Jingleheimer-Schmidt");
} |
Example 2b – a method that returns a string
Remember that methods may (or may not) return values.
Methods And Properties
A class is made up of methods and properties. Methods (covered in the previous post) define the behavior of classes. Properties on the other hand define the non-behavioral aspects of a class. For example, if we were to think of a Person as a class, breathing, running and jumping would be considered methods. Name, hair color, height, weight and gender would be some of the properties of the Person class.
Lets create a class called “RegularDrip.java” into a package named “coffee”. Your code should look like the example in Figure 1.
1
2
3
4
5
6
7
8
9
10
| package coffee;
public class RegularDrip {
private static String whoAreYou = "I am a cup of regular drip coffee";
public static String getWhoAreYou(){
return whoAreYou;
}
} |
Figure 3a – Class RegularDrip.java
Two items of note here. The first is the code on line 5. This is the classes only property. It’s name is “whoAreYou” and it’s type is a “String”.
5
| private static String whoAreYou = "I am a cup of regular drip coffee"; |
Figure 3b – the whoAreYou property of class RegularDrip.java
Data Types
All properties have a data type. Data types are just that…one of the many different type of data. Our whoAreYou property on line 5 is the “string” datatype. Let’s add another property to our object. Add the code below after line 5.
private static int ouncesRemaining = 8; |
Figure 4a – the ouncesRemaining property of class RegularDrip.java
Our RegularDrip class now has two properties! There are a few differences between the two properties that we should look into.
5
6
| private static String whoAreYou = "I am a cup of regular drip coffee";
private static int ouncesRemaining = 8; |
Figure 4b – the properties of class RegularDrip.java
The second one has a type of “int”. That’s Java-speak for “integer”, which is math speak for “number”. The other difference is on the right side of the equals sign. The whoAreYou property is a string, which means that we have to wrap it’s value in quotes. The ouncesRemaining property however, is an int…which means that we need to declare it’s value without quotes.
Lets Make Coffee
Using MrJava5000.java from the previous lesson lets add a few additional lines of code. After the package declaration add the following code:
import coffee.RegularDrip; |
Figure 5a – an import statement
This code is an import statement. It allows us to access the RegularDrip class.
And after the sayHello() method call in the main() method add this code:
RegularDrip myMorningCup = new RegularDrip(); // new
System.out.println(myMorningCup.getWhoAreYou()); |
Figure 5b – make a new cup of coffee, then tell us about it
This code creates a new instance of RegularDrip named ‘myMorningCup’, then sends the returned value of the RegularDrip instance’s getWhoAreYou() method to the console window.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| package coffeemakers;
import coffee.RegularDrip; // new
public class MrJava5000 {
public static void main(String[] args) {
sayHello();
RegularDrip myMorningCup = new RegularDrip(); // new
System.out.println(myMorningCup.getWhoAreYou());
}
public static void sayHello(){
System.out.println("hello world");
}
} |
Figure 5c – MrJava5000.java
Run the MrJava5000.java class now and prepare to be amazed as your creation actually produces a (fake) cup of coffee!
Many Ways To Say Hello
Lets take a look at the println() method. We know that
Here are a In all three examples we output the word “hello” to the console window. In each of the three examples we pass a string into the println() method. In the first example we create a string on-the-fly simply by wrapping some text in quotes.
1
2
3
4
| public static void main(String[] args) {
// say hello
System.out.println("hello...is it me you're looking for");
} |
Example 6a – Hello
Check out the println() method call. Note that “hello” is wrapped in quotes because println() expects a string.
1
2
3
4
5
| public static void main(String[] args) {
// say hello again
String greeting = "hello...is it me you're looking for";
System.out.println(greeting);
} |
Example 6b – Hello
Again focusing on println(), note that “greeting” is not wrapped in quotes. This is because “greeting” is a variable of type “string”.
1
2
3
4
5
6
7
8
| // say hello a third time
public static string getHello(){
return "hello...is it me you're looking for";
}
public static void main(String[] args) {
System.out.println(getHello());
} |
Example 6c – Hello
This time we pass the returned value from the getHello() method into the println() method.
Next Time
Next time we’ll dig deeper into what an “instance” of a class is.
Posted: February 13th, 2012 | Author: Christopher Vigliotti | Filed under: Java, O-O | No Comments »
Welcome to the first of the “Java-licious Java Primer” series. The series was created for folks that are new to software development (experienced code-heads and vulcans may want to skip this one). In this post we’ll be covering how to create a class, how to add a method to the class, and how to “call” the method.

Start Here
In order to follow along you will need to download and install the Eclipse IDE. IDE is fancy-talk for “interactive development environment”…which is fancy talk for “the program that we will edit and run java files in”. Download the zip file, and unzip the contents to to c:\Eclipse. To open Eclipse simply browse to c:\Eclipse and double-click eclipse.exe.
Create A New Project
In Eclipse follow these two simple steps to create a new project…
- Click on “File” > “New” > “New Java Project”
- Name your project “Javalicious” and click “Finish”
Create Your First Class
- In the Package Explorer pane, right click on the Javalicious project, select “New” > “Class”
- Name your class “MrJava5000″ and give it a package name of “coffeemakers”
- Under “Which method stubs would you like to create” make sure that “public static void main(String[] args)” is checked.
- Click “Finish”
Your new class is now created and should look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
| package coffeemakers;
public class MrJava5000 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
} |
Figure 1 – MrJava5000.java
What Does It All Mean?
Before we proceed with attempting to understand all the strange letters, squiggles and assorted shapes in Figure 1 lets take a step back and talk about code comments. Here is how code comments are written in Java.
// I am a single-line code comment. |
/**
* I am a multi-line
* code comment.
*/ |
/*
I am also a multi-line
code comment.
*/ |
Code comments are the ideal place to leave notes for yourself, and to explain what a given section/line of code does to other developers. I’ve modified the code in Figure 1, adding comments and removing a few things.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| // this is the package declaration
package coffeemakers;
/*
this is the class declaration. it's "public" which means that it can be used by other classes.
note the curly brace '{' after the class name. it's matching curly brace is on line 14
*/
public class MrJava5000 {
// this is a method named 'main'. this method begins on line 11 and ends on line 13.
public static void main(String[] args) {
}
} |
Figure 2 – MrJava5000.java with lots of code comments
Package Declaration
So the code on line 2 is the package declaration. It basically says “the MrJava5000 class is found in the folder named ‘coffeemakers’. Think of packages as folders. If we were to change the name to from “coffeemakers” to “coffeemakers.mrjava” Eclipse would simply move the file from [project root]\src\coffeemakers\ to [project root]\src\coffeemakers\mrjava\.
Class Declaration
You may notice several occurrences of the left and right curly braces “{” and “}”. The class declaration on line 8 has a left curly brace. It’s matching right curly brace is found on line 14. Everything between these two symbols is a part of class body.
The “Main” Method
Lines 11 through 13 contain the a method. This is a special method named ‘main’. It is special in that it will run whenever you run the class.
11
12
13
| public static void main(String[] args) {
} |
Figure 3 – The “main” Method
Lets Add Another Method
Below the closing curly brace for the main method(and before the closing curly brace for the class) add the following code.
public static void sayHello(){
System.out.println("Hello world");
} |
Figure 3a – The “sayHello” Method
This is a new method named “sayHello”. It calls a method named “println”. This method displays whatever text is contained within the parenthesis and quotes.
Your code should look like this…
1
2
3
4
5
6
7
8
9
10
11
12
| package coffeemakers;
public class MrJava5000 {
public static void main(String[] args) {
}
public static void sayHello(){
System.out.println("hello world");
}
} |
Figure 3b – MrJava5000.java, including our new “sayHello” method
Now let’s run this Java class and see what happens. Highlight MrJava5000.java in the Package Explorer window and press the green play button. Observe the results. Actually that’s a joke, as there are no results to observe. The reason why we didn’t see the “hello world” text that we wanted to is due to the fact that we aren’t “calling” the helloWorld() method from our main() method. Let’s do that now by adding the following code to the main method.
Figure 4a – calling the “sayHello” method
OK, now we have added code inside of the main() method that calls the helloWorld() method. Your code should now look like this…
1
2
3
4
5
6
7
8
9
10
11
12
| package coffeemakers;
public class MrJava5000 {
public static void main(String[] args) {
sayHello();
}
public static void sayHello(){
System.out.println("hello world");
}
} |
Figure 4b – MrJava5000.java, ready to say hello
Run the code again and you should see the following text in the Console panel.
hello world
You’ve just created your first Java class. When run, this classes main method runs. The main method calls the sayHello method, which in turn outputs the text “hello world” to the console panel. This of course means that you are one step closer to becoming a Java legend!

Posted: February 2nd, 2012 | Author: Christopher Vigliotti | Filed under: Java, O-O | 2 Comments »
If you are new to the strange and wonderful world of Java development, Head First Java is the essential primer.
Do you have a favorite “Intro to Java” or “Intro to Object Oriented Development” resource? Please share in the comments
Posted: January 6th, 2012 | Author: Christopher Vigliotti | Filed under: Java, Selenium | 2 Comments »
This post is a part of my Learn Selenium series.
HEY THERE! In order to better understand this post (as well as the rest of the Learn Selenium Series) I suggest that you be familiar with basic Object-Oriented concepts in Java. I suggest picking up the most excellent book “Head First Java” and working through the first five or so chapters. If you have a preferred Intro to Java or Intro to Object Oriented Development resource please share it in the comments of this post.
As I said in the previous post “Selenium IDE is a free and awesome Firefox plugin that records and plays automated tests”. If you want to add conditions, looping and other logic to your tests you will need to move your test from Selenium IDE to either Selenium WebDriver or Selenium RC. At the time of this post Selenium RC is a more stable and robust platform than Selenium WebDriver (link).
Setting Up
In order to complete the tasks in this post you will need to perform these three steps:
- Download and install the free and awesome Eclipse IDE.
- Download and run the Selenium server. I suggest that you copy this file to a easy to access, non-network path. I use C:\selenium. Also note that Selenium Server will only work if you have the Java Development Kit (JDK) installed and running on your machine.
- Create a new Java project in Eclipse, referencing the external JAR from the previous post. Lets call the project ‘Tests Are Awesome’
Do I have JDK Installed?
In a command prompt type the word “java” and hit return. If you receive the following message
“Java” is not recognized as internal or external command, operable program or batch file
then you need to install the JDK, which can be downloaded here.
Start Selenium Server With A Batch File
I like to start and run Selenium Server via a batch file. The following batch file can be created by opening notepad, pasting the three lines of code and saving the file to your Desktop with the name “Start Selenium Server.txt”
1
2
3
| Cd C:\selenium
Java -jar selenium-server-standalone-2.13.0.jar -port 4444
pause |
Potential Issues With Running Selenium Server
If you run into an error where something else is running on port 4444, change line 2 of your batch file to run on a different port. Try port 4448. For more information on troubleshooting this issue click here.
Optional Installs
- jxl.jar – If you want to read data from an Excel file for use in your test scripts download jxl.jar. We’ll explore this more in a future post.
- Tortoise SVN – If you are running through this any my other Selenium tutorials in one of my classes you will be accessing code via Subversion. Please download and install Tortoise SVN.
Exporting A Selenium IDE Test
For this example I’ll use the test from my previous post. It has four steps. Here are the details
The Base URL is http://code.christophervigliotti.com/
1st command
command: open
target: /
value: [blank]
2nd command
command: clickAndWait
target: link=Excel Entity Service
value: [blank]
3rd command
command: type
target: id=comment
value: Test Comment.
4th command
command: clickAndWait
target: id=submit
value: [blank]
With the test case open in Selenium IDE, click File > Export Test Case > JUnit 3 (Remote Control). Lets save the file as AnAwesomeTest.txt. Open the file and you’ll see the following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| package com.example.tests;
import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;
public class awesome extends SeleneseTestCase {
public void setUp() throws Exception {
setUp("http://code.christophervigliotti.com/", "*chrome");
}
public void testAwesome() throws Exception {
selenium.open("/");
selenium.click("link=Excel Entity Service");
selenium.waitForPageToLoad("30000");
selenium.type("id=comment", "Test comment.");
selenium.click("id=submit");
selenium.waitForPageToLoad("30000");
}
} |
Recreating The Test In Selenium RC
Create a new Java class in your project. Call the file ‘AnAwesomeTest.java’ and specify the package ‘awesomeTests’. Open your new class file and check it out
1
2
3
4
| package awesomeTests;
public class AnAwesomeTest {
} |
Now it’s time to do some minor cut-and-paste surgery. We need to move the import statements and logic from AnAwesomeTest.txt over to AnAwesomeTest.java. We’ll also need to make AnAwesomeTest.java extend SeleneseTestCase. The result of this cutting and pasting is as follows…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| package awesomeTests; // changed this
import com.thoughtworks.selenium.*;
import java.util.regex.Pattern; // you can delete this line
@SuppressWarnings("deprecation") // I added this to suppress Eclipse warnings
public class AnAwesomeTest extends SeleneseTestCase {
public void setUp() throws Exception {
setUp("http://code.christophervigliotti.com/", "*chrome");
}
public void testAwesome() throws Exception {
selenium.open("/");
selenium.click("link=Excel Entity Service"); // if your code crashes here change this to an XPath selector
selenium.waitForPageToLoad("30000");
selenium.type("id=comment", "Test comment.");
selenium.click("id=submit");
selenium.waitForPageToLoad("30000");
}
} |
Running The Test
Verify that Selenium Server is running on your local machine. Highlight the file AnAwesomeTest.java in Eclipse and press the green play button. Sit back and enjoy the show. The JUnit tab in Eclipse should appear and tell you that your test passed.
What Just Happened?
If your test ran too fast to observe the system interactions you can add commands to slow it down. Lets add a few Thread.sleep() commands…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| package awesomeTests;
import com.thoughtworks.selenium.*;
@SuppressWarnings("deprecation")
public class AnAwesomeTest extends SeleneseTestCase {
public void setUp() throws Exception {
setUp("http://code.christophervigliotti.com/", "*chrome");
}
public void testAwesome() throws Exception {
selenium.open("/");
selenium.click("link=Excel Entity Service");
Thread.sleep(30000); // add one here
selenium.waitForPageToLoad("30000");
selenium.type("id=comment", "Test comment.");
Thread.sleep(30000); // add one here
selenium.click("id=submit");
selenium.waitForPageToLoad("30000");
Thread.sleep(30000); // add one here
}
} |
Re-run the test using the above code and you can observe each action as it’s happening.
Now What?
Now that your code is in Java/JUnit land you can leverage the power of Java to write your tests. In a follow-up post I’ll demonstrate the hows and whys of adding a parent class to your test cases.
I want more Selenium!!! Check out this post on adding a parent class to your test cases
Posted: January 5th, 2012 | Author: Christopher Vigliotti | Filed under: Java, Selenium | 1 Comment »
This post is a part of my Learn Selenium series.
Requirement
I’m working with a team of testers that are developing Selenium RC scripts (in Java). They needed a quick and easy way to read data from Excel for use in Selenium tests.
Dependencies
This code requires jxl.jar, which can be downloaded here.
Usage
Entities (such as “Users”) can be defined in Excel using (1) the worksheet name as the entity name, (2) the first row of the sheet as the property names and (3) subsequent rows as the values.
So if you wanted to create a list of user accounts to test against a login page, you can create a worksheet named “users”, and specify the “username” and “password” property names in the first row. Once you’ve done that, you may add one or more usernames and passwords, and using ExcelEntityService.java you can easily grab an ArrayList of User entities using the following code…
1
| ArrayList<Hashtable<String, String>> users = excelEntityService.getExcelEntities("users"); |
Once you have your ArrayList of users you can easily loop through it and get each username and password…
2
3
4
5
6
| for(int i = 0; i < users.size(); i++){
String username = users.get(i).get("username");
String password = users.get(i).get("password");
// your fancy Selenium code goes here...
} |
You can also get a specific row by searching using the getExcelEntityBySearch() method, or specify the row number using the getExcelEntityByRowNumber() method.
The Code
If you are new to Java or don’t understand the code below you can simply cut and paste the code into a new class and use it as detailed above. If you have any questions feel free to ask in the comments section below.
Package declaration & imports….
1
2
3
4
5
6
7
8
| package com.vigliotti.selenium;
import java.io.File;
import java.io.IOException;
import java.util.*;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException; |
…class declaration, inputFile property and mutator “setter” method…
9
10
11
12
13
| public class ExcelEntityService {
private String inputFile;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
} |
Next is the private method getEntityPropertiesArrayList(). This method gets an ArrayList of entities for the specified Excel worksheet name.
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| private ArrayList getEntityPropertiesArrayList(String sheetName) throws IOException{
ArrayList entityPropertiesArrayList = new ArrayList();
int columnCount = -1;
String propertyName = "";
try{
Sheet sheet = getSheet(sheetName);
columnCount = sheet.getColumns();
for(int i = 0; i < columnCount; i++){
Cell headerCell = sheet.getCell(i, 0);
propertyName = headerCell.getContents();
entityPropertiesArrayList.add(propertyName);
}
} catch (IOException e) {
e.printStackTrace();
}
return entityPropertiesArrayList;
} |
The getExcelEntities() method gets an ArrayList of Hashtables for all entities of the specified worksheet name.
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
| public ArrayList getExcelEntities(String sheetName) throws IOException{
ArrayList> entities = new ArrayList>();
jxl.Sheet sheet = null;
int rowCount = -1;
sheet = getSheet(sheetName);
rowCount = sheet.getRows() - 1;
for(int i = 1; 1 0){
Hashtable entityHashtable = getExcelEntityByRowNumber(sheetName, i);
entities.add(entityHashtable);
}else{
break;
}
}
return entities;
} |
Here is the awesomely awesome getExcelEntityBySearch(), for when you want a Hashtable of a single entity.
34
35
36
37
38
39
40
41
42
43
| public Hashtable getExcelEntityBySearch(String sheetName, String columnName, String columnValue) throws IOException{
System.out.println("ExcelEntityService.getExcelEntityBySearch()");
Hashtable entityHashtable = new Hashtable();
jxl.Sheet sheet = null;
int rowNumber = -1;
sheet = getSheet(sheetName);
rowNumber = sheet.findCell(columnValue).getRow();
entityHashtable = getExcelEntityByRowNumber(sheetName, rowNumber);
return entityHashtable;
} |
And if you know the row number of the entity, you can use this method…
44
45
46
47
48
49
50
51
52
53
54
55
56
| public Hashtable getExcelEntityByRowNumber(String sheetName, int rowNumber) throws IOException{
Hashtable entityHashtable = new Hashtable();
jxl.Sheet sheet = null;
ArrayList propertiesArrayList = new ArrayList();
int columnCount = -1;
propertiesArrayList = getEntityPropertiesArrayList(sheetName);
sheet = getSheet(sheetName);
columnCount = sheet.getColumns();
for(int i = 0; i < columnCount; i++){
entityHashtable.put(propertiesArrayList.get(i), sheet.getCell(i, rowNumber).getContents());
}
return entityHashtable;
} |
This private method interacts with jxl.jar, getting a Sheet object for use in some of the other methods.
57
58
59
60
61
62
63
64
65
66
| private Sheet getSheet(String sheetName) throws IOException{
File excelFile = new File(inputFile);
jxl.Sheet sheet = null;
try {
sheet = Workbook.getWorkbook(excelFile).getSheet(sheetName);
} catch (BiffException e) {
e.printStackTrace();
}
return sheet;
} |
If you cut and paste the code samples and add an extra “}” at the end you will have a working ExcelEntityService.java file.
Posted: January 5th, 2012 | Author: Christopher Vigliotti | Filed under: Java | 3 Comments »
As part of my Geeky Goals for 2012 I’m spending some time solving the problems found at Project Euler.
Here’s the solution for Problem 1…
int total = 0;
for(int i = 1; i < 1000; i++){
if(i % 3 == 0 || i % 5 == 0){
total = total + i;
}
}
System.out.println(total); |
…and Problem 2…
int ceiling = 4000000; // four million
int total = 2;
int firstTerm = 1;
int secondTerm = 2;
int thirdTerm = 3;
int newFirstTerm = 0;
int newSecondTerm = 0;
int newThirdTerm = 0;
while (thirdTerm < ceiling) {
if(thirdTerm%2==0){
total = total + thirdTerm;
}
newSecondTerm = thirdTerm; // previous third becomes second
newFirstTerm = secondTerm; // previous second becomes first
newThirdTerm = newFirstTerm + newSecondTerm; // get the new third term
firstTerm = newFirstTerm;
secondTerm = newSecondTerm;
thirdTerm = newThirdTerm;
}
System.out.println(total); |