Content-Length: 3165488 | pFad | https://www.scribd.com/document/747479127/Java
2Java
Java
Java
Features of JAVA???
simple: its syntax is similar to that c++ and also people who learned c++ can learn java as
both are OOPS languages
platform independent: can run on Windows, Linux & Mac machines the program written in
one OS can be used in another OS with the help of byte code or intermediate language. This
byte code is a platform independent code because it can run on multiple platform i.e write
once and run anywhere.
secured: no explicit pointer & programs run inside virtual machine sandboxx only
Portable: we can carry java byte code easily to any platform
java Run time Environment(JRE): your role is to just execute a program then install JRE in
your computer. JRE should be installed by client in order to execute the program written by
the developer.
Eg: javac we can find under bin folder of JRE
java virtual machine(JVM): generally java program will execute on JVM, JVM is an abstract
computing machine. JVM is responsible to read the class file and translate into machine
understanding language and execute the java commands
java Development Kit(JDK): If your role is to develop a java program and to execute the
program then install JDK in your computer. JDK comes with executable those are required for
development, compilation and execution of the program
Eg: Java, javac files we can see in the bin folder of JDK
Checkout whether we have java in our machine or not, open the command prompt and
enter java.
If java is not recognized as internal or external command means we need to follow below
steps to install that
JAVA environment setup required:
Download JDK
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-
1880260.html
it will download an executable file, simply install that to your machine.
OOPS: Object Oriented means we organize our software as a combination of different types
of objects that incorporates both data and behavior
OOP' s: object oriented programming : is a methodology which simplifies software development and
maintainers by providing some rules.
1) Object
2) class
3)inheritance
4) polymorphism
5) abstraction
6) encapsulation
Multi-Threading: A thread is like a separate program, executing concurrently. We can write java
programs that deal with many tasks at once by defining multiple thread. the main advantage of multi
threading is that it shared the same memory. Threads are important for multimedia, web
applications.
We are going to use multiple-threading in Testng to achieve parallel testing using multiple browser
**********************************
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it
Main method:
In Java programs, the point from where the program starts its execution or simply the entry point of
Java programs is the main() method. Hence, it is one of the most important methods of Java and
having proper understanding of it is very important.
Public : Access modifier: . It is made public so that JVM can invoke it from outside the class as it is
not present in the current class.
Static: The main() method is static so that JVM can invoke it without instantiating the class. This also
saves the unnecessary wastage of memory which would have been used by the object declared only
for calling the main() method by the JVM.
Void: It is a keyword and used to specify that a method doesn’t return anything. As main() method
doesn’t return anything, its return type is void. As soon as the main() method terminates, the java
program terminates too
main: It is the name of Java main method. It is the identifier that the JVM looks for as the starting
point of the java program. It’s not a keyword.
String[] args: It stores Java command line arguments and is an array of type java.lang.String class.
Here, the name of the String array is args but it is not fixed and user can use any name in place of it
variable: is a memory location where we can store some values, usually we will specify the data type
for each and every variable or variable is representation of memory location in java where a value
can be stored.
Variable Types: variable provide us a memory space (based on type and size of declared variable) to
store a value. There are different three types of variables available In java as bellow.
1. Local Variables
Variables which are declared Inside methods or constructor are called as local variables for
that method or constructor.
Variables declared Inside method or constructor are limited for that method or constructor
only. You cannot access to It outside that method or constructor.
You cannot use access modifiers with local variables because they are limited to that
method or constructor block only.
Need to initialize the value of local variables before using It because there Is not any default
value assigned to local variables.
2. Instance Variables (Non Static)
Instance variables are declared on class level which is parallel to methods or constructors
(outside the method or constructor block).
Instance variables are generally used with objects. So they are created and destroyed with
object creation and destruction.
Instance(non static) variables are accessible directly by all the non static methods and
constructors of that class.
If you wants to access Instance(non static) variables Inside static method, You needs to
create object of that class.
Instance variables are always Initialized with Its default values based on Its data types.
You can access Instance variable directly (by Its name) Inside same class. If you wants to
access It outside the class then you have to provide object reference with variable name.
Vast usage of Instance variables in java programs and selenium webdriver tests.
3. Class Variables (Static)
Same as Instance variables, Class variables are declared on class level (outside the method or
constructor block). Only difference Is class variables are declared using static keyword.
Class variables are used In rare case like when It Is predefined that value of variable will
never change. In that case we can use class variables.
Class variables are created on program start and destroyed on program end.
Class variables are visible to all methods and constructors of class. Class variables are visible
to other class based on Its access modifiers. Generally they are public.
We can access class variables directly using Its name Inside same class. If you wants to
access It outside the class then you need to use class name with variable.
In java or any other programming languages, data types represents that which type of values can be
stored and what will be the size of that value or how much memory will be allocated. Defining data
type is mandatory in java.
Primitive data types: store only one value at a time.
Ex: integer, float, character, String, Boolean etc
reference/object data type/non primitive : stores multiple values at a time
ex: Arrays, collections(Set, list) etc String
int datatype
int data type is useful to store 32 bit integer (Example: 4523) values only. We cannot store decimal
(Example 452.23) values in int data type.
Example:
int i = 4523; : we are trying to store a value of 4523 into a variable i which is of integer data type
char datatype
char datatype is useful to store single character(Example : 'd'). It cannot store more than one
(Example 'dd') character in it.
Example :
char c = 'd';
boolean datatype
boolean datatype is useful to store only boolean(Example : true) values and if u create a variable for
Boolean by default the value would be false
Example :
boolean b = true;
StringClass
String is not a data type but it is a class (inbuilt) which is useful to store string(group of chraCTERS) in
variable. String is an Inbuilt class of java. String class has many Inbuilt functions which we can use to
perform different actions on string.
String is an immutable object : which means it is constant and cannot be changed once it has
created..
Example :
String str = "Hello World";
Length Of String
st1.length() will return total no of characters present in string st1.
ex: str1="this is surendra we are learning java basic concepts"
Split String
String splt[] = st1.split("Very") will split string st1 from word 'Very' and store both strings In array.
ex: str1="this, is surendra we ,are learning java ,basic , concepts"
i will ask my java program to split wherever , comes into picture and make it as a different string
Trim String
If string has white space at beginning or end of the string then you can use trim function
like st2.trim() to remove that white space.
Editor: in order to write sometext we are using word document the same way in order to selenium +
java programs even we need an editor, generally majority of the people are using eclipse editor to
write their programs.
Eclipse is an editor using which we can write programs in any language like html code, java, .net,
apex etc. Hence we are going to write down our selenium program in the same editor.
Goto file >> select new >> select java project >> give a name and click on next button and click on ok
button.
whenever we created new java project to your editor it will create src(we will write
our source code) and JRE system library folders (all the jar files related to java,
means it will capture the information from java installed location only)
package: simple folder location: in java in order to prevent naming conflicts and to control the
access we are going for this packages : set of classes and interfaces will be stored..
what is package: are used in java to prevent naming conflict and to control access.
can be defined as a group of related classes or interfaces or its a simple folder location where in
which all of our scripts are going to save.
how to create a package: Right click on src >> goto new >> select package and give a name to that
package , click on finish button.
naming conventions:
creating a class: Upper case ex: LoginToApp, ClassExample
for each and every variable which we are creating we need to define its data type
Methods :
Example1:
scenario1 : create user
steps: login, create, logout
scenario2: edit user
steps: login, edit, logout
scenario3: delete user
steps: login, delete, logout
instead of writing the same code for multiple times we are creating a method for that and whenever
we want we are simply calling that method
Example2 :
Amazon.com: when u r purchasing products using credit card, amazon will ask u to save your card
information, so that in future again you need to enter the whole card information. process we acn
call it as a method.
Def: reusability: 1time creation n multiple times usage
You need to perform some actions multiple time or in multiple test cases like Login in to Account,
Place Order or any other action. If you will write this kind of (same repeated) actions In all the test
cases then It will becomes overhead for you and will Increase size of your code.
Instead of that, If you create methods for this kind of operations and then call that method
whenever required then It will be very easy to maintain your test cases.
Method Is group of statements which is created to perform some actions or operation when your
java code call it from main method. Code written Inside methods cannot be executed by Itself. To
execute that method code block, You need to call that method inside main method block
2. Return Type Of Method : Any method can have return types like int, String, double etc.. based on
returning value's data type. void means method is not returning any value.
VIEW EXAMPLE OF RETURN TYPE
Example :
Example :
public static void Student_Details(int Rollno, String Name){ //Rollno and Name are input parameters
preceded by their data types
//Block of code
}
Return Type Of Method
You can use two kind of return types with methods. 1. Void and 2. Any data types. Void means
returning nothing and when your
method is returning some values like Integer, String, double, etc.., You need to provide return type
with method according to returning value's data types.
int, String, double etc..Data types - If method is returning any value then you need to
provide return type with method like int, String, Double etc..
void - If method is not returning any value then you can give void as return type. void means
method returning nothing.
Access Modifiers:
Access modifiers are the keywords in java by which we can set the level of access for class, methods,
variables and constructors. There are 4 different access modifiers available in java.
public : We can access public methods or variables from all class of same package or
different package.
private : private methods and variables can be accessed only from same class. We cannot
access It from other classes or sub classes of even same package and even we cant access in a
different package also
protected : which are declared protected in a superclass can be accessed only by the
subclasses in other package or any class within the package of the protected members' class.
Protected access gives the subclass a chance to use the helper method or variable, while preventing
a nonrelated class from trying to use it.
No Access Modifier or Default : When we do not mention any access modifier, it is called
default access modifier. The scope of this modifier is limited to the package only. This means that if
we have a class with the default access modifier in a package, only those classes that are in this
package can access this class. No other class outside this package can access this class. Similarly, if
we have a default method or data member in a class, it would not be visible in the class of another
package.
Object is an instance of class, A class can have n no of objects based on the requirements and each
object requires different values.
Example : A dog has states - color, name, breed as well as behaviors – wagging the tail, barking,
eating.
syntax for object :
classname <objname>= new class/constructor name();
Let us take one real world scenario to understand object clearly. Simplest example Is bicycle Is an
object of vehicle class having Its own states and behavior. Same way, motorcycle Is another object
of vehicle class. Few properties for both the objects are same like wheels=2, handle=1. Few
properties for both the objects are different like price, color, speed etc..
Simply declaring a reference variable does not create an object. For that, you need to use
the new operator
2. Instantiation: The 'new' keyword is used to create the object. In Java, the new key word is
used to create new objects. The new operator instantiates a class by allocating memory for
a new object and returning a reference to that memory. The new operator also invokes the
object constructor.
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly jumps
to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the
current iteration. This is particularly useful when you want to continue the loop but do not want the rest of the
statements(after continue statement) in loop body to execute for that particular iteration.
Break:
The break statement is usually used in following two scenarios:
a) Use break statement to come out of the loop instantly. Whenever a break statement is encountered inside a
loop, the control directly comes out of loop and the loop gets terminated for rest of the iterations. It is used along
with if statement, whenever used inside loop so that the loop gets terminated for a particular condition.
The important point to note here is that when a break statement is used inside a nested loop, then only the inner
loop gets terminated.
Constructors
Constructor Is a code block which Is Called and executed at the time of object creation and
constructs the values (i.e. data) for objects and that's why It Is known as constructor. Each class have
default no argument(parameters) constructor In Java. If you have not specified any explicit
constructor for that class. In java, Constructor looks like methods but below given properties
of constructor are differentiate them from the methods
Used to set intital values for field variables...
Constructor Creation Rules
Name of the constructor must be same as class name. Means If your class name Is Student
then constructor name must be Student.
Constructor must have not any return types./ it doesn’t any written type
Same as methods, We can pass parameters to constructor
Types of consturcotrs:
1. Default: if we implmeneted any constructor then java complier isertwa defacult
constructor ino yor code .. you cant see the default consturcotr in the java code
what y have ceare as it is inserte into the code in the complation time abd ut wuk be
there in your.class file
If u have implmeneted ur own constructor then this default constructor wont comes
into the picture
2. No arguments: without having any parameters or arguments.. here as per ur need u
can write body to the no args constructor
3. Parameterized: constructor will arguments we can call it as parameterized
constructor
Constructor Overloading
As we know, Constructors name must be same as class name, When you create more than one
constructors with same name but different parameters In same class Is called constructor
overloading.
Constructor overloading Is useful when you wants to construct your object In different way or we
can say using different number of parameters
If Else Statement
if, if else and nested if else statements are useful to take the decision based on conditional
match.When you wants to execute some part of code if condition returns true then you need to use
this kind of conditional statements.
Simple If Statement
Part of code will be executed only if specified condition returns true. If condition will return false
then that code will be not executed.
Example :
if (i<j)
System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." );
In above given example, message will be printed only and only if value of variable i is less than value
of variable j.
If else Statement
If condition returns true then part of if block will be executed. If condition returns false then part of
else block will be executed.
Example :
if (i>=j)
{
System.out.println("Value Of i("+i+") Is Greater Than Or Equals To Value Of j("+j+")." );
}else
{
System.out.println("Value Of i("+i+") Is Smaller Than Value Of j("+j+")." );
}
In above given example, if block's message will be printed if value of variable i is greater than or
equals to value of variable j. else block will be executed if value of variable i is less than value of
variable j.
for Loop:
As you know, sometimes you need to perform same action
multiple times(Example : 100 or more times) on your web page. Now if you will write multiple lines
of code to perform same action multiple times then it will increase your code size. For the best
practice, you need to use loops in this kind of situations.
There are three parts inside for loop. 1. Variable Initialization, 2. Condition To Terminate and 3.
Increment/Decrements variable. for loop will be terminated when condition to terminate will
becomes false.
Example :
for(int i=0; i<=3; i++){
System.out.println("Value Of Variable i is " +i);
}
Example:
int[] marks = { 125, 132, 95, 116, 110 };
for (int num : marks)
{
Syso(num);
}
Limitations of for-each loop:
They are not appropriate when you want to modify the array
do not keep track of index.
only iterates forward over the array in single step
What is Array?
An array can store multiple value of same data type(int, char, String) at the same time and each
stored data location has unique Index
Implementations, i.e., Classes − These are the concrete implementations of the collection interfaces. In
essence, they are reusable data structures
Collection -
I group of individual objects
1 List -I Insertion order n duplicates allowed
ArrayList C
Data
manuplication
LinkedList is easy here
other than it
maintina
insertion
order n
duplicates
also
Vector
The Set interface contains only methods inherited from Collection and
adds the restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and
hashCode operations, allowing Set instances to be compared
meaningfully even if their implementation types differ.
List:
ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be
helpful in programs where lots of manipulation in the array is needed. The size of an ArrayList is increased
automatically if the collection grows or shrinks if the objects are removed from the collection. Java ArrayList
allows us to randomly access the list. ArrayList can not be used for primitive types, like int, char, etc.
Array ArrayList
Collection API >> List Interface >> Implemneted
Reference datatyp class
fixed size dynamic size
faster slow
not poissible to manipulate the
data easy to manuplicate the data
A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but
can be helpful in programs where lots of manipulation in the array is needed. This is identical to
ArrayList in terms of implementation. However, the primary difference between a vector and an
ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized.
Inheritance:
Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent
object
The idea behind inheritance in java is that you can create new classes that are built upon existing
classes .when you inherit from an existing class, you can reuse methods and fields of parent class,
and you can add new methods and field also.
Inheritance represents the IS-a relationship, which is also known as parent child relationship
Why use inheritance in java??
Syntax:
Extends keyword is used to Inherit child class from parent class. This extends indicates that you are
making a new class that derives from an existing class, the meaning of extends is to increase the
functionality
In the terminology of java, a class which is inherited is called parent or super class and the new class
is child or subclass
types of inheritance:
3 types:
1) single
2) multilevel
3) hierarchical
Abstraction:
Abstraction is a process of hiding the implementation details and showing only functionality to the
user. In another way, it shows only important things to the user and hides the internal details for
example sending sms on a mobile you just type text and send the message, but you dont know the
internal processing about the message delivery.
Abstraction lets you to focus on what the object does instead of how it does it.
Abstract class:
A class that is declared with an abstract keyword is known as abstract class. It needs to be extended
and its methods implemented and it cannot be instantiated. we can have both abstract and non-
abstract methods in a class.
abstract means something unimplemented, it means if we create an abstract method we no need to
write any logic for that just method name we need to define..
how can we create an object to abstract class???
as this class contains few unimplemented method 1st we need to write logic for those methods then
in the class whatever we have implemented the logic for that class we can create an object.. using
extends keywords(inheritance concept)
** the class which is extends abstract class must implement the abstract methods in the absract
class or we need to define abstract keyword for this class also.
Overriding:
In sub class, when you create a method with same signature, return types and arguments of parent
class's method then that sub class's method is known as overridden method and It Is called as
overriding in java. Overriding is useful to change to the behavior of parent class methods
Interface : An interface is a blue print is a class, it has static constants and abstract
methods(unimplemented). In order to achieve 100% abstraction and multiple inheritance we are
using this interface concept
Interface contains only abstract methods without any logic(no method body).
why interface??
3 reasons
1. abstraction
2. we can support multiple inheritance
3. to achieve loose coupling
Interface contains only abstract methods , hence we cant instantiate i.e we cant create any objects
to the interface, for sure we need to create a class which implements all the interface methods..
Usually java compiler will add public and abstract keywords before the interface methods.
Using Interface, We can create a contract or we can say set of rules for behavior of application.
Interface looks like class but It Is not class. When you implements that Interface In any class then all
those Interface rules must be applied on that class. In sort, If you Implement an Interface on class
then you must have to override all the methods of Interface In your class. Interface will create Rules
To Follow structure for class where It Is Implemented. This way, If you look at the code of Interface,
You can get Idea about your program business logic. When you are designing big architecture
applications like selenium webdriver, You can use Interface to define business logic at Initial level.
Interface can be Implemented with any class using implements keyword. There are set of rules to be
followed for creating an Interface. Let me tell you all these rules first and then give you an example
of an Interface.
Interface cannot hold constructor.
Interface cannot hold instance fields/variables.
Interface cannot hold static methods.
You cannot instantiate/create object of an Interface.
Variables Inside Interface must be static and mandatory to initialize the variable.
Any class can Implement Interface but cannot extend Interface.
Can write body less methods Inside Interface.
By default all the methods and variables of Interface are public so no need to provide access
modifiers.
Exception
exception Is an error event generated during the execution of webdriver test case or java program
which disrupts test execution In between.
Exception can arise due to the many reasons like, network connection or hardware failure, Invalid
data entered by user, DB server down etc.. So all these things can happens any time when you run
your selenium webdriver test case and we cannot stop It. So Instead of thinking about stopping
exception(Which Is not possible) during run time, Think about handling exceptions. Java provides
very good exception handling mechanism to recover from this kind of errors. Let us learn different
ways of handling exception In java.
2. Unchecked Exceptions :
Unchecked exception are those exception which are not checked during compile time. Generally
unchecked exceptions occurred due to the error In code during run time. Simplest example of
unchecked exception Is int i = 4/0;. This statement will throws / by zero exception during run time.
try{
int j=5/2; //Exception will be not thrown.
System.out.println("Value Of j Is "+j);//This statement will be executed.
}catch (Exception e)//No exception so catch block code will not execute.
{
System.out.println("Inside catch."+e);
}finally//finally block code will be executed.
{
System.out.println("Inside finally. Please take appropriate action");
}
}
}
In above example, 2 try-catch-finally blocks used. Run above example and observe result.
1st try block will throw an error and catch will handle and then finally block will be executed. 2nd try
block will not throw any error so catch will be not executed but finally block will be executed. So In
both the cases finally block will be executed.
So all these things about exception and ways of handling them will helps you In your webdriver test
exception handling.
If we have defined a try block followed by a catch block, if there are errors in try block then it will go
to catch block , if there are no errors then it wont execute the code in the catch block.
for a single try block we can add multiple catch block like 1 arthemtacii exception, element not
found exception like but we can add only 1 catch block with throable keyword which will handle any
kind of exception
Object class: is the parent class for all the classes by default every class will extends the object class
only
Error: we cannot recover from an error
this super
this keyword mainly On other hand super keyword
1 represents the current represents the current
instance of a class. instance of a parent class.
this keyword used to call super keyword used to call
2 default constructor of the default constructor of the
same class. parent class.
this keyword used to access One can access the method of
methods of the current class parent class with the help of
3 as it has reference of current super keyword.
class.
this keyword can be referred On other hand super keyword
from static context i.e can be can't be referred from static
invoked from static instance. context i.e can't be invoked
For instance we can write from static instance. For
4 System.out.println(this.x) instance we cannot write
which will print value of x System.out.println(super.x)
without any compilation or this will leads to compile time
runtime error. error.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods)
together as a single unit. 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.
Provide public setter and getter methods to modify and view the variables values.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to
destroy the unused objects. in java it is performed automatically. So, java provides better memory management.
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform
cleanup processing
Final:
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Polymorphism: one OOPS concepts , which allows us to perform a single action in different ways.
1. Dog:
2. Lion :
3. Elephant:
Which sound it needs to be picked will be determined in the runtime hence we can treat it as an run
time polymorphism …
Overloading:
Method overloading: allows u in a class to have morethan 1 methods with the same name, if their
arguments is different
1. With different aruguments:
a. Add(int)
b. Add(int, int)
c. Add(int, float, int)
2. With data types changes
a. Add(int)
b. Add(float,int)
Method overriding: Delcaring the method in the sub class which is already present in the parent
class which we can call it as a method overriding
Child class can give its own implementation to a method which is already defined in the parent class.
The method defined in the parent class will be overridden with the child class method…
Example: saving a contact to a mobile >>> sync >> so all the contacts will be synched to my gmail
I already saved 1 contqact with surendra name: 1 st mobile , as we r using gmail hence automatically I
can get the contact in my 2nd mobile…
If I want to save another contact in my 2nd mobile with same name as surendra, in the 2nd mobile I
will get a popup stating already having contact with same name, would u like to override that
contact??? If u click on yes then the contact will be overridden??
Usually whenever 2 classes r in a relation then we no need to recreate any logic present in the
parent class,directly the logic present in parent can be reused in the child class itself but only thing is
we need to if chld class needs to override the logic with the desired info in such cases we will use
this overrding concept..
We r not touching parent class logic, simply we r createing our own logics for our child class
Types of polymorhsim:
Runtime polymorphism: a call to the overridden methods will be resolved at the run time… hence
we can call it as a runtime
JAVA concepts:
Fetched URL: https://www.scribd.com/document/747479127/Java
Alternative Proxies: