Friday, August 30, 2019

Finding the numbers in Array for Given Sum


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class LocalTest {

// Finding sum of two numbers using O(n2)
public static int[] getSum(int arra[], int sum) {

for (int i = 0; i < arra.length; i++) {
for (int j = 0; j < arra.length; j++) {
if (arra[i] + arra[j] == sum) {
return new int[] { arra[i], arra[j] };
}

}
}
return null;
}

//Finding sum of two numbers using O(n)
public static int[] findSum(int arra[], int sum) {

Map<Integer, Integer> arraryMap = new HashMap<Integer, Integer>();
for (int i = 0; i < arra.length; i++) {
int value = arra[i];
if (arraryMap.containsKey(sum - value)) {
return new int[] { arra[arraryMap.get(sum - value)], arra[i]  };
}
arraryMap.put(value, i);
}
return null;
}

public static void main(String[] args) {
int arrValues[] = {2,5,7,9,11,3,8 };
System.out.println(Arrays.toString(getSum(arrValues,13)));
System.out.println(Arrays.toString(findSum(arrValues,13)));

}

}

Output
[2, 11]

[2, 11]
Thanks for your valuable comments

Thursday, January 29, 2015

Interview Questions Part 1

  • ·         Traverse a binary tree
  • ·         Reverse every k-element in a linked list
  • ·         Find the combination of elements with sum as N.
  • ·         Find the duplicates in Linked List
  • ·         Print binary tree in level order
  • ·         Validation of parenthesis in string (Total number should be equal for “(“ and “)”  )
  • ·         Swap the nodes in binary tree.
  • ·         Print Binary tree in pre order/post order/ inorder
  • ·         Stack operations using O(1)
  • ·         Implement Queue Using Linked List
  • ·         Merge Sort implementation.
  • ·         How to find the linked list is circular or not.
  • ·         Find the repeated values in String.


Thursday, December 25, 2014

Basic Sql interview questions

How to find highest salary
How to find nth salary
What's the use of joins
Use of aggregate operations like min Max avg count ..
How to eliminate duplicate records
Use of inner and outer joins
Left right full outer joins
Basic crud operations in SQL example using create select insert delete
Use of in and between operations
Conditional statement in SQL
Use of views trigger and procedure
Group by having example
String operations
Inner and outer queries

Selenium webdriver interview questions

How to navigate between frames
Navigation between two window frames
Javascript Calendar validation
Select the dynamic elements using dynamic xpath
How to diff between Firefox chrome internet explore browser testing using webdriver
how to execute JavaScript using web driver
Implicit and explicit wait
Difference between selenium RC and webdriver
Use of selenium Grid
How to handle pop ups
How to select element with same of in two different places
How to test password
Data driven and keyword driven architecture

Algorithm coding interview questions

Following should be prepared before preparing interview for product/development base companies

Implement stack
Implementation of queue
Linked list implementation
Stack and queue implementation using linked list
Tree and binary tree implementation
Double linked list
Merge and quick sort
String operations
Arrays rotation
Search for integers in collection
Min, max and sum of elements

Friday, December 12, 2014

Fields for Selenium Testing

My form - Formoid html5 form

My form

Check boxes


Radio Buttons


Date Picker


Select File

Click on alert

Generics in Java

Generics:

Type Safety Objects: Allow one type of object, does not allow other object

No Casting required.

For example in Collection

List<String> list = new ArrayList<String>
Allow only string objects to List.

Map<String,Integer> map = new TreeMap<String,Integer>
Allow String and Integer to Map.


When we try to add number it will throw compile time.

General Generic Example

class Generic<T>{
T object;

void add(T object)
{
              this.object=object;
        }

T get()
{
            return object;
        }
public static void main(String[] args) {
     Generic<Integer> ingen = new Generic<Integer>();
     Generic<String> strgen = new Generic<String>();
 
     ingen.add(new Integer(11));
     strgen.add(new String("Generic"));

     System.out.printf("Integer =%d", ingen.get());
     System.out.printf("String =%s", strgen.get());
  }

}

Print Integer =11  String =Generic.

Thursday, December 11, 2014

How to find min Stack using min time

Number of Stacks: 2

Push: Push the items in S1 and Push the item to S2 if the item (top) is less than S1

Pop: Pop the item from S2 because its min value and compare with S1, if both are same then pop item from S1 also.

Popped item is min

Thursday, December 4, 2014

Advanced Selenium Web Driver Commands

Implicit Timeout in Web Driver:
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Get text for Particular Element:
driver.findElement(By.id("ElementId")).getText())

