Java Study

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 61

jHow to work Java Properties file examples

Load a properties file


Properties prop = new Properties();
try {
InputStream input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
Write to properties file
Properties prop = new Properties();
try {
OutputStream output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
In which condition finally block is not executed in java
If the JVM exits while the try or catch code is being executed, then the finally block may not
execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the
finally block may not execute

Can we override static method in Java?


No, you cannot override static method in Java because method overriding is based upon dynamic
binding at runtime. Usually static methods are bonded using static binding at compile time before
even program runs.

Can we overload static methods?


The answer is ‘Yes’. We can have two or more static methods with same name, but differences in
input parameters. For example, consider the following Java program.
Public class Calculation{
public static void sum(int a,int b)
{
System.out.println(a+b);
}
public static void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation.sum(2,3)
Calculation.sum(2,3,4)
}
}

Output:
5
9

What is Static Block - Static block is used for initializing the static variables. static block helps to
initialize the static data members, just like constructors help to initialize instance members.
This block gets executed when the class is loaded in the memory.
class Test{
static int num;
static String mystr;
//First Static block
static{
System.out.println("Static Block 1");
num = 68;
mystr = "Block1";
}
//Second static block
static{
System.out.println("Static Block 2");
num = 98;
mystr = "Block2";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
Output:
Static Block 1
Static Block 2
Value of num: 98
Value of mystr: Block2

Can we have multiple static blocks for same static variables- yes we can have multiple
static block for same static variable but last block value will be final value of static variables

Difference between static block and constructor


static blocks
The static blocks are executed at the time of class loading.
The static blocks are executed before running the main () method.
The static blocks don't have any name in its prototype.
If we want any logic that needs to be executed at the time of class loading that logic needs to
placed inside the static block so that it will be executed at the time of class loading.

Constructor
A Constructor will be executed while creating an object of class in Java.
The name of a constructor must be always the same name as a class.
The constructor gets executed automatically when the object is created.

Can we use data provider to fetch data from excel -Yes we can Data provider returns a two-
dimensional JAVA object 
http://www.seleniumeasy.com/testng-tutorials/import-data-from-excel-and-pass-to-data-provider
It can be used when one Testcase has to execute with different set of data

public class TestDDT {


// this will take data from dataprovider which we created
@Test(dataProvider = "testdata")
public void TestFireFox(String uname, String password) {
// Open browser
WebDriver driver = new FirefoxDriver();
// Maximize browser
driver.manage().window().maximize();
// Load application
driver.get("http://www.facebook.com");
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
// clear email field
driver.findElement(By.id("email")).clear();
// Enter usename
driver.findElement(By.id("email")).sendKeys(uname);
// Clear password field
driver.findElement(By.id("pass")).clear();
// Enter password
driver.findElement(By.id("pass")).sendKeys(password);
}
// this is DataProvider which actually feed data to our test cases here I have
// taken 2 D array with 2 rows and 2 column it means. It will run our test case two
times because we have taken 2 rows. While first iteration this will pass username and
password to test case and in second iteration perform the same for second rows
@DataProvider(name = "testdata")
public Object[][] TestDataFeed() {
//Create object array with 2 rows and 2 column-first parameter is row and second is
column Object[][] facebookdata = new Object[2][2];
// Enter data to row 0 column 0
facebookdata[0][0] = "Selenium1@gmail.com";
// Enter data to row 0 column 1
facebookdata[0][1] = "Password1";
// Enter data to row 1 column 0
facebookdata[1][0] = "Selenium2@gmail.com";
// Enter data to row 1 column 0
facebookdata[1][1] = "Password2";
// return arrayobject to testscript
return facebookdata;
}
}

Can we create object of abstract class and interface


No, We cannot
Abstract class has not implemented method so, we cant create the object" "The word 'Abstract'
instruct the compiler to not create an object of the class"
You cannot create an instance of an abstract class because it does not have a complete
implementation.
No, we can’t create an object of an Interface ,we use an Interface to hide the implementations
from user.
Interface contains only abstract methods and as abstract methods do not have a body (of
implementation code) we can not create an object without constructor also 

Redefining base class static method in the subclass is called method hiding in Java.
Redefining base class instance method in the subclass is called method overrides in Java.
This is the difference between overrides and hiding,
1. If both method in parent class and child class are an instance method, it called
overrides.
2. If both method in parent class and child class are static method, it called hiding.
Method hiding is the concept that a method in a base class is hidden from view within a
sub-class.

public class Animal {


public static void hide() {
System.out.println("The hide method in Animal.");
}
public void override() {
System.out.println("The override method in Animal.");
}
}
The second class, a subclass of Animal, is called Cat:
public class Cat extends Animal {
public static void hide() {
System.out.println("The hide method in Cat.");
}
public void override() {
System.out.println("The override method in Cat.");
}

public static void main(String[] args) {


Cat myCat = new Cat();
Animal myAnimal = (Animal)myCat;
myAnimal.hide();
myAnimal.override();
}
}
The Cat class overrides the instance method in Animal called override and hides the class method
in Animal called hide

Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It
can be physical and logical.
An object is an instance of a class. You can create many instances of a class.

Class
Collection of objects is called class. It is a logical entity.

PIEA
Polymorphism- compile time and run time
Inheritance- Single level, Multi-level(not supported), Hierarchical
Encapsulation – binds together code and the data it manipulates
Abstraction- Abstract class and Interface

What is polymorphism?
Ans) The ability to define a function in multiple forms is called Polymorphism. In java, c++ there are two
types of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).
Polymorphism
When one task is performed by different ways i.e. known as polymorphism
Polymorphism definition is that Poly means many and morphs means forms

Static Polymorphism (compile time polymorphism/ Method overloading/Early binding)


The ability to execute different method implementations by altering the argument used with the method
name is known as method overloading. In below program we have three print methods each with different
arguments. When you properly overload a method, you can call it providing different argument lists, and the
appropriate version of the method executes.

By changing the no. of arguments


1. class Calculation{  
2.   void sum(int a,int b){System.out.println(a+b);}  
3.   void sum(int a,int b,int c){System.out.println(a+b+c);}  
4.   
5.   public static void main(String args[]){  
6.   Calculation obj=new Calculation();  
7.   obj.sum(10,10,10);  
8.   obj.sum(20,20);  
9.   }  
10. }  

by changing data type of argument


Void sum(double a,double b){System.out.println(a+b);}  

Dynamic Polymorphism (run time polymorphism/ Method Overriding/late binding)


When you create a subclass by extending an existing class, the new subclass contains data and methods that were
defined in the original superclass. In other words, any child class object has all the attributes of its parent.
Sometimes, however, the superclass data fields and methods are not entirely appropriate for the
subclass objects; in these cases, you want to override the parent class members.

1. class Bank{  
2. int getRateOfInterest(){return 0;}  
3. }  
4.   
5. class SBI extends Bank{  
6. int getRateOfInterest(){return 8;}  
7. }  
8.   
9. class ICICI extends Bank{  
10. int getRateOfInterest(){return 7;}  
11. }  
12. class AXIS extends Bank{  
13. int getRateOfInterest(){return 9;}  
14. }  
15.   
16. class Test3{  
17. public static void main(String args[]){  
18. Bank b1=new SBI();  
19. Bank b2=new ICICI();  
20. Bank b3=new AXIS();  
21. System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());  
22. System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());  
23. System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());  
24. }  
25. }  

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
What is inheritance?
Ans) Inheritance allows a Child class to inherit properties from its parent class.
In Java this is achieved by using extends keyword.
Only properties with access modifier public and protected can be accessed in child class.
When one object acquires all the properties and behaviors of parent object i.e. known as inheritance.
Advantages- Inheritance is mainly used for code Reusability, achieve runtime polymorphism (overriding /
dynamic binding), Data hiding
Inheritance:
Is the process by which one object acquires the properties of another object.

What is multiple inheritance and does java support?


Ans) If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not
allow to extend multiple classes, to overcome this problem it allows to implement multiple Interfaces.
problem is the diamond problem that occurs in multiple inheritance.
Encapsulation:
Binding (or wrapping) code and data together into a single unit is known as encapsulation.A java class
is the example of encapsulation.
Encapsulation means putting together all the variables (instance variables) and the methods into a single unit
called Class
Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside
interference and misuse.
Meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this,
you must:
a) declare class variables/attributes as private i.e. declare all the data members of the class
private
b) provide public get and set methods to access and update the value of a private variable

public class Person {


private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}}

For example: capsule, it is wrapped with different medicines.


