Quick Java for QA Automation Engineers

Quick Java for QA Automation Engineers

The Quick and Essential Java Guide for every QA Automation Engineer

Java is one of the most widely used programming languages for QA automation. This guide covers Quick Java for QA Automation Engineers, covering all major topics.


Java is a high-level, object-oriented, class-based programming language designed to be platform-independent — “Write Once, Run Anywhere.”

  • Developed: Java was developed by James Gosling and his team at Sun Microsystems.
  • Started: Development began in 1991 under the project name Oak.
  • Released: Java was officially released in 1995.
  • Current Ownership: Oracle acquired Sun Microsystems in 2010, so Java is now maintained primarily by Oracle along with the broader Java community.

JDK, JRE, and JVM

Think of them as:

JDK → JRE → JVM

  • JDK (Java Development Kit): Used by developers to develop, compile, debug, and run Java applications. It includes the JRE, compiler (javac), and other development tools.
  • JRE (Java Runtime Environment): Provides the environment required to run Java applications. It includes the JVM and Java class libraries.
  • JVM (Java Virtual Machine): Executes Java bytecode (.class files) and makes Java platform-independent by providing a JVM implementation for each operating system.

How Java Code Runs

Java Source Code (.java)
↓
javac
↓
Bytecode (.class)
↓
JVM
↓
Operating System

Key interview point:

JDK is for development, JRE is for running Java applications, and JVM is responsible for executing Java bytecode.

Why Should QA Automation Engineers Learn Java?

A strong Java foundation helps you:

  • Write better Selenium automation scripts
  • Build reusable automation frameworks
  • Work with test data effectively
  • Handle API responses and JSON data
  • Understand existing framework code
  • Debug automation failures
  • Prepare for Java and Selenium interviews

The goal is not to learn every feature of Java. Instead, focus on the Java concepts that are most useful in real-world test automation.


0. What is OOP in Java?

OOP (Object-Oriented Programming) is a programming approach based on objects and classes. Java uses four main OOP concepts: Encapsulation, Inheritance, Polymorphism, and Abstraction.

Example – Encapsulation:

class Employee {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}

Here, name is private and can only be accessed through getName() and setName(). This is Encapsulation.

Inheritance: Allows one class to acquire the properties and methods of another class using extends.

Polymorphism: Allows the same method or interface to behave differently depending on the object.

Abstraction: Hides implementation details and exposes only the essential functionality to the user.

1. Java Primitive Data Types

Java has eight primitive data types:

TypeSizeExample
byte8-bit100
short16-bit1000
int32-bit100000
long64-bit100000L
float32-bit10.5f
double64-bit10.5
char16-bit'A'
boolean—true / false

int vs Integer

This is a common Java interview question.

int a = 10;
Integer b = 10;

The difference is:

  • int is a primitive data type.
  • Integer is a wrapper class.
  • Java collections store objects, not primitive data types.

For example:

List<Integer> numbers = new ArrayList<>();

Here, Integer is used instead of int.


2. Arrays in Java

An array stores multiple values of the same data type.

int[] numbers = {10, 20, 30, 40};

Arrays are frequently used in coding interviews and automation tasks.

Find the Maximum Number in an Array

int[] arr = {5, 9, 2, 15, 7};
int max = arr[0];
for(int i = 1; i < arr.length; i++){
if(arr[i] > max){
max = arr[i];
}
}
System.out.println(max);

Output:

15

Find the Sum of an Array

int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for(int num : arr){
sum += num;
}
System.out.println(sum);

Output:

15

Reverse an Array

int[] arr = {1, 2, 3, 4, 5};
for(int i = arr.length - 1; i >= 0; i--){
System.out.print(arr[i] + " ");
}

Output:

5 4 3 2 1

3. Java String

String manipulation is one of the most common topics in QA Automation.

Reverse a String

String str = "Java";
String reversed = "";
for(int i = str.length() - 1; i >= 0; i--){
reversed += str.charAt(i);
}
System.out.println(reversed);

