Showing posts with label Java Tutorials for Beginners. Show all posts
Showing posts with label Java Tutorials for Beginners. Show all posts

Handle Bootstrap Dropdown in Selenium

What is Bootstrap?
Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Refer below links to know more about bootstrap.
https://www.w3schools.com/bootstrap/default.asp
https://getbootstrap.com/docs/4.0/components/dropdowns/

Bootstrap dropdown
Bootstrap dropdown is not like traditional dropdowns as it doesn't use <select> tags, rather it uses <ul> and <li> tags to make a dropdown.

Bootstrap Dropdown UI

Inspecting Bootstrap Dropdown
So to handle bootstrap dropdown, you need to use findElements() method which will return all the options of the dropdown.
Following code shows how to handle a bootstrap dropdown in Selenium WebDriver:

public class BootstrapDropDown {



     public static void main(String[] args) throws InterruptedException {

         

          WebDriver driver;

          System.setProperty("webdriver.chrome.driver","C:\\Users\\Hitendra\\Downloads\\chromedriver_win32 (1)\\chromedriver.exe");

          driver = new ChromeDriver();

          driver.manage().window().maximize();

          driver.get("https://www.automationtestinginsider.com/2019/12/bootstrap-dropdown-example_12.html");

          Thread.sleep(2000);

         

          driver.findElement(By.xpath("//button[@id='bootstrapmenu']")).click();

         

          List <WebElement> options=driver.findElements(By.xpath("//ul[@class='dropdown-menu']//li/a"));

         

          for(WebElement ele:options) {

             

              String value=ele.getText();

              System.out.println(value);

             

              if(value.equalsIgnoreCase("contact us")) {

                   ele.click();

                   break;

              }

          }

         

          Thread.sleep(2000);

          driver.close();

     }

}




Please watch below youtube video for detail explanation:



Exception Handling in Java

What is an Exception?

--An exception is a problem that arises during the execution of a program
--Its an event that disrupts the normal flow of the program

How exception occurs?

Following are some scenarios where an exception occurs.

1. A user has entered an invalid data.

2. A file that needs to be opened cannot be found.

3. A network connection has been lost in the middle of communications or the JVM has run out of memory.


Exception Classes
Exception Class Hierarchy


Types of java exceptions:

1. Checked Exception -  Checked exceptions are checked at compile-time so this is also called compile time exceptions. Example of checked exceptions are : ClassNotFoundException, IOException, SQLException and so on.They occur usually interacting with outside resources/network resources e.g. database problems, network connection errors, missing files etc.

2. UnChecked Exception - Unchecked exceptions are not checked at compile-time, but they are checked at runtime. Also Called Run time Exceptions. Example of unchecked exceptions are : ArithmeticException, ArrayStoreException, ClassCastException and so on.

3. Error - Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

How to handle exception?

Java exception handling is managed via five keywords:

try: this keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.

catch:  this block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

finally: this block is used to execute the important code of the program. It is executed whether an exception is handled or not.

throw: this keyword is used to throw an exception.

throws: this keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

try catch syntax:

try{
//code that may throw an exception 
}catch(ExceptionClassName ref){
}


try finally block

try{
//code that may throw an exception 
}finally{
}

To get more details please watch below youtube video and Subscribe the channel.

https://www.youtube.com/watch?v=P-KR6Eq4CM0&feature=youtu.be

Part1:


Part2:


super Keyword in Java

Three Important Usage of super keyword:

Use of super with variables: We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.

Use of super with methods: It should be used if subclass contains the same method as parent class.

Use of super with constructors: super is used to invoke parent class constructor.

To get more details please watch below youtube video and Subscribe the channel.


Map Interface in Java

Properties: A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.

A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.


HashMap Class

Properties: 
Java HashMap class contains values based on the key.
Java HashMap class contains only unique keys.
Java HashMap class may have one null key and multiple null values.
Java HashMap class is non synchronized.
Java HashMap class maintains no order.

Methods: void clear(), Object clone(), boolean containsKey(Object key), boolean containsValue(Object Value) , Object get(Object key), boolean isEmpty(), Set keySet(), Object put(Key k, Value v), int size(), Collection values(), Value remove(Object key)


LinkedHashMap Class

Properties: 
Java LinkedHashMap contains values based on the key.
Java LinkedHashMap contains unique elements.
Java LinkedHashMap may have one null key and multiple null values.
Java LinkedHashMap is non synchronized.
Java LinkedHashMap maintains insertion order.

Methods: void clear(), void size(), void isEmpty(), boolean containsKey(Object key), boolean containsValue(Object key), Object get(Object key)


TreeMap Class

