Java Study
Java Study
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
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
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.
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
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.
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
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[];
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 casting? Casting is used to convert the value of one type to another.
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.
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.
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 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.
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.
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;
}
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.
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.
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
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
}
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.
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();
}
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.
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
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
log("Done.");
}
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.
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.
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
int i = 1;
Integer intObj = new Integer(i);
System.out.println(i+"==="+intObj);
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.
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).
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
.
2 public Object next() It returns the element and moves the cursor
pointer to the next element.
Output:
=====Direct list print[Mango, Apple, Banana, Grapes]
Ravi
Vijay
Ravi
Ajay
ArrayList LinkedList
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.
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)
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>();
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.
List allows any number of null values. Set can have only a single null value
at most
List interface has one legacy class called Vector whereas Set interface does not
have any legacy class.
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.
What is Hashing
It is the process of converting an object into an integer value. The integer value helps in
indexing and faster searches.
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
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
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.
Hashtable HashMap
Hashtable doesn't allow any null key or 2) HashMap allows one null key and multiple
value. null values.
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);
ArrayList and Vector both implements List interface and maintains insertion order.
ArrayList Vector
Comparable Comparator
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.
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
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)
// 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);
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
The toString() method returns the string representation of the object. It comes
from Object Class
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;
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.