Output:

avaJ

Reverse a String Using StringBuilder

A simpler and more efficient approach is to use StringBuilder.

String str = "Java";
String reversed =
new StringBuilder(str)
.reverse()
.toString();
System.out.println(reversed);

Output:

avaJ

Check Whether a String Is a Palindrome

A palindrome reads the same forward and backward.

Examples:

madam
racecar

Example:

String str = "madam";
String reversed =
new StringBuilder(str)
.reverse()
.toString();
if(str.equals(reversed)){
System.out.println("Palindrome");
}

Count Character Occurrences

String str = "automation";
char target = 'o';
int count = 0;
for(char c : str.toCharArray()){
if(c == target){
count++;
}
}
System.out.println(count);

Output:

2

Remove Spaces from a String

String text = "Hello World Java";
String result = text.replace(" ", "");
System.out.println(result);

Output: HelloWorldJava

Interview Question: What does it mean when we say “Strings are immutable” in Java?

When we say Strings are immutable in Java, it means that once a String object is created, its value cannot be changed. If we perform an operation that appears to modify a String, Java actually creates a new String object rather than modifying the existing one.

Example

String name = "Java";
name.concat(" Programming");
System.out.println(name);

Output: Java

Why? concat() does not modify the original "Java" object. It creates a new String.

To use the new value:

String name = "Java";
name = name.concat(" Programming");
System.out.println(name);

Output: Java Programming

Here, name is now pointing to a new String object.


Why are Strings immutable?

There are several important reasons:

1. String Pool

Java maintains a String Pool to reuse String objects.

String a = "Hello";
String b = "Hello";

Both variables can refer to the same "Hello" object.

If Strings were mutable, changing a could unexpectedly affect b.

Because Strings are immutable, this is safe.


2. Security

Strings are frequently used for sensitive or critical information such as:

String username = "admin";
String url = "https://example.com";
String filePath = "/home/user/data";

If String values could be modified after creation, it could create security problems.


3. HashCode / HashMap

Strings are commonly used as keys in HashMap.

Map<String, Integer> map = new HashMap<>();
map.put("Java", 100);

If the String could change after being used as a key, its hashCode() could change and the map might not be able to locate the key correctly.


How do we “overcome” String immutability?

This is an important interview point:

You cannot make a String mutable.

Instead, if you need to perform multiple modifications, Java provides:

  • StringBuilder
  • StringBuffer

For most single-threaded applications, StringBuilder is preferred.

StringBuilder example

StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
sb.append(" Language");
System.out.println(sb);

Output: Java Programming Language

Here, the same StringBuilder object is modified instead of creating a new String for every operation.


Important String Methods — Interview Examples

Here are some methods worth knowing besides replace().

1. length()

Returns the number of characters.

String str = "Automation";
System.out.println(str.length());

Output:

10

2. charAt()

Returns the character at a particular index.

String str = "Java";
System.out.println(str.charAt(2));

Output: v

Remember: indexing starts from 0.

J → 0
a → 1
v → 2
a → 3

3. substring()

Extracts part of a String.

String str = "Playwright";
System.out.println(str.substring(5));

Output: right

You can also specify the starting and ending indexes:

String str = "Playwright";
System.out.println(str.substring(0, 5));

Output: Playw

The ending index is exclusive.


4. contains()

Checks whether a String contains a particular sequence.

String message = "Test automation with Playwright";
System.out.println(message.contains("Playwright"));

Output:

true

Very useful in automation assertions.

Assert.assertTrue(message.contains("Playwright"));

5. equals()

Compares the actual contents of two Strings.

String a = "Java";
String b = "Java";
System.out.println(a.equals(b));

Output:

true

Important interview point

Don’t use == to compare String contents.

String a = new String("Java");
String b = new String("Java");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true

== compares references, while equals() compares content.


6. equalsIgnoreCase()

Compares Strings without considering uppercase/lowercase differences.

String expected = "PASS";
String actual = "pass";
System.out.println(expected.equalsIgnoreCase(actual));