It also means hiding data and methods within an Object.
We can create a fully encapsulated class in java by making all the data members of the class
private. The Java Bean class is the example of fully encapsulated class.
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than
100 only, you can write the logic inside the setter method.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the
user. For example: phone call, we don't know the internal processing.
it shows only important things to the user and hides the internal details for example sending sms, you just
type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods

Key Differences Between Encapsulation and Data Hiding


1. Encapsulation deals with hiding/Reducing the complexity of a program in order to make the application
more user-friendly . On the other hand, data hiding deals with the security of data in a program.
2. Encapsulation focuses on wrapping (encapsulating) the complex data in order to present a
simpler view for the user. On the other hand, data hiding focuses on restricting the use of data,
intending to assure the data security.
3. In encapsulation data can be public or private but, in data hiding, data must be private only.
4. Data hiding is a process as well as a technique whereas, encapsulation is subprocess in data
hiding.

What declarations are required for every Java application?


Ans: A class and the main( ) method declarations.
What are the two parts in executing a Java program and their purposes?
Ans: Two parts in executing a Java program are: Java Compiler and Java Interpreter.
The Java Compiler is used for compilation and the Java Interpreter is used for execution of the
application.

What is the return type of program’s main( ) method? Ans : void

What is the argument type of program’s main( ) method? Ans : string array.
initialization -Very first time you assign a variable with value is called as initialization

What are the kinds of variables in Java? What are their uses?
Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable.
Local variables are used inside blocks as counters or in methods or constructors as temporary variables
and are used to store information needed by a single method. The scope of these variables exists only within
the block in which the variable is declared. Initialization of Local Variable is Mandatory. Local variable
destroyed after exiting from the block or when the call returns from the function
Instance variables are non-static variables and are declared in a class outside any method, constructor
or block. As instance variables are declared in a class, these variables are created when an object of the class is
created and destroyed when the object is destroyed. Instance Variable can be accessed only by creating
objects. it is used to define attributes or the state of a particular object and are used to store information
needed by multiple methods in the objects.
Class variables is also known as static variables and These variables are declared similarly as instance
variables, the difference is that static variables are declared using the static keyword within a class
outside any method constructor or block. Those are global to a class and to all the instances of the class
and are useful for communicating between different objects of all the same class or keeping track of global
states.
we can only have one copy of a static variable per class irrespective of how many objects we create.
If we access the static variable like Instance variable (through an object), the compiler will show the
warning message and it won’t halt the program. The compiler will replace the object name to class
name automatically.
If we access the static variable without the class name, Compiler will automatically append the class
name.

1. class A{  
2. int data=50;//instance variable  
3. static int m=100;//static variable  
4. void method(){  
5. int n=90;//local variable  
6. }  
7. }
assignment operator =. And compare==

What is an array?
Ans: array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we store
similar elements. We can store only fixed set of elements in a java array. An array is an object that stores a
list of items int arr[];

Addition operator (+) operator is to create and concatenate string.


What are primitive data types?A primitive type is predefined by the language and is named by a reserved
keyword. 8 primitive type byte, short, int, long, float, double, Boolean, char
What is static variable? Ans: Static variables are shared by all instances of a class.
What are operators and what are the various types of operators available in Java?
Ans: Operators are special symbols used in expressions.
Arithmetic operators,
Assignment operators, =
Increment & Decrement operators, --++
Logical operators, OR (|), AND (&), XOR (^) AND NOT (~).
Bitwise operators,
Comparison/Relational operators and
Conditional operators
What are difference between break and continue?
Ans: The break keyword halts the execution of the current loop and forces control out of the loop.
The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.
A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do
statement will always execute the body of a loop at least once.

The new operator creates a single instance named class and returns a reference to that object.

What is mean by garbage collection?


Ans: When an object is no longer referred to by any variable, Java automatically reclaims memory used by that
object. This is known as garbage collection.
finalize () method is used to garbage collect an object
getClass( ) method can be used to find out what class the belongs to.

What is casting? Casting is used to convert the value of one type to another.

Can we overload main() method?


Yes, by method overloading. You can have any number of main methods in a class by method overloading.

why java main method is static?


Ans) because object is not required to call static method if it were non-static method, jvm create object first then
call main() method that will lead the problem of extra memory allocation.
Java final variable - If you make any variable as final, you cannot change the value of final variable(It
will be constant).
Java final method - If you make any method as final, you cannot override it. But we can overload it
Why - Final cannot be overridden because that is the purpose of the keyword, something that cannot be
changed or overridden.
Java final class -If you make any class as final, you cannot extend it.

An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction and multiple inheritance in Java. There
can be only abstract methods in the java interface not method body.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritance.
 Interface cannot be instantiated
 Abstract class also cannot be instantiated

Abstraction: Hiding the internal implementation of the feature and only showing the
functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract
class and interface are used for abstraction.

when to use abstract class and interface in java


Abstract Class : use it when we may want to override some of functions in
child class
Abstract class is used when you know something and rely on others for what you
don't know.(here it is partial abstraction as some of the things you know and some
you don't know.)