Properties: 
Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
Java TreeMap contains only unique elements.
Java TreeMap cannot have a null key but can have multiple null values.
Java TreeMap is non synchronized.
Java TreeMap maintains ascending order.

Methods: void clear(), void size(), void isEmpty(), boolean containsKey(Object key), boolean containsValue(Object key), Object get(Object key), Object firstKey(), Object lastKey()


HashTable Class:

Properties: Hashtable internally contains buckets in which it stores the key/value pairs. The Hashtable uses the key’s hashcode to determine to which bucket the key/value pair should map.
A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
Java Hashtable class contains unique elements.
Java Hashtable class doesn't allow null key or value.
Java Hashtable class is synchronized.

Methods: void clear(), void size(), void isEmpty(), boolean containsKey(Object key), boolean containsValue(Object key), Object get(Object key)

To get more details please watch below youtube video and Subscribe the channel.




Java Data Types Questions and Answers

1. What are the primitive data types in Java ?
Answer: There are eight primitive data types.
byte.
short.
int.
long.
float.
double.
boolean.
char.

2. Is Java primitive data type stored on stack or heap?
Answer: Primitive types declared locally will be on the stack while primitive types that are defined as part of an object instance are stored on the heap. Local variables are stored on stack while instance and static variables are stored on the heap.

3. What is the output?
Answer: 
System.out.println(1.0/0);
There will be no exception instead it prints Infinity.
1.0 is a double literal and double datatype supports infinity.

4. What are the Wrapper classes available for primitive types ?
Answer:  following are the wrapper classes available:
boolean  - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void

5. What are wrapper classes ?
Answer:  They are wrappers to primitive data types. They allow us to access primitives as objects.

6. What is casting?
Answer:  There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Queue and Set Interface

Queue Interface:

Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed first and last element is removed at last.

How to create the objects?

Queue<String> q1 = new PriorityQueue();
Queue<String> q2 = new ArrayDeque();

PriorityQueue Class

Properties: It holds the elements or objects which are to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.

Methods: boolean add(object), boolean offer(object), boolean remove(object), Object poll(), Object element() , Object peek(), void clear(), int size()

Deque Interface:

Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the side. Deque stands for a double-ended queue which enables us to perform the operations at both the 

Deque d = new ArrayDeque();


ArrayDeque Class

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Set Interface

Properties: Set Interface in Java is present in java.util package. It extends the Collection interface.It represents the unordered set of elements which doesn't allow us to store the duplicate items. 

We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Set<data-type> s1 = new HashSet<data-type>();  
Set<data-type> s2 = new LinkedHashSet<data-type>();  
Set<data-type> s3 = new TreeSet<data-type>(); 

HashSet Class

Properties: This class implements the Set interface.
--HashSet doesn’t maintain any order,
--HashSet doesn’t allow duplicates
--HashSet allows null values however if you insert more than one nulls it would still return only one null value.
--HashSet is non-synchronized.
--Hashing is used to store the elements in the HashSet

HashSet<String> hset = new HashSet<String>();

Methods: boolean add(E e) , void clear(), Object clone(), boolean contains(Object o), boolean isEmpty(), int size().

LinkedHashSet Class

Properties: This class implements the Set interface.
--LinkedHashSet maintains insertion order,
--LinkedHashSet doesn’t allow duplicates
--LinkedHashSet allows null values however if you insert more than one nulls it would still return only one null value.
--LinkedHashSet is non-synchronized.
LinkedHashSet<String> set=new LinkedHashSet<String>(); 

Methods: boolean add(E e) , void clear(), Object clone(), boolean contains(Object o), boolean isEmpty(), int size(), boolean remove(Object o), removeAll().


TreeSet Class

Properties: This class implements the SortedSet interface.
--The access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
--TreeSet doesn’t allow duplicates
--TreeSet doesn’t allows null values 
--TreeSet is non-synchronized.

TreeSet<String> tset = new TreeSet<String>();

Methods: boolean add(E e) , void clear(), Object clone(), boolean contains(Object o), boolean isEmpty(), int size(), boolean remove(Object o), Object first(), Object last(). 

To get more details please watch below youtube video and Subscribe the channel.




Constructors in Java

Constructor Definition:

1. It is called constructor because it constructs the value at the time of object creation.
2. Block of code similar to method.
3. It is called when an object of class is created.
4. At the time of calling constructor, memory for the object is allocated in the memory.
5. It is used to initialize the object.
6. Java compiler created the default constructor if your class doesn't have any constructor.

Rules to Create Constructor:

1. Constructor name must be the same as its class name
2. Must have no return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Constructor:

1. Default or no arguments – Provides default values
2. Parameterized constructor

Constrtuctore Overloading:

having more than one constructor with different parameter lists.

Constructor Vs Method:

Java Constructor Vs Java method

Java Constructor Vs Java method 


To get more details please watch below youtube video and Subscribe the channel.


Encapsulation in Java

1. Encapsulation in Java is a mechanism of wrapping the data (variables) and methods together as a single unit.
2. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

How to Achieve?

1. Declare the variables of a class as private.
2. Provide public setter and getter methods to modify and view the variables values.


Benefits:

1. The fields of a class can be made read-only (class which has only getter method) or write-only (class which has only setter method) .
2. A class can have total control over what is stored in its fields.

To get more details please watch below youtube video and Subscribe the channel.


Abstraction and Interface in Java

Abstraction:

--Abstraction is a process of hiding the implementation details and showing only functionality to the user.
--In Abstraction only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual.
--There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract Class:

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented.
An abstract class must be declared with an abstract keyword.
Abstract Class can have abstract and non-abstract methods.
Abstract class cannot be instantiated.
Abstract class can have constructors final and static methods also.
Abstract class can have final methods
If there is an abstract method in a class, that class must be abstract.

Interface:

--An interface in java is a blueprint of a class. It has static constants and abstract methods.
--There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
--It cannot be instantiated just like the abstract class.
--In interface we can have default and static methods.
--In interface we can have private methods.

Class and Interface Relationships:

Class and Interface in Java

Class and Interface Relationships

Why we use Interface?

--It is used to achieve abstraction.
--By interface, we can support the functionality of multiple inheritance.

Multiple inheritance in Java by interface:

--If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.
--Multiple inheritance is not supported through class in java, but it is possible by an interface,

Multiple Inheritance in Java


Abstract Class Vs Interface

Difference between Abstract Class and Interface
Difference between Abstract Class and Interface


To get more details please watch below youtube video and Subscribe the channel.



Polymorphism in Java

What is Polymorphism?

--Polymorphism in Java is a concept by which we can perform a single action in different ways.
--Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
--There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism.
--Polymorphism can be achieved by method overloading and method overriding

Method Overloading:

--Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different.
--Signature should be different:

      1. Number of parameters.
      2. Data type of parameters.
      3. Sequence of Data type of parameters.

Method Overriding:

--Declaring a method in sub class which is already present in parent class is known as method overriding.
--Advantage: The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code.

Types of Polymorphism:

1. Static Polymorphism (Static Binding - Early binding) is also known as compile time binding or compile time polymorphism-- Method Overloading in an example -- when type of object is determined at compiled time it is known as Static binding.
2. Dynamic Polymorphism (Dynamic Binding -late binding) is also known as runtime time binding or run time polymorphism -- example method overriding-- When type of object is determined at run time, it is known as dynamic binding.

To get more details please watch below youtube video and Subscribe the channel.




Inheritance in Java

What is Inheritance?

Defnition 1: Inheritance in Java is a mechanism in which one object acquires all the properties and behaviours of a parent object
Defnition 2: The process by which one class acquires the properties(data members) and functionalities(methods) of another class is called inheritance.
Defnition 3: Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.

Why we use Inheritance?

--For Code Re-usability- The biggest advantage of Inheritance is that the code that is already present in base class need not be rewritten in the child class.
--Avoid duplication in code.
--For method overriding

Different terms associated with Inheritance:

Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
There are two ways we can do code reuse either by the implementation of inheritance (IS-A relationship), or object composition (HAS-A relationship)

Syntax:
class Subclass-name extends Superclass-name
     {
          //data members and methods
      }

Types of Inheritance

inheritance in java
Types of Inheritance in Java

Multiple and Hybrid Inheritance
Multiple Inheritance and Hybrid Inheritance in Java

Various Scenarios to create Parent/Child objects:

1. Sub(Child) Class reference and Sub(Child) Object- Allow you to access all the methods and data members of super class and sub class.
2. Super(Parent) Class reference and Sub(Child) Class Object- Allow you to access all the methods and data members of Super class only.
3. Super(Parent) Class reference and Super(Parent) Class Object - Allow you to access all methods and data members of super class only.
4. Sub(Child) Class reference and Super(Parent) Class object- child cannot hold parent object

Usage of inheritance in selenium:

1. We create a Base Class in the Framework to initialize WebDriver interface, WebDriver waits, Property files, Excels, etc., in the Base Class.

2. We extend the Base Class in other classes such as Tests and Utility Class.

To get more details please watch below youtube video and Subscribe the channel.



Why String is Immutable in Java?

In java, string objects are immutable. Immutable simply means unmodified or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.

To get more details please watch below youtube video and Subscribe the channel.


String Class and Built in Methods in Java

String:

In Java, string represents sequence of char values. An array of characters works same as Java string. For example:

char[] h={'H','E','L','L','O'};
String s=new String(h);

String s=“HELLO";

Java String class provides a lot of methods to perform operations on string

How to create string object?

The java.lang.String class is used to create a string object.
There are two ways to create String object:

By string literal - Java String literal is created by using double quotes. For Example:
String s1=“Selenium";

By new keyword - String s=new String(“Selenium");

Built in Methods:

Java has a librabry of classes and methods organised in packages
Import java.io.console
Import java.io.*

In order to use built in methods we need to import packages or classes
Java.lang package is automatically imported in every java Built in methods categories
String methods
Array methods
Number methods
Character methods

Different String methods:

compareTo - The Java String compareTo() method is used for comparing two strings lexicographically.

boolean equals() - The java string equals() method compares the two given strings based on the content of the string (case sensitive)
String concat() – concat two strings
boolean equalsIgnoreCase() - The java string equals() method compares the two given strings based on the content of the string (not casesensitive)
char charAt() – index position - The java string charAt() method returns a char value at the given index number.
boolean contains()
toUpperCase() – convert to upper case
toLowerCase() – convert to lower case
trim() – remove spaces from both sides of string
substring() --  returns part of string
boolean endsWith()
boolean startWith() – ends with specified suffix or not
int length()
replace()

Java Convert String to int:

Convert String to int using Integer.parseInt(String)
      String str = “54321";
      int num = Integer.parseInt(str);
Convert String to int using Integer.valueOf(String)
      String str=“123";
      int num = Integer.valueOf(str);

Java int to String Conversion:

Convert int to String using String.valueOf() 
 
        String int ivar = 123;
String str = String.valueOf(ivar);
System.out.println("String is: "+str);
System.out.println(555+str);
Convert int to String using Integer.toString()
      int ivar = 123;
      String str = Integer.toString(ivar);
      System.out.println("String is: "+str);
      System.out.println(555+str);

To get more details please watch below youtube video and Subscribe the channel.



Methods in Java

What is a method?

A java method is a set of statements or steps that are grouped together to perform an operation
Method are also known as functions
When we use methods? – whenever we want to perform an operation multiple times
Advantage of methods – code reusability
Types of methods -  built in (predefined) and user defined

1. Built in Methods:

Java has a librabry of classes and methods organised in packages
Import java.io.Console
Import java.io.*

In order to use built in methods we need to import packages or classes
Java.lang package is automatically imported in every java Built in methods categories
String methods
Array methods
Number methods
Character methods

2. User Defined Methods:

Different Method types:
Method without returning any values
Method with returning values
Method using passing parameters

Different ways to call Methods:
Using Objects
Without Using object
Call external methods (from external class)

To get more details please watch below youtube video and Subscribe the channel.

Part1:


Part2:



Class and Object in Java

What is OOP?

Object oriented programming – As the name suggests uses objects in programming. Object oriented programming aims to implement real world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operates on them so that no other part of code can access this data except that function.

Oops Concept

Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts −

Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Methods

1. What is an Object:

In object oriented programming Whenever you do something you need an object.
Print, calculate, execute, process, save and to return
Object don't do things individually
Basically object has couple of information
What object knows  variables  -- to store values
What object does   methods (execute and process)
Object are crated using class. Objects and classes are interrelated to each other.

If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behaviour.

If we consider a dog, then its state is - name, breed, color, and the behaviour is - barking, wagging the tail, running.

2. What is a Class?

A class is a blueprint or design from which individual objects are created.

public class Dog {
   String breed;
   int age;
   String color;

   void barking() {
   }

   void hungry() {
   }

   void sleeping() {
   }
}

How to Create an Object?

In Java, an object is created from a class.

Syntax -  <ClassName> Reference = new <ClassName()>;

When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behaviour of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.

To get more details please watch below youtube video and Subscribe the channel.




Modifiers in Java

Modifiers are key words in java that is used to restrict or add access level for classes, attributes, methods and constructors.

Access Modifiers - default, Private, Protected, Public
Non Access modifiers
      For Classes – final, abstract
      For Methods or attributes – final, static, abstract, transient, synchronized, volatile

Access Modifiers Visibility
Access Modifiers Visibility

1. Default:

When no access modifier is specified for a class , method or data member – It is said to be having the default access modifier by default.

The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package.

Scope – within same package

2. Private

The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in which they are declared.
Any other class of same package will not be able to access these members.


Scope – within same class

3. Protected

The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within same package or sub classes in different package.

Scope – within same package and other package using inheritance

4. Public

The members, methods and classes that are declared public can be accessed from anywhere. This modifier doesn’t put any restriction on the access.

Scope – accessible from anywhere inside or outside of the package.

To get more details please watch below youtube video and Subscribe the channel.