Java Notes
Java Notes
What is Java ?
• Java is a simple and most widely used programming language.
• Java is fast, reliable and secure.
• default Package in java : java.lang
• Why we go for java : Platform independent, opensource & multi-threading
• It runs multiple application at a time.
• Components of Java: JDK, JVM, JRE
3 packages :
1. Java.lang – package of predefined
2. Java.util – Collections
3. Java.io - FIles
1.CLASS:
Class is the collection of objects and methods.
Class contains attributes(variables and methods) that are common to all the objects created in a
class.
In our project We are using lots of predefined classes like
1.ChromeDriver
2.FireFoxDriver
3.InternetExplorerDriver
4.Actions
5.Robot
6.Select
7.RemoteWebDriver
2.OBJECT: (Object is the super class of all java)
Object is an instance of a class. Using object,we can able to access the methods in a class.
It is a runtime memory allocation.
3.METHODS:
Set of actions to be performed. Reusable lines of code can be kept inside a method.
We can access the method using object whenever needed.
How to access class properties using object:
object.variable; , object.method();
In real time I’m using lots of methods like :
get(), getTitle(), getCurrentUrl(), getText(), getAttribute()
1.INHERITANCE:
--------------
→ Using inheritance we can access one class properties in another class without multiple object
creation. So we can save memory. Also we can achieve code reusability.
➔ In real time, I m using inheritance concept in base class where i will maintain all reusable
methods. So, by extending base class i can call reusable methods wherever i want.
Single Inheritance:
One child class extends one parent class.
Multilevel Inheritance:
One child class extends more than one parent class in tree level structure.
Multiple Inheritance:
More than one parent class parallelly supporting into one child class. We can't achieve multiple
inheritance in java with extends due to
1.Syntax error/compilation error(After extends keyword we cannot specify more than one class)
2.Priority problem(When parent classes having same method name with same arguments)
extending into same child class,
We can achieve multiple inheritance in interface using implements keyword.
HYBRID INHERITANCE:
It is the combination of hierarchical and multiple inheritance.
HIERARCHIAL INHERITACE:
More than one child class inheriting the same parent class.
3.POLYMORPHISM:
Performing single action in different ways or completing task in different ways.
For example: In realtime I’m overloading println, sendkeys and frame methods
System.out.println("Renu");
System.out.println(123);
System.out.println(12.2);
driver.switchTo.frame(String id);
driver.switchTo.frame(String name);
driver.switchTo.frame(int index);
driver.switchTo.frame(Webelement ); //For same methods i m passing String type,int type and
Webelement type
Notes:
-->A constructor cannot be overridden.
-->Final - declared methods cannot be overridden
-->Any method that is static cannot be used to override.
5. DATA ABSTRACTION:
====================
Hiding the implementation of the program.
(or)
Process of hiding certain details and showing only essential information to the user.
Notes on Interfaces:
-->Interface methods do not have a body - the body is provided by the "implement" class
-->On implementation of an interface, you must override all of its methods
-->Interface methods are by default abstract and public
-->Interface attributes(variables) are by default public, static and final
-->An interface cannot contain a constructor (as it cannot be used to create objects)
STRING:
What is String?
• String is a sequence of characters that’s stored in a character Array. It is a text that is
enclosed in double quotes.
• String is a non- primitive data type, index based class in Java.
• It is a predefined class & it is present in java.lang package
• It stored data based on index position.
• Index starts from 0 to n-1
• Substring() & indexof() supports method overloading.
String Literal:
String str = “Java”;
->Literal string shares the same memory incase of duplicates.
->It is stored in String pool constants(String pool constants present inside heap memory)
->When String declared like this, intern() method on String is called. This method references internal pool
of string objects. If there already exists a string value “Java”, then str will get reference of that string and
no new String object will be created.
When there is a string class why we need to go for string buffer and string builder?
The objects of String class are immutable in nature, i.e. you can’t modify them once they are
created. If you try to modify them, a new object will be created with modified content. This may
cause memory and performance issues if you are performing lots of string modifications in your
code. To overcome these issues, we use StringBuffer and StringBuilder classes.
Immutable String:
• Immutable string once string created, value can't be changed in reference.
Eg: String literals
Mutable String:
• For mutable string, we can change the value in reference.
Eg: StringBuffer, StringBuilder
Advantage:
In a single variable we can store multiple values.
Easier to access data using the index number and easier to manipulate the data
Disadvantages:
It support only similar data types.
Size fixed at compile time.
Memory wastage is high.
For-Loop:
1. It is based on index
2. We can apply conditions
3. Possibility of occurring IndexOutOfBound exception
4. We can able to do backward / forward
5. We can able to get particular value
For-Enchanced:
1. It is based on value
2. We cannot able to apply conditions
3. We cannot able to do backward / forward
4. We cannot able to get particular value
What is Collection ?
• Collection is an interface in java.util package
• Collection Framework is a combination of classes and interface, which is used to store and
manipulate the data in the form of objects. It provides various classes such as ArrayList,
Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set, etc. for this purpose.
• It will support storage of multiple values with dissimilar data types.
• It is dynamic memory allocation.
• No memory wastage like array.
• Iterable is the super class of collection
ArrayList Vector
ArrayList is not synchronized i.e. executed Vector is Synchronous ( executed one by
parallel one)
Not Thread safe Vector is thread safe
Arraylist is not a legacy class Vector is a legacy class
ArrayList increases its size by 50% of the Vector increase its size by doubling the
Array size Array size
LinkedList:
Insertion and deletion is a best one.
Searching/retrieving is a worst.
It makes performance issue.
ArrayList:
In Arraylist retrieve/searching is a best one
In ArrayList deletion and insertion is a worst one because if we delete/insert one index value after all
the index move to forward/backward.
It makes performance issue.
Hash Set:
1. Hash set is implemented using HashTable
2. HashSet allows a null object
3. Hash set use equals method to compare two objects
4. Hash set doesn't now allow a heterogeneous object
5. HashSet does not maintain any order
Tree Set :
1. The tree set is implemented using a tree structure.
2. The tree set does not allow the null object. It throws the null pointer exception.
3. Tree set use compare method for comparing two objects.
4. Tree set allows a heterogeneous object
5. TreeSet maintains an object in sorted order
1. Map interface has key value pair combination where key don’t allow duplicate elements but
values allow duplicates
2. Map doesn’t maintain insertion order
3. Map allows single Null key at most and n number of null values
4. Map implementation classes are HashMap, Linked HashMap, TreeMap, HashTable and
Concurrent HashMap
5. If we want to store the data in the key value pair combination, we can go for Map.
Write the methods to get the key only and value only?
For key only keySet() method is used.
For value only values() method is used.
Entryset() – set<Entry<>>
Keyset() – set
Values () – collection
getKey() – based on datatype
getValue() – based on the datatype
Hash Map:
1. HashMap is non synchronized. It is not-thread safe and can't be shared between many
threads without proper synchronization code.
2. HashMap allows one null key and multiple null values.
3. HashMap is a new class introduced in JDK 1.2.
4. HashMap is fast.
5. We can make the HashMap as synchronized by calling this code Map m =
Collections.synchronizedMap(hashMap);
6. HashMap is traversed by Iterator.
7. Iterator in HashMap is fail-fast.
8. HashMap inherits AbstractMap class.
Hash Table:
1. Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2. Hashtable doesn't allow any null key or value.
3. Hashtable is a legacy class
4. Hashtable is slow.
5. Hashtable is internally synchronized and can't be unsynchronized.
6. Hashtable is traversed by Enumerator and Iterator.
7. Enumerator in Hashtable is not fail-fast.
8. Hashtable inherits Dictionary class.
CONSTRUCTOR: ( Purpose to initialize the variable )
• Whenever you create object for a class, default constructor will automatically invoked since class
name and constructor name are same.
Purpose of constructor:
-->A constructor in Java is a special method that is used to initialize objects.
-->The constructor is called when an object of a class is created.
-->All classes have constructors by default: if you do not create a class constructor yourself, Java creates
one
Rules:
-->constructor name must match the class name.
-->It cannot have a return type (like void)
--> A java constructor cannot be abstract, static, final and synchronized.
Constructor chaining:
• The process of calling one constructor from another constructor with respect to current
object creation is called constructor chaining.
• Keywords : this(), super()
• this() – used to call the current class constructor
• super() – used to call the parent class constructor
• Rules : should be present at the first line of constructor.
1..Abstract
Class level : If we declare class as abstract, we can’t create object
Method level : If we declare method as abstract, we can’t write business logic
Variable level : We cannot able to declare variable as abstract.
2..Static
Class level : We cannot able to declare class as static.
Method level :
In Same Class : When a method is declared as static, we need not create object to call the particular
method. Static method in java belong to the class(not to an object).
In different Class : Using extends keyword we can directly the method, without using the extends
keyword we can call as Classname.methodname()
Variable level :
In Same Class : When a variable is declared as static, we need not create object to call the particular
variable.
In different Class : Using extends keyword we can directly the variable, without using the extends
keyword we can call as Classname.variablename()
3..Final
Class level : If we declare class as final, we can’t create inherit
Method level : If we declare method as final, we can’t override
Variable level : If we declare variable as final, we can’t change the value
What is mean by static keyword in java?
The static keyword is mainly used for memory management.
It is used to share the same variable or method by objects of given class.
TYPES OF VARIABLES:
LOCAL VARIABLE:
• It is declare inside the method block or constructor block
• It gets activated when the control enters to the method
• It gets de-activated when the control enters to the method
• We can’t declare any access specifier
• We need to initialise the value it doesn’t take the default value automatically
• It stored in Stack memory ( temp memory )
Exception:
Exception results in abnormal termination of the program (or)Whenever exception occurs,
program terminates at the particular line itself.
We can avoid the abnormal termination of the program by handling the exception.
Object
|
Throwable
|
Exception
Exception handling:
try block:
The code which is expected to throw exceptions is placed in the try block.
Catch block:
When an exception occurs, that exception occurred is handled by catch block associated with it.
Every try block should be immediately followed either by a catch block or finally block.
finally block:
The finally block follows a try block or a catch block.
A finally block of code will always be executed whether exception occurs or not.
Impossible combination:
-->Throwable class is the super class of all exception.
-->This will handle all the exceptions.so all the child catch blocks will not be used/reached by any code.
-->so while writing the program itself,it will show error.
try
{
}
Catch(Throwable e){
}
Catch(Exception e){
}
Catch(ArithmeticException e){
}
possible combination:
-->we can specify multiple catch blocks
try {
}
Catch(ArithmeticException e){
}
Catch(IndexOutOfBoundException e){
}
Catch(Throwable e){
}
What are the differences between final finally and finalize in java?
Final:
A final class variable whose value cannot be changed.
A final method is declared in class level, they cannot be inherited.
A class declared as final can't be inherited.
Finally:
-It’s a block of statement that definitely executes after the try catch block.
Exception occurs or not, finally block always get executed.
Finalize:
It is method of object class
It is a method that the Garbage collector always calls just before the deletion / destroying the object
which is eligible for garbage collection.
Throw Throws
Throw is a keyword used explicitly to throw Throws keyword is used to declare an
an exception exception
Checked Exceptions can not be propagated Checked Exceptions can be propagated using
using Throw only Throws
Throw is followed by an instance Throws is followed by a class
Throw is used within the method Throws is used in the method signature
We can only throw one exception Multiple exceptions can be declared using
throws
Eg: Public void method()throws IO
exception,SQL Exception
Errors :
These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because we cannot handle the error.
For example, JVM crash, stack overflow, insufficient memory. They are also ignored at the time of
compilation.
Note:
-->A catch block cannot exist without a try statement.
-->It is not compulsory to have finally block whenever a try/catch block is present.
-->The try block cannot be present without either catch block or finally block.
-->No code can be present in between the try, catch, finally blocks.
-->We can have 'n' number of exception throwing statements in try block, once an exception caught
control will be moved to catch block, all the remaining lines won’t be executed.
POM framework:
Page Object Model or Pattern Object Model is a framework or design pattern mainly used to maintain the
locators. In realtime – for every time of your application there will be separate POJO( Plain Old Java
Object) -- we can achieve encapsulation concept (data security or data hiding)
In POM Framework,
POJO class can contain :
1. Default constructor (PageFactory.initElements)
2. Private WebElements
3. Getters to access those webElements outside the class
Types:
1. With pageFactory (StaleElementReferenceException)
2. Without pageFactory
What is Upcasting?
Upcasting is the process of accessing the method of parent class by creating an object for the child
class. It is the typecasting of a child object to a parent object. Upcasting can be done implicitly.
What is downcasting?
Downcasting is the process of accessing the method of the child class by creating an object for the
parent class. It is the typecasting of a parent object to a child object. Downcasting can not be implicit.
A Wrapper class is a class whose objects wraps or contains primitive data types. It provides the
mechanism for an object to be converted to a primitive datatype(Unboxing) or a primitive datatype
to an object(autoboxing).
Eg: Byte, Integer, Short,Long, Float, Double,Character,Boolean
What is mean by File? In which package it is available?
File is a class and it is used to achieve the file operation.
It is available in java.io package.
What are the differences between append and updating the file?
Enumeration:
It is an interface used to iterate only legacy class or interface.
Only iterates in forward direction
Iterator:
It is an interface used to iterate the collection objects
Only iterates in forward direction
List Iterator:
It is an interface used for iterating list type classes
iterates in forward as well as backward direction
What are the methods available in Enumerator, Iterator and List Iterator?
Enumerator Methods:
hasMoreElements();
nextElement();
Iterator Methods:
hasNext();
next();
remove();
ListIterator Methods:
next();
remove();
hasPrevious();
previous();
Different control statements available in java
Break: It is used to terminate the loop
Continue: It is used to skip the current iteration.
While: It is entry check loop.
Do While: It is a exit check loop.
If : Executes only when the condition becomes true.
if else : Executes the else part when the condition becomes false and executes if part when condition
becomes true
What are the difference between equals() & hashcode()?
equals:
-------
Used to compare the two string.
Hashcode:
----------
Used to return the address where it stored.
Replace()
• We can use both single quotes and double quotes
• Not support regex
ReplaceAll()
• We can use only double quotes
• Support regex
>>Method Chaining
• We can call one method by another method by this()
• It reduce object creation / memory space
>>If we’ve two interface has same method & implement both interface in one class what will happen?
• Which interface you gave first, compiler will take the firstone
2 Types
• Upcasting : Lower data --------> Higher data
Eg : WebDriver driver = new ChromeDriver();
• Downcasting : Higher data --------> Lower data
Eg : TakesScreenShot s = (TakesScreenshot)driver;
>>Deserialization
• Byte Stream convert to object (java)
• Eg : FileInputStream
>> Serialization
• Object (java) to Byte Stream convert
• Eg : FileOutputStream
>>Auto Boxing
• Datatype→Wrapper class ( object )
• Eg : int ---> Integer
>> Un Auto-Boxing
• Wrapper class ( object ) → Datatype
• Eg : Integer --> int
>> CharAt() : return type int as well as char