Accept Alert:

  Alert alert = driver.switchTo().alert();
  String text = alert.getText();

Select Frame with Xpath.
   driver.findElement(By.xpath("(//a[contains(text(),'Frames')])[2]")).click();
driver.findElement(By.linkText("Small Window ("popup")")).click();

Selenium WebDriver baisc Commands

Initialize the Web Driver
       WebDriver driver = new FirefoxDriver();

Navigate to Web Page.
      driver.get("http://www.google.com");

Navigate to particular button and Click on It.
       driver.findElement(By.id("idname")).click();

Wait using driver Manage
       driver.manage().wait(3000);

Typing the Keys in TextBox.
       driver.findElement(By.id("userid")).sendKeys("bposthkseller1");

Click on Submit Button.
       driver.findElement(By.id("sgnBt")).submit();
       driver.manage().wait(3000);

Click on Link which contains Text.
       driver.findElement(By.linkText("Preferences")).click();

Click on Button with XPath Value.
       driver.findElement(By.xpath("//li[2]/span[2]/div")).click();

Monday, December 3, 2012

Java Interview Questions -1


System.gc() & Runtime.gc()
=============================
System.gc() internally calls Runtime.gc() or Runtiem.getRuntime().gc();
System.gc() is class method. Runtime.gc() is instance method.

public class Test {

protected void finalize(){

System.out.println("Finalize");

}

int i;
void intaliI(int i)
{ this.i=i; }

int retValueI()
  { return i; }

}


public  class SystemRuntimeGC {

public static void main(String args[]){

System.out.println("Starting");
System.gc();
System.out.println("Ending");

Test t1=new Test();
t1=null;
System.gc();
}
}

Garbage collection is happening via garbage collector.
OutOfMemoryError  Unchecked

Synchronization Block vs method
===============================
Method:
public synchronized void testFun()
{
statements;

}

Block
public void testFun(){

statements;
synchronized(this){
statements...;
}
}

Vector vs ArrayList
==================
Vector is synchronized & arraylist is not.
Vector double the size and arraylist is 50%.
Adding , removing at O(1)
Removing at particular position O(n-i) i is index

Abstract methods & Non Abstract Methods
=====================
Abstract methods can be called via non abstract methods

public abstract class AbstractExamples {

public int i;

public abstract void function1();

public void function2(){
System.out.println("Non abstract method");
function1();
}
}

public class AbstractClassExample extends AbstractExamples {

/**
* @param args
*/
public static void main(String[] args) {

AbstractClassExample abs=new AbstractClassExample();
abs.function1();
abs.function2();

System.out.println("int"+abs.i);

}

@Override
public void function1() {
System.out.println("Implemention abstract methods");

}

}

iterator
==========
iterator is an interface

Used step through collection of elements.

import java.util.Iterator;
import java.util.LinkedList;

public class IteratorExample {

/**
* @param args
*/
public static void main(String[] args) {
LinkedList ll=new LinkedList();
ll.add(2);
ll.add(5);

Iterator it=ll.iterator();
while(it.hasNext())
System.out.println(it.next());
}

}

Interface vs abstract
======================
we can implement multiple interface for class
Interface is limited to public and abstract methods. Abstract class can provide non abstract methods also.
Interface will take time for finding the corresponding methods. Abstract are fast

public abstract class AbstractExamples {

public int i;

public abstract void function1();

public void function2(){
System.out.println("Non abstract method");
function1();
}
}

public interface InterfaceExample {

public int j=0;

public void  interfaceFun1();

public void interfaceFun2();
}

public interface InterfaceExample2 {

public void interfaceExample2Fun1();
}

public class AbstractInterfaceExampleiMpl extends AbstractExamples implements InterfaceExample,InterfaceExample2{

@Override
public void interfaceFun1() {
// TODO Auto-generated method stub
System.out.println("Interface Fun1");
}

@Override
public void interfaceFun2() {
// TODO Auto-generated method stub
System.out.println("Interface Fun2");
}

@Override
public void function1() {
// TODO Auto-generated method stub
System.out.println("Abstract Fun1");
}

public static void main(String args[]){

}

@Override
public void interfaceExample2Fun1() {
// TODO Auto-generated method stub
System.out.println("Interface Example2 Fun1");
}
}

Virtual Functions in Java
=============
Abstract classes contain pure virtual functions in java.
Virual functions are like normal functions in java and we can override in subclasses.