Interface : use it when you want to change each and every method of it in
child class.
interface is used when you want to define a contract and you don't know anything
about implementation. (here it is total abstraction as you don't know anything.)
 In java application, there are some related classes that need to share some lines of
code then you can put these lines of code within abstract class and this abstract class
should be extended by all these related classes.

if you have some common methods that can be used by multiple classes go
for abstract classes. Else if you want the classes to follow some definite
blueprint go for interfaces.

Now let’s say we have an application that uploads different kind of files. So we
could have an Abstract class called FileUpload which has an abstract method
uploadFile defined. Now we can extend this class for different kind of files-
DocumentUpload for documents, ImageUpload for Images, VideoUpload for Videos
which implement the uploadFile method in their own way. The advantage here is
that tomorrow if this application has to upload Audio files, we could simply extend
FileUpload for a new class AudioUpload. In this case your abstract class is provide a
base implementation for uploading files.

Also in future let’s say, you want to upgrade the application to download files too,
you can add another method downloadFile, which then can be defined in the
derived class. One more thing is that unlike an interface, where all methods must
be public, here in an Abstract class, you can add private, protected methods too.
The main advantage though is that unlike an interface, you do not have to define
any new method you add in an abstract class, to it’s base class.

Following is an implementation of abstract class in Java

1. abstract class animals


2. {
3. // They all love to eat. So let's implement them for everybody
4. void eat()
5. {
6. System.out.println("Eating...");
7. }
8. // The make different sounds. They will provide their own implementation.
9. abstract void sound();
}
10.
11. class dog extends animals
12. {
13. void sound()
14. {
15. System.out.println("Woof Woof");
16. }
17. }
18.
19. class cat extends animals
20. {
21. void sound()
22. {
23. System.out.println("Meoww");
24. }
25. }

Following is an implementation of interface in Java

interface animalSound(){
void sound();
}
class cat implements animalSound (){
void sound(){
syso("myav myav")

}}

1. interface Shape
2. {
3. void display();
4. double area();
5. }
6.  
7. class Rectangle implements Shape
8. {
9. int length, width;
10. Rectangle(int length, int width)
11. {
12. this.length = length;
13. this.width = width;
14. }
15. @Override
16. public void display()
17. {
18. System.out.println("****\n* *\n* *\n****");
19. }
20.
@Override
21. public double area()
22. {
23. return (double)(length*width);
24. }
25. }
26.  
27. class Circle implements Shape
28. {
29. double pi = 3.14;
30. int radius;
31. Circle(int radius)
32. {
33. this.radius = radius;
34. }
35. @Override
36. public void display()
37. {
38. System.out.println("O"); // :P
39. }
40. @Override
41. public double area()
42. {
43. return (double)((pi*radius*radius)/2);
44. }
45. }

Abstract class can have protected , public abstract methods,


Interface can have only public abstract methods i.e. by default.

Abstract class can extend only one class or one abstract class at a
time, Interface can extend any number of interfaces at a time.

A class can extend only one abstract class at a time, A class can
implement any number of interfaces at a time.

Abstract class can be inherited by a class or an abstract class.


Interfaces can be extended only by interfaces. Classes has to
implement them instead of extend.

In abstract class, the keyword ‘abstract’ is mandatory to declare a


method as an abstract. In interfaces, the keyword ‘abstract’ is
optional to declare a method as an abstract because all the methods
are abstract by default

Abstract class vs interface


Difference No.1:
Abstract class can extend only one class or one abstract class at a
time
class Example1{
public void display1(){
System.out.println("display1 method");
}
}
abstract class Example2{
public void display2(){
System.out.println("display2 method");
}
}
abstract class Example3 extends Example1{
abstract void display3();
}
class Example4 extends Example2{
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example4 obj=new Example4();
obj.display3();
}
}
Output:
display3 method
Interface can extend any number of interfaces at a time 
//first interface
interface Example1{
public void display1();
}
//second interface
interface Example2 {
public void display2();
}
//This interface is extending both the above interfaces
interface Example3 extends Example1,Example2{
}
class Example4 implements Example3{
public void display1(){
System.out.println("display2 method");
}
public void display2(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example4 obj=new Example4();
obj.display1();
}
}
Output:
display2 method
Difference No.2:
Abstract class can be inherited by a class or an abstract class
class Example1{
public void display1(){
System.out.println("display1 method");
}
}
abstract class Example2{
public void display2(){
System.out.println("display2 method");
}
}
abstract class Example3 extends Example2{
abstract void display3();
}
class Example4 extends Example3{
public void display2(){
System.out.println("Example4-display2 method");
}
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example4 obj=new Example4();
obj.display2();
}
}
Output:
Example4-display2 method
Interfaces can be extended only by interfaces. Classes has to
implement them instead of extend
interface Example1{
public void display1();
}
interface Example2 extends Example1{
}
class Example3 implements Example2{
public void display1(){
System.out.println("display1 method");
}
}
class Demo{
public static void main(String args[]){
Example3 obj=new Example3();
obj.display1();
}
}
Output:
display1 method
Difference No.3
Abstract class can have both abstract and concrete methods
abstract class Example1 {
abstract void display1();
public void display2(){
System.out.println("display2 method");
}
}
class Example2 extends Example1{
public void display1(){
System.out.println("display1 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
Interface can only have abstract methods, they cannot have
concrete methods
interface Example1{
public abstract void display1();
}
class Example2 implements Example1{
public void display1(){
System.out.println("display1 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
Difference No.4
A class can extend only one abstract class at a time
abstract class Example1{
public void display1(){
System.out.println("display1 method");
}
}
abstract class Example2{
abstract void display2();
}
class Example3 extends Example1{
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example3 obj=new Example3();
obj.display3();
}
}
A class can implement any number of interfaces at a time
interface Example1{
public void display1();
}
interface Example2{
public void display2();
}
class Example3 implements Example1,Example2{
public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example3 obj=new Example3();
obj.display1();
obj.display3();
}
}
Difference No.5
In abstract class, the keyword ‘abstract’ is mandatory to declare a
method as an abstract
abstract class Example1{
public abstract void display1();
}

class Example2 extends Example1{


public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
In interfaces, the keyword ‘abstract’ is optional to declare a method
as an abstract because all the methods are abstract by default
interface Example1{
public void display1();
}
class Example2 implements Example1{
public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
Difference No.6
Abstract class can have protected abstract and public abstract
methods
abstract class Example1{
protected abstract void display1();
public abstract void display2();
public abstract void display3();
}
class Example2 extends Example1{
public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
public void display3(){
System.out.println("display3 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
Interface can have only public abstract methods i.e. by default
interface Example1{
void display1();
}
class Example2 implements Example1{
public void display1(){
System.out.println("display1 method");
}
public void display2(){
System.out.println("display2 method");
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}
Difference No.7
Abstract class can have static,not-static, final, non-final or static
final variables with any access specifier
abstract class Example1{
private int numOne=10;
protected final int numTwo=20;
public static final int numThree=500;
public void display1(){
System.out.println("Num1="+numOne);
}
}
class Example2 extends Example1{
public void display2(){
System.out.println("Num2="+numTwo);
System.out.println("Num2="+numThree);
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
obj.display2();
}
}
Interface can have only static final (constant) variable i.e. by default
interface Example1{
int numOne=10;
}
class Example2 implements Example1{
public void display1(){
System.out.println("Num1="+numOne);
}
}
class Demo{
public static void main(String args[]){
Example2 obj=new Example2();
obj.display1();
}
}

Difference between Abstract methods and concrete method


Abstract methods are those which need to be implemented in subclass/child class. Abstract
methods are only defined in superclass/parent class(Abstract class) but with no body.
A method which is not abstract i.e. if a methods definition is given in the same class its
declared is called concrete. 

* we can not use non static variables in static method

difference between non-static and static variable


Non-static variable Static variable

These variables are preceded by static


These variable should not be preceded by
keyword.
any static keyword Example:
Example
1 class A
class A
{
{
int a;
static int b;
}
}

Memory is allocated for these variable Memory is allocated for these variable at the
2
whenever an object is created time of loading of the class.

3 Memory is allocated multiple time whenever Memory is allocated for these variable only
once in the program.
a new object is created.

Global variable - Memory is allocated at the


Non-static variable also known as
4 time of loading of class so that these are also
instance variable while because memory
known as class variable.
is allocated whenever instance is created.

Static variable are common for every object


that means there memory location can be
5 Non-static variable are specific to an object
sharable by every object reference or same
class.

Non-static variable can access with Static variable can access with class
object reference. reference.
6 Syntax Syntax

obj_ref.variable_name class_name.variable_name

A static method belongs to the class and a non-static method belongs to an object of a
class. I am giving one example how it creates difference between outputs.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;

public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}

public int getCount1() {


return count1;
}

public void setCount1(int count1) {


this.count1 = count1;
}

public static int countStaticPosition() {


count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}

public class StaticNonStaticCheck {


public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is "
+DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is "
+DifferenceBetweenStaticAndNonStatic.countStaticPosition());

System.out.println("next case: ");


System.out.println(" ");
}
}
}
Now output will be
static count position is 0
static count position is 1
static count position is 1
next case:

static count position is 1


static count position is 1
static count position is 2
next case:

static count position is 2


static count position is 1
static count position is 3
next case:
Static methods are useful if you have only one instance (situation, circumstance)
where you're going to use the method, and you don't need multiple copies
(objects).
Non-static methods are used if you're going to use your method to create multiple
copies/instances.
public class JavaTester {
public static void main(String args[]) {
Tiger.roar();
Tiger tiger = new Tiger();
tiger.eat();
}
}
class Tiger {
public void eat(){
System.out.println("Tiger eats");
}
public static void roar(){
System.out.println("Tiger roars");
}
}
Output
Tiger roars
Tiger eats

Sr. Key Static method Non-Static method


No
.

Access A static method can access only A non-static method can


1 static members and can not access both static as well as
access non-static members. non-static members.

Binding Static method uses complie Non-static method uses run


2 time binding or early binding. time binding or dynamic
binding.

Overriding A static method cannot be A non-static method can be


3 overridden being compile time overridden being dynamic
binding. binding.

Memory Static method memory A non-static method memory


allocation allocation happens once. allocation happens when
4 method is invoked and memory
is deallocated once method is
executed completely.

5 Keyword A static method is declared A normal method is not


using static keyword. required to have any special
Sr. Key Static method Non-Static method
No
.

keyword.
Constructor in java 
Constructor in java is a special type of method that is used to initialize the object.
Constructor must not have return type
Constructor is invoked implicitly.
Constructor name must be same as the class name.
If there is no constructor in a class, compiler automatically creates a default constructor.

Types of constructors

Default Constructor
Default constructor provides the default values to the object like 0, null etc. depending on the type.

Parameterized Constructor
Parameterized constructor is used to provide different values to the distinct objects.
1. Class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
13. Student4 s2 = new Student4(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }

Data Type
Primitive data type- Boolean,byte,short,Int,float,char,long ,double
Non Primitive data type-String, array, class,interface
1 byte = 8 bits

Exa
mple:
Boolean one = false
char letter= 'A'
byte a = 10, byte b = -20
short s = 10000, short r = -5000
int a = 100000, int b = -200000
long a = 100000L, long b = -200000L
float f1 = 234.5f
double d1 = 12.3
 Widening Casting(Implicit)
Automatic Type casting take place when,
 the two types are compatible
 the target type is larger than the source type
 Narrowing Casting(Explicitly done)
When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit
type casting.

Example
public class TypeCasting {
public static void main(String[] args) {
int i = 100;
float f = i; //no explicit casting required
System.out.println(i+"=="+f);
//output -> 100==100.0
double d = 100.04;
int j =(int)d; // explicit casting required
System.out.println(d+"==="+j);
//output -> 100.04===100
}
}
void setUp() - Sets up the fixture, for example, open a network connection.
void tearDown() - Tears down the fixture, for example, close a network connection.

How to run java program


Javac abc.java- for compilation
Java abc - to run program
Compilation and execution process of java program
Compilation
During compile time Java program is compiled using Java compiler and converts java
code into byte code file which having extension as “.class”.
Execution
Then “.class” file is loaded with class loader. Class loader is part of JVM which loads
byte code file i.e. .class file. Then there is another component Bytecode verifier which
checks loaded bytecode are valid and does not violates any security
Then there is interpreter which reads bytecode stream and will execute program
Jdk= java compiler+jre [jvm+lib files]
 JDK = JRE + Development tools. JRE= JVM +Library classes
 JDK – Java Development Kit (in short JDK) is Kit which provides the environment
to develop and execute(run) the Java program. JDK is a kit(or package) which
includes two things
1. Development Tools(to provide an environment to develop your java
programs)
2. JRE (to execute your java program).
The JDK is a superset of the JRE, and contains everything that is in the JRE, plus
tools such as the compilers and debuggers necessary for developing applets and
applications
Note : JDK is only used by Java Developers.
 JRE – Java Runtime Environment (to say JRE) is an installation package which
provides environment to only run(not develop) the java program(or application)onto
your machine. JRE is only used by them who only wants to run the Java
Programs i.e. end users of your system.
provides the libraries, the Java Virtual Machine, and other components to run
applets and applications written in the Java programming language.
 JVM – Java Virtual machine(JVM) is a very important part of both JDK and JRE
because it is contained or inbuilt in both. Whatever Java program you run using JRE or
JDK goes into JVM and JVM is responsible for executing the java program line by
line hence it is also known as interpreter. is the virtual machine that runs the Java
bytecodes. The JVM doesn't understand Java source code,

Every word in the public static void main statement has got a meaning to the JVM.
1. public: It is a keyword and denotes that any other class (JVM) can call the main()
method without any restrictions. It means that you can call this method from outside
of the class you are currently in.
2. static: It is a keyword and denotes that any other class (JVM) can call the main()
method without the help of an object. When the JVM makes call to the main
method there is no object existing for the class being called therefore it has to have
static method to allow invocation from main method
3. void: It is keyword, denotes that main() method doesn’t return a value.
4. main(): It is the name of the method. This name is fixed and as it's called by the JVM
as entry point for an application.
5. String args[]: The parameter is a String array by name args. The string array is used
to access command-line arguments. args receives any command-line arguments present
when the program is executed.
Whether we pass right now command-line arguments or not, we must have the string
array as parameter as it is the part of syntax.

System.out.println(e);- only showing the exception. e.g.java.lang.ArithmeticException:/by zero 


e.printStackTrace(); :- showing the details of exception and where to cause exception in program
with line number e.g. java.lang.ArithmeticException: / by zero at test.Test.main(Test.java:7)

exception handling in java is mechanisms to handle the runtime errors so that normal flow of
the application can be maintained. Exception is an event that terminates the normal flow of
program, Exceptions may occur at run time or compile time.
Exception Information displaying methods are:
1.printStackTrace(): prints the stack trace ,line number, exception name and description.
2.toString(): returns a text message describing the exception name and description.
3.getMessage(): displays the description of exception
Difference between Exception and Error:
Exception: Exception occurs in the programmers code which can be handled and resolvable.
---->>>>>>> Example: AritmeticException, DivideByZeroException, NullPointerException,
ClassNotFoundException etc
Error: Errors are not resolvable by programmer. Error occurs due to lack of system
resources
---->>>>>>> Example: Stack over flow, hardware error, JVM error etc.

package com.seleniumeasy.ExceptionHandling;
public class ExceptionMethods {
public static void main(String[] args) {
try{
int x=0;
int y=10;
System.out.println(y/x);
}
catch(ArithmeticException ae){
ae.printStackTrace();
System.out.println(ae.toString());
System.out.println(ae.getMessage());
}
}
}
output:
java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
/ by zero
The Throwable class is the superclass of all errors and exceptions in the Java language. 
Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

The below are the five keywords which plays the role in Exception handling : -
1. try
2. catch
3. finally
4. throw
5. throws
The key word throws is used in method declaration, this specify what kind of
exception[Throwable class] we may expect from this method.
The key word throw is used to throw an object that is instance of class Throwable

Diff between throw and throws


Throws clause is used to declare an exception, which means it works similar to the try-catch
block. On the other hand throw keyword is used to throw an exception explicitly.

Throws is used in method signature to declare the exceptions Throw keyword is used in the
method body to throw an exception
you can handle multiple exceptions by declaring them using throws keyword but
You can throw one exception at a time
Throw:
void myMethod() {
try {
//throwing arithmetic exception using throw
throw new ArithmeticException("Something went wrong!!");
}
catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}
Throws:
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
//Statements
}

Java try block


Java try contains the code that might throw an exception. It must be used within the
method.
Java try block must be followed by either catch or finally block.
1. try{  
2. //code that may throw exception  
3. }catch(Exception_class_Name ref){}
Or
try{  
1. //code that may throw exception  
2. }finally{}  
Java catch block
- Java catch block is used to handle the Exception.
- It must be used after the try block only.
- You can use multiple catch block with a single try.

Rule: At a time only one Exception is occurred and at a time only one catch
block is executed.
Rule: All catch blocks must be ordered from most specific to most general i.e.
catch for ArithmeticException must come before catch for Exception.
finally block:
finally block will executes irrespective of exception raises or not and exception handled or not. finally
block appears after catch block or after try block when there is no catch block. we cannot place middle of try
and catch block. cleanup code like open files or database connections should be placed in finally block.
Note:
1. try always follow catch or finally block.
2. there may be nested try, multiple catch blocks for each try but there should be only one finally block.
3. In between try catch there should not be finally block.
4. try with finally is possible without catch.
5. there should not be any code in between try, catch or finally block
The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class.
static String college ="ITS"
In java, this is a reference variable that refers to the current object.
The this keyword can be used to refer current class instance variable Constructor
Student(int rollno,String name,String course){  
this.rollno=rollno;  
this.name=name;  
this.course=course;  
}  
The super keyword in java is a reference variable which is used to refer immediate
parent class object.
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
class Animal{  
String color="white";  
}  
class Dog extends Animal{  
String color="black";  
void printColor(){  
System.out.println(color);//prints color of Dog class  
System.out.println(super.color);//prints color of Animal class  
}  }
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

There are 4 types of java access modifiers:


1. Private - The private access modifier is accessible only within class
2. Default -The default modifier is accessible only within package.
3. Protected - The protected access modifier is accessible within package and outside
the package but through inheritance only.
4. Public - The public access modifier is accessible everywhere.
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
You can perform many operations together so it saves time.
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Java I/O package
Java I/O (Input and Output) is used to process the input and produce the output. The
java.io package contains all the classes required for input and output operations. We can
perform file handling in java by Java I/O API.

JDBC
In Sql connection manager we will get port and hostname details
Steps
1.Download Microsoft JDBC driver for SQL server
2.We have to add that driver jar file in our project or we can use maven
dependency directly if project in maven based project
3.Register jdbc driver for sql server
4.Establish connection using connection string
5.Perform operation
The syntax of database URL for SQL Server is as follows:
jdbc:sqlserver://[serverName[\instanceName][:portNumber]]
[;property=value[;property=value]]
Where:
serverName: host name or IP address of the machine on which SQL server is running.
instanceName: name of the instance to connect to on serverName. The default instance is
used if this parameter is not specified.
portNumber: port number of SQL server, default is 1433. If this parameter is missing, the
default port is used.
property=value: specify one or more additional connection properties. To see the properties
specific to SQL server, visit Setting the Connection Properties.
NOTE:SQL Server has two authentication modes:
Windows authentication: using current Windows user account to log on SQL Server. This
mode is for the case both the client and the SQL server are running on the same machine.
We specify this mode by adding the property integratedSecurity=true to the URL.
e.g.jdbc:sqlserver://localhost;integratedSecurity=true;
SQL Server authentication: using a SQL Server account to authenticate. We have to specify
username and password explicitly for this mode.
e.g. jdbc:sqlserver://dbHost\sqlexpress;user=sa;password=secret
Connect to a named database testdb on localhost using Windows authentication:
jdbc:sqlserver://localhost:1433;databaseName=testdb;integratedSecurity=true;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn =
DriverManager.getConnection("jdbc:sqlserver://HOSP_SQL1.company.com;user=nam
e;password=abcdefg;database=Test");
System.out.println("test");
//Create statement
Statement sta = conn.createStatement();
String Sql = "select * from testing_table";
ResultSet rs = sta.executeQuery(Sql);
//iterate through result set
while (rs.next()) {
//Retrieve by column name
System.out.println(rs.getString("txt_title"));
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("firstname"));
}
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}

An array of characters works same as java string. String is an object that represents a


sequence of characters. 
The java String is immutable i.e. it cannot be changed. Whenever we change any string,
a new instance is created. For mutable string, you can use StringBuffer and StringBuilder
classes.

Why string are immutable in java


 When a string is created and if the string already exists in the String pool, the reference of
the existing string will be returned, instead of creating a new object and returning its
reference. There are 2 reference variables,all referes to one object "Old Value".If one
reference variable changes the value of the object, it will be affected to all the reference
variables. That is why string objects are immutable in java.

1. String string1 = "abcd"; 


2. String string2 = "abcd"; // wont create new instance in memory
Now if Strings are mutable then updating the value of string1 to some other value then it
will update to value of string 2 as well that’s why it

char charAt(int index) - returns char value for the particular index
int length()- returns string length
String substring(int beginIndex) - returns substring for given begin index
String substring(int beginIndex, int endIndex) - returns substring for given begin index and
end index
boolean equals(Object another) - Checks the equality of string with object
boolean isEmpty() - checks if string is empty
String concat(String str) - concatinates specified string
String replace(CharSequence old, CharSequence new) - replaces all occurrences of specified
CharSequence
static String equalsIgnoreCase(String another) - compares another string. It doesn't check
case.

String[] split(String regex) - returns splitted string matching regex – used for splitting string
into substring based on given parameter
String[] split(String regex, int limit) - returns splitted string matching regex and limit
int indexOf(int ch) -returns specified char value index
int indexOf(String substring, int fromIndex) - returns specified substring index starting with
given index
String trim() - removes beginning and ending spaces of this string.
static String valueOf(int value) - converts given type into string. It is overloaded.

// Java code to illustrate different constructors and methods


// String class.
import java.io.*;
import java.util.*;
class Test
{
    String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");
// Returns the number of characters in the String.
System.out.println("String length = " + s.length());
// Returns the character at ith index.
System.out.println("Character at 3rd position = " + s.charAt(3));
// Return the substring from the ith index character
// to end of string
System.out.println("Substring " + s.substring(3));
// Returns the substring from i to j-1 index.
System.out.println("Substring = " + s.substring(2,5));
// Concatenates string2 to the end of string1.
String s1 = "Geeks";
String s2 = "forGeeks";
System.out.println("Concatenated string = " +s1.concat(s2));
// Returns the index within the string
// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " + s4.indexOf("Share"));
// Returns the index within the string of the
// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " +s4.indexOf('a',3));
// Checking equality of Strings
Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equals("Geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equalsIgnoreCase("gEeks ");
System.out.println("Checking Equality" + out);
int out1 = s1.compareTo(s2);
System.out.println("If s1 = s2" + out);
// Converting cases
String word1 = "GeeKyMe";
System.out.println("Changing to lower Case " +word1.toLowerCase());
// Converting cases
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +word1.toUpperCase());
// Trimming the word
String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());
// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
    }
}
Output :

String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equalityfalse
If s1 = s2false
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks

String class is immutable. i.e. it cannot be changed. Whenever we change any


string, a new instance is created.
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.
Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-
synchronized.
Paramete
String StringBuffer StringBuilder
r
Storage String Pool Heap Heap
Immutable
i.e. it cannot be
Mutabilit changed. Whenever
Mutable Mutable
y we change any
string, a new
instance is created.
Not used in a It is thread-safe. So,
Thread It is not thread-safe hence
threaded multiple threads can’t
Safe access at the same time, faster than String Buffer 
environment
Slower than
Performa StringBuilder but faster Faster than StringBuffer
Slow
nce than String hence less hence more efficient
efficient
String var
=“Edureka”;  StringBuffer var StringBuilder var
Syntax String = new StringBuffer("Edu = new StringBuilder("Edu
var=new String(“Edure reka"); reka");
ka”);  

Random Numbers Using the Math Class


Java provides the Math class in the java.util package to generate random numbers.
The Math class contains the static Math.random() method to generate random
numbers of the doubletype.
The random() method returns a double value with a positive sign, greater than or
equal to 0.0 and less than 1.0.

Random Number Generation Using the Random Class


You can use the java.util.Random class to generate random numbers of different types,
such as int, float, double, long, and boolean.
To generate random numbers, first, create an instance of the Random class and then call
one of the random value generator methods, such as nextInt(), nextDouble(),
or nextLong().

import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {

public static final void main(String... aArgs){


log("Generating 10 random integers in range 0..99.");

//note a single Random object is reused here


Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}

log("Done.");
}

private static void log(String aMessage){


System.out.println(aMessage);
}
}

Example run of this class:


Generating 10 random integers in range 0..99.
Generated : 44
Generated : 81
Generated : 69
Generated : 31
Generated : 10
Generated : 64
Generated : 74
Generated : 57
Generated : 56
Generated : 93
Suppose I wish to generate a number between 5-10:
int max = 10;
int min = 5;
int diff = max - min;
Random rn = new Random();
int i = rn.nextInt(diff + 1);
i += min;
System.out.print("The Random Number is " + i);

Creating a New JAR File


To create a new JAR file in the workbench:
1. In the Package Explorer, you can optionally pre-select one or more Java elements to
export. (These will be automatically selected in the   JAR Package
Specification wizard page, described in Step 4.)
2. Either from the context menu or from the menu bar's File menu, select Export.
3. Expand the Java node and select JAR file. Click Next.
4. In the JAR File Specification page, select the resources that you want to export in
the Select the resources to export field.
5. Select the appropriate checkbox to specify whether you want to Export generated
class files and resources or Export Java source files and resources. Note:
Selected resources are exported in both cases.
6. In the Select the export destination field, either type or click Browse to select a
location for the JAR file.
7. Select or clear the Compress the contents of the JAR file checkbox.
8. Select or clear the Overwrite existing files without warning checkbox. If you
clear this checkbox, then you will be prompted to confirm the replacement of each
file that will be overwritten.
9. Note: The overwrite option is applied when writing the JAR file, the JAR description,
and the manifest file.
10. You have two options:
o Click Finish to create the JAR file immediately.
o Click Next to use the JAR Packaging Options page to set advanced options,
create a JAR description, or change the default manifest.

Local variable contains garbage values


Global variable contains null/default values

String st = "143";
System.out.println("before "+st );
int i = Integer.parseInt(st);
System.out.println("After "+i);
int j= 5555;
System.out.println("before "+j);
String st1 = String.valueOf(j);
System.out.println("After "+st1);

Wrapper classes
Wrapper class in java provides the mechanism to convert primitive types into object
and object into primitive type.
The wrapper class is used to do boxing (i.e. autoboxing) and unboxing, it means
that converting a primitive type to object type.

Why we need wrapper classes


Object oriented programming is all about objects. The eight primitive data types
byte, short, int, long, float, double, char and boolean are not objects, so they do
not belong to any class. While storing in data structures which support only
objects, it is required to convert the primitive type to object first which we can do
by using wrapper classes.
For example
Data structures in the Collection framework such as ArrayList and Vector,HashMap
store only the objects (reference types) and not the primitive types.

HashMap<Integer, String> hm = new HashMap<Integer, String>();

So for type safety we use wrapper classes. This way we are ensuring that this
HashMap keys would be of integer type and values would be of string type.

Ex. int x=10; //it is a primitive data type.


Integer i=new Integer(x); // it is converted as Integer object type) they convert
primitive data type into object. Objects are needed if we wish to modify the arguments
passed into a method. 

The 8 primitive types and its wrapper classes are,

The automatic conversion of (POB)primitive into object is known as


autoboxing/boxing and object into primitive (OPU) type is unboxing
Autoboxing: Automatic conversion of primitive types to the object of
their corresponding wrapper classes is known as autoboxing. For
example – conversion of int to Integer, long to Long, double to Double etc.
// int data type
        int b = 10;
 //wrapping around Integer object
 Integer intobj = new Integer(b);

Unboxing: It is just the reverse process of autoboxing. Automatically


converting an object of a wrapper class to its corresponding primitive
type is known as unboxing. For example – conversion of Integer to int, Long
to long, Double to double etc.
// objects to data types (retrieving data types from objects)
int iv = intobj;

class WrappingUnwrapping
{
    public static void main(String args[])
    {
        byte a = 1; //  byte data type
        Byte byteobj = new Byte(a); // wrapping around Byte object
         
        int b = 10; // int data type
        Integer intobj = new Integer(b);          //wrapping around Integer object
 
        float c = 18.6f;         // float data type
        Float floatobj = new Float(c); // wrapping around Float object
 
        double d = 250.5;         // double data type
        Double doubleobj = new Double(d);          // Wrapping around Double object
 
        char e='a'; // char data type
        Character charobj=e; // wrapping around Character object

     //  printing the values from objects


        System.out.println("Values of Wrapper objects (printing as objects)");
        System.out.println("Byte object byteobj:  " + byteobj);
        System.out.println("Integer object intobj:  " + intobj);
        System.out.println("Float object floatobj:  " + floatobj);
        System.out.println("Double object doubleobj:  " + doubleobj);
        System.out.println("Character object charobj:  " + charobj);
 
        // objects to data types (retrieving data types from objects)
        byte bv = byteobj;
        int iv = intobj;
        float fv = floatobj;
        double dv = doubleobj;
        char cv = charobj;
 
        // printing the values from data types
        System.out.println("Unwrapped values (printing as data types)");
        System.out.println("byte value, bv: " + bv);
        System.out.println("int value, iv: " + iv);
        System.out.println("float value, fv: " + fv);
        System.out.println("double value, dv: " + dv);
        System.out.println("char value, cv: " + cv);
    }
}
Run on IDE
Output:
Values of Wrapper objects (printing as objects)

Byte object byteobj: 1

Integer object intobj: 10

Float object floatobj: 18.6

Double object doubleobj: 250.5

Character object charobj: a

Unwrapped values (printing as data types)

byte value, bv: 1

int value, iv: 10

float value, fv: 18.6

double value, dv: 250.5

char value, cv: a

Wrapper class Example: Primitive to Wrapper / autoboxing

int i = 1;
Integer intObj = new Integer(i);
System.out.println(i+"==="+intObj);

Wrapper class Example: Wrapper to Primitive / unboxing

Integer k = new Integer(5);


int v = k;
System.out.println(v);

Iterable Interface
The Iterable interface is the root interface for all the collection classes.
The Collection interface extends the Iterable interface and therefore all the subclasses of
Collection interface also implement the Iterable interface.
It contains only one abstract method. i.e., Iterator<T> iterator()  
It returns the iterator over the elements of type T.

Diffrence between collection and collections


Collection is interface which can be used to represent group of individual
objects as single entity and Collections is utility class which gives several utility
methods like searching, sorting for collection objects. E.g. collections.sort(<Arrya
list object>)
Collection is root level interface in java collection framework. Collections is utility
class in java which contains only static methods that operate on collection
Collection interface extends iterable interface and on the other hand
collections class extend object class
Methods of collection interface
Boolean add ( Object obj), Boolean addAll ( Collection c), void clear(), etc. which
are implemented by all the subclasses of Collection interface

Methods of collections class


Collections.sort(),Collections.reverse(),Collections.copy()

Similarity between both collection and collections


Both are part of java collection framework and both are present in java.util.package

Collections in Java
Collections in java is a framework that provides an architecture to store and
manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.
Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet etc).

