Wrapper Class In Java
before this , there is a question Question :- Java is 100% Object Oriented Programing Language or not? Answer :- Java is 99.9 % object Oriented Programming Language
It is not 100% Object Oriented Programing language , due to its primitive data Types :-
int, float , char, double etc..
These are derived from C and these are not objects
and 100% object oriented means that every thing should be in form of object.
and primitive data types are not object for example :-
int data;
here data is not an object, it's a variable.
So in java , we have classes for every data types, we call the as wrapper classes,
Table for primitive data type and wrapper classes
Primitive Type
Wrapper Class
boolean
BOOLEAN
char
Character
byte
>
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
for example for int, we have class Integer
primitive int variable
int x = 20;
not if i want to convert this varibale into an object, then i have to write
Integer i = new Interger(x); OR Integer i = new Interger(20);
now i is 20;
This way of converting primitive into object is called as AutoBoxing
Now, how to take out value from Integer Object
Interger i = new Integer(20);
direct value can't be assigned to object so we need to use a method datatypeValue
int j = i.intValue();
now j = 10;
So getting the priitive value from object is called as Unboxing
public class Wrappractice
{
public static void main(String args[])
{
int i = 20;
Interger mydata = new Integer(i); //Autoboxing
System.out.println("value of i is " + i);
int j;
j = mydata.intValue();
System.out.println( "value od j is " +j); //Unboxing
}
}
--------------------------------------------------------
Wrapper class are Immutable in Java
All primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.
Example to prove that wrapper classes are Immutable
public class Wrap
{
public static void main(String[] args)
{
Integer x = new Integer(20);
System.out.println("before modification value of x is :" +x);
add(x);
System.out.println("After modification value of x is :" +x);
}
public static void add(int x)
{
x = x+1;
System.out.println(x);
}
}
Output :-
before modification value of x is :20
21
After modification value of x is :20
Listeners are interfaces used in selenium webdriver script that modifies the default behaviour of the system.
The main purpose of listeners is to create Logs and reports.
We can fully customize the logs using Listeners.
Types of Listeners 1). WebDriver Listeners 2). TestNG Listeners
Types of Listeners in TestNG :-
There are several interfaces that allow you to modify TestNG behaviour.
Here are few listeners :- 1).IAnnotation Transformer 2).IAnnotation ransformer2 3). IHookable 4). IInvokeMethodListener 5). IMethodInterceptor 6). Ireporter 7). ISuiteListener 8). ITestListener
How to implement the Listener :- a). Extends 'TestListenerAdapter' Class b). Implement Interface 'ITestListener' also we implement Listeners in Class Level as well as Suite Level
TestNG Listeners
TestNG provides the @Listeners annotation whic listens to every event that occurs in your selenium script.
As the name suggests Listeners "listen" to the event defined in the selenium script and behave accordingly. It is used in selenium by implementing Listeners Interface.
Listener is an interface that modifies the TestNG behaviour. Types of Listeners in TestNG
There are many types of listeners which allows you to change the TestNG's behavior.
Below are the few TestNG listeners:
1.IAnnotationTransformer , 2.IAnnotationTransformer2 , 3.IConfigurable , 4.IConfigurationListener , 5.IExecutionListener, 6.IHookable , 7.IInvokedMethodListener , 8.IInvokedMethodListener2 , 9.IMethodInterceptor , 10.IReporter, 11.ISuiteListener, 12.ITestListener .
Listeners are implemented by the ITestListener interface.
An ITestListener interface has the following methods: onTestStart(): An onTestStart() is invoked only when any test method gets started.
onTestSuccess(): An onTestSuccess() method is executed on the success of a test method.
onTestFailure(): An onTestFailure() method is invoked when test method fails.
onTestSkipped(): An onTestSkipped() run only when any test method has been skipped.
onTestFailedButWithinSuccessPercentage(): This method is invoked each time when the test method fails but within success percentage.
onStart(): An onStart() method is executed on the start of any test method.
onFinish(): An onFinish() is invoked when any test case finishes its execution.
In 2004, Jason Huggins, an engineer at Throghtworks(Chicago) was working on a web Application that required frequent testing.
Manual testing was becoming hard as it was time-consuming and inefficient.
He wrote a Javascript program that could interact with the browser and do actions.
He called it "Javascript Test Runner"
He started giving demos about this tool and soon there were discussions to make it open source as a re-usable testing framework.
but some how , there was Same Original Policy Issue What is Same Origin Policy Issue ?
The same origin policy is an important concept in the web application information security domain.
In this Policy, a web browser allows scripts contained in a first web page "A" to access data/resources in a second web Page "B",
however, only if both web pages have the same origin.
To come out from this problem Paul Hammant started to work on it
After Jason Huggins started giving demo of JavaScriptTestRunner, Paul Hammant another Throughtworks engineer started working to overcome the
Same Origin Policy Issue.
He(and his team) added a server that will act as http proxy to trick the browser to believe that selenium core and web application
being tested , come from the same domain.
This came to be known as : Selenium Remote Control(RC)
In 2004 selenium become open source.
In 2006 the enhanced Selenium RC completely took over Selenium Core and released as Selenium 1.
In 2006, Shinya Kasatani(Japan) Created a Firefox extension that can enable record and replay of browser actions.
He named it Selenium IDE.
He donated it to the selenium project in 2006.
In 2006, Simon Stewart, another Thoughtworks engineer started working on a project to create another testing tool
to overcome some limitation of selenium 1.
He called it WebDriver.
At the same time Jason Huggins left Thoughtworks to join google where he continued his work on Selenium 1.
in 2011 the 2 tools merged to form Selenium 2.0 and was released on July, 2011.
In 2007, Philippe Hanrigou, then at ThoughtWorks made a server tool to enable parallel execution of selenium tests across multiple machines.
This was named as Selenium Grid.
Selenium Grid extends Selenium RC and enables running tests on multiple servers in parallel, saving running tests on multiple servers in parallel,
saving time and cost.
Selenium Grid was released at end of 2007.
WebDriver's doubt in 2007 fuelled a desire for features that were not available in Selenium 1 that time
In 2011 the 2 projects were merged and Selenium 2.0 was born and released in July 2011.
All Seleniu RC(Core) implementation is replaced with webdriver compatible components.
Last stable release of Selenium 2 was 2.53.1
Selenium RC no longer available for download from SeleniumHQ site.
What is Selenium ?
Features of Selenium
4 Components of Selenium
Browsers |OS | Languages What is selenium
Selenium is a set of tools and libraries that automates web browser actions.
In other words "Selenium provides tools that can interact with browser and can
automate browser actions like click, input, select, navigate etc. with the help
of scripts.
Actually , we use to do three things in selenium :-
1). Iidentify Web Elements (Using identifiers like id, xpath etc.)
2). Add Actions (Using own preferred programming language) with Test data.
3). Run and validate Data.
Note :-
1). Selenium is not a tool but a library of tools.
2). Selenium is free and open Source.
Features of Selenium
Flexible and Extensible
Multiple Programming Languages Supported
Multiple Browsers Supported
Four Components of Selenium
1). Selenium IDE
Selenium IDE is a Firefox add-on & a Record and playback plugin, Useful for quick prototype testing
2). Selenium RC (Remove Control)
Also known as Selenium 1, used to execute scripts(written in any language) usiing java script.
Now Selenium 1 is deprecated and is not actively supported.
3). WebDriver
An API used to send commands directly to the browser. It is a successor to Selenium RC.
Selenium RC and WebDriver are merged to form Selenium 2.
4). Selenium Grid
for parallel and distributed execution
A tool to run tests in parallel across different machines and different browsers simultaneously.
Used to minimize execution time.
Selenium was created by Jason Huggins
Selenium IDE created by Shinya Kasatani
Selenium RC created by Paul Hammant
Selenium WebDriver created by Simon Stewart
Selenium Grid created by Patrick Lightbody
Browsers Supported by the Selenium
Firefox
Chrome
Internet Explorer
Safari
Opera
Operating System Supported by the Selenium
Windows
Mac OS
Linux
Solaries
Programming Languages Supported by the Selenium
Java
Perl
Php
C#
Python
Ruby
Introduction of Selenium & Architecture
What is selenium :-
Selenium is an open source tool which is used to automating the tests carried out on web browsers.
In other words Selenium is an open source tool to automate the browser only.
Always remember only testing of web application is possible with selenium.
Also we can neither test any desktop application(Software) nor test any mobile application using selenium.
But there are many tools for testing software and mobile applications like IBM's RFT, HP'QTP, Appium etc.
Since Selenium is an open-source, there is no liecensing cost involved, which is a major advantage over other testing tools.
Selenium is now a day's getting popularity due to following reasons :- 1). Test scripts can be written in any of there programming languages :- Java,Phython,C#,PHP,RUBY,Perl,.Net,etc. 2). Tests can be carried out in any of these OS: Windows, Mac, or Linux 3). Tests can be carried out using any browser like HtmlUnit, Mozilla firefox, Internet Explorer, Google chrome, Safari or Opera. 4). It can be integrated with tools such as TestNG & JUNIT for managing test cases and generating reports. 5). It can be integrated with Maven, Jenkins & Docker to achieve Continuous Integration Testing.
Limitation of selenium :-1). There is no support available for selenium. We need to leverage on the available customer communities. 2). We can use selenium only to test web applications. We can not test desktop applications or any other software. 3). There is no native reporting facility but we can overcome that issue by integrating iy with frameworks like TestNG&JUnit 4). It is not possible to perform testing on images. we need to integrate selenium with sikuli for image based testing. Architecture of selenium
This wire protocol defines a REStFUL (REpresentational State Transfer) web services using JSON over HTTP.
JSON :- Java Script Object Notation
Http :- HyperText Transfer Protocol
What a tester needs to do in selenium 1).Identify web Elements, using identifiers like id, xpath etc. 2).Add Actions, usiing your preferred programming language along with the test data. 3).and finally run the test.
Selenium Hierarchy
Explanation :-
SearchContext is the super most interface in selenium, which is extended by another interface called WebDriver.
All the abstract methods of SearchContext and WebDriver interfaces are implemented in RemoteWebDriver class.
All the browser related classes such as FirefoxDriver, ChromeDriver etc., extends the RemoteWebdriver class.
JDBC Introducton JDBC stands for Java Database connectivity
The Java JDBC API enables Java applications to connect to relational database via standard API, so your Java applications become
independent of the database the application uses.
Java application using JDBC to connect to a database.
JDBC standardizes how to connect to a database, how to execute queries against it, how to navigate the result of such a query, and
how to execute updates in the database. JDBC does not standardize the SQL sent to the database. This may still vary from database
to database.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage. 1). Making a connection to a database. 2). Creating SQL or MySQL statements. 3). Executing SQL or MySQL queries in the database. 4). Viewing & modifying the resulting records.
JDBC Overview 1). Core JDBC Components. 2). Common JDBC use cases. 3). A JDBC Component Interaction Diagram.
The JDBC API consists of the following core parts :- 1). JDBC Drivers 2). Connections 3). Statements 4). Result Sets
There are four basic JDBC use cases around which most JDBC work evolves :- 1). Query the database(read data from it).
One of the most common use cases is to read data from a database. Reading data from a database is called querying the database. 2). Query the database meta data.
Another common use case is to query the database meta data. The database meta data contains information about the database itself. For instance, information
about the tables defines, the column in each table, the data type etc. 3). Update the database.
Another very commong JDBC use case is to update the database. Updating the database means writing data to it. In other words, adding new records or
modifying(updating) exiting records. 4). Perform transactions.
Transaction is another common use case. An transaction groups multiple updates and possible queries into a single action. Either all of the
actions are executed, or none of them are.
Core JDBC Components JDBC Driver
A JDBC driver is a collection of Java classes that enables you to connect to a certain database. For instance, MySQL will have its own
JDBC driver. A JDBC driver implements a lot of JDBC interfaces. When your code uses a given JDBC driver, it actually just uses the
standard JDBC interfaces. The concrete JDBC driver used in hidden behind the JDBC interfaces. Thus you can plugin a new JDBC driver
without your code noticing it.
Of course, the JDBC drivers may vary a little in the features they support.
Connection
Once a JDBC driver is loaded and initialized, you need to connect to the database. You do so by obtaining a connection to the database
via the JDBC API and the loaded driver. All Communication with the database happens via a connection.
An Application can have more than one connection open to a database at a time. This is actually very common when you have web application.
Statement
A statement is what you use to execte queries and updates against the database. There are a few different types of statements you can
use in JDBC. ResultSet
When you perform a query against the database you get back a ResultSet. You can then traverse this ResultSet to read the result of the query. What is JDBC Driver in JAVA ?
A driver is nothing but software required to connect to a database from java program. JDBC is just an API, which java has designed and to
implementation of these APIs lies on different vendor because different database works in a different way, they internally use different protocols.
So mySQL gives its own implementation of JDBC, we call it MySQL JDBC driver and we use it when we want to cennect to MySQL database from Java Program.
Similarly Oracle, SQL Server, Sybase and postgreSQL have provided their own implementation of JDBC API to connect them.
Since Java Program uses JDBC API, they are portable across different database, all you need to do is change the JDBC driver, which is just a JAR file
if you are using type 4 JDBC driver.
Type of JDBC Driver :- There are four types of JDBC drivers :-
1). JDBC-ODBC Bride Driver 2). JDBC-Native Driver 3). JDBC-Net pure Java or Network Protocol driver 4). All Java driver or Thin driver
Why many types of JDBC Drivers
The different types of JDBC driver comes from the fact how they work, which is basically driven by two factors, portability and performance.
Type 1 JDBC driver is the poorest in terms of portability and performance while type 4 JDBC drivers are highly portable and gives the best performance.
Since the database is very important and almost all java application uses the database is some form or other, it's important to learn JDBC well.
What is type 1 driver in JDBC?
This is the oldest JDBC driver, mostly used to connect databaase like MS Access from Microsoft Windows operation System. Type 1 JDBC driver actually
translate JDBC calls into ODBC(Object Database connectivity) calls, which in turn connects to the database. Since it acts as bridge between JDBC and ODBC, it is
also know as JDBC ODBC bridge driver.
This driver had very poor performance because of several layers of translation which took place before your program connects to database.
It has also less portable because it relies on ODBC driver to connect to database which is platform dependent, It is now obsolete and ubly used for developmenet
and testing, Java 8 even removed this driver from JDK.
What is type 2 driver in JDBC?
This was the second JDBC driver introduced by Java after Type 1, hence it known as type 2. In this driver, performance was improved by reducing
communication layer.
Instead of talking of ODBC driver, JDBC driver directly talks to DB client using native API. That's why it's also known as native API or partly Java driver.
Since it required native API to connect to DB client it is also less portable and platform dependent. Performance of type 2 driver is slightly better than
type 1 JDBC driver. What is type 3 driver in JDBC?
This was the third JDBC driver introduced by Java, hence known as type 3. It was very different than type 1 and type 2 JDBC driver in sense that it was
completely written in JAVA as opposed to previous two drivers which were not written in Java. That's why this is also knwon as all Java drivers.
This driver uses 3 tier approach i.e. client, server and database. So you have a Java Client talking to a java server and Java Server talking to database.
Java client and server talk to each other usiing net protocol hence this type of JDBC driver is also known as Net protocol JDBC driver.
This driver never gained popularity because database vender was reluctant to rewrite their existing natve library which was mainly in C and C++.
What is type 4 driver in JDBC?
This is the driver you are most likely using to connect to modern database like Oracle, SQL Server, MySQL, SQLLite and postgreSQl etc. This driver is
implemented in Java and directly talks to database using its native protocol. This driver includes all database call in one JAR file, which makes it very easy
easy to use. All you need to do to connect a database from java program is to include JAR file of relevant JDBC driver, because of light weight this is
also known as Thin JDBC driver. Since this driver is also written in pure Java, It's portable across all platforms, which means you can use same JAR
file to connect to MySQL even if your Java program is running on Windows, Linux or Solaris.
Performance of this type of JDBC driver is also best among all of them because database vendor liked this type and all enhancement they make thay also
port for type 4 drivers.
1). Multitasking refers to a computer's ability to perform multiple jobs concurrently.
For Example :- more than one program are running concurrently.
2).A Thread is a single sequence of execution within a program. MultiThreading in java is a process of executing multiple threads simultaneously.
Multithreading refers to multiple threads of control with in a single program.
Each program can run multiple threads of control within it.
A Thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading both are used to acheive
multitasking.
Threads use a shared memory area but processes are not.
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.
Java Multithreading is mostly used in games, animation etc.
For Example : Web browser is a program and its tabs are single thread.
Process :- An execution instance of a program is called a process. A thread is a subset of the process.
Advantage of Thread
1). To maintain responsiveness of an application during a long running task. 2).To enable cancellation of separable tasks. 3).Some problems are intrinsically parallel. 4).To monitor status of some resource (DB) 5). Some APIs and Systems demand it : Swing.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time. 2) You can perform many operations together, so it saves time. 3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Application Thread
When we execute an application :-
The JVM creates a Thread object whose task is defined by the main() method.
It Starts the thread.
The thread executes the statements of the program one by one until the method returns and the thread dies.
Multiple Threads in an Application
Each thread has its private run-time stack
if two threads execute the same method, each will have its own copy of the local variables the methods uses.
However, all the threads see the same dynamic memory(heap)
Two different threads can act on the same object and same static fields concurrently.
Creating Thread
There are two ways to create our own Thread Object 1). By Extending Thread class OR Subclassing the Thread class and instantiating a new object of that class. 2). Implementing the Runnable interface.
In both the case the run() method should be implemented.
Life Cycle of a Thread
New Thread :- When a new thread is created, it is in new state. The thread has not yet started to run when thread is in this state. Runnable State :- A thread that is ready to run is moved to runnable state. In this state, a thread might actually be running or int might be ready
run at any instant of time. It is the responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread. Blocked/Waiting state: When a thread is temporarily inactive, then it’s in one of the following states:
Blocked
Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked state. It’s the responsibility of the thread scheduler to reactivate and schedule a blocked/waiting thread. A thread in this state cannot continue its execution any further until it is moved to runnable state. Any thread in these states do not consume any CPU cycle.
A thread is in the blocked state when it tries to access a protected section of code that is currently locked by some other thread. When the protected section is unlocked, the schedule picks one of the thread which is blocked for that section and moves it to the runnable state.
Time waitingA thread lies in timed waiting state when it calls a method with a time out parameter. A thread lies in this state until the timeout is completed or until a notification is received. Terminated State: A thread terminates because of either of the following reasons:
Because it exists normally. This happens when the code of thread has entirely executed by the program.
Because there occurred some unusual erroneous event, like segmentation fault or an unhandled exception.
A thread that lies in terminated state does no longer consumes any cycles of CPU.
import java.util.*;
class A extends Thread
{
public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
A obj = new A();
obj.start();
}
}
Output :-
Enter your name
way2testing
Enter your surname
singh
Your full Name is way2testing singh Thread[Thread-0,5,main]
package com.lang.beginner;
class A
{
public void test()
{
System.out.println("i am inside A class");
}
}
class B extends A implements Runnable
{
public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
B obj = new B();
obj.test();
Thread th = new Thread(obj);
th.start();
}
}
Output :-
i am inside A class
Enter your name
way2testing
Enter your surname
.com
Your full Name is way2testing .com Thread[Thread-0,5,main]
---------------------------------------------------------------------------------------------------------
Example of Thread Synchronization
package com.lang.beginner;
import java.util.*;
class A implements Runnable
{
synchronized public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
A obj = new A();
Thread th = new Thread(obj);
th.start();
A obj2 = new A();
Thread th2 = new Thread(obj);
th2.start();
}
}
Output :-
Enter your name
csc
Enter your surname
baji
Your full Name is csc baji Thread[Thread-0,5,main]
Enter your name
adhi
Enter your surname
raaj
Your full Name is adhi raaj Thread[Thread-1,5,main]
class parent
{
public void k()
{
System.out.println("i am inside parent class");
}
}
class test extends parent implements Runnable
{
public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("This is CSC" + " " + i);
}
}
public void run(int x)
{
for(int i = 0; i<x; i++)
{
System.out.println("This is run 2 CSC" + " " + i);
}
}
}
class test2 extends Thread
{
public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("This is way2testing" + " " + i);
}
}
}
public class ThreadPractice
{
@Test
public void k()
{
test obj = new test();
Thread td = new Thread(obj);
td.start();
test obj2 = new test();
obj2.run(7);
for(int i = 0; i<5; i++)
{
System.out.println("This is way2shayari" + " " + i);
}
test2 obj3 = new test2();
obj3.start();
}
@Test
public void l()
{
Thread t1 = new Thread(new Runnable()
{public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("i am thread 1 in same class");
}
}
}
);
Thread t2 = new Thread(new Runnable()
{public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("i am thread 2 in same class");
}
}
}
);
t1.start();
t2.start();
}
} ---------------------------------------------------------------------------------- Example of Threads
import java.util.Scanner;
class A implements Runnable
{
synchronized public void run()
{
for(int i = 1; i<11; i++)
{
System.out.println(i +" " +Thread.currentThread());
}
}
}
public class Oopstutorial
{
public static void main(String[] args)
{
A obj = new A();
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.start();
t2.start();
}
}
Dictionary:- Dictionary is an abstract class that represents a key/value storage repository and operates much like Map.
With dictionaries, we can
1). INSERT
2). FIND
3). DELETE
public class DisctionaryPractice
{
public static void main(Striing[] args)
{
Map<String, String> stardictionary = new HashMap<String, String>();
stardictionary.put("Julia", "America");
stardictionary.put("Nicole", "USA");
stardictionary.put("Kiera", "UK");
stardictionary.put("Anne", "new york");
}
System.out.println(stardictionary.get("Julia"));
System.out.println(stardictionary.toString());
System.out.println(stardictionary.keySet());
System.out.println(stardictionary.values());
}
Serialization in Java
Serialization in java is a mechanism of writing the state of an object into a byte stream. In other Word
Serialization is a mechanism of convertion the state of an object into a byte stream.
The reverse operation of serialization is called deserialization. In other Word
Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.
The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.
Advantage of Java Serialization
It is mainly used to travel object's state on the network(known as marshaling).
Example of Serialization:-
class Employee implements Serializable
{
int empid;
String empname;
public Employee(int empid, String empname)
{
this.empid = empid;
this.empname = empname;
}
}
public class Persist
{
public static void main(String[] args)
{
Employee emp = new Employee(308, "Chandan");
FileOutputStream fout = new FileOutputStream("file.text");
ObjectOutputStream Oout = new ObjectOutputStream(fout);
Oout.writeObject(emp);
Oout.flush();
System.out.println("Serialization Completed");
}
}
Example of Deserialization:-
class Employee implements Serializable
{
int empid;
String empname;
public Employee(int empid, String empname)
{
this.empid = empid;
this.empname = empname;
}
}
public class Depersist
{
public static void main(String[] args) throws Exception
{
FileInputStream fin = new FileInputStream("file.txt");
ObjectInputStream Oin = new ObjectInputStream(fin);
Employee emp = (Employee)Oin.readObject();
System.out.println(emp.empid+ " " + emp.empname);
Oin.close();
System.out.println("DeSerialization Completed");
}
}
:- It is an Interface
It is available in Java utility package.
Enumeration is used to process the elements of the collection objects which are introduce in jdk 1.0 for example vector.
There are two types of methods declared by Enumeration :- hasMoreElements :- It returns Boolean value like True or False nextElement :- It returns the next object in the enumeration.
public class ENUM {
public static void main(String args[]) {
Enumeration name;
Vector starNames = new Vector(5,3); (here 5 and 3 are initial and incremental capacity)
starNames.add("Julia Robert");
starNames.add("keanu reeves");
starNames.add("Akshay");
starNames.add("Maria");
starNames.add("Keira");
starNames.add("Frida");
starNames.add("Will");
name = starNames.elements(); //It will return Enumeration object
while (name.hasMoreElements()) {
System.out.println(name.nextElement());
}
}
}
Output :-
Julia Robert
keanu reeves
Akshay
Maria
Keira
Frida
Will
Vector :- It is a Class
Vector implements a dynamic array.
Implements List Interface & extends AbstractList.
Vector v = new Vector() Creates default vector of capacity 10.
Vector v = new Vector(int size, int incre) defines vectors Initial size & incremental size.
Example of vector class :-
public class Vectortutorial
{
Enumeration enum;
public static void main(String[] args)
{
Vector v = new Vector();
v.add("way2testing");
v.add("chandan");
v.add("Testing Tutorials");
v.add(7);
Iterator itr = v.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
Vector<Integer> vec = new Vector<Integer>();
vec.add(1);
vec.add(2);
vec.add(4);
enum = vec.elements();
while (enum.hasMoreElements()) {
System.out.println(enum.nextElement());
}
}
}
Output :-
way2testing
chandan
Testing Tutorials
1
2
4
Difference between Vector and ArrayList In Java
1). java.util.Vector came along with the first version of java development kit(JDK).
java.util.ArrayList was introduced in java version 1.2 as part of Java collection framework.
2). Vector is synchronized but ArrayList is not or we can say also
"All the methods of vector is synchronized but the methods of ArrayList is not synchronized."
So ArrayList is fast because it is not synchronised & vector is slow because it is synchronized.
3). Vectors doubles(100%) the size of its when its size is increased and ArrayList increases by half(50%) of its size when its size is increased.
4). ArrayList uses Iterator Interface to traverse the elements but A vector can use Iterator interface or Enumeration interface
to traverse the elements.
Hello Friends,
In this article , we will describe that in java we can not override private or static method :-
You cannot override a private or static method in Java. If you create a similar method with same return type and same method arguments
in child class then it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method
in sub class because it’s not accessible there. What you can do is create another private method with the same name in the child class.
Let’s take a look at the example below to understand it better.
Example :-
class Parent
{
private static void test() {
System.out.println("Static or class method from parent");
}
public void quality() {
System.out.println("Non-static or instance method from parent");
}
class Child extends Parent {
private static void test() {
System.out.println("Static or class method from child");
}
public void quality() {
System.out.println("Non-static or instance method from child");
}
public class myprogram {
public static void main(String args[])
{
Parent obj= new Child();
obj.test();
obj.quality();
}
}
Hello Friends,
In this article , i will describe about collection in Java Language :-
COLLETION IN JAVA
Java collections refer to a single unit of objects.
You can perform all operations on data such as searching, sorting, insertion, manipulation,
deletion, etc. by Java collections.
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is a Java Collection Framework?
A Java collection framework provides an architecture to store and manipulate a group of objects. A Java collection framework includes the following:
Interfaces
Classes
Algorithm
Let’s learn about them in detail: Interfaces: Interface in Java refers to the abstract data types. They allow Java collections to be manipulated independently from the details of their representation. Also, they form a hierarchy in object-oriented programming languages. Classes: Classes in Java are the implementation of the collection interface. It basically refers to the data structures that are used again and again. Algorithm: Algorithm refers to the methods which are used to perform operations such as searching and sorting, on objects that implement collection interfaces. Algorithms are polymorphic in nature as the same method can be used to take many forms or you can say perform different implementations of the Java collection interface.
The Java collection framework provides the developers to access prepackaged data structures as well as algorithms to manipulate data. Next, let us move to the Java collections framework hierarchy and see where these interfaces and classes resides.
Java Collections : Interface Iterator interface : Iterator is an interface that iterates the elements. It is used to traverse the list and modify the elements. Iterator interface has three methods which are mentioned below: public boolean hasNext() – This method returns true if the iterator has more elements. public object next() – It returns the element and moves the cursor pointer to the next element. public void remove() – This method removes the last elements returned by the iterator.
There are three components that extend the collection interface i.e List, Queue and Sets. Let’s learn about them in detail:
Java collections: List
A List is an ordered Collection of elements which may contain duplicates. It is an interface that extends the Collection interface. Lists are further classified into the following:
ArrayList
LinkedList
Vectors
Let’s go into detail on each one of them: Array list: ArrayList is the implementation of List Interface where the elements can be dynamically added or removed from the list. Also, the size of the list is increased dynamically if the elements are added more than the initial size.
ArrayList object = new ArrayList ();
Linked List: Linked List is a sequence of links which contains items. Each link contains a connection to another link.
Syntax: Linkedlist object = new Linkedlist();
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List
Doubly Linked List Singly Linked List: In a singly Linked list each node in this list stores the data of the node and a pointer or reference to the next node in the list. Refer to the below image to get a better understanding of single Linked list.
Doubly Linked List: In a doubly Linked list, it has two references, one to the next node and another to previous node. You can refer to the below image to get a better understanding of doubly linked list.
Vector:- Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.
Stack :- The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
A Collection is a group of individual objects represented as a single unit.
Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
The Collection interface (java.util.Collection) and Map interface (java.util.Map)
are the two main “root” interfaces of Java collection classes.
1). List Interface
Child Interface of collection interface is List. It have a list type data structure in which we can store the ordered collection of objects also it can have duplicate values.
List alist= new ArrayList();
List llist = new LinkedList();
List vlist = new Vector();
List slist = new Stack();
2).Java Collections – Set
A Set is a Collection that cannot contain duplicate elements. There are three main implementations of Set interface:
HashSet, TreeSet, and LinkedHashSet. HashSet, which stores its elements in a hash table, is the best-performing
implementation; however it makes no guarantees concerning the order of iteration. TreeSet, which stores its elements
in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet. LinkedHashSet,
which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they
were inserted into the set (insertion-order).
Set hs = new HashSet();
Set ls = new LinkedHashSet();
Set ts = new TreeSet();
3).Queue Interface
Queue interface maintains the first-in-first-out order. It
can be defined as an ordered list that is used to hold the elements which are about to be processed.
There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
Queue pq = new PriorityQueue();
Queue aq = new ArrayDeque();
ArrayList Example
Array List maintain the insertion order and non-synchronized
public class ConsTest
{
public static void main(String args[]) throws IOException
{
ArrayList alist = new ArrayList();
alist.add("chandan");
alist.add("Singh");
alist.add("chauhan");
alist.add("chandan");
Iterator itr = alist.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output :-
chandan
Singh
chauhan
chandan
LinkedList example
It can store the duplicate elements. It maintains the insertion order and is not synchronized
public class ConsTest
{
public static void main(String args[]) throws IOException
{
LinkedList alist = new LinkedList();
alist.add("chandan");
alist.add("Singh");
alist.add("chauhan");
alist.add("chandan");
Iterator itr = alist.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output :-
chandan
Singh
chauhan
chandan
Example of Vector :-
public class ConsTest
{
public static void main(String args[]) throws IOException
{
Vector alist = new Vector();
alist.add("chandan");
alist.add("Singh");
alist.add("chauhan");
alist.add("chandan");
Iterator itr = alist.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output :-
chandan
Singh
chauhan
chandan
Example of Stack :-
public class ConsTest
{
public static void main(String args[]) throws IOException
{
Stack stk = new Stack();
stk.push("chandan");
stk.push("Singh");
stk.push("chauhan");
stk.push("chandan");
stk.push("Singh");
stk.pop();
Iterator itr = stk.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output :-
chandan
Singh
chauhan
chandan
PriorityQueue
The PriorityQueue class implements the Queue interface. 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.
Output :-
Adhiraaj
Adhiraaj
Adhiraaj
Anngraaj
Amit
ChandanSingh
After removing elements
Anngraaj
ChandanSingh
HashSet :-
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items
public class ConsTest
{
public static void main(String args[])
{
HashSet hset = new HashSet();
hset.add("chandan");
hset.add("chandan");
hset.add(null);
hset.add("Singh");
Iterator itr = hset.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
} Output :-
null
chandan
Singh
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements.
public class ConsTest
{
public static void main(String args[])
{
LinkedHashSet hset = new LinkedHashSet();
hset.add("chandan");
hset.add("chandan");
hset.add(null);
hset.add("Singh");
Iterator itr = hset.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
} Output :-
chandan
null
Singh
TreeSet :-
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
public class ConsTest
{
public static void main(String args[])
{
TreeSet hset = new TreeSet();
hset.add("chandan");
hset.add("chandan");
//hset.add(null);
hset.add("Singh");
Iterator itr = hset.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
} Output:-
Singh
chandan
Array List
Linked List
Array List is not Synchronized
Linked List is also not synchronized
Array List maintain insertion order
Linked List Also Maintain insertion order
Array List can have multiple null values and multiple duplicate values
Linked List can also have multiple null values and multiple duplicate values
ArrayList internally uses a dynamic array to store the elements
LinkedList internally uses a doubly linked list to store the elements.
Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the other elements are shifted in memory
Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
When read scenarios are more as complare to add and remove scenario, then linked list preferred
When Add remove scenarios are more than read scenarios then linked list preferred
HashSet
LinkedHashset
Treeset
HashSet uses hashmap for it’s internal storage
LinkedHashSet extends HashSet class and implements Set interface and use HashMap internally to store it's element
TreeSet extends AbstractSet and implements NavigableSet interface use TreeMap internally to store it's element
Hashset does not maintains any order
Linked HashSet maintains insertion order
maintains ascending order of inserted items
HashSet represents a group of unique elements
LinkedHashSet represents a group of unique elements
it also represents a group of unique elements
HashSet can have one null value
LinkedHashSet can also have one null value
No null values allows in TreeSet
not synchronized and hence not Thread safe
not synchronized and hence not Thread safe
not synchronized and hence not Thread safe
When To Use?
1). Use HashSet if you don’t want to maintain any order of elements.
2). Use LinkedHashSet if you want to maintain insertion order of elements.
3). Use TreeSet if you want to sort the elements according to some Comparator.
Hello Friends,
In this article , i will describe about mobile automation toolAppium :-
Before starting with the appium we should know about Emulator, Simulator & Real Devices
Simulator
A simulator is used in another thinking context, e.g a plane simulator, a car simulator, etc.
The simulation will take care only of some aspect of the actual thing, usually those related to how a human being will perceive and control it.
The simulator will not perform the functions of the real stuff, and cannot be sustituted to it.
Emulator
An emulator is a device that mimics something close enough so that it can be substituted to the real thing.
E.g you want a circuit to work like a ROM (read only memory) circuit, but also wants to adjust the content until it is what you want.
Difference between Emulator & Simulator
1).An emulator can replace the original for real use.
A Virtual PC emulates a PC.
A simulator is a model for study and analysis.
2).
Simulation = For analysis and study
Emulation = For usage as a substitute
What is Emulator & Simulator in terms of mobile?
Emulator and simulator are virtual devices, A virtual devices is not the real phone but software
which gives same functionality as the real phone(Except few functionality like camera).
Android Virtual devices : Emulator
iOS Virtual device : Simulator.
Important Points
An Appium is an open source tool for automating mobile application which can be :-
Native
Hybrid
Web
Examples of hybrid apps
For many it is surprising to learn that some of the world’s most popular mobile apps turn out to be…hybrid!
This includes: Amazon (for iOS and Android), Evernote (for iOS and Android), Netflix (for iOS and Android).
Appium supports platforms such as :-
Andriod
iOS
Firefox OS
Appium was designed to meet mobile automation needs according to a philosophy outlined by the following four tenets :-
1). You should not have to recompile your app or modify it in any way in order to automate it.
2). You should not be locked into a specific language or framework to write and run your tests.
3). A mobile automation framework should not reinvent the wheel when it comes to automation APIs.
4). A mobile automation framework should be open source, in spirit and practice as wll as in name.
we don't have to recompile or modify anything in our application under test(AUT) to perform automated test with appium, sience appium
under the hood uses the vendor specific frameworks meaning :- Android :- UIAutomator(developed by Android developers) iOS :- UIAutomation(developed by Apple Inc)
Sience Appium has extended web driver client library, appium also support all the languages which webdriver suports like :-
Java
C#
Ruby
Python
Php etc.
How is Appium Built 1). Appium is basically an HTTP server written in Node.js that creates and handles webdriver sessions. 2). Node.js is a platform build on Chrome's javaScript runtime for easily building fast, scalable network applications.
Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive
real-time applications that run across distributed devices.
Appium Architecture :-
As appium is an HTTP server, its performs pretty much same as Selenium Webdriver server by :- 1). Receiving request/commands from clent libraries. 2). Executes the command on the target devices/emulators . 3). Responds with an HTTP response.
Hence Appium Works as a client/server architecture.
Client Librares -
Appium Client libraries has different language bindngs like :-
Ruby
Python
Java
JavaScript
PHP
C#
RobotFramework
How Appium Works? 1).As we already know that Appium suports Andriod, iOS and Firefox OS platforms, there should be a mechanism
for appium to handle them.
2).Hence Appium handles these platforms using vender-provided frameworks.
The Vendor-provided frameworks for differnt platforms are :- iOS Apple's UIAutomations Android 4.2+ Google's UiAutomator Andriod 2.3+Google's Instrumentation (Instrumentation support is provded by bundling a seprate projects, Selendroid)
How Appium Works in Android
How Appium Works in iOS
What is appium desired capabilities
Desired capabilities are keys and values and they are encoded in a JSON Object.
Desired capabilities sent by the appium client to the server when a new automation session is requested.
They tell the Appium drivers all kinds of important things about how you want your test to work. Each Appium client builds capabilities in a way
specific to the client's language,
but at the end of the day, they are sent over to Appium as JSON objects.
appPackage, appActivity, appWaitPackage, appWaitActivity, LaunchTimeout & UDID all are capabilities.
appPackage call desired JAVA package in android that user want to run. appActivity Application Activity that user wants to launch from the package. appWaitPackage Package from which application needs to wait for appWaitActivity Any Android activity that user need wait time LaunchTimeout Total time(in ms) to wait for instrumentation. UDID To identity unique device number for connected physical device.
What is the full form of ADB Ans :-Android Debug Bridge