QA AND TEST AUTOMATION · PART 2 · PROGRAMMING FOR TESTERS · JAVA · 21 OF 112

Java for Testers: Setup and the Basics You Need

Why Java is the common language of SDET work, how to set up JDK 21 and an IDE, and the basics automation code needs: types (and why money uses long cents, not double), strings, conditions, loops and methods, written as a small ShopRung pricing check you can run. With the Java questions SDET interviews start with.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 14

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • JDK 21 and an IDE
  • compile then run on the JVM
  • types, strings, conditions, loops, methods
  • money in cents

Notes

Why Java

Why Java? Most classic automation tools were built for Java first: Selenium, REST Assured, TestNG, Cucumber and Appium. Many company back ends are written in Java, so the test code can live next to the product code. And many SDET coding rounds are done in Java. Python and TypeScript are common too, especially with Playwright. The real advice is: learn one language well. The ideas carry over to the others.

Why Java for testers
  • Selenium, REST Assured, TestNG, Cucumber, Appium: Java first
  • many enterprise back ends are Java (Spring)
  • interviews: coding rounds in Java are common
  • Python and TypeScript are common too: learn one well

Setup

Install a JDK, the Java development kit, version twenty one, which is a long term support release. Temurin is a free, popular build. On a Mac use Homebrew, on Windows use winget, and on Linux use SDKMAN. Then open a terminal and run java dash version: it must say twenty one. For writing code, install an IDE. IntelliJ IDEA Community Edition is free and is what most Java testers use.

Install
# a JDK 21 build, e.g. Temurin
mac:     brew install --cask
           temurin@21
windows: winget install
           EclipseAdoptium.Temurin.21.JDK
linux:   sdk install java
           21-tem   (SDKMAN)

$ java -version
openjdk version "21..."

How it runs

Here is how Java runs. You write source code in a dot java file. The compiler, javac, turns it into bytecode, and the Java virtual machine runs the bytecode on any operating system. Every program starts at a method called main inside a class. For a single file you can simply run java Hello dot java, and Java compiles and runs it in one step. In real projects, a build tool called Maven does this for you, which is a later episode.

Your first program
// Hello.java
public class Hello {
  public static void main(
      String[] args) {
    System.out.println(
      "ShopRung tests start");
  }
}
$ java Hello.java
ShopRung tests start

Types

Java is statically typed: every variable has a type that does not change. An int holds whole numbers up to about two point one billion, like a quantity. A long holds much bigger whole numbers. A boolean is true or false. A String holds text, in double quotes. The word var lets Java work out the type from the value, which keeps local code short. Pick types that match the data, because the compiler then catches mistakes before your test even runs.

Types you will use
int quantity = 4;
long subtotalCents = 5000L;
boolean inStock = true;
String code = "SAVE10";
var sku = "BK-101"; // inferred

int: whole numbers up to ~2.1e9
long: bigger whole numbers
String: text, in double quotes

Money trap

Here is the trap. Print zero point one plus zero point two in Java and you get zero point three, followed by many zeros and a four. A double stores fractions in binary, so most decimal amounts are not exact. Five Testing Field Guides at twenty four ninety nine come out as one hundred twenty four point nine four nine nine nine and more nines. Assert that equals one twenty four ninety five and the test fails. That is why ShopRung stores money in whole cents as long, and why your tests should too, or use BigDecimal.

double vs long cents
System.out.println(0.1 + 0.2);
// 0.30000000000000004

double total = 24.99 * 5;
// 124.94999999999999

// do this instead:
long cents = 2499L * 5;
// 12495  → $124.95 exactly
// or java.math.BigDecimal

Strings

Strings are everywhere in tests: messages, codes, URLs. Length, contains, equals, trim and to upper case cover most needs. Trim and upper case together turn space save ten space into SAVE10, which is exactly what ShopRung does with coupon codes. String format builds text like a price from cents. And one rule to remember: compare strings with equals, never with double equals, which checks whether they are the same object, not the same text.

String essentials
String msg = "Coupon applied";
msg.length()          // 14
msg.contains("applied") // true
msg.equals("Coupon applied")
 " save10 ".trim()
   .toUpperCase()    // "SAVE10"
String.format("$%d.%02d",
   cents / 100, cents % 100)

compare with equals, never ==

Conditions

Conditions turn rules into decisions. Here is ShopRung's shipping rule as a method: zero for an empty cart, free from seven thousand five hundred cents, otherwise four hundred ninety nine. Notice greater than or equal, because the rule says seventy five dollars or more. The question mark and colon is a short if else, called the ternary operator. Careful: the label method has a bug for amounts like five cents, which would print point five. Spotting that is a tester's job.

PRICE-9 as code
static long shipping(long after) {
  if (after == 0) return 0;
  if (after >= 7500) return 0;
  return 499;
}

