Java Tutorials

Java – Home

Introduction to Java programming language and its features.Example:System.out.println("Welcome to Java!"); Read More

Java – Overview

Java is a high-level, object-oriented programming language used for building web, desktop, and mobile applications.Example:public class MyApp { public static void main(String[] args) { System.out.println("This is a Java program."); }} Read More

Java – History

Java was developed by Sun Microsystems in 1995, later acquired by Oracle. It was initially designed for interactive television. Read More

Java – Features

Java is platform-independent, object-oriented, multithreaded, and supports automatic memory management (garbage collection).Example:class Example { public void display() { System.out.println("Java Features!"); }} Read More

Java Vs. C++

Java is simpler and easier to use compared to C++, which is more complex and provides low-level features.Example:System.out.println("Java is platform-independent"); Read More

JVM – Java Virtual Machine

The JVM is responsible for running Java programs. It converts bytecode into machine code for execution.Example:System.out.println("Java bytecode executed by JVM."); Read More

Java – JDK vs JRE vs JVM

JDK (Java Development Kit) includes tools for developing Java applications. JRE (Java Runtime Environment) allows running Java applications. JVM is the engine that executes bytecode.Example:JDK includes javac compiler,JRE includes the JVM. Read More

Java – Hello World Program

The traditional "Hello, World!" program in Java to display a message on the screen.Example:public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }} Read More

Java – Environment Setup

Steps to set up the Java development environment, including downloading and installing JDK and setting up the PATH variable.Example:javac MyProgram.javajava MyProgram Read More

Java – Basic Syntax

Java syntax includes the rules for defining variables, functions, classes, and other basic elements of a program.Example:public class Example { public static void main(String[] args) { int x = 5; System.out.println(x); }} Read More

Java – Variable Types

Java supports various types of variables, including int, double, String, and boolean. These are used to store different types of data.Example:int num = 10;double price = 19.99;String name = "Java"; Read More

Java – Data Types

Java has both primitive data types (like int, double) and reference data types (like objects and arrays).Example:int age = 25;double height = 5.9;String name = "John"; Read More

Java – Type Casting

Type casting is converting one data type to another.Example:int x = 10;double y = (double) x;System.out.println(y); Read More

Java – Unicode System

Java uses Unicode to represent characters, allowing it to support characters from all languages and symbols.Example:char c = 'u0041'; // Unicode for 'A'System.out.println(c); Read More

Java – Basic Operators

Java supports various types of operators:Example:int a = 10, b = 5;System.out.println(a + b); // Addition Read More

Java – Comments

Comments are used to annotate code for clarity. Single-line comments use "//", and multi-line comments use "/*...*/".Example:// This is a single-line comment/* This is a multi-line comment */ Read More

Java – User Input

Java can take user input using the Scanner class.Example:Scanner scanner = new Scanner(System.in);System.out.print("Enter your name: ");String name = scanner.nextLine();System.out.println("Hello, " + name); Read More

Java – Loops

Loops in Java are used for repeated execution of a block of code. Common types include for, while, and do-while loops.Example:for (int i = 0; i < 5; i++) { System.out.println(i);} Read More

Java – Functions

Functions are reusable blocks of code that perform specific tasks. They are defined using the public static void syntax.Example:public static void greet() { System.out.println("Hello, World!");}public static void main(String[] args) { greet();} Read More

Java – OOP Concepts

Java is an object-oriented programming language that includes Inheritance, Polymorphism, Encapsulation, and Abstraction.Example:class Animal { void sound() { System.out.println("Animal makes a sound"); }}class Dog extends Animal { void sound() { System.out.println("Dog barks"); }} Read More

Java – Exceptions

Exception Handling in Java is used to manage runtime errors using try, catch, finally, and throw statements.Example:try { int result = 10 / 0;} catch (ArithmeticException e) { System.out.println("Division by zero error!");} Read More

Java – Collections Framework

