Java Basics & Setup: Your First Program
Welcome to the very beginning. This lesson assumes you have never written a line of code in your life, and that is exactly the right place to start. By the end you will understand what Java actually is, how the pieces (JDK, JRE, JVM) fit together, how to install everything on your own machine, and you will have written, compiled, and run a real Java program that prints to the screen, stores data in variables, and reads what you type. We go slowly and explain the why behind every step, because the people who struggle later are almost always the ones who skipped the foundations. And because this is a course for testers, we finish by explaining why Java is the language most Selenium automation is written in—so you know this groundwork pays off directly.
Learning objectives
By the end of this lesson you will be able to:
- Explain in plain words what Java is and what makes it “write once, run anywhere”.
- Describe the difference between the JVM, the JRE, and the JDK—and know which one you install.
- Install the JDK and an IDE (IntelliJ IDEA or Eclipse) and confirm they work.
- Write, compile, and run a first program using the
mainmethod andSystem.out.println. - Add comments, declare variables, and use Java’s primitive data types and
String. - Convert between types with casting, and read user input with
Scanner. - Explain why Java is so widely used for Selenium test automation.
What is Java?
Java is a programming language—a structured way of writing instructions that a computer can carry out. You write those instructions as plain text (called source code), and a chain of tools turns them into something the machine runs. Java was created in the mid-1990s and is still, decades later, one of the most popular languages in the world. It powers banking systems, Android apps, huge enterprise back-ends, and—importantly for us—a very large share of the world’s automated software tests.
Java’s most famous promise is “write once, run anywhere”. Code you write on a Windows laptop runs unchanged on a Mac, a Linux server, or a cloud build machine. That portability is not magic; it comes from a clever design we will unpack in a moment. Java is also statically typed (you declare what kind of data each variable holds, and the compiler checks it before the program runs) and object-oriented (code is organised into reusable building blocks called classes and objects—the subject of Module 4). For now, just hold onto one idea: Java catches a lot of your mistakes before the program ever runs, which is exactly the kind of safety a tester appreciates.
JVM, JRE, and JDK: three letters that confuse everyone
These three acronyms trip up nearly every beginner, so let us settle them clearly, from the inside out.
- JVM — Java Virtual Machine. This is the engine that actually runs Java programs. When you compile your code, it does not turn into Windows-specific or Mac-specific instructions; it turns into an in-between format called bytecode. The JVM reads that bytecode and executes it on whatever platform it is installed on. There is a different JVM built for Windows, for Mac, for Linux—but they all understand the same bytecode. That is the secret behind “write once, run anywhere”.
- JRE — Java Runtime Environment. This is the JVM plus the standard libraries (ready-made code for things like text, dates, and collections) that programs need to run. If all you wanted to do was run an existing Java program, the JRE would be enough.
- JDK — Java Development Kit. This is the JRE plus the tools you need to create Java programs—most importantly the compiler (
javac), which turns your source code into bytecode. Because we are writing code, the JDK is what you install. It contains everything else inside it.
An analogy: writing and sending a letter
Think of your Java source code as a letter you write in your own handwriting. The compiler is a translator who rewrites your letter into a universal shorthand (that is the bytecode)—the same shorthand no matter who will read it. The JVM is the local reader at the destination who understands that shorthand and acts on your instructions. There is a different reader in each country (Windows, Mac, Linux), but because they all learned the same shorthand, your one letter works everywhere. The JDK is your complete writing desk: pen, paper, the translator, and the postbox all in one. The JRE is just the reader on the other end. You install the full writing desk (JDK) because you are the author.
Installing the JDK
Let us get a working Java on your machine. You only need to do this once.
- Download a JDK. A good, free choice is Eclipse Temurin (from Adoptium) or Oracle JDK. Pick a long-term support (LTS) version such as Java 17 or Java 21—these are stable and widely supported by Selenium.
- Run the installer and accept the defaults. On Windows, allow it to set the
JAVA_HOMEenvironment variable and add Java to yourPATHif the installer offers—this lets you run Java from any terminal. - Verify it worked. Open a terminal (Command Prompt, PowerShell, or Terminal) and type the command below. You should see a version number printed back.
java -version
javac -version
If both commands print a version (for example openjdk version "21.0.2"), your JDK is installed correctly. java runs programs; javac compiles them—seeing both confirms you have the full development kit, not just the runtime.
Installing an IDE
You can write Java in Notepad, but nobody does. An IDE (Integrated Development Environment) is a specialised editor that highlights your code, auto-completes as you type, flags mistakes instantly, and runs your program with one click. The two most popular for Java are:
- IntelliJ IDEA (Community Edition is free). This is the most popular choice in the test-automation world and what most Selenium tutorials use. Its autocomplete and error detection are excellent for beginners.
- Eclipse (free and open source). A long-standing, capable IDE still used in many companies.
Either is fine; this course uses examples that work in both. Download one, install it, and when it asks, point it at the JDK you just installed (most IDEs detect it automatically). Then create a new Java project to get started.
Tutor tip: let the IDE teach you
Resist the urge to turn off the red squiggly underlines. When the IDE underlines something in red, it has found a mistake before you even run the code—a free lesson. Hover over the underline to read the explanation. Beginners who read those messages learn Java’s rules far faster than those who ignore them. The same instant feedback that makes you a better programmer will later make you a sharper tester, because reading error messages carefully is the single most useful debugging habit there is.
Your first program
Create a new file called Hello.java and type this exactly. The file name must match the class name (Hello)—that is a firm Java rule.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, QALaunch!");
}
}
Click Run in your IDE. You should see Hello, QALaunch! appear in the console at the bottom. Congratulations—you are a programmer. Now let us understand every piece, because this skeleton appears in almost every Java program you will ever write:
public class Hello { ... }— A class is a container for your code. Everything in Java lives inside a class. This one is namedHello, matching the file name.public static void main(String[] args)— This is the main method, the single entry point where the program starts running. When you hit Run, the JVM looks for exactly this line and begins here. The exact wording matters; we will decodestatic,void, and parameters in later modules. For now, treat it as the fixed “start here” sign.System.out.println("...")— This prints a line of text to the console.printlnmeans “print line” (it adds a line break after); its cousinSystem.out.printprints without the line break.- The semicolon
;ends a statement, like a full stop ends a sentence. Forgetting it is the most common beginner error.
Comments
Comments are notes for humans that the computer ignores completely. Use them to explain why code does something. Java has two kinds:
// This is a single-line comment. Everything after // on this line is ignored.
/* This is a block comment.
It can span multiple lines. */
System.out.println("Running"); // comments can also sit after code
Variables and primitive data types
A variable is a named box that stores a value. In Java you must declare what type of value a box holds before you use it. Java has eight built-in primitive types—the simplest, most basic kinds of data. Here are the ones you will actually use day to day:
int score = 95; // whole numbers (integers)
long bigNumber = 9000000000L; // very large whole numbers (note the L)
double price = 19.99; // decimal numbers (the default for decimals)
float rate = 3.5f; // decimal numbers, less precise than double (note the f)
boolean isPassing = true; // only two values: true or false
char grade = 'A'; // a single character, in single quotes
The pattern is always the same: type, name, equals sign, value, semicolon. The remaining primitives—byte and short—are rarely needed by beginners. The one you will reach for most in testing is boolean, because assertions ultimately boil down to true-or-false questions: did the page title match? Is the button enabled?
Strings
A String is a piece of text—a sequence of characters like a word, a sentence, or a URL. Strings are so common they feel like a primitive, but technically String is a class (note the capital S). You write string literals in double quotes (single quotes are only for a single char).
String name = "Priya";
String url = "https://the-internet.herokuapp.com";
// Joining strings together is called concatenation, using +
String greeting = "Hello, " + name + "!";
System.out.println(greeting); // Hello, Priya!
// Strings have useful built-in methods:
System.out.println(name.length()); // 5
System.out.println(name.toUpperCase()); // PRIYA
System.out.println(url.contains("heroku")); // true
That last method, contains, returns a boolean—and it is exactly the kind of check you will write constantly when verifying that a web page shows the right text.
Type casting
Sometimes you need to convert a value from one type to another. This is called casting. Converting a smaller type into a larger one (say int into double) is safe and automatic—this is widening. Going the other way (double into int) can lose information, so Java forces you to say so explicitly with a cast in parentheses—this is narrowing.
int whole = 10;
double asDecimal = whole; // automatic widening: 10.0
double pi = 3.99;
int truncated = (int) pi; // explicit narrowing cast: 3 (decimals dropped, not rounded)
System.out.println(asDecimal); // 10.0
System.out.println(truncated); // 3
Notice that casting a double to an int simply chops off the decimal part—it does not round. That surprise catches people out, so remember it.
Common beginner mistakes
- Mismatched quotes.
charuses single quotes ('A');Stringuses double quotes ("A"). Swapping them is a frequent error. - Integer division surprise.
5 / 2gives2, not2.5, because dividing twoints produces anint. Use5.0 / 2or cast one operand todoubleto get2.5. - Comparing Strings with
==. For text,==can give wrong answers; use.equals()instead (for examplename.equals("Priya")). We cover why in later modules—just build the habit now. - Forgetting the semicolon or mismatching
{ }braces. The IDE will flag both—read the message. - File name not matching the public class name.
public class Hellomust live inHello.java.
Reading input with Scanner
Programs become interactive when they can read what the user types. Java’s Scanner class does this. To use it, you first import it (bring it in from Java’s standard library), then create one that reads from System.in (the keyboard).
import java.util.Scanner; // put this at the very top of the file
public class Greeter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your name? ");
String name = scanner.nextLine(); // reads a whole line of text
System.out.print("What is your age? ");
int age = scanner.nextInt(); // reads a whole number
System.out.println("Hi " + name + ", next year you will be " + (age + 1));
scanner.close(); // tidy up when finished
}
}
Key Scanner methods: nextLine() reads a full line of text, next() reads a single word, nextInt() reads a whole number, and nextDouble() reads a decimal. A classic gotcha: mixing nextInt() and nextLine() can leave a stray line break behind—if a later nextLine() seems to be skipped, that is why, and an extra scanner.nextLine() to consume the leftover fixes it.
Why Java for Selenium automation?
You might wonder why a testing course starts with Java at all. Here is the honest, practical answer. Selenium—the dominant tool for automating web browsers—offers official support for several languages, but Java has by far the largest testing ecosystem around it. The vast majority of job postings for automation engineers list Java; the most tutorials, Stack Overflow answers, and sample frameworks are in Java; and the key testing tools (TestNG, JUnit, Maven, Cucumber, RestAssured) are mature and first-class in the Java world. Java’s static typing also means many mistakes are caught at compile time rather than mid-test-run, which makes large automation suites more reliable. In short: learning Java well is the single highest-leverage investment you can make as a web-automation tester, and everything you learned today—variables, types, strings, input—is used in every single Selenium test you will ever write.
Hands-on exercise
Create a new file Profile.java and build a small interactive program:
- Import
Scannerand create one reading fromSystem.in. - Ask the user for their name (read with
nextLine()), their favourite number (read withnextInt()), and a decimal such as their height in metres (read withnextDouble()). - Declare a
booleanvariable set totruecalledisLearningJava. - Print a tidy summary line using string concatenation, for example:
"Priya, your number doubled is 14 and you are learning Java: true". - Add a line that casts the decimal height to an
intand prints it, then write a comment explaining why the decimal part disappeared. - Stretch: print the user’s name in uppercase using
.toUpperCase(), and print its length using.length().
Knowledge check
- In one sentence, what does “write once, run anywhere” mean, and which component makes it possible?
- What is the difference between the JDK and the JRE, and which do you install to write programs?
- What is the single entry point where a Java program starts running?
- What is the difference between
System.out.printandSystem.out.println? - Name three primitive data types and the kind of value each holds.
- What does
(int) 3.99produce, and why is it not4? - Which
Scannermethod reads a whole line of text, and which reads a whole number? - Give one practical reason Java is the most common choice for Selenium automation.
Show answers
- Code compiled once into bytecode runs on any platform; the JVM (Java Virtual Machine) makes it possible by executing that bytecode on each operating system.
- The JDK includes the JRE plus development tools like the compiler; the JRE only runs programs. You install the JDK to write programs.
- The
mainmethod—public static void main(String[] args). printoutputs text with no line break;printlnadds a line break after the text.- Any three of:
int(whole numbers),double(decimals),boolean(true/false),char(single character),long(large whole numbers),float(smaller decimals). - It produces
3—casting adoubletointtruncates (drops) the decimal part rather than rounding. nextLine()reads a whole line;nextInt()reads a whole number.- Any one of: largest testing ecosystem and job demand; mature tools (TestNG, JUnit, Maven); static typing catches errors before run; most tutorials and community support.
Key takeaways
- Java compiles to bytecode, which the JVM runs on any platform—the basis of “write once, run anywhere”.
- Install the JDK (it contains the JRE and the compiler) plus an IDE such as IntelliJ IDEA or Eclipse.
- Every program lives in a class; execution starts at the
mainmethod;System.out.printlnprints output; statements end with;. - Declare variables as type name = value; know the primitives (
int,double,boolean,char…) and thatStringholds text. - Widening casts are automatic; narrowing casts need explicit
(type)and may lose data. Read input withScanner. - Java is the dominant language for Selenium automation—these fundamentals underpin every test you will write.
Go deeper
Once the basics click, a few extra details make your code cleaner and head off surprises that bite beginners later.
- Local
var(Java 10+). Inside a method you can let Java infer a local variable’s type:var name = "Priya";is still aString—the type is fixed, just not spelled out. It works only for local variables that have an initial value, never for fields or method parameters. - Readable number literals. You may place underscores inside numeric literals to group digits:
int salary = 1_000_000;reads far more easily than1000000and compiles to exactly the same value. - Integer overflow is silent. An
inttops out at 2,147,483,647; add one more and it quietly wraps around to a large negative number with no error. For values that can grow large—timestamps, counters—reach forlong.
Two more habits worth forming early. A char is secretly a number (its Unicode code point), so arithmetic on it works and can be cast back:
char letter = 'A';
int code = letter; // 65
char next = (char) (letter + 1); // 'B'
System.out.println(code + " " + next); // 65 B
And when you just want to try a snippet without a full class and main, launch jshell from the terminal: it is Java’s interactive REPL, perfect for typing a single expression such as 5 / 2 and seeing the integer-division result for yourself.