static String label(long c) {
  return c == 0 ? "Free"
               : "$" + c / 100
                 + "." + c % 100;
}

Loops

Loops repeat work over data. The for each loop walks through an array or a list. Here we check the four boundary quantities from the boundary value episode: zero and eleven are not allowed, one and ten are. The classic for loop counts with an index, and a while loop repeats until a condition changes, like retrying a flaky call up to three times. In test frameworks, loops are often replaced by parameterized tests, which you will meet with JUnit.

Loops
int[] quantities = {0, 1, 10, 11};
for (int q : quantities) {
  boolean ok = q >= 1 && q <= 10;
  System.out.println(q + " -> "
    + ok);
}
// 0 -> false   1 -> true
// 10 -> true   11 -> false

for (int i = 0; i < 3; i++) {}
while (retries < 3) { ... }

Methods

Methods give a rule a name, inputs and an output, which makes it testable. The discount method returns zero below five thousand cents, and otherwise ten percent, rounded to the nearest cent by adding fifty before dividing by one hundred. In main, four notebooks at twelve fifty make five thousand cents, the discount is five hundred, shipping is four ninety nine, and the program prints four thousand nine hundred ninety nine. That is forty nine ninety nine, the same total the shop shows.

Pricing.java
static long discount(long sub) {
  if (sub < 5000) return 0;
  return (sub * 10 + 50) / 100;
}
public static void main(String[] a){
  long sub = 4 * 1250L;
  long d = discount(sub);
  long t = sub - d + shipping(sub-d);
  System.out.println(t); // 4999
}

Rules of thumb

Habits for test code from day one. Money in long cents or BigDecimal, never double. Equals for strings. Small methods with clear names, like discount for cart. No magic numbers: give values like seven thousand five hundred a name, such as free shipping from. When the compiler complains, read the first error and fix it before the others, because one mistake often causes many messages. And run your code often, in small steps.

Rules of thumb
  • money in long cents or BigDecimal, never double
  • equals() for strings
  • small methods with clear names: discountFor(cart)
  • no magic numbers: name them FREE_SHIPPING_FROM = 7500
  • read compiler errors from the top; fix the first one run code often, small steps

Common mistakes

Beginner mistakes that break tests. Using double equals on strings. Double for money. An int overflowing on very large totals. Integer division, where five divided by two is two, not two and a half. Forgetting break in an old style switch, which the newer arrow switch avoids. A null pointer exception from a field nobody set. And skipping past the error message instead of reading it; Java's messages usually point at the exact line.

Avoid these
  • == on strings
  • double for money
  • int overflow on big totals
  • integer division: 5 / 2 = 2
  • forgetting break in switch (or use the new arrow form)
  • NullPointerException from an unset field
  • skipping the error message

Say it like this

A favourite interview question for SDETs is: why not use double for prices? Say: double stores binary fractions, so zero point one plus zero point two is not exactly zero point three, and money drifts by tiny amounts. I use long cents or BigDecimal with an explicit rounding mode, and in tests I compare exact cents, never doubles with double equals. It shows you think about correctness, not just syntax.

In the interview
  • "double stores binary
  • fractions, so 0.1 + 0.2 is not exactly 0.3 and money
  • drifts by tiny amounts. I use
  • long cents or BigDecimal with an explicit rounding mode. In tests I compare exact cents, never doubles with =="

Interview questions

Q1What is the difference between JDK, JRE and JVM?

The JVM runs bytecode; the JRE is the JVM plus the standard libraries needed to run programs; the JDK adds the compiler (javac) and tools needed to develop. Testers install the JDK.

Q2Why should you not use double for money?

Doubles are binary floating point, so many decimal values cannot be stored exactly (0.1 + 0.2 != 0.3). Use long cents or BigDecimal with a rounding mode.

Q3What is the difference between == and equals() for strings?

== compares references (the same object); equals() compares the characters. Always use equals() to compare string values.

Q4What is the result of 5 / 2 in Java?

2, because integer division drops the remainder. Use 5 / 2.0 or cast to double for 2.5, or BigDecimal for money.

Q5What does the main method signature mean?

public static void main(String[] args): public so the JVM can call it, static so no object is needed, void because it returns nothing, and args holds command-line arguments.

Q6What is var in Java?

Local variable type inference (Java 10+): the compiler infers the type from the value; the variable is still statically typed.

Q7Why is Java popular for test automation?

Mature tools (Selenium, REST Assured, TestNG, JUnit, Cucumber, Appium), strong typing and IDE support, and many enterprise systems are already in Java.

Q8What is a NullPointerException?

An error thrown when code uses a reference that is null, such as calling a method on an unset field; fix by initialising values or checking for null (or using Optional).