wait vs sleep
================
wait can resume by notify or notifyall
sleep canto resume
wait can be called via synchronized block or method
wait is on Object and sleep is on Thread(sleep is static method)
yield pause the exection and give chance to other thread for execution
IllegalMonitorStateException occur in java if we dont call wait,notify,notifyAll in Synchronized method and race condition may happen between wait and notify



Checked vs Unchecked Exceptions
=============================

Checked exceptions should be handled in the code.

Compile error will throw for checked exception if we are not handling in  code.

Unchecked exception
===================
NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Checked exception
=============
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException

Final
=======
Final methods canot be overriden but can be overloaded.
Final variable canot be reassigned or intialized.
Final classes canot be subclassed

Primitive Vs Wrapper
==============
Primitive - int,double,float,...
Wrapper- Integer,Double...

Reference: http://en.wikipedia.org/wiki/Primitive_wrapper_class

Sunday, September 9, 2012

Streams in Java


Java Streams has following abstract classes:
InputStream , OutputStream , Reader and Writer

IO Streams: Designed for byte streams
Reader and Writer: Character Streams

Writing to File Using Java Programming Language


package com.io;

import java.io.*;
import java.util.Scanner;

public class FileWrite {

public static void main(String args[]){

try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name");

//Passing File name to File Class
String file=br.readLine();
File fname = new File(file);

boolean exist=fname.createNewFile();

                       //Verifying file exists or not ..
if(!exist){
System.out.println("File already exists");
System.exit(0);
}
else
{
FileWriter fwrite=new FileWriter(file);
BufferedWriter bwr=new BufferedWriter(fwrite);
bwr.write(br.readLine());
bwr.close();

System.out.println("Successfully created");
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

Output:
========
Enter File name
Hello.txt
Hello first file
Successfully created

Reading File in Java Using Java Programming


package com.io;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileRead {

public static void main(String args[]){

try
{
String str;
FileInputStream in=new FileInputStream("C:\\Downloads\\FRead.txt.txt");
DataInputStream din=new DataInputStream(in);
BufferedReader br=new BufferedReader(new InputStreamReader(in));

while((str=br.readLine())!= null){
System.out.println(str);
}
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}

}
}

Output:
==========
Hi,
This is first file for reading
Thanks

Saturday, September 1, 2012

Polymorphism in Java Using Overloading and Overridden methods


Polymorphism
One form and many implementations.
It can be acheived by using inheritence,overloading and Overriding.
Compile time Polymorphism: Over loading
Runtitme Polymorphism: Over riding
Runtime Polymorphism /Dynamic method dispatch:
Its a process in which a call to an overridden methodis resolved at runtime rather than compile itme.
Dynamic Binding: Refers to linking of a procedure call to the code to be executed in response to the call
Also known as late binding :Code associated to procedure call is not known untile the time of the call at runtime.

Overloading.
Two or more methods with same name in the same class with different arguments.

  • Overloaded methods Must change the argument list
  • May change the return type
  • May change the access modifiers.
  • May change the checded exceptions.

Example:
package com.oops;

public class OverLoadingExample {

public int sum(int a,int b){
System.out.println("Int Int");
return a+b;
}

public double sum(double a,double b){
System.out.println("Double Double");
return a+b;
}

public int sum(int a,double b){
System.out.println("Int Double");
return (int) (a+b);
}
public static void main(String args[]){

OverLoadingExample oe=new OverLoadingExample();
System.out.println("Overloading method"+oe.sum(3, 7));
System.out.println("Overloading method"+oe.sum(2.5, 5.7));
System.out.println("Overloading method"+oe.sum(2, 5.5));
}
}

Output:
=======
Int Int
Overloading method10
Double Double
Overloading method8.2
Int Double
Overloading method7


Overriding:

Occurs in the subclass and declares method that has same type arguments as a method and declared by one of its super class.

  • It can be used for defining the behaviour of child class.
  • Argument list same as overriden method.
  • Constructors canot be overridden.
  • final methods canot be overridden.
  • Static method cannot be overridden but can be re-declared.
  • super() can be used for invoking parent class(Super class) methods.

Example
package com.oops;

class OverExample{

public void fun1(){
System.out.println("Super Function1");
}

public void fun2(){
System.out.println("Super Using super() Function2");
}

}
public class OverRiddingExample extends OverExample{

public void fun1(){
System.out.println("Subclass Function1");
}


public void fun2(){
super.fun2();
System.out.println("Subclass Function2");
}

public static void main(String[] args) {
OverExample or=new OverRiddingExample();
OverExample oe=new OverExample();
or.fun1();
oe.fun1();
or.fun2();
}

}

Output:
========

Subclass Function1
Super Function1
Super Using super() Function2
Subclass Function2


Inheritance in Object Orient Programming and Java


Inheritance
Its a process where one object acquire properites another.
Inheritence reduces the code re-usablity.

Inheritence can be achieved by using extends or implemnts keyword

Single Inheritance:
Class A extends B{
statements
}

Example:
=============
Pulsar is subclass of Bike
TVS is subclass of Bike.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){
System.out.println("Color: Red & Brand:Own");
}

}
public class SingleInheritence extends TwoWheeler {

public static void main(String args[]){
TwoWheeler two=new TwoWheeler();
SingleInheritence si=new SingleInheritence();

System.out.println(si instanceof TwoWheeler);
System.out.println("Calling method in SuperClass");
si.setProp();
}
}

Output
=======
true
Calling method in SuperClass
Color: Red & Brand:Own

Multiple Inheritance can be acheived by using interface. 

Interface in Java Language (Click on link to know about interfaces)

Below example contains Single Inheritance and Multiple Inheritance Using Interfaces.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){
System.out.println("Color: Red & Brand:Own");
}

}

interface Car
{
   public void setBrandname(String name);
}

interface HeaveyVechile{

public void setProperites(String prop);
}

public class Wheeler extends TwoWheeler implements Car, HeaveyVechile{


public static void main(String args[]){

TwoWheeler two=new TwoWheeler();
Wheeler si=new Wheeler();

System.out.println(si instanceof TwoWheeler);
System.out.println("Calling method in SuperClass");
si.setProp();
si.setBrandname("First");
si.setProperites("HeavyLoadVechile");
}

@Override
public void setBrandname(String name) {
System.out.println("Brand name is"+name);

}

@Override
public void setProperites(String prop) {
System.out.println("Heavy Vechile with 4 or 8 Wheels "+prop);


}

}

Output
=========
true
Calling method in SuperClass
Color: Red & Brand:Own
Brand name isFirst
Heavy Vechile with 4 or 8 Wheels HeavyLoadVechile

interfaces in Object Oriented Programming Language


interface
==========
Descriptive set of methods. Implements class needs to be implemented methods in interface.

Properties of interface:
=========================
Canot mark interface as final
Cannot instiate interface.
Default: Methods in interface are abstract
fields in interface are static and final.
interface can implement class.
interface can extend multiple interfaces.

Class Implementing Interface
============================
package com.oops;

interface Bike{

//final static fields as default
int Capacity=150;

//abstract  methods as default
public void speed();
public void price();
}
public class InterfaceExample implements Bike {

@Override
public void speed() {
System.out.println("Speed of Bike is 100 KMPH");

}

@Override
public void price() {
System.out.println("Price of Bike is 75K");

}

public static void main(String args[]){

InterfaceExample it=new InterfaceExample();
it.speed();
it.price();
}

}

Interface extends Multiple Interfaces

public interface Computer
{
   public void setBrandname(String name);
}

public interface Desktop extends Computer
{
   public void setProperty(String prop);
   public void viewProperty(String id);
}

public interface Laptop extends Computer
{
   public void setProcess(double process);
   public void setScreen(int size);
}

public interface Laptop extends Computer,Device{

statements
}

Encapsulation in Java Programming


Encapsulation: is like information Hiding.
Hiding the properites and behaviors of object and allowing outside access via public methods.

Example for Encapsulation:
============================

EmpDetails.java:
package com.oops;

public class EmpDetails {

private int empid;
private String empname;

public void setEmpid(int id){
empid=id;
}

public int getEmpid(){
return empid;
}

public void setEmpName(String name){
empname=name;
}

public String getEmpName(){
return empname;
}
}

EncapsulationExample.java

package com.oops;

public class EncapsulationExample {

/**
* @param args
*/
public static void main(String[] args) {

EmpDetails emp1=new EmpDetails();
emp1.setEmpid(1);
emp1.setEmpName("First");

System.out.println("Employee details id: "+emp1.getEmpid()+" and name:"+emp1.getEmpName());

}

}

Output
==========
Employee details id: 1 and name:First

Abstraction and Abstract Class in java


Abstraction: Abstraction is act of representing data without including background details.

In java it can be achieved by using abstract classes/interfaces.
Hiding information can be achieved by modifiers.

Example for Abstract method:
  abstract  void function();