Why collection concept is added in java.


Problems like - Because in normal arrays if we can’t create dynamic array
using only array ad only homogeneous data will be stored
Java List Interface
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have
duplicate values. It contains methods to insert and delete elements in index basis.
List interface is implemented by ArrayList class, LinkedList class, vector(extended by
stack)

When to use- when we want to store group of elements in collections and want to
maintain insertion order and duplicates should be allowed then we can use List
To instantiate the List interface, we must use :
1. List <data-type> list1= new ArrayList();  
2. List <data-type> list2 = new LinkedList();  
3. List <data-type> list3 = new Vector();  
4. List <data-type> list4 = new Stack();  

Iterator interface
Iterator interface provides the facility of iterating the elements in forward
direction only.
There are only three methods in the Iterator interface. They are:

No Method Description
.

1 public boolean hasNext() It returns true if the iterator has more


elements otherwise it returns false.

2 public Object next() It returns the element and moves the cursor
pointer to the next element.

3 public void remove() It removes the last elements returned by the


iterator. It is less used.

Java ListIterator Interface


ListIterator Interface is used to traverse the element in backward and forward
direction.
ListIterator Interface declaration
1. public interface ListIterator<E> extends Iterator<E>  

-Java ArrayList class


Java ArrayList class uses a dynamic array for storing the elements. It implements
List interface.
The important points about Java ArrayList class are:
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.
1. import java.util.*;  
2. class TestJavaCollection1{  
3. public static void main(String args[]){  
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
5. list.add("Ravi");//Adding object in arraylist  
6. list.add("Vijay");  
7. list.add("Ravi");  
8. list.add("Ajay");  
9. System.out.println("=====Direct list print"+list);
10. //Traversing list through ListIterator  
11. ListIterator<String> itr=list.listIterator();
12. while(itr.hasNext()){  
13. System.out.println(itr.next());  
14. }  }} 