The Java Collections Framework provides reusable data structures like ArrayList, HashMap, and HashSet.Example:ArrayList list = new ArrayList();list.add("Apple");list.add("Banana");System.out.println(list); Read More

Java – Generics

Generics enable type-safe programming by specifying data types for classes and methods.Example:ArrayList numbers = new ArrayList();numbers.add(10);System.out.println(numbers); Read More

Java – Streams API

The Streams API introduced in Java 8 enables functional-style operations on collections.Example:List names = Arrays.asList("Alice", "Bob", "Charlie");names.stream().filter(name -> name.startsWith("A")) .forEach(System.out::println); Read More

Java – Lambda Expressions

Introduced in Java 8, Lambda Expressions enable functional programming with concise syntax.Example:List numbers = Arrays.asList(1, 2, 3, 4, 5);numbers.forEach(n -> System.out.println(n)); Read More

Java – Modules (Java 9)

Java 9 introduced the Module System, allowing developers to modularize applications and improve performance.Example:module mymodule { exports com.example.myapp;} Read More

Java – Optional Class

The Optional class helps handle null values and avoid NullPointerException.Example:Optional name = Optional.ofNullable(null);System.out.println(name.orElse("Default Name")); Read More

Java – Switch Expressions (Java 12+)

Switch expressions introduced in Java 12 allow concise case statements.Example:int day = 2;String dayName = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; default -> "Invalid Day";};System.out.println(dayName); Read More

Java – Records (Java 14+)

Records provide a compact syntax for creating data classes.Example:record Point(int x, int y) {}Point p = new Point(10, 20);System.out.println(p.x() + ", " + p.y()); Read More

Java – Pattern Matching (Java 16+)

Java introduced Pattern Matching for type checks with instanceof in Java 16.Example:Object obj = "Hello";if (obj instanceof String s) { System.out.println(s.toUpperCase());} Read More

Java – Sealed Classes (Java 17+)

Sealed Classes restrict which classes can extend or implement them.Example:sealed class Shape permits Circle, Rectangle {}final class Circle extends Shape {}final class Rectangle extends Shape {} Read More

Java – Virtual Threads (Java 19)

Java 19 introduced Virtual Threads, making it easier to handle concurrency.Example:try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { executor.submit(() -> System.out.println("Hello from Virtual Thread"));} Read More

Java Loops

Java – Loops

Loops are control flow statements that repeat code execution until a specified condition is met. Types of loops include For, While, Do-While, and For-Each. Each has specific use cases. Read More

Java – For Loop

For Loop: Iterates for a specific number of times.Example:for (int i = 1; i Read More

Java – While Loop

While Loop: Executes as long as the condition is true.Example:int i = 1;while (i Read More

Java – Do-While Loop

Do-While Loop: Executes at least once before condition check.Example:int i = 1;do { System.out.println(i); i++;} while (i Read More

Java – Do-While Loop (Validation)

Validate user input with do-while loop:Example:Scanner sc = new Scanner(System.in);int input;do { System.out.print("Enter a positive number: "); input = sc.nextInt();} while (input Read More

Java – For-Each Loop

For-Each Loop: Used to iterate over arrays or collections.Example:int[] numbers = {1, 2, 3, 4, 5};for (int num : numbers) { System.out.println(num);} Read More

Java – For-Each Loop (Sum Example)

Sum of array elements:Example:int[] numbers = {1, 2, 3, 4, 5};int sum = 0;for (int num : numbers) { sum += num;}System.out.println("Total: " + sum); Read More

Java OOPS

Java – OOP Concepts

Object-Oriented Programming (OOP): Java follows OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction. These principles help in building modular, scalable, and maintainable applications. Read More

Java – Encapsulation

Encapsulation: Restricting direct access to object data and methods by using private access modifiers and providing public getters and setters.Example:class Employee { private String name; private int id; public String getName() { return name; } public void setName(String name) {... Read More

Java – Inheritance

Inheritance: Enables one class to acquire the properties and behavior of another class using the extends keyword.Example:class Animal { void eat() { System.out.println("This animal eats food."); }}class Dog extends Animal { void bark() { System.out.println("Dog barks."); }}Dog myDog = new... Read More

Java – Polymorphism

Polymorphism: The ability of a method to perform different tasks based on its parameters or the object it is called on. Types: Method Overloading and Method Overriding.Example:Overloading:class MathOps { int add(int a, int b) { return a + b; }... Read More

Java – Abstraction

Abstraction: Hiding implementation details and showing only essential features using abstract classes or interfaces.Example:Abstract Class:abstract class Shape { abstract void draw();}class Circle extends Shape { void draw() { System.out.println("Drawing Circle"); }}Shape s = new Circle();s.draw();Interface:interface Animal { void sound();}class Cat... Read More

Java – Functional Interfaces (Java 1.8+)

Functional Interfaces: An interface with a single abstract method. Used with Lambda Expressions.Example:@FunctionalInterfaceinterface Greeting { void sayHello(String name);}Greeting greet = (name) -> System.out.println("Hello, " + name);greet.sayHello("John"); Read More

Java – Streams (Java 1.8+)

Streams: Used for processing collections with declarative programming. Supports operations like map, filter, reduce.Example:List numbers = Arrays.asList(1, 2, 3, 4, 5);numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); Read More

Java – Default Methods in Interfaces (Java 1.8+)

Default Methods: Allows interfaces to have concrete methods with default implementation.Example:interface Vehicle { default void start() { System.out.println("Vehicle is starting."); }}class Car implements Vehicle {}Car myCar = new Car();myCar.start(); Read More

Java – Record Classes (Java 14+)

Records: Simplifies creating immutable data classes. Automatically generates constructors, equals, hashCode, and toString.Example:record Person(String name, int age) {}Person p = new Person("Alice", 25);System.out.println(p.name() + ", " + p.age()); Read More

Java – Pattern Matching (Java 16+)

Pattern Matching: Simplifies conditional code by type-checking in expressions.Example:Object obj = "Hello";if (obj instanceof String str) { System.out.println(str.toUpperCase());} Read More

Java – Sealed Classes (Java 17+)

Sealed Classes: Restricts which classes can extend or implement a class/interface.Example:sealed class Shape permits Circle, Rectangle { }final class Circle extends Shape { }final class Rectangle extends Shape { } Read More

Java Collections

Java – Arrays

Arrays: A collection of elements of the same type, stored in contiguous memory locations. Used to store fixed-size sequential elements.Example:int[] arr = {1, 2, 3, 4, 5};for (int i : arr) { System.out.println(i);}System.out.println("Length: " + arr.length);Multi-Dimensional Arrays:int[][] matrix = {{1,... Read More

Java – ArrayList (Collections Framework)

ArrayList: A resizable array implementation in Java Collections. Allows dynamic size changes.Example:import java.util.ArrayList;ArrayList list = new ArrayList();list.add("Apple");list.add("Banana");list.add("Cherry");System.out.println(list);list.remove(1);System.out.println(list);for (String fruit : list) { System.out.println(fruit);} Read More

Java – LinkedList (Collections Framework)

LinkedList: A doubly-linked list implementation of the List interface. Efficient for insertions and deletions.Example:import java.util.LinkedList;LinkedList list = new LinkedList();list.add(10);list.add(20);list.addFirst(5);list.addLast(30);System.out.println(list);list.remove(2);System.out.println(list); Read More

Java – HashMap (Collections Framework)

HashMap: A map-based collection that stores key-value pairs. Provides constant-time complexity for basic operations.Example:import java.util.HashMap;HashMap map = new HashMap();map.put(1, "John");map.put(2, "Alice");map.put(3, "Bob");System.out.println(map);System.out.println("Key 2: " + map.get(2));map.remove(1);System.out.println(map);for (int key : map.keySet()) { System.out.println(key + " -> " + map.get(key));} Read More

Java – HashSet (Collections Framework)

HashSet: A set-based collection that stores unique elements. No duplicate values allowed.Example:import java.util.HashSet;HashSet set = new HashSet();set.add("Apple");set.add("Banana");set.add("Cherry");set.add("Apple"); // DuplicateSystem.out.println(set);set.remove("Banana");System.out.println(set);for (String fruit : set) { System.out.println(fruit);} Read More

Java – TreeMap (Collections Framework)

TreeMap: A map-based collection that stores key-value pairs in sorted order.Example:import java.util.TreeMap;TreeMap map = new TreeMap();map.put(3, "Alice");map.put(1, "John");map.put(2, "Bob");System.out.println(map);map.remove(3);System.out.println(map);for (int key : map.keySet()) { System.out.println(key + " -> " + map.get(key));} Read More

Java – Stack (Collections Framework)

Stack: A last-in-first-out (LIFO) data structure. Allows push, pop, and peek operations.Example:import java.util.Stack;Stack stack = new Stack();stack.push(10);stack.push(20);stack.push(30);System.out.println(stack);System.out.println("Peek: " + stack.peek());System.out.println("Pop: " + stack.pop());System.out.println(stack); Read More

Java – Queue (Collections Framework)

Queue: A first-in-first-out (FIFO) data structure. Common implementations include LinkedList and PriorityQueue.Example:import java.util.LinkedList;Queue queue = new LinkedList();queue.add("Task1");queue.add("Task2");queue.add("Task3");System.out.println(queue);System.out.println("Poll: " + queue.poll());System.out.println(queue); Read More

Java – PriorityQueue (Collections Framework)

PriorityQueue: A queue that retrieves elements based on priority.Example:import java.util.PriorityQueue;PriorityQueue pq = new PriorityQueue();pq.add(30);pq.add(10);pq.add(20);System.out.println(pq);System.out.println("Poll: " + pq.poll());System.out.println(pq); Read More

Java – Iterators (Collections Framework)

Iterators: Used for traversing collections.Example:import java.util.ArrayList;import java.util.Iterator;ArrayList list = new ArrayList();list.add("Apple");list.add("Banana");list.add("Cherry");Iterator iterator = list.iterator();while (iterator.hasNext()) { System.out.println(iterator.next());} Read More

Java Exceptions

Java – NullPointerException

NullPointerException: Thrown when an application attempts to use a `null` object reference where an object is required.Example:String str = null;try { System.out.println(str.length());} catch (NullPointerException e) { System.out.println("Caught NullPointerException: " + e.getMessage());} Read More

Java – ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException: Thrown when an application tries to access an array with an illegal index.Example:int[] arr = {1, 2, 3};try { System.out.println(arr[5]);} catch (ArrayIndexOutOfBoundsException e) { System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());} Read More

Java – ClassCastException

ClassCastException: Thrown when an invalid cast is attempted between incompatible types.Example:Object obj = "Hello World";try { Integer i = (Integer) obj;} catch (ClassCastException e) { System.out.println("Caught ClassCastException: " + e.getMessage());} Read More

Java – ArithmeticException

ArithmeticException: Thrown when an exceptional arithmetic condition occurs, such as division by zero.Example:int a = 10;int b = 0;try { System.out.println(a / b);} catch (ArithmeticException e) { System.out.println("Caught ArithmeticException: " + e.getMessage());} Read More

Java – IllegalArgumentException

IllegalArgumentException: Thrown to indicate that a method has been passed an illegal or inappropriate argument.Example:public static void checkAge(int age) { if (age < 18) { throw new IllegalArgumentException("Age must be at least 18"); }}try { checkAge(16);} catch (IllegalArgumentException e) {... Read More

Java – NumberFormatException

NumberFormatException: Thrown when an attempt to convert a string to a numeric type fails.Example:String str = "ABC";try { int number = Integer.parseInt(str);} catch (NumberFormatException e) { System.out.println("Caught NumberFormatException: " + e.getMessage());} Read More

Java – FileNotFoundException

FileNotFoundException: Thrown when an attempt to open the file denoted by a specified pathname has failed.Example:import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;try { File file = new File("nonexistent.txt"); Scanner sc = new Scanner(file);} catch (FileNotFoundException e) { System.out.println("Caught FileNotFoundException: " + e.getMessage());} Read More

Java – InterruptedException

InterruptedException: Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted.Example:try { Thread.sleep(1000);} catch (InterruptedException e) { System.out.println("Caught InterruptedException: " + e.getMessage());} Read More

Java – IOException

IOException: A general exception thrown when an I/O operation fails or is interrupted.Example:import java.io.FileReader;import java.io.IOException;try { FileReader reader = new FileReader("test.txt");} catch (IOException e) { System.out.println("Caught IOException: " + e.getMessage());} Read More

Java – NoSuchElementException

NoSuchElementException: Thrown when one tries to access an element that is not present, such as an empty iterator.Example:import java.util.Iterator;import java.util.NoSuchElementException;Iterator iterator = new ArrayList().iterator();try { System.out.println(iterator.next());} catch (NoSuchElementException e) { System.out.println("Caught NoSuchElementException: " + e.getMessage());} Read More

Java – ConcurrentModificationException

ConcurrentModificationException: Thrown when an object is concurrently modified while iterating through it, in a way that is not allowed.Example:import java.util.ArrayList;import java.util.Iterator;import java.util.ConcurrentModificationException;ArrayList list = new ArrayList();list.add("One");list.add("Two");list.add("Three");Iterator iterator = list.iterator();try { list.remove("Two"); iterator.next();} catch (ConcurrentModificationException e) { System.out.println("Caught ConcurrentModificationException: " +... Read More

Java – IllegalStateException

IllegalStateException: Thrown when a method has been invoked at an illegal or inappropriate time.Example:import java.util.Iterator;import java.util.NoSuchElementException;Iterator iterator = new ArrayList().iterator();try { iterator.remove();} catch (IllegalStateException e) { System.out.println("Caught IllegalStateException: " + e.getMessage());} Read More

Java – UnsupportedOperationException

UnsupportedOperationException: Thrown to indicate that a requested operation is not supported.Example:import java.util.Collections;import java.util.List;List list = Collections.unmodifiableList(new ArrayList());try { list.add("Hello");} catch (UnsupportedOperationException e) { System.out.println("Caught UnsupportedOperationException: " + e.getMessage());} Read More

Java – NoClassDefFoundError

NoClassDefFoundError: Thrown when the JVM cannot find a class it needs to load.Example:try { Class.forName("com.example.NonExistentClass");} catch (ClassNotFoundException e) { System.out.println("Caught ClassNotFoundException: " + e.getMessage());} Read More

Java – StackOverflowError

StackOverflowError: Thrown when the stack is exhausted due to deep recursion.Example:public static void recursiveMethod() { recursiveMethod();}try { recursiveMethod();} catch (StackOverflowError e) { System.out.println("Caught StackOverflowError: " + e.getMessage());} Read More

Java – OutOfMemoryError

OutOfMemoryError: Thrown when the JVM cannot allocate an object due to insufficient memory.Example:try { int[] arr = new int[Integer.MAX_VALUE];} catch (OutOfMemoryError e) { System.out.println("Caught OutOfMemoryError: " + e.getMessage());} Read More

Java – FileAlreadyExistsException

FileAlreadyExistsException: Thrown when an attempt is made to create a file that already exists.Example:import java.nio.file.*;import java.io.IOException;try { Path path = Paths.get("existingFile.txt"); Files.createFile(path);} catch (FileAlreadyExistsException e) { System.out.println("Caught FileAlreadyExistsException: " + e.getMessage());} Read More

Java – TimeoutException

TimeoutException: Thrown when a blocking operation times out.Example:import java.util.concurrent.*;ExecutorService executor = Executors.newSingleThreadExecutor();Future future = executor.submit(() -> { Thread.sleep(2000); return "Task Completed";});try { String result = future.get(1, TimeUnit.SECONDS);} catch (TimeoutException e) { System.out.println("Caught TimeoutException: " + e.getMessage());} Read More

Java – ExecutionException

ExecutionException: Thrown when attempting to retrieve the result of a task that aborted by throwing an exception.Example:ExecutorService executor = Executors.newSingleThreadExecutor();Future future = executor.submit(() -> { throw new IllegalStateException("Execution Error");});try { future.get();} catch (ExecutionException e) { System.out.println("Caught ExecutionException: " + e.getMessage());} Read More

Java – ClassCastException

ClassCastException: Thrown when an object is cast to a subclass type that it is not an instance of.Example:Object obj = new String("Hello World");try { Integer number = (Integer) obj;} catch (ClassCastException e) { System.out.println("Caught ClassCastException: " + e.getMessage());} Read More

Java – NumberFormatException

NumberFormatException: Thrown when an attempt is made to convert a string into a number, but the string does not have an appropriate format.Example:String str = "abc";try { int number = Integer.parseInt(str);} catch (NumberFormatException e) { System.out.println("Caught NumberFormatException: " + e.getMessage());} Read More

Java – NullPointerException

NullPointerException: Thrown when the JVM attempts to access a method or field of a null object.Example:String str = null;try { int length = str.length();} catch (NullPointerException e) { System.out.println("Caught NullPointerException: " + e.getMessage());} Read More

Java – ArithmeticException

ArithmeticException: Thrown when an illegal arithmetic operation, such as division by zero, is performed.Example:int a = 10;int b = 0;try { int result = a / b;} catch (ArithmeticException e) { System.out.println("Caught ArithmeticException: " + e.getMessage());} Read More

Java – IllegalArgumentException

IllegalArgumentException: Thrown when a method receives an illegal or inappropriate argument.Example:public class Test { public static void checkAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } } public static void main(String[] args) { try... Read More

Java – FileNotFoundException

FileNotFoundException: Thrown when an attempt to open the file denoted by a specified pathname has failed.Example:import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;try { File file = new File("nonexistentFile.txt"); FileReader fr = new FileReader(file);} catch (FileNotFoundException e) { System.out.println("Caught FileNotFoundException: " + e.getMessage());} Read More

Java – ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException: Thrown when trying to access an array with an invalid index.Example:int[] arr = new int[3];try { arr[5] = 10;} catch (ArrayIndexOutOfBoundsException e) { System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());} Read More

Java – NoSuchElementException

NoSuchElementException: Thrown when one tries to access an element that isn't present.Example:import java.util.Iterator;import java.util.NoSuchElementException;Iterator iterator = new ArrayList().iterator();try { iterator.next();} catch (NoSuchElementException e) { System.out.println("Caught NoSuchElementException: " + e.getMessage());} Read More

Java – SQLException

SQLException: Thrown when there is an error in accessing a database.Example:import java.sql.*;try { Connection con = DriverManager.getConnection("jdbc:invalid:url");} catch (SQLException e) { System.out.println("Caught SQLException: " + e.getMessage());} Read More

Java – RemoteException

RemoteException: Thrown when a remote method call fails.Example:import java.rmi.RemoteException;try { throw new RemoteException("Remote exception occurred");} catch (RemoteException e) { System.out.println("Caught RemoteException: " + e.getMessage());} Read More

Java – SecurityException

SecurityException: Thrown when a security manager denies a requested permission.Example:System.setSecurityManager(new SecurityManager());try { System.getProperty("user.home");} catch (SecurityException e) { System.out.println("Caught SecurityException: " + e.getMessage());} Read More

Java – InterruptedException

InterruptedException: Thrown when a thread is interrupted while it is waiting, sleeping, or performing some other activity.Example:Thread thread = new Thread(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Caught InterruptedException: " + e.getMessage()); }});thread.start();thread.interrupt(); Read More

Java Questions

What is a NullPointerException, and how to fix it?

A NullPointerException (NPE) is a runtime exception in Java that occurs when your code tries to use a reference that is null (i.e., it doesn't point to any object) to: Call a method on it. Access or modify its fields.... Read More

Questions

How to compare strings in Java?

In Java, strings are compared using different methods depending on the type of comparison you want to perform. Here’s a detailed guide with examples: 1. Using equals() for Content Comparison The equals() method compares the actual content of two strings... Read More

Differences between Checked and Unchecked Exceptions at Runtime?

In Java, exceptions are categorized into Checked and Unchecked exceptions. While they differ primarily at compile-time, there are also runtime considerations. Here's an explanation with examples: 1. Checked Exceptions Definition: Checked exceptions are exceptions that must be declared in a... Read More

var in Java 11 bypass the protected access restriction

The behavior of var in Java, introduced in Java 10, does not bypass the protected access restriction in any special way. Instead, the misunderstanding often arises from how var is interpreted and its interactions with visibility rules in Java. Let’s... Read More

Is it true a Sorted array process faster than an unsorted array?

Processing a sorted array is often faster than an unsorted array because sorted arrays enable more efficient algorithms and optimizations. For example, operations like searching, range queries, and duplicate removal can take advantage of the order in the sorted data.... Read More

Other Topics

webdriver navigate to website

  WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com"); or use driver.navigate().to("http://www.google.com"); (not recommended ) Read More

Run tests on safari | safari driver using selenium webdriver

import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.safari.SafariDriver; public class SafariTest { private WebDriver driver = null; @Test public void myTest() throws IOException, InterruptedException { driver.get("http://www.google.com"); } // Get the platform details private static boolean isSupportedPlatform()... Read More

Wait for multiple elements presents

import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class waitForMultipleElements { WebDriver driver = new FirefoxDriver(); public boolean isElementPresent(By by) { try { driver.findElements(by); return true; } catch (org.openqa.selenium.NoSuchElementException e) { return false; } } public void... Read More

setup remote web driver to run on another machine | selenium webdriver

In A machine run your driver code, given below. import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; public class RemoteDriver { private WebDriver driver = null; @Test public void myTest() throws IOException,... Read More

working on canvas svg using selenium webdriver | xpath | highchart

For below example you have to use xpath with name space. <!DOCTYPE html> <html><body> <div id="overview-layout"> <div id="overview-body"> <div class="" id="overview-tabcontent-container"> <div data-highcharts-chart="7" class="chart" id="chart_1"> <div id="highcharts-26" class="highcharts-container"> <svg height="304" width="1154" version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect zIndex="1"></rect> <path zIndex="2"></path> <g transform="translate(73,0)" style="cursor:default;text-align:center;"... Read More

selenium select listbox options using mouse send keys

WebElement selectListBoxElement = driver.findElement("xyz"); Actions action = new Actions(driver); action.moveToElement(selectListBoxElement).click().sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).click(). build().perform(); or action.moveToElement(selectListBoxElement).click().sendKeys(Keys.ARROW_DOWN) .sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build() .perform(); just use keys.Enter to select any options to selection. Read More

How to switch between tabs using selenium webdriver

driver.get("http://www.w3schools.com/"); String firstWindow = driver.getWindowHandle(); System.out.println(firstWindow); driver.findElement(By.xpath("/html/body/div[3]/div[1]/a[1]")).click(); driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL, "t"); driver.get("http://www.tutorialspoint.com"); driver.findElement( By.xpath("/html/body/div[2]/header/div[2]/div/nav/ul/li[1]/a")) .click(); driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL, "1"); driver.switchTo().window(firstWindow); Thread.sleep(5000); driver.findElement(By.linkText("REFERENCES")).click(); Read More

org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.ie.driver system property; for more information, see http://code.google.com/p/selenium/wiki/InternetExplorerDriver. The latest version can be downloaded from http://selenium-release.storage.googleapis.com/index.html

This is due to not setting the webdriver.ie.driver correctly. Download the ie driver from selenium hq website. Parse the correct iedriver path with register node -Dwebdriver.ie.driver C:\Users\Admin\Downloads>java -jar selenium-server-standalone-2.44.0.jar -role w ebdriver -hub http://localhost:4444/grid/register -Dwebdriver.ie.driver=C:\Users \Admin\Downloads\IEDriverServer_Win32_2.44.0\IEDriverServer.exe -port 5566 And my... Read More

selenium webdriver – mouse click on an input field

  <input type="button" value="Edit" class="edit-cat" name=""> -- WebElement edit = driver.findElement(By.className("edit-cat")); Actions action = new Actions(driver); action.moveToElement(edit).click().perform(); Read More

how to set java_home on ubuntu

- open terminal and sudo su to root. - in terminal type which java and copy the java installation path - now type, gedit .bashrc - on the bottom of the file add below lines JAVA_HOME=/usr/lib/jvm/java-8-oracle (the path of java... Read More

selenium webdriver set window size using dimension

java.awt.Dimension screenSize = Toolkit.getDefaultToolkit() .getScreenSize(); Dimension dimension = new Dimension(screenSize.width, screenSize.height); driver.manage().window().setSize(dimension); and if you are getting any exception like this in linux java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. 1.... Read More

extract numbers from string – java

for example if you want to compare any phone number with actual value, 555-666-777 and want to avoid hyphens or what ever..and extract only numbers use replaceall with correct regular expressions. simply do replace the non digits with blank value.... Read More

verify a radio button is selected or not

  <form> <input type="radio" name="sex" value="male">Male<br> <input type="radio" name="sex" value="female">Female </form> assertTrue(driver.findElement(By.name("sex")).isSelected()) the line will verify whether the radio button is selected or not. If selected the test will pass otherwise it will return 0 and assert will fail.  ... Read More

org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html

This is due to missing the chrome driver path with the node. So in machine A Run hub java -jar lib/selenium-server-standalone-2.44.0.jar -role hub In machine B register node with parameter -Dwebdriver.chrome.driver so the command should be something like this. C:\Users\Admin\Downloads>java... Read More

read a value from properties file using java

Create a property file with values userName = "test" import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class GetDataFromProperties { public static void main(String[] args) throws IOException { Properties prop = new Properties(); FileInputStream fileInput = new FileInputStream( "give the property... Read More

override an alert using javascript executor selenium web driver

[code language="javascript"] <script type="text/javascript"> function setInnerText(id, value) { document.getElementById(id).innerHTML = '<p>' + value + '</p>'; } </script> <p>This tests alerts: <a href="#" id="alert" onclick="alert('cheese');">click me</a></p> public void overrideAlert() { ((JavascriptExecutor) driver).executeScript( "window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }"); driver.findElement(By.id("alert")).click();... Read More

Read PDF file using Selenium Webdriver

Download pdfbox and fontbox jars from https://pdfbox.apache.org/download.cgi To read pdf file and verify the content is present in the pdf using. import java.io.BufferedInputStream; import java.io.IOException; import java.net.URL; import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.util.PDFTextStripper; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class PdfRead... Read More

Read excel and convert to Hashmap ConcurrentHashMap using Java

public static ConcurrentHashMap<String, ConcurrentHashMap<String, String>> dataMap = new ConcurrentHashMap<>(); public static ConcurrentHashMap<String, String> cellValues = null; public static void main(String[] args) { getData(); for (String key : dataMap.keySet()) { System.out.println(dataMap.get(key)); } } private static Object getCellValue(Cell cell) { switch (cell.getCellType())... Read More

How to do a RegEx match open tags except XHTML self-contained tags

To match open HTML tags but exclude self-closing XHTML tags using Regular Expressions (RegEx), you can use the following pattern: RegEx Pattern <([a-zA-Z][a-zA-Z0-9]*)(?![^>]*\/>)> Explanation of the Pattern <: Matches the opening < of an HTML tag. ([a-zA-Z][a-zA-Z0-9]*): Captures the tag... Read More