Java Notes With Example
Java Notes With Example
Java Notes With Example
Constructor –
-> With private constructor instance of class can be created inside declaring class(singleton pattern)
-> singleton class is one which limits the number of objects creation to one. Using private
constructor we can ensure that no more than one object can be created at a time. By providing
a private constructoryou prevent class instances from being created in any place other than this
very class.
->
Control+click -> to get information
Constructor –
We can call variable, method constructor using super and this keyword.
Exception Handling
Exception are not compile time, its run time.
Control+click -> to get information
Constructor –
We can call variable, method constructor using super and this keyword.
Exception Handling
Exception are not compile time, its run time.
Control+click -> to get information
Constructor –
We can call variable, method constructor using super and this keyword.
Exception Handling
Exception are not compile time, its run time.
Control+click -> to get information
Constructor –
We can call variable, method constructor using super and this keyword.
Exception Handling
Exception are not compile time, its run time.
We can call variable, method constructor using super and this keyword.
Exception Handling
Exception are not compile time, its run time.
What is exception in java - exception are usually are object thrown by jvm.
2 type of exception:
Exception Handling -
1. Try-catch-finally block
2. throw keyword
Try-catch block:
try {
Code which may cause exception
}
catch (exception e){
Handling code
}
2.Finally block surely execute regardless of exception. Wrap up code will be written in finally
Structure -
Try {
//code may cause exception
} catch (exception e)
Handling code
} finally
//wrap up code
}
Try{
}catch{
Try{
}catch{
}
}
Allowed:
1.try{
}catch(){}
catch(){}
catch(){}
if you write try under other try ,then only 1st try exception will work.
Throws-send exception by method to other method and said that i am not able to handle see if you can
handle it
ex.
1.
public class Test1{
public void m1 throws ArrayIndexOutOfBoundException(){
int a={1,2,3,4,5};
System.out.println(a[5]);
}
}
2.
public class Test2{
public void m2 throws ArrayIndexOutOfBoundException(){
Test1 t = new Test1();
t.m1();
}
}
3.
public class Test3{
public static void main(String[] args){
test2 t2 = new test2();
try{
t2.m2();
}catch(Exception e){
Syso(exception handled);
}
}
}
if(user.equals("exist")&&passwd.equals("exist")){
Syso("login valid);
else{
}
Customised exception:
ex.
Collection
Array:
Homogenous in nature
Fixed in size
Array data structure
Collection framework:
Collection interfaces:
List
Set
Queue
Map
List interface:
1. Duplicate allowed
2. Its variable in size
3. Insertion order preserve
ArrayList© -
Backend stru is array.
Duplicate allowed
Heterogeneous
Typecast happens automatically
Random access possible
Null insertion is also possible
New capacity = initial capacity*3/2+1
Memory efficiency is more in arrayList than array
For performance wise array is better, because to add/delete element is easy in array while it take time
in arraylist.
Disadvantage:
Insertion & deletion operation are frequent then AL not preferred.
Frequent operation of reading data, AL is recommended
Constructor:
ArrayList()
ArrayList(int capacity):it will create arraylist with specific capacity
ArrayList(collection c):its will create arraylist of collection(collection of collection)
LinkList©:
Use double linklist structure
It’s recommended where frequent operations are insertion and deletion.
Not recommended where frequent operation are reading.
Constructors:
LinkedList() – creates empty linkedlist
LinkedList(collection c) – this will create a LinkedList of collection.
Vector©:V1.0 Legacy class (legacy means classes present from starting of java)
ArrayList & vector are same except1 feature that synchronized in nature.
Backend structure is array.
Variable in size.
Synchronized (Thread safe)
All methods are synchronized in vector.
Constructor:
Vector()
Vector(int)
Vector(collection)
Vector(int capacity,int incrementcapacity)
SET:
Doesn’t preserve insertion order.
Heterogeneous
Sort data in natural sorting order.
Datastrucutre is Hashtable
Set(I):
1.HashSet©
1.LinkedHashSet©
2.SortedSet(I)
1.NavigableSet(I)
2.TreeSet©
HashSet©:
It sorts data in natural sorting order.
It does not preserve insertion order.
It’s variable in size
Backed data structure is hash table (key & value pair).
Random access is not possible
Null insertion is possible,
LinkedHashSet©:
Insertion order preserve
Consistent performance
Backend data structure is hash table and doubly linked list.
Null insertion is possible
Doesn’t sort data even if data is of same type.
TreeSet©:
Sort data in natural order
Homogenous in nature (can’t add diff type of data)
Does not preserve insertion order.
Backend data structure is tree
If we tried to add heterogeneous data to tree set then will get class cast exception
Iterator:
Use cursors:
1. Iterator: iterator is used to iterate any element in collection. Its interface which has abstract
method.
Iterator itr = al.iterator();
|->interface |->method
While(itr.hasNext()){
|->return Boolean value true/false ,if its true then it will go on syso statement and
return object.if its false then it will finish while loop.
Syso(itr.next());
|->return object
}
While(itr.hasNext()){
Int element= (int)itr.next();
Element = element+2;
2. List Iterator(I):
Syso(“iterator for fwd direction”);
ListIterator itr = al.listIterator();
While(itr.hasNext()){
Syso(Itr.next());
}
For backward direction:
While(Itr.hasPrevious()){
Syso(itr.previous());
}
//for hashmap we need to take app keys into set and then print the value of keys
HashMap map = new HashMap();
Set allkeys = Hs.setKeys();
Iterator itr = allkeys.iterator();
While(itr.hasNext()){
Syso(map.get(Itr.next());
3. Numerator
SELENIUM
For webdriver testing: QTP, selenium webdriver, load runner
, selenium IDE
Regression testing – its part of testing, which test previous test cases to check whether new deployed
code impacted.
Selenium WebDriver:
3. Collection of interface, abstract class, classes which can be used to automate web application.
4. Selenium Automate only web application.
5. Support multiple languages like java,python,ruby,C# etc
6. It support multiple browsers
7. Third party library integration is easy and supported.
8. Platform independant
HtmlUnitDriver:
Headless browser
Implimenettion of webdriver
Fastest & lightweight
Methods of WebDriver(I):
<tagname attribute=”value1” attrib2=”vaalue2”>Text</name>
1. click() – click on particular webelement including button,link,radio button ,checkboxes
2. submit() – use to submit form
3. sendKeys(charSequence ..keys) –it can type in text boxes,text areas etc..
4. clear() – can be clear text area.
4. getTagName():get name of tag
5. getAttribute():use to get the attribute of specific tag mentioned as parameter
6. isSelected() : give Boolean value true or false if check boxes is present or not
7. gettext():This method can b use to get text of webelement including label,link etc
8. findElement() – return type webelement .
9. FindElements() – return type is list.
Locators in selenium:
By Claas
1. id
2. Name
3. xPath
4. css selector
5. class name
6. linkText
7. partialLinkText
2.Child :
//tagA>[@attrib=’value’]/child::<tagB>[@attrib=’value’]
Following-sibling
//ul[@class=’sub-menu collapse in’]/li[1]/following-sibling::li] //traverse all li which are present under ul
tag
Preceding-sibling:
//li[@data-target=’#security’]/preceding-sibling::li
//div[@class=’col-md-3 col-sm-4 left-menu’]/div[3]/preceding-sibling::div
Ancesester:
// div[@class=’col-md-3 col-sm-4 left-menu’]/ancestor::*
Descendant:
// div[@class=’col-md-3 col-sm-4 left-menu’]/descendant::*
Self:
//div[@class=’col-md-3 col-sm-4 left-menu’]/self::*
Ancestor-or-self:
Descendant-or-self
2. Explicit Wait:
1. Wait only for particular element which takes little more time than other element
2. Highly customizable
3. We can ignore unwanted exception using explicit wait
4. We can wait for particular web element or its state or particular event on webpage.
5. We can specify polling time using explicit wait.
6. We can achieve explicit wait using 2 classes
WebDriverWait()
FluentWait()
To handle windows:
getWindowHandle() : Return type is string
-Return hexadecimal string handle of window to which web driver instance is currently pointing
getWindowHandles() : Return type is set of strings
-Return set of window handles of windows which are open by driver instance only.
Frames:
Driver.switchTo.frame() //index,webelement,nameorid
Window popup – html dom,close,minimize,maximize
Pop-up – model popup div:not html dom container
Frames – inline frame
Alert –
1. Java script element or functions
2. Used to attract the focus of user towards some action
3. Its javascript function with which we can create alert – ie alert(),prompt(),confirm()
4. There is no chance of having multiple alert on same webpage at a time.
3 types of alert:
1. Simple Alert
2. Prompt alert
3. Confirmation alert
To handle alert we should use alert(I) – 2 methods for alert handling accept() & dismiss()
Simple Alert:
They have only 1 button and text
They r u se to notify about something to user
Alert alert = driver.switchTo.alert();
Alert.accept();
Action class:keyboard n mouse event .we can mouse hover,right click ,left click
We can press only shift ,ALT,cntrl key through action class.if we try to press any other class then we wll
get illegalArgumentException
For up –
Js.executeAsyncScript(“window.scrollby(0,-100)”)
Select class:
Methods:
SelectByIndex()
SelectByValue()
SelectByVisibleText()
To Deselect the element:this method we can use when it will allow multiple select option,it will not
work for single option.
1. DeselectbyIndex()
2. DeselectByValue()
3. DeselectByvisibleText()
getOptions() –
1.list of web element
2.this list contains all the options available in dropdown.
CSS Selector:
ANNOTATION:
1.@Test:
Method with this annotation known as as test case.
Method level and class level.
2.@beforeTest:
Method with this annotation will be executed exactly before <test> tag of testing.xml
Method level annotation
3.@AfterTest
Executed after only <test> tag of testing.xml
Method level annotation.
4.BeforeSuite():
Method will execute just before suite tag of testing.xml
Method level annotaton.
5.AfterSuite:
Method execute just after suite tag of testing.xml
Method level annotation
6.@Beforemethod:
Execute just before each and every test method
Method level
7.@AfterMethod:
method with this annotation execute after test annotated tag
DataProvider():
For data driver testing
In 1 class,we can have multiple dataPrivder()
Its method level annotation
Method with this annotation Provide data to test case as per choice.
@BeforeClass:excute before each and every<class> tag presnt in testing.xml
@AfterClass:execute after <class> tag present in testing.xml
@Parameter:method with this annotation will accept parameter from testing.xml file.
Method level
@Parameters({“rollNumber”})
@Test
Parameters of @Test annotation:
invocation count – how much time test case will be executed.
@Test(invocationCount=3)
invocationTimeout:
@Test (invocationTimeout=1000) -> it will 1000 mili sec for execute
Thread Pool Size = how many threads are invoke during test case
@dataprovider(name=”LoginDataProvider”)
Public object[][] loginData(){
Object[][] values={{“user1”,”pass1”},{“user2”,”pass2”},{“user3”,”pass3”}}
Return value;
Read test data from excel sheet and providing case by mean of data provider
Reading excelsheet:
.xls
.xlsx
Groups:
If want to exclude particular group
Listener:
ITestListener(I)
1. onStart() – executed before each <test> tag of testing.xml
2. OnFinish() – executed after <test> tag of testing.xml
3. OnTestSuccess() –invoked after passing each test cases mentioned in class or
testing.xml
4. onTestfailure() – invoke after failure of test case mentioned in class.
5. onTesttStart() – invoked before every invocation of every test case
6. OnFailedButWithSuccessPercentage() – invoke after failing a test case if it is in success
percentage
7. OnTestSkipped() – invoked after test case is skipped.
How to execute:
From test case class
FRAMEWORK:
POM:
Operations and elements of particular page in one java class
PageFactory class:
ClassA a = new ClassA();
Lazy proxy for every webelement
Reflection API:
Reflection is use to create image of any class,so that we can get detailed info about class,like method
haing body,no of abstract method,constructor,return type of any mrthod,Access modifier
getClass
class Reflection=new Demo.getClass();
the .class syntax
class Reflection=demo.class;
for methods:
For field:
AUTOIT
ControlFocus("Open","","Edit1")
ControlSetText("Open","","Edit1","D:\puja\flat_pics\IMG_0049.JPG")
ControlClick("Open","","Button1")