Output:

true

Very useful when validating UI/API responses where case may vary.


7. toUpperCase() and toLowerCase()

String str = "Playwright";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());

Output:

PLAYWRIGHT
playwright

Again, these don’t modify the original String.


8. trim()

Removes leading and trailing whitespace.

String str = " Java Automation ";
System.out.println(str.trim());

Output:

Java Automation

Interview note: trim() removes characters considered <= U+0020. For more Unicode-aware whitespace handling, modern Java provides strip(), stripLeading(), and stripTrailing().


9. startsWith() and endsWith()

String url = "https://example.com/login";
System.out.println(url.startsWith("https"));
System.out.println(url.endsWith("/login"));

Output:

true
true

These are particularly useful for URL and file-name validations.


10. indexOf()

Finds the position of a character or String.

String str = "Test Automation";
System.out.println(str.indexOf("Automation"));

Output:

5

If the value isn’t found, it returns:

-1

Example:

System.out.println(str.indexOf("Selenium"));

Output:

-1

11. split()

Splits a String into an array.

String data = "Java,Selenium,Playwright";
String[] tools = data.split(",");
for (String tool : tools) {
System.out.println(tool);
}

Output:

Java
Selenium
Playwright

This is a very useful method for QA automation interviews, particularly when processing CSV-like data.


12. concat()

Combines Strings.

String firstName = "John";
String lastName = "Smith";
String fullName = firstName.concat(" ").concat(lastName);
System.out.println(fullName);

Output:

John Smith

Remember: concat() creates a new String.


13. join()

The String.join() method is used to combine multiple strings with a specified delimiter.

Syntax:

String.join(delimiter, elements);

Example:

String result = String.join(", ", "Java", "Selenium", "Playwright");
System.out.println(result);

Output:

Java, Selenium, Playwright

It can also be used with a List:

List<String> tools = List.of("Java", "Selenium", "Rest Assured");
String result = String.join(" | ", tools);
System.out.println(result);

Output:

Java | Selenium | Rest Assured

Key point: .join() is useful when you need to combine strings while inserting the same delimiter between them.


String vs StringBuilder — Important Interview Comparison

FeatureStringStringBuilder
Mutable❌ No✅ Yes
ModificationCreates new objectModifies existing object
Thread-safeTechnically Yes (immutable)No
Performance for repeated changesLowerBetter
Suitable forFixed textFrequently changing text

Example

Using String:

String result = "";
for (int i = 1; i <= 5; i++) {
result = result + i;
}
System.out.println(result);

Multiple String objects can be created here because every concatenation produces a new String.

Using StringBuilder:

StringBuilder result = new StringBuilder();
for (int i = 1; i <= 5; i++) {
result.append(i);
}
System.out.println(result);

This is more efficient for repeated modifications.


4. Java Loops

Loops are frequently used in automation frameworks to process browsers, test data, web elements, and API responses.

For Loop

for(int i = 1; i <= 5; i++){
System.out.println(i);
}

While Loop

int i = 1;
while(i <= 5){
System.out.println(i);
i++;
}

Enhanced For Loop

The enhanced for loop is commonly used in automation frameworks.

String[] browsers =
{"Chrome", "Firefox", "Edge"};
for(String browser : browsers){
System.out.println(browser);
}

5. Conditional Statements in Java

Conditional statements allow your automation code to make decisions.

if-else

int age = 20;
if (age >= 65) {
System.out.println("Senior");
}
else if (age >= 18) {
System.out.println("Adult");
}
else {
System.out.println("Minor");
}

switch Statement

The switch statement is useful when you need to perform different actions based on a value.

String browser = "Chrome";
switch(browser){
case "Chrome":
System.out.println("Launching Chrome");
break;
case "Firefox":
System.out.println("Launching Firefox");
break;
default:
System.out.println("Invalid Browser");
}

6. List Collection in Java

A List is useful when:

  • Duplicate values are allowed.
  • Insertion order matters.

The most commonly used implementation is ArrayList.

List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple");
System.out.println(fruits);

Output:

[Apple, Banana, Apple]

Duplicates are allowed.

Iterate Through a List

for(String fruit : fruits){
System.out.println(fruit);
}

Remove an Element

fruits.remove("Banana");

7. Set Collection in Java

A Set is used when duplicate values are not allowed.

Set<String> set = new HashSet<>();
set.add("Java");
set.add("Selenium");
set.add("Java");
System.out.println(set);

Output:

[Java, Selenium]

The duplicate "Java" is automatically removed.


8. LinkedHashSet in Java

LinkedHashSet is frequently discussed in Java interviews.

CollectionOrder
HashSetNo guaranteed insertion order
LinkedHashSetMaintains insertion order

Example:

Set<String> set = new LinkedHashSet<>();
set.add("Java");
set.add("Selenium");
set.add("API");
System.out.println(set);

Output:

[Java, Selenium, API]

Remove Duplicates from an Array

String[] names = {"John", "Mike", "John", "David"};
Set<String> unique = new LinkedHashSet<>(Arrays.asList(names));
System.out.println(unique);

Output:

[John, Mike, David]

This is a very common QA automation interview question.


9. Map Collection in Java

A Map stores data in key-value pairs.

Map<Integer, String> map = new HashMap<>();
map.put(1, "John");
map.put(2, "Mike");
map.put(3, "David");
System.out.println(map);

Output:

{1=John, 2=Mike, 3=David}

Get a Value from a Map

System.out.println(map.get(2));

Output:

Mike

Iterate Through a Map

for(Map.Entry<Integer, String> entry : map.entrySet()){
System.out.println(entry.getKey() + " " + entry.getValue());
}

10. LinkedHashMap in Java

LinkedHashMap maintains insertion order.

MapOrder
HashMapNo guaranteed insertion order
LinkedHashMapInsertion order maintained

Example:

Map<Integer, String> map = new LinkedHashMap<>();
map.put(101, "Chrome");
map.put(102, "Firefox");
map.put(103, "Edge");
System.out.println(map);

Output:

{101=Chrome, 102=Firefox, 103=Edge}

Count Character Frequency

This is a frequently asked Java coding problem.

String str = "banana";
Map<Character, Integer> map = new HashMap<>();
for(char c : str.toCharArray()){
map.put( c, map.getOrDefault(c, 0) + 1);
}
System.out.println(map);

Output:

{b=1, a=3, n=2}

This technique is useful for analyzing text and test data.


Find Duplicate Elements in an Array

int[] arr = {1, 2, 3, 2, 4, 1};
Set<Integer> unique = new HashSet<>();
Set<Integer> duplicate = new HashSet<>();
for(int num : arr){
if(!unique.add(num)){
duplicate.add(num);
}
}
System.out.println(duplicate);

Output:

[1, 2]

The add() method returns false when the value already exists in the set.


11. ArrayList vs LinkedList

ArrayListLinkedList
Uses a dynamic arrayUses a doubly linked list
Fast random accessSlower random access
Fast read operationsFaster insertion/deletion in certain cases
More common in automationLess common in automation

For Selenium and TestNG automation frameworks, ArrayList is used far more frequently.


12. HashMap vs Hashtable

HashMapHashtable
Not synchronizedSynchronized
FasterSlower
Allows one null keyDoes not allow null keys
Preferred todayLegacy class

In modern Java applications, HashMap is generally preferred unless synchronization requirements dictate otherwise.


13. Abstract Class vs Interface

This is an important Java OOP interview topic.

Abstract ClassInterface
Can have abstract and concrete methodsCan have abstract, default, and static methods
Can have instance variablesFields are constants
Supports constructorsDoes not have constructors
A class can extend only one classA class can implement multiple interfaces
Useful for shared behaviorUseful for defining a contract

Abstract Class Example

abstract class Vehicle {
abstract void start();
void stop(){
System.out.println("Vehicle stopped");
}
}