Output:
=====Direct list print[Mango, Apple, Banana, Grapes]
Ravi
Vijay
Ravi
Ajay

-Java LinkedList class


LinkedList implements List and Deque interfaces. LinkedList class uses doubly linked
list to store the elements. In case of doubly linked list, we can add or remove
elements from both side.
The important points about Java LinkedList are:
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to be
occurred.
Example
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
ListIterator<String> itr1=al.listIterator();
while(itr1.hasNext()){
System.out.println(itr1.next());
}
Output:
Ravi
Vijay
Ravi
Ajay

Doubly Linked List


In case of doubly linked list, we can add or remove elements from both side.
Difference between ArrayList and LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both
are non synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given
below.

ArrayList LinkedList

1) ArrayList internally uses dynamic array to LinkedList internally uses doubly linked list


store the elements. to store the elements.

2) Manipulation with ArrayList is slow because Manipulation with LinkedList is faster than


it internally uses array. If any element is ArrayList because it uses doubly linked list so
removed from the array, all the bits are no bit shifting is required in memory.
shifted in memory.

3) ArrayList class can act as a list only LinkedList class can act as a list and queue
because it implements List only. both because it implements List and Deque
interfaces.

4) ArrayList is better for storing and LinkedList is better for manipulating data.


accessing data.