Example of abstract class:
 abstract class TestAbstract{

   abstract void fun1();
   public void fun2(){
    statements
   }

abstract classes contain abstract methods and normal methods.

Abstract Class Example:
package com.oops;

abstract class Area{
int side;

Area(int a){
side=a;
}
abstract int area();
public void nonAbstractMethod(){
System.out.println("Non abstract Method");
}
}

class Square extends Area{

Square(int a) {
super(a);
}

@Override
int area() {

System.out.println("Square Area");
return side*side;
}

}

class Rect extends Area{

public Rect(int a) {
super(a);
// TODO Auto-generated constructor stub
}

@Override
int area() {
// TODO Auto-generated method stub
System.out.println("Area of Triangle");
return side*side;
}

}

public class AbstractClassExample {

public static void main(String args[]){

Square sq=new Square(3);
Rect rt=new Rect(5);

Area ar;

ar=sq;
System.out.println("Square Area"+ar.area());

ar=rt;
System.out.println("Rectangle area"+ar.area());
}
}

Output:
============
Square Area
Square Area9
Area of Triangle
Rectangle area25

Sunday, August 26, 2012

Thread Programming Interview Questions in Java 2


Q) How to set & get Priority in Threads using java?

public class ThreadExample implements Runnable{

public  void run(){
System.out.println("Thread Starting");

{
for(int i=0;i<9;i++)
System.out.print(i);
}
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();

Thread t2= new Thread(new ThreadExample());
t2.start();

System.out.println("Thread 1 Priority"+t1.getPriority());

t2.setPriority(9);

System.out.println("Thread 2 Priority "+t2.getPriority());

}

}

Output
=============
Thread Starting
Thread Starting
012345678Thread 1 Priority5
Thread 2 Priority 5
012345678

Q) Difference between green thread and native thread in Java?
A) Native threads can switch between threads pre-emptively, switching control from a running thread to a non-running thread at any time. Green threads only switch when control is explicitly given up by a thread (Thread.yield(), Object.wait(), etc.) or a thread performs a blocking operation (read(), etc.).
On multi-CPU machines, native threads can run more than one thread simultaneously by assigning different threads to different CPUs. Green threads run on only one CPU.

Q)  Difference between thread and process?
A) Threads share the address space of the process that created it; processes have their own address space.
Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.

Q) Thread Life Cycle?



Q) What is context switching in multi-threading?
A) When doing context switching on a single-core processor, the code responsible is executed on the only CPU which takes care of switching the threads.
The kernel is multi-threaded. It can execute on any core. When a core comes to need to swap threads, it invokes the part of the kernel responsible for selecting the next thread it should execute.

5)  What thread-scheduling algorithm is used in Java?
6)  What is thread-scheduler in Java?
7)  How do you handle un-handled exception in thread?
8)  What is thread-group, why its advised not to use thread-group in Java?
9)  Why Executor framework is better than creating and managing thread by application ?
10) Difference between Executor and Executors in Java?
10) How to find which thread is taking maximum cpu in windows and Linux server?


Q) In which class would you find the methods sleep() and yield()?  Thread class

Q) Can you notify a particular thread? :   No

Q) How to make a normal thread as daemon thread?
A) We should call setDaemon(true) method on the thread object to make a thread as daemon thread.

Q) Give one good example of a daemon thread? : Garbage Collector is a low priority daemon thread.

Q) What are the two ways that a code can be synchronised?
A) Method can be declared as synchronised and A block of code be sychronised.


Q)What happens when I make a static method as synchronized?
A) Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.


Q) Can a thread execute another objects run() method?
A) A thread can execute it's own run() method or another objects run() method.

Q) What are different ways in which a thread can enter the waiting state?
A) A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object's lock
4. By invoking an object's wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Q) What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.

Q)What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
A)Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

Q) What is the difference between preemptive scheduling and time slicing?
A) Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Q) run(): After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

Q) wait(), notify(), and notifyAll() methods : Methods are used to provide an efficient way for thread inter-communication.

Q) Thread & States ?
A) A thread is an independent path of execution in a system. The high-level thread states are ready, running, waiting and dead.

Q) What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Q) What happens when a thread cannot acquire a lock on an object?
A) Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

Q) What is the difference between process and thread?
A) A thread is a separate path of execution in a program. A Process is a program in execution.

Q) Why would you use a synchronized block vs. synchronized method?
A) Synchronized blocks place locks for shorter periods than synchronized methods.

Q) What is an object's lock and which objects have locks?
A) An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Q)Let`s say you have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
(A) It can be achieved using join method of Thread class.

Q)How to know the thread priority?
A) isAlive() —it returns true when Thread is running
A) join() these two methods are used to know thread priority.

Q) What is a deadlock?
Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. Deadlock ocurred on Two threads call Thread.join() on each other and Two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.