Interface Example

interface Engine {
void fuelType();
}

Interview Answer

Use an abstract class when related classes share common state and behavior.

Use an interface when you want to define a contract or capability that different classes can implement.


14. Compile-Time and Runtime Polymorphism

Static/Compile-Time Polymorphism

Static polymorphism is achieved through method overloading.

class Calculator {
int add(int a, int b){
return a + b;
}
int add(int a, int b, int c){
return a + b + c;
}
}

The compiler decides which method to call.

Runtime Polymorphism

Runtime polymorphism is achieved through method overriding.

class Animal {
void sound(){
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound(){
System.out.println("Bark");
}
}
Animal a = new Dog();
a.sound();

Output:

Bark

The JVM decides at runtime which method to execute.


15. Method Overloading vs Method Overriding

OverloadingOverriding
Same method nameSame method name
Different parametersSame parameters
Usually within the same classParent-child relationship
Compile-time polymorphismRuntime polymorphism

Method Overloading

void login(String username){
}
void login(String username, String password){
}

Method Overriding

class Parent {
void display(){
}
}
class Child extends Parent {
@Override
void display(){
}
}

16. this vs super

this

this refers to the current object.

class Employee {
String name;
Employee(String name){
this.name = name;
}
}

super

super refers to the parent class.

class Parent {
String company = "ABC";
}
class Child extends Parent {
void print(){
System.out.println(super.company);
}
}
thissuper
Refers to current class objectRefers to parent class
Accesses current variables and methodsAccesses parent variables and methods
Can call current constructorCan call parent constructor

17. Checked and Unchecked Exceptions

Checked Exceptions

Checked exceptions are checked at compile time.

Examples:

  • IOException
  • SQLException
  • FileNotFoundException

Example:

FileReader file = new FileReader("test.txt");

The compiler requires the exception to be handled or declared.

Unchecked Exceptions

Unchecked exceptions occur at runtime.

Examples:

  • NullPointerException
  • ArithmeticException
  • ArrayIndexOutOfBoundsException

Example:

String str = null;
System.out.println(str.length());

18. throw vs throws

throw

Used to explicitly throw an exception.

throw new RuntimeException("Error");

throws

Used in a method declaration.

public void readFile() throws IOException {
}
throwthrows
Used inside a methodUsed in method signature
Throws one exception at a timeCan declare multiple exceptions
Creates an exception objectDeclares the possibility of an exception

19. try-catch-finally

try{
int result = 10 / 0; // divide by Zero -> ArithmeticException
}catch(Exception e){
System.out.println("Error");
}
finally{
System.out.println("Always executes");
}

Output:

Error
Always executes

The finally block is commonly used for cleanup operations such as:

  • Closing database connections
  • Closing file streams
  • Closing browser sessions

For example:

driver.quit();

20. Functional Interfaces and Lambda Expressions

A functional interface contains exactly one abstract method.

Examples include:

  • Runnable
  • Comparator
  • Predicate
  • Consumer

Example:

@FunctionalInterface
interface Calculator {
int add(int a, int b);
}

Using a lambda expression:

Calculator c = (a, b) -> a + b;

Lambda expressions are widely used with Java Streams and collections.

list.forEach(item -> System.out.println(item));

21. Singleton Design Pattern

The Singleton Design Pattern ensures that only one object of a class exists.

Common automation examples include:

  • WebDriver managers
  • Configuration readers
  • Loggers
class Singleton {
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}

Usage:

Singleton obj = Singleton.getInstance();

Why Is the Constructor Private?

A private constructor prevents other classes from creating objects using the new keyword.


22. Factory Design Pattern

The Factory Pattern creates objects without exposing the object creation logic.

interface Browser {
void launch();
}

Chrome implementation:

class Chrome implements Browser {
public void launch(){
System.out.println("Chrome");
}
}

Firefox implementation:

class Firefox implements Browser {
public void launch(){
System.out.println("Firefox");
}
}

Factory class:

class BrowserFactory {
public Browser getBrowser(String browser){
if(browser.equals("chrome")){
return new Chrome();
}
if(browser.equals("firefox")){
return new Firefox();
}
return null;
}
}

Usage:

Browser driver = factory.getBrowser("chrome");

Factories are commonly used for browser initialization in Selenium frameworks.


23. Builder Design Pattern

The Builder Pattern is useful when an object has many parameters.

Without a Builder:

Employee emp = new Employee(
"John",
30,
"QA",
"USA",
10000
);

This can become difficult to read and maintain.

With a Builder:

Employee emp = new Employee.Builder()
.setName("John")
.setAge(30)
.setDepartment("QA")
.build();

Benefits of the Builder Pattern