Example of ArrayList and LinkedList in Java


Let's see a simple example where we are using ArrayList and LinkedList both.
1. import java.util.*;    
2. class TestArrayLinked{    
3.  public static void main(String args[]){    
4.   List<String> al=new ArrayList<String>();//creating arraylist    
5.   al.add("Ravi");//adding object in arraylist    
6.   al.add("Vijay");    
7.   al.add("Ravi");    
8.   al.add("Ajay");    
9.   List<String> al2=new LinkedList<String>();//creating linkedlist    
10.   al2.add("James");//adding object in linkedlist    
11.   al2.add("Serena");    
12.   al2.add("Swati");    
13.   al2.add("Junaid");        
14.   System.out.println("arraylist: "+al);  
15.   System.out.println("linkedlist: "+al2);  
16.  }    
17. }    
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]

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 pop(object o)

Java Queue Interface


Queue follow First in First Out concept. – Priority queue class implements 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
1. Queue<String> q1 = new PriorityQueue();  
2. Queue<String> q2 = new ArrayDeque();  

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.
Java Set Interface
When to use- when we don’t want to allow duplicate valued and don’t want
to maintain insertion order(i.e. unordered collection )
The set interface present in the java.util package
It extends the Collection interface 
We can store at most one null value in Set.
Set interface is extended by SortedSet interface and implemented by HashSet, Tree set and
LinkedHashset class
Set can be instantiated as:
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();

// Java program to demonstrate a Set


import java.util.*;
public class SetExample{
public static void main(String[] args)
{
// Set demonstration using HashSet
Set<String> hash_Set = new HashSet<String>();
hash_Set.add("Geeks");
hash_Set.add("For");
hash_Set.add("Geeks");
hash_Set.add("Example");
hash_Set.add("Set");
System.out.println(hash_Set);
}
}
Output:
[Set, Example, Geeks, For]

Java HashSet class


Java HashSet class is used to create a collection that uses a hash table for storage.
It implements Set interface.
The important points about Java HashSet class are:
o HashSet stores the elements by using a mechanism called hashing.
o HashSet contains unique(no duplicates) elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on
the basis of their hashcode.
o HashSet is the best approach for search operations.
1. Import java.util.*;  
2. public class TestJavaCollection7{  
3. public static void main(String args[]){  
4. //Creating HashSet and adding elements  
5. HashSet<String> set=new HashSet<String>();  
6. set.add("Ravi");  
7. set.add("Vijay");  
8. set.add("Ravi");  
9. set.add("Ajay");  
10. //Traversing elements  
11. Iterator<String> itr=set.iterator();  
12. while(itr.hasNext()){  
13. System.out.println(itr.next());  
14. }  
15. }  
16. }  
Output:
Vijay
Ravi
Ajay
Java LinkedHashSet class
LinkedHashSet extends the HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
o Like HashSet, It also contains unique elements
o Provides all optional set operations, and permits null elements.
o Maintains insertion order.
1. import java.util.*;  
2. public class TestJavaCollection8{  
3. public static void main(String args[]){  
4. LinkedHashSet<String> set=new LinkedHashSet<String>();  
5. set.add("Ravi");  
6. set.add("Vijay");  
7. set.add("Ravi");  
8. set.add("Ajay");  
9. Iterator<String> itr=set.iterator();  
10. while(itr.hasNext()){  
11. System.out.println(itr.next());  
12. }  
13. }  
14. }  
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements.
The elements of the SortedSet are arranged in the increasing (ascending) order. The
SortedSet provides the additional methods that inhibit the natural ordering of the
elements.
The SortedSet can be instantiated as:
1. SortedSet<data-type> set = new TreeSet();  

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.

Difference between List and Set


List can contain duplicate elements whereas Set contains unique elements
only.
List implementations: ArrayList, LinkedList etc.
Set implementations: HashSet, TreeSet etc.

List allows any number of null values. Set can have only a single null value
at most

List is an ordered collection it maintains the insertion order, which means


upon displaying the list content it will display the elements in the same order in
which they got inserted into the list.
Set is an unordered collection, it doesn’t maintain any order. There are few
implementations of Set which maintains the order such as LinkedHashSet

ListIterator can be used to traverse a List in both the directions(forward and


backward) However it can not be used to traverse a Set. We can use Iterator (It
works with List too) to traverse a Set

List interface has one legacy class called Vector whereas Set interface does not
have any legacy class.

What is map in java


The Map is a Interface and it is not child interface of collection interface. A map
contains values on the basis of key, i.e. key and value pair. 
A Map is an object that maps keys to values.
A Map contains unique keys.
A Map doesn't allow duplicate keys, but you can have duplicate values.
There is one interfaces extending Map interface in java: SortedMap, and
implemented by three classes: HashMap, LinkedHashMap, and TreeMap. The
hierarchy of Java Map is given below:

HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't
allow any null key or value.
1. import java.util.*;  
2. class MapExample2{  
3.  public static void main(String args[]){  
4.   Map<Integer,String> map=new HashMap<Integer,String>();  
5.   map.put(100,"Amit");  
6.   map.put(101,"Vijay");  
7.   map.put(102,"Rahul");  
8.   //Elements can traverse in any order  
9.   for(Map.Entry m:map.entrySet()){  
10.    System.out.println(m.getKey()+" "+m.getValue());  
11.   }  
12.  }  
13. }  
Output:
102 Rahul
100 Amit
101 Vijay
Java HashMap class
Java HashMap class implements the Map interface which allows us to store key and
value pair, where keys should be unique. If you try to insert the duplicate key, it
will replace the element of the corresponding key. It is easy to perform operations
using the key index like updation, deletion, etc.

The important points about Java HashMap class are:


o A HashMap contains values based on the key.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It uses a technique called Hashing to faster serach
o Java HashMap maintains no order.
o Java HashMap is non synchronized.
o HashMap class is found in the java.util package

What is Hashing
It is the process of converting an object into an integer value. The integer value helps in
indexing and faster searches.

HashMap class Parameters


Let's see the Parameters for java.util.HashMap class.
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
1. import java.util.*;  
2. public class HashMapExample1{  
3.  public static void main(String args[]){  
4.    HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating Hash
Map    
5.    map.put(1,"Mango");  //Put elements in Map  
6.    map.put(2,"Apple");    
7.    map.put(3,"Banana");   
8.    map.put(4,"Grapes");   
9.        
10.    System.out.println("Iterating Hashmap...");  
11.    for(Map.Entry m : map.entrySet()){    
12.     System.out.println(m.getKey()+" "+m.getValue());    
13.    }  
14. }  
15. }  
Output:
Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes

Difference between HashSet and HashMap


HashSet contains only values whereas HashMap contains an entry(key and value).

Java LinkedHashMap class


It inherits HashMap class and implements the Map interface.

Points to remember
o Java LinkedHashMap contains values based on the key.
o Java LinkedHashMap contains unique elements.
o Java LinkedHashMap may have one null key and multiple null values.
o Java LinkedHashMap is non synchronized.
o Java LinkedHashMap maintains insertion order(difference in Map)
o import java.util.*;  
o class LinkedHashMap1{  
o  public static void main(String args[]){  
o   LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();    
o   hm.put(100,"Amit");  
o   hm.put(101,"Vijay");  
o   hm.put(102,"Rahul");  
o for(Map.Entry m:hm.entrySet()){  
o    System.out.println(m.getKey()+" "+m.getValue());  
o   }  
o  }  
o }  
Output:100 Amit
101 Vijay
102 Rahul

Java TreeMap class


Java TreeMap class is a red-black tree based implementation. It provides an efficient
means of storing key-value pairs in sorted order.
The important points about Java TreeMap class are:
o Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
o Java TreeMap contains only unique elements.
o Java TreeMap cannot have a null key but can have multiple null values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.

Example
o import java.util.*;  
o class TreeMap1{  
o  public static void main(String args[]){  
o    TreeMap<Integer,String> map=new TreeMap<Integer,String>();    
o       map.put(100,"Amit");    
o       map.put(102,"Ravi");    
o       map.put(101,"Vijay");    
o       map.put(103,"Rahul");            
o       for(Map.Entry m:map.entrySet()){    
o        System.out.println(m.getKey()+" "+m.getValue());    
o       }    
o  }  
o }  
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul

Java Hashtable class


Java Hashtable maps keys to values. It inherits Dictionary class and implements the
Map interface.
The important points about Java Hashtable class are:

o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket
is identified by calling the hashcode() method. A Hashtable contains values based
on the key.
o It contains only unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.

Let's see the Parameters for java.util.Hashtable class.


o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
o import java.util.*;  
o class Hashtable1{  
o  public static void main(String args[]){  
o   Hashtable<Integer,String> hm=new Hashtable<Integer,String>();  
o   hm.put(100,"Amit");  
o   hm.put(102,"Ravi");  
o   hm.put(101,"Vijay");  
o   hm.put(103,"Rahul");  
o   for(Map.Entry m:hm.entrySet()){  
o    System.out.println(m.getKey()+" "+m.getValue());  
o   }  
o  }  
o }  
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Difference between HashMap and Hashtable
HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.

Hashtable HashMap

Hashtable is synchronized. It is thread- 1) HashMap is non synchronized. It is not-


safe and can be shared with many thread safe and can't be shared between
threads. many threads without proper
synchronization code.

Hashtable doesn't allow any null key or 2) HashMap allows one null key and multiple
value. null values.

Hashtable is a legacy class. 3) HashMap is a new class introduced in JDK


1.2.

Hashtable is slow. 4) HashMap is fast.

Hashtable is internally synchronized and can't 5) We can make the HashMap as synchronized
be unsynchronized. by calling this code
Map m =
Collections.synchronizedMap(hashMap);

Hashtable is traversed by Enumerator and 6) HashMap is traversed by Iterator.


Iterator.

Enumerator in Hashtable is not fail-fast. 7) Iterator in HashMap is fail-fast.


Hashtable inherits Dictionary class. 8) HashMap inherits AbstractMap class.
Difference between ArrayList and Vector

ArrayList and Vector both implements List interface and maintains insertion order.

ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of current Vector increments 100% means doubles the


array size if number of element array size if total number of element
exceeds from its capacity. exceeds than its capacity.

3) ArrayList is not a legacy class, it is Vector is a legacy class.


introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is synchronized i.e. in


synchronized. multithreading environment, it will hold the other
threads in runnable or non-runnable state until
current thread releases the lock of object.

5) ArrayList uses Iterator interface to Vector uses Enumeration interface to traverse


traverse the elements. the elements. But it can use Iterator also.

Difference between Comparable and Comparator


Comparable and Comparator both are interfaces and can be used to sort collection
elements. However, there are many differences between Comparable and Comparator
interfaces that are given below.

Comparable Comparator

1) Comparable provides a single sorting The Comparator provides multiple sorting


sequence. In other words, we can sort the sequences. In other words, we can sort the
collection on the basis of a single element such collection on the basis of multiple elements such as
as id, name, and price. id, name, and price etc.

2) Comparable affects the original class, i.e., Comparator doesn't affect the original class,
the actual class is modified. i.e., the actual class is not modified.

3) Comparable provides compareTo() Comparator provides compare() method to sort


method to sort elements. elements.

4) Comparable is present in java.lang package. A Comparator is present in the java.util package.

5) We can sort the list elements of Comparable We can sort the list elements of Comparator type
type by Collections.sort(List) method. by Collections.sort(List, Comparator) method.
s
There are two ways in installing TestNG in Eclipse
First Way on installing Eclipse is using "Install new software" option.
Second way is using "Eclipse Market Place". - This option will be available in new
versions of eclipse.
What is log4j?
Log4j is an open source logging framework.
Log4j is a fast, flexible and reliable logging framework (APIS) written in Java .
It is distributed under the Apache Software License. 
 It is an open source
 With Log4j, it is possible to store the flow details of our Selenium Automation
in a file or databases
 Log4j is used for large as well as small projects
 In Log4j, we use log statements in the code to know the status of a project while it is
executing
Log4j has three principal components
Loggers: It is responsible for logging information
Appenders: In simple words, it is used to write the logs in file. 
Layouts:  It is responsible for formatting logging information in different
styles.
The log4j.properties file is a log4j configuration file which stores properties in key-value
pairs.
Log4j.appender.file.append = true --- will append logs to same file without deleting
previous fille
Log4j.appender.file.level = off – it will stop logging
Adding log4j in project
Step 1:Add Log4j libraries in the java projector you Can add jar files or maven dependency
https://logging.apache.org/log4j/2.x/...
Step 2 : Create reference for Logger in the class(Class where you want to add log statements )
static Logger log = Logger.getLogger(<Current class name>.class);
Step 3 : Create log4j.xml or log4j.properties file<structure is present above>
Syntax:
Log.info(“”)/Log.Error(“”),Log.Fatal()
2016-06-21 15:47:11 INFO AbstractAcceptance:14 - Executing the before block
2016-06-21 15:47:11 ERROR PropertyReader:17 – Not launching
2016-06-21 15:47:11 INFO PropertyReader:32 - Executing getProperty

Listeners are a group of interfaces. Listeners are capable to handle the


events generated by the components like button, mouse click, frame etc.
These listeners are implemented to the class which requires handling of
events.
EventListner interface - It is a marker interface which every listener
interface has to extend.This interface is defined in java.util package.
Class declaration
Following is the declaration for java.util.EventListener interface:

public interface EventListener


Lambda expressions basically express instances of functional interfaces (An
interface with single abstract method is called functional interface.
lambda expressions are added in Java 8 and provide below functionalities.
 Optional data type declaration − No need to declare the type of a
parameter. The compiler can inference the same from the value of the
parameter.
//with type declaration
MathOperation addition = (int a, int b) -> a + b;
//with out type declaration
MathOperation subtraction = (a, b) -> a - b;
 Optional parenthesis around parameter − No need to declare a single
parameter in parenthesis. For multiple parameters, parentheses are
required
//with parenthesis
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
//without parenthesis
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
 Optional curly braces − No need to use curly braces in expression
body if the body contains a single statement
//with return statement along with curly braces
MathOperation multiplication = (int a, int b) -> { return a * b; };
//without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;
 Optional return keyword − The compiler automatically returns the
value if the body has a single expression to return the value. Curly
braces are required to indicate that expression returns a value.
 A function that can be created without belonging to any class.

How to accept value from console


String str;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string: ");
str = in.nextLine();
System.out.println("Input String is: "+str);

Immutable class means that once an object is created, we cannot change its
content
Following are the requirements:
• Class must be declared as final (So that can’s extend it)
• Data members in the class must be declared as final (So that we can’t
change the value of it after object creation).
Make all fields private so that direct access is not allowed
• A parameterized constructor
• Getter method for all the variables in it
• No setters (To not have option to change the value of the instance variable)

Example to create Immutable class


// An immutable class
public final class Student
{ final String name;
final int regNo;
public Student(String name, int regNo)
{
this.name = name;
this.regNo = regNo;
}
public String getName()
{
return name;
}
public int getRegNo()
{
return regNo;
}
}

// Driver class
class Test
{
public static void main(String args[])
{
Student s = new Student("ABC", 101);
System.out.println(s.name);
System.out.println(s.regNo);

// Uncommenting below line causes error


// s.regNo = 102;
}
}
Output :
ABC
101

A thread is actually a lightweight process


Threads exist in several states. Following are those states:  
 New – When we create an instance of Thread class, a thread is in a new
state.
 Running – The Java thread is in running state.
 Suspended – A running thread can be suspended, which temporarily
suspends its activity. A suspended thread can then be resumed, allowing it to
pick up where it left off.
 Blocked – A java thread can be blocked when waiting for a resource.
 Terminated – A thread can be terminated, which halts its execution
immediately at any given time. Once a thread is terminated, it cannot be
resumed. 

Java lets you create thread in following two ways:- 


 By implementing the Runnable interface.
 By extending the Thread
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because
Java doesn’t support multiple inheritance. But, if we implement the Runnable
interface, our class can still extend other base classes.

1. We can achieve basic functionality of a thread by extending Thread class


because it provides some inbuilt methods like yield(), interrupt() etc. that are
not available in Runnable interface.

Runnable Interface
The easiest way to create a thread is to create a class that implements
the Runnable interface.
To implement Runnable interface, a class need only implement a single method
called run( ), which is declared like this:
/ Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}

// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override
run() method. Then we instantiate a Thread object and call start() method on this
object.
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +" is running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

public void run(): is used to perform action for a thread.


public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.

The toString() method returns the string representation of the object. It comes
from Object Class

base class in java - java.lang.Object class

what are the latest version of selnium ,java,testng


java 10 selenium 3.14 testng 6.14.0

Can we overload methods that differ only by static keyword?


We cannot overload two methods in Java if they differ only by static keyword
(number of parameters and types of parameters is same).
Ctrl+Shift+F – auto alignment

Design pattern – never worked on it but I know few of them


Design Patterns are very popular among software developers. Common software problem
are resolved using Design pattern. Or we can say it is best practices that developer has to
follow while creating software.
Design patterns are used to provide standard terminology that everybody
understands and Not to repeat the same mistakes over and over again

Common problems like


How to write reusable code
Hot to create class properly
How to instantiate object
How to interact between object

Using design patterns promotes reusability that leads to more robust and highly maintainable code.


Java Design Pattern are divided into three categories creational, structural,
and behavioral design patterns.
Creational - Creational patterns deal with the creation of objects.
Structural - Structural patterns deal with the composition of objects.
It deals with questions such as:
What does a class contain?
What are the relationships of a class with other classes? Is it inheritance or composition?
Behavioral patterns-focus more on the behavior of objects, or more precisely, interactions between
objects.

Singleton pattern(Creational pattern type) - it allows only one object of a class at


any point in time.
class must ensure that only single instance should be created and single object can be used
by all other classes.
A good real-world comparison would probably be the president of a nation.
Saves memory because object is not created at each request. Only single instance
is reused again and again
To create the singleton class, we need to have static member of class, private constructor
and static method.
o Static member: It gets memory only once because of static, itcontains the instance
of the Singleton class.
o Private constructor: It will prevent to instantiate the Singleton class from outside
the class.
o Static method: This provides the global point of access to the Singleton object and
returns the instance to the caller.
1. class A{  
2.  private static A obj=new A();//Early, instance will be created at load time  
3.  private A(){}  
4.   public static A getA(){  
5.   return obj;  
6.  }  
7.   public void doSomething(){ 
8.  }  
9. }  
When to use – when we want to create only one object and use it every place.
Real time example. When we creating JDBC connection for DB connectivity we can
use only one object throughout

If we clone object in singleton then How can we restrict object cloning in


singleton?
We will add try catch block and in try block we will add code which will check if object is
already created then object should not be created and if anyone tried it we will throw an
exception.
Marker interface in Java
It is an empty interface (no field or methods). Examples of marker interface are
Serializable, Clonnable and Remote interface. All these interfaces are empty interfaces.

Cloneable interface is present in java.lang package. There is a method clone() in Object class.


A class that implements the Cloneable interface indicates that it is legal for clone() method to
make a field-for-field copy of instances of that class.
Invoking Object’s clone method on an instance of the class that does not implement the
Cloneable interface results in an exception CloneNotSupportedException being thrown. By
convention, classes that implement this interface should override Object.clone() method.
Does clone object and original object point to the same location in
memory
The answer is no. The clone object has its own space in the memory where it
copies the content of the original object. That’s why when we change the content
of original object after cloning, the changes does not reflect in the clone object. 

Object cloning
The object cloning is a way to create exact copy of an object. The clone() method of
Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object we
want to clone. If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as
follows:
1. protected Object clone() throws CloneNotSupportedException  
public class Employee implements Cloneable {
int id;
String name;

Employee(int id, String name) {


this.id = id;
this.name = name;
}

public Object clone() throws CloneNotSupportedException {


return super.clone();
}

public static void main(String[] args) {


Employee emp = new Employee(115, "Rahul");
System.out.println(emp.name);
try {
Employee emp1 = (Employee) emp.clone();
System.out.println(emp1.name);
} catch (CloneNotSupportedException cnse) {
cnse.printStackTrace();
}
}
Output:
Rahul
Rahul

The clone() copies the values of an object to another. So we don't need to write explicit
code to copy the value of an object to another.

You might also like