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 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 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
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
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
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
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 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 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 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 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
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 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
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
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 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
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
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
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
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 9 introduced the Module System, allowing developers to modularize applications and improve performance.Example:module mymodule { exports com.example.myapp;} Read More
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
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 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
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 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com"); or use driver.navigate().to("http://www.google.com"); (not recommended ) Read More
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
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
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
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
Verify the type of that password field that's the only way to identify in html. :) driver.findElement(By.id("xyz")).getAttribute("type").equals("password"); Read More
driver.findElement(By.id("id")).sendKeys("\u2019t"); find more unicode http://www.ssec.wisc.edu/~tomw/java/unicode.html http://unicode-table.com/en/#00A9 Read More
- 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
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
simply add Actions action = new Actions(driver); action.sendKeys(Keys.F12).build().perform(); it will invoke the firebug, or the default firefox insepector. Read More
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
<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
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
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
1. Verify you have given permission to the user who runs the selenium test from bash having prvilage to invoke Firefox. 2. Verify the given port is free. 3. Stop jenkins server 4. Run jenkins from war folder as root/administrator... Read More
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
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
In Java, pattern matching with switch statements or expressions can fail with a compiler error like: 'does not cover all possible input values' This happens because the compiler requires exhaustive coverage of all possible cases for a given type. For... Read More