  • More readable code
  • Flexible object creation
  • Easier maintenance
  • Supports immutable object design

The Builder Pattern is widely used in automation frameworks.


24. static Keyword in Java

The static keyword means that a member belongs to the class rather than a specific object.

Static Variable

class Employee {
static String company = "ABC";
}

The variable is shared by all objects.

Static Method

class Utility {
static void print(){
System.out.println("Hello");
}
}

Call the method without creating an object:

Utility.print();

Static Block

A static block runs when the class is loaded.

static {
System.out.println("Loading");
}

Interview Question

Can a static method directly access non-static variables?

Answer: No. Static methods belong to the class, while non-static variables belong to individual objects.


25. Type Casting and Type Conversion

Implicit Casting

Also called widening conversion.

int a = 100;
long b = a;

The conversion happens automatically.

Typical widening conversion:

int → long → float → double

Explicit Casting

Also called narrowing conversion.

double d = 10.5;
int i = (int)d;
System.out.println(i);

Output:

10

The decimal portion is lost.


26. Upcasting and Downcasting

Upcasting

Animal a = new Dog();

Upcasting is automatic and generally safe.

Downcasting

Dog d = (Dog) a;

Downcasting requires an explicit cast.


27. The Collections Utility Class

Collections is a utility class in the java.util package.

It provides static methods for working with collections.

import java.util.Collections;

Because its methods are static, you do not create a Collections object.

Collections.sort(list);

Collections.sort()

Sorts a list.

List<Integer> numbers = Arrays.asList(5, 2, 9, 1);
Collections.sort(numbers);
System.out.println(numbers);

Output:

[1, 2, 5, 9]

Sorting strings:

List<String> names = Arrays.asList(
"John",
"Adam",
"Mike"
);
Collections.sort(names);
System.out.println(names);

Output:

[Adam, John, Mike]

Collections.reverse()

List<String> names = Arrays.asList("A", "B", "C");
Collections.reverse(names);
System.out.println(names);

Output:

[C, B, A]

Collections.shuffle()

Randomizes the order of a list.

Collections.shuffle(names);

This can be useful when generating random test data.

Collections.max()

List<Integer> nums = Arrays.asList(10, 50, 30);
System.out.println(Collections.max(nums));

Output:

50

Collections.min()

System.out.println(Collections.min(nums));

Output:

10

Collections.frequency()

Counts how many times an element occurs.

List<String> list = Arrays.asList(
"Chrome",
"Firefox",
"Chrome"
);
int count = Collections.frequency(list, "Chrome");
System.out.println(count);

Output:

2

This is useful in validation scenarios.

Collections.binarySearch()

Searches for an element in a sorted list.

List<Integer> nums =Arrays.asList(10, 20, 30, 40);
int index = Collections.binarySearch(nums, 30);
System.out.println(index);

Output:

2

The list must be sorted before using binary search.

Collections.swap()

Swaps two elements.

List<String> list = Arrays.asList("A", "B", "C");
Collections.swap(list, 0, 2);
System.out.println(list);

Output:

[C, B, A]

Collections.fill()

Replaces every element in a list.

List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Collections.fill(list, "Test");
System.out.println(list);

Output:

[Test, Test, Test]

Collections.copy()

Copies elements from one list to another.

List<String> source = Arrays.asList( "A", "B", "C");
List<String> destination = new ArrayList<>(Arrays.asList("X", "Y", "Z"));
Collections.copy(destination, source);
System.out.println(destination);

Output:

[A, B, C]

28. Collection vs Collections

This is another common Java interview question.

CollectionCollections
An interfaceA utility class
Parent interface of List, Set, and QueueContains static utility methods
Implemented by classes such as ArrayList and HashSetUsed for sorting, searching, reversing, and other operations

29. == vs equals() in Java

Understanding the difference between == and equals() is extremely important.

== Operator

The == operator checks whether two references point to the same object in memory.

String a = "Hello";
String b = "Hello";
System.out.println(a == b);

Output:

true

Why? Because identical string literals are stored in the String Pool, and Java may reuse the same object.

Conceptually:

String Pool
"Hello" ← a
← b

equals()

The equals() method compares the content of objects.

String a = "Hello";
String b = "Hello";
System.out.println(a.equals(b));

Output:

true

Example: String Literal vs new String()

String a = "Hello";
String c = new String("Hello");
System.out.println(a == c);
System.out.println(a.equals(c));

Output:

false
true

Why? new String("Hello") creates a new object.

The references are different, but the contents are the same.

Simple Rule

Use:

==

to compare references.

Use:

equals()

to compare object content.


30. Converting int to String

Using String.valueOf()

int num = 123;
String str = String.valueOf(num);
System.out.println(str);

Output:

123

Using Integer.toString()

int num = 123;
String str = Integer.toString(num);

Using Concatenation

int num = 123;
String str = num + " ";

This works, but String.valueOf() is generally preferred in interviews because it clearly communicates the conversion.


31. Converting String to int

Using Integer.parseInt()

This is the most common approach.

String str = "123";
int num = Integer.parseInt(str);
System.out.println(num);

Output:

123

Using Integer.valueOf()

String str = "123";
Integer num = Integer.valueOf(str);

Integer.valueOf() returns an Integer object.

Java can automatically unbox it into an int when required.

int num = Integer.valueOf(str);

What Happens with Invalid Input?

String str = "123abc";
int num = Integer.parseInt(str);

This results in:

NumberFormatException

The reason is that "123abc" is not a valid integer.

31. Scanner Class

Java provides the Scanner class to read user input from the console. It is part of the java.util package and is commonly used when learning Java fundamentals, writing simple programs, and handling Java user input.

To use Scanner, first import the class:

import java.util.Scanner;

Create a Scanner object using System.in:

Scanner scanner = new Scanner(System.in);

You can then read different types of input using methods such as nextInt(), nextDouble(), and nextLine().

Reading Integer Input

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Your age is: " + age);

Reading String Input

Use nextLine() when you want to read a complete line of text:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);

Reading Multiple Values

Scanner scanner = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println("Sum: " + (a + b));

Important: Be careful when mixing nextInt() and nextLine(). After nextInt(), you may need an additional nextLine() to consume the leftover newline character.

int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();

Using Scanner input in Java is one of the simplest ways to make console-based programs interactive.


Final Thoughts

Learning Java for QA Automation does not mean that you need to master every advanced Java topic. Your goal should be to understand the concepts that help you write reliable, maintainable, and reusable automation code.

Start with the fundamentals:

  • Data types
  • Arrays
  • Strings
  • Loops
  • Conditions
  • Collections

Then move on to:

  • OOP
  • Exception handling
  • Lambda expressions
  • Design patterns
  • Type conversion

The most important step is consistent practice. Try writing small Java programs, solve common coding interview problems, and apply these concepts while building Selenium or API automation frameworks.

With a solid Java foundation, learning tools such as Selenium WebDriver, TestNG, Rest Assured, and Cucumber becomes much easier.

Related Links

Java Guide Page

Selenium Guide Page

Playwright Guide Page

REST Assured Guide Page


Discover more from Rotebit

Subscribe to get the latest posts sent to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply