You are on page 1of 79

How hashmap works ?

on principle of hashing. Hashing means to assign a unique code to any variable or


object after doing the calculations or applying the algorithm.

Hashmap has an inner class called Entry

static class Entry<K,V> implements Map.Entry<K,V>{


final K key;
V value;
Entry<K,V> next;
final int hash;

Entry class objects are stored in an array, not as key value pair.

transient Entry[] table;

Now how this put method works?

1) first key object is checked for null.If key is null ,value is stored in table[0]
position.bcoz hashcode of null is 0.

2) then the hashcode() method is called to calculate hash value.this hash value is
used to calculate the index in array to store the Entry object.

3) then indexFor(hash,table.length) function is called to calculate exact index


position in array to store the entry object.

4) now if two unequal objects have the same hashcode, how they can be stored in the
same array location or bucket?
Answer is Linkedlist. Like linked list entry class has an attribute "next".

when an entry object is to be stored in a particular calculated index,hashmap


checks if there is already an entry.If no entry,entry object is stored there. If
there is an entry, its next attribute is checked.if it is null, the entry object
becomes next node in linked list.if it is not null,procedure is followed until next
attribute is null.

5) now if another object with same key is entered ,it should replace the old
value,last value is returned.how?
While iterating over linked list to store the entry object in its calculated
index,hashmap calls equals method on key object.all the entry objects in linked
list have same hashcode but equals() method checks for equality.if key.equals(k) is
true,then both keys are treated as same key objects.Only the values are replaced in
entry object.By this way, hashmap does not allow duplicate keys.

now key uniqueness is maintained using put method.using get method,if hashmap finds
the match for the key object,it returns the value stored in entry object.if no
match is found,get() method returns null.

Q. how hashset works?

hashset contain unique elements and that is acheived through hashmap.when an object
of hashset is created ,it will create an object of hashmap.when an element is
passed to hashset,it is added as a key in hashmap in add(elemnt e) method. now a
value needs to b associated with the key. Java uses the dummy value(new Object)
which is PRESENT in hashset.

public class HashSet extends AbstractSet implements Set{


private transient Hashmap<E,Object> map;

private static final Object PRESENT= new Object();

public HashSet()
{
map=new HashMap<>();
}

public boolean add(E e)


{
return map.put(e,PRESENT)==null;
}
}

soap body req and resp:

request:
<soap:body>
<m:GetStockPrice>
<m:stockName>IBM</m:stockname>
</m:getStockPrice>
</soap:body>

response:

<m:GetStockPriceResponse>
<m:price>34.5</m:price>
</m:GetStockPriceesonse>
</soap:body>
WSDL contents:

<definitions

name="guru99webservice"
targetNmaeSpace=http://example.org/math
xmlns=http://schemas.xmlsoap.org/wsdl/>
<types>
<messgae>
<portType>

<binding>
<service>
</definition>

<message> has both input and output operations.

e.g.

<message name="EmpNameRequest">
<part name="EmpId"type="xsd:number">
</message>

<message name="EmpNameResponse">
<part name="EmpName" type="xsd:string"/>
</message>

For binding:

<binding name="TutorialSoapBinding" type="tns:TutorialPortType">


<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

class Animal{
public void animalSound(){
System.out.println("Default Sound");
}
}
public class Dog extends Animal{

public void animalSound(){


System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();//upcasting
obj.animalSound();
}
}
Output:

Woof
Animal obj = new Animal();
obj.animalSound();
// This would call the Animal class method

Dog obj = new Dog();


obj.animalSound();
// This would call the Dog class method

Animal obj = new Dog();


obj.animalSound();
// This would call the Dog class method

These cannot be abstract

Constructors
Static methods
Private methods
Methods that are declared �final�

Why can�t constructors be final, static or abstract in Java?

When you set a method as final, it means : �You don�t want any class override it�,
but constructor by JLS definition can�t overridden,so it is clean.

When you set a method as �abstract�,it means:�Method don�t have any body and you
want to implement it at another time in a child class�, but the constructor is
called implicitly when the new keyword is used so it can�t lack a body.

When you set a method as �static�, it means: �Method belong to class, not a
particular object� but constructor implicitly called to initialize an object, so
there is no purpose in having a static constructor.

public class FinalConstructor {

//Illegal modifier for the constructor in type FinalConstructor;


//only public, protected & private are permitted
private final FinalConstructor () { }

Example of Private Constructor

public class SingleTonClass {


//Static Class Reference
private static SingleTonClass obj=null;
private SingleTonClass(){
/*Private Constructor will prevent
* the instantiation of this class directly*/
}
public static SingleTonClass objectCreationMethod(){
/*This logic will ensure that no more than
* one object can be created at a time */
if(obj==null){
obj= new SingleTonClass();
}
return obj;
}
public void display(){
System.out.println("Singleton class Example");
}
public static void main(String args[]){
//Object cannot be created directly due to private constructor
//This way it is forced to create object via our method where
//we have logic for only one object creation
SingleTonClass myobject= SingleTonClass.objectCreationMethod();
myobject.display();
}
}

Constructor chaining:

class Test
{
Test()
{
this(10);
}
Test(int x)
{
System.out.println("x="+x);
}
public static void main(String arg[])
{
Test object = new Test();
}
}

wait() - it tells the calling thread to release the lock from resource and go to
sleep state until some other thread enters into the resource and calls notify()
method.

public class example{

psvm(){

final PC pc=new PC();

Thread t1=new Thread(new Runnable()


{
public void run(){
pc.produce();
}
});
Thread t2=new Thread(new Runnable()
{
public void run()
{
pc.consume();
}
});

t1.start();
t2.start();

t1.join();
t2.join();

public static class PC{


public void produce() throws InterruptedException{

synchronized(this)
{
wait();
}

public void consume() throws InterruptedExc{

Thread.sleep(1000);
synchronized(this)
{
notify();
Thread.sleep(1000);
}
}

Example of multithreading with synchronized:

class Sender{
public void send(String msg){
Thread.sleep(1000);
}
}

class Thread1 extends Thread{


private String msg;
private Thread t;
Sender sender;

Thread1(String m,Sender s)
{
msg=m;
sender=s;
}

public void run()


{
synchronized(sender)
{
sender.send(msg);
}
}

class Sync{
psvm(){
Sender snd=new Sender();
Thread1 t1=new Thread1("hi",snd);
Thread1 t2=new Thread("bye",snd);

t1.start();
t2.start();

t1.join();
t2.join();
}
}

public class Thread1{


psvm(){
final PC pc=new PC();
Thread t1=new Thread(new Runnable()
{
public void run()
{
pc.produce;
}
});
Thread t2=new Thread(new Runnable()
{
public void run(){
pc.consume();
}
});

public static class PC{

LinkedLIst<Integer> list=new LinkedList<>();


int capacity=2;

public void produce() throws InterruptedException{


int value=0;
while(true){

synchronized(this){
while(list.size()==capacity)
{
wait();

list.add(value++);

notify();
Thread.sleep(1000);
}
}
}

public void consume(){


while(true)
{
synchronized(this){
while(list.size==0)
wait();

int val=list.removeFirst();
notify();
}}}

Thread pools:

class Task implements Runnable{


private String name;
public Task(String s)
{
name=s;
}
public void run(){
for(int i=0;i<=5;i++)
[
Date d=new Date();
SimpleDateFormat ft=new SimpleDateFormat(hh:mm:ss);
ft.format(d);

Thread.sleep(1000);
}
}

public class Test{


static final int MAX_T=3;
psvm(){
Runnable r1=new Task("task 1");
Runnable r2=new Task("task 2");
Runnable r3=new Task("task 3");
Runnable r4=new Task("task 4");
Runnable r5=new Task("task 5");

ExecutorService pool=Executors.newFixedThreadPool(MAX_T);
pool.execute(r1);
pool.execute(r2);
pool.execute(r3);
pool.execute(r4);
pool.execute(r5);
pool.shutdown();
}
}

risks in thread pool:

1)deadlock - all the executing threads are waiting for results from blocked threads
in the queue due to the unavailability of threads for eecution.

2)thread leakage - if a thread is removed from the pool to execute a task but not
returned to it after the task execution, thread leakage occurs.
e.g. If the thread throws an exception and the pool class is unable to catch
it,thread exits reducing the size of thread pool by one.

3)resource thrashing- if thread pool size is very large,time is wasted in context


switching between threads.this mmay cause starvation problem also.

deadlock:

class Util{
static void sleep(long millis)
{
Thread.sleep(millis);
}
}

class Shared{
synchronized void test1(Shared s2){
Utils.sleep(1000);
s2.test2(this);
}

synchronized void test2(Shared s1){


Util.sleep(1000);
s1.test1(this);
}
}

class Thread1 extends Thread{


private Shared s1;
private Shared s2;

public Thread1(Shared s1,Shared s2)


{
this.s1=s1;
this.s2=s2;
}

public void run()


{
s1.test1(s2);
}
}

class Thread2 extends Thread{


private Shared s1;
private Shared s2;

public Thread2(Shared s1,Shared s2){


this.s1=s1;
this.s2=s2;
}

public void run(){


s2.test2(s1);
}
}

public class GFG{


psv(){
Shared s1=new Shared();
Shared s2=new Shared();

Thread t1=new Thread(s1,s2);


Thread t2=new Thread(s1,s2);

t1.start();
t2.start();

Utils.sleep(2000);
}
}

how to avoid deadlock condition?

1)avoid nested locks - avoid giving lock to multiple threads when u have given to
one.

2)avoid unnecessary locks

3)using thread join- deadlock occurs when one thread is waiting for other to
finish. using thread.join with maximum time u think the exection will take .

the endpoint interface is the URL where your service can be accessed by a client
application. The same web service can have multiple endpoints, for example in order
to make it available using different protocols.

jax ws- RPC style

helloworld.java

@WebService
@SoapBinding(style=Style.RPC)
public interface HelloWorld{
@WebMethod String getHelloWorldAsString(String name);
}

helloworldimpl.java
@Webservice(endpointInterface="com.javatpoint.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
public String getHelloWorldAsString(String name){
return "hello"+name;
}
}

publisher.java:

public class HelloWorldPublisher{


psvm(){
Endpoint.publish("http://localhost:7779/ws/hello",new HelloWorldImpl());
}
}

after running publisher code,wsdl file is generated by:

http://localhost:7779/ws/hello?wsdl

helloworldclient.java

public class helloworldclient{


psvm(){
URL url=new URL(http://localhost:7779/ws/hello?wsdl");
QName qname=new QName("http://javatpoint.com/","HelloWorldImplService");
1st arg- service uri
2nd arg-service name

Service service=Service.create(url,qname);
HelloWorld hello=service.getPort(HelloWorld.class);
sop(hello.getHelloWorldAsString("javatpoint rpc"));
}
}

Op o=new O("okay")

2 objects and 1 reference variable

String s1="java";
String s2="java";

1 object only

jax-rs example:

we need to load jersey jar files.


3 files -hello.java,web.xml and index.html are created for server side and
helloworldclient.java created on client side.

1)hello.java

@Path("/hello")
public class Hello{
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello(){
return "hello jersey";
}

2)web.xml

<servlet>
<s-n>jersey rest service</s-n>
<s-c>org.glassfish.jersey.servlet.ServletContainer</s-c>
<load-on-startup>1</l-o-s>
</s>

<s-mapping>
<s-n>jerse rest service</s-n>
<url-pattern>/rest/*</u-p>
</s-m>

index.html

<a href="rest/hello">click here</a>

Annotations:

@Path("/hello")
public class HelloService{
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param")String msg){
String output=msg;
return Response.status(200).entity(output).build();
}
}

<s>jersey rest service</s>


<s-c>org.glassfish.jersey.servlet.ServletContainer</s-c>

<s-n>
<u-p>/rest/*</u-p>

index.html:
<a href="rest/hello/javatpoint"</a>

@Path("/hello")
public class HelloService{
@GET
@Path("{year}/{month}/{day}")
public Response getDate(
@PathParam("year")int year,
@PathParam("month")int month,
@PathParam("day") int day){
String date=year+"/"+month+"/"+day;
return Response.status(200).entity(date).build();
}
}

<a href="rest/hello/2014/12/05">click here</a>

POST:

@Path("/product")
public class ProductService{
@POST
@Path("/add")
public Response addUser(@FormParam("id")int id,@FormParam("name")String
name,@FormParam("price")float price){
return Response.status(200).entity(id+name+price).build();
}
}

index.html
<form action="rest/product/add" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="text" name="price"/>
<input type="submit" value="add product"/>
</form>

public class Test{


psvm(){
Test t=new Test();
t.hashcode();

t=null;
System.gc();
}

protected void finalize(){


}
}

when we override equals(), it is recommended to also override the hashCode()


method. If we don�t do so, equal objects may get different hash-values;

advantages of java inner classes:

1)nested class can access members(data members n methods) of outer class including
private.

2)makes code more readable bcoz it logically group classes n interfaces in one
place only

service transport layer-transport messages btwn applications.includes ftp,http,smtp


description layer- describe services.this is handled by wsdl

discovery layer- centralizing services to a common registry for easy availabilty of


services/resources.

imp one--- object serialization with interface

Difference between Normal/Regular class and Anonymous Inner class:

A normal class can implement any number of interfaces but anonymous inner class can
implement only one interface at a time.
A regular class can extend a class and implement any number of interface
simultaneously. But anonymous Inner class can extend a class or can implement an
interface but not both at a time.
For regular/normal class, we can write any number of constructors but we cant write
any constructor for anonymous Inner class because anonymous class does not have any
name and while defining constructor class name and constructor name must be same.

A non-static class that is created inside a class but outside a method is called
member inner class.

class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

output: data is 30

e.g. of static nested class:

class Test{
static int data=30;
static class Inner{
void msg(){
syso("data is"+data);
}
}
psvm(){
Test.Inner obj=new Test.Inner();
obj.msg();
}
}

output: data is 30

static nested class with instance method:

class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}

you need to create the instance of static nested class because it has instance
method msg().

If you have the static member inside static nested class, you don't need to create
instance of static nested class.

class TestOuter2{
static int data=30;
static class Inner{
static void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter2.Inner.msg();//no need to create the instance of static nested class
}
}

output: data is 30

Points to remember for nested interfaces:

Nested interface must be public if it is declared inside the interface but it can
have any access modifier if declared within the class.
Nested interfaces are declared static implicitely.

nested interface declared within interface:

interface Showable{
void show();
interface Message{
void msg();
}
}

class Test implements Showable.Message{

public void msg(){


syso("hello");
}

psvm(){
Showable.Message message=new Test();
mesaage.msg();
}
}
Example of nested interface which is declared within the class:

class A{
interface Message{
void msg();
}
}

class Test implements A.Message{


public void msg{
syso("hello");
}

psvm(){
A.Message msg=new Test();
msg.msg();
}
}

Can we define a class inside the interface?

Yes, If we define a class inside the interface, java compiler creates a static
nested class. Let's see how can we define a class within the interface:

interface M{
class A{}
}

Aliases are the temporary names given to table or column for the purpose of a
particular SQL query.

SELECT Branch AS Stream,Grade as CGPA FROM Student_Details;

SELECT s.NAME, d.Grade FROM Student AS s, Student_Details


AS d WHERE s.Age=20 AND s.ROLL_NO=d.ROLL_NO;

You can use set intersection operations with your ArrayList objects.

Something like this:

List<Integer> l1 = new ArrayList<Integer>();

l1.add(1);
l1.add(2);
l1.add(3);

List<Integer> l2= new ArrayList<Integer>();


l2.add(4);
l2.add(2);
l2.add(3);

System.out.println("l1 == "+l1);
System.out.println("l2 == "+l2);
List<Integer> l3 = new ArrayList<Integer>(l2);
l3.retainAll(l1);

System.out.println("l3 == "+l3);
System.out.println("l2 == "+l2);
Now, l3 should have only common elements between l1 and l2.

CONSOLE OUTPUT
l1 == [1, 2, 3]
l2 == [4, 2, 3]
l3 == [2, 3]
l2 == [4, 2, 3]

using set :

List<String> lista =new ArrayList<String>();


List<String> listb =new ArrayList<String>();

lista.add("Isabella");
lista.add("Angelina");
lista.add("Pille");
lista.add("Hazem");

listb.add("Isabella");
listb.add("Angelina");
listb.add("Bianca");

// Create an aplusb list which will contain both list (list1 and list2)
in which common element will occur twice
List<String> listapluslistb =new ArrayList<String>(lista);
listapluslistb.addAll(listb);

// Create an aunionb set which will contain both list (list1 and list2)
in which common element will occur once
Set<String> listaunionlistb =new HashSet<String>(lista);
listaunionlistb.addAll(listb);

for(String s:listaunionlistb)
{
listapluslistb.remove(s);
}
System.out.println(listapluslistb);

cartesian join:

In the below query we will select NAME and Age from Student table and COURSE_ID
from StudentCourse table. In the output you can see that each row of the table
Student is joined with every row of the table StudentCourse. The total rows in the
result-set = 4 * 4 = 16.
SELECT Student.NAME, Student.AGE, StudentCourse.COURSE_ID
FROM Student
CROSS JOIN StudentCourse;
self join:

SELECT a.ROLL_NO , b.NAME


FROM Student a, Student b
WHERE a.ROLL_NO < b.ROLL_NO;

SQL constaints:

1) we cannot store null values in a column.


2) all the values in a column should b unique
3) a primary key is a field which uniquely identify each row in the table
4) a foreign key uniquely identify each row in another table
5) check- this ensures that values stored in a column meets a particular condition
6) default - this specifies a default value for the column when no value is
specified by user

How to specify constraints?


We can specify constraints at the time of creating the table using CREATE TABLE
statement. We can also specify the constraints after creating a table using ALTER
TABLE statement.

syntax:
1) not null:

create table student


(
id int(6) not null,
name varchar(10) not null,
address varchar(20)
);

2) unique

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);

3) primary key

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
primary key(id)
);

4)foreign key

Consider the two tables as shown below:


Orders

O_ID ORDER_NO C_ID


1 2253 3
2 3325 3
3 4521 2
4 8532 1
Customers

C_ID NAME ADDRESS


1 RAMESH DELHI
2 SURESH NOIDA
3 DHARMESH GURGAON

create table orders


(

o_id int not null,


order_no int not null,
c_id int.
primary key(o_id).
foreign key(c_id) references customers(c_id)
)

5) check
create table student
(
id int(6) not null,
name varchar(10) not null,
age int not null check(age>=18)
);

6) default
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
age int default 18
);

Overriding and constructor : We can not override constructor as parent and child
class can never have constructor with same name(Constructor name must always be
same as Class name).

overriding and exception handling:

If the super-class overridden method does not throws an exception, subclass


overriding method can only throws the unchecked exception, throwing checked
exception will lead to compile-time error.

If the super-class overridden method does throws an exception, subclass overriding


method can only throw same, subclass exception. Throwing parent exception in
Exception hierarchy will lead to compile time error.Also there is no issue if
subclass overridden method is not throwing any exception.

Abstract methods in an interface or abstract class are meant to be overridden in


derived concrete classes otherwise compile-time error will be thrown.
The presence of synchronized/stricfp modifier with method have no effect on the
rules of overriding, i.e. it�s possible that a synchronized/stricfp method can
override a non synchronized/stricfp one and vice-versa

sub query:

select s_id from student_course where c_id in(select c_id from course where
c_name='dsa' or c_name='dbms'));

select s_name from student s where exists(select * from student_course scwhere


s.s_id=sc.c_id and sc.c_id='c1');

super key- combination of columns that uniquely identifies a row in a table

candidate key is a minimal super key which cannot have any columns removed from it.

A Primary Key is one of the candidate keys.There cannot be more that one primary
keys in a table.

difference betwn primary and unique key:

primary key cannot have null value .unique constraints can have null.
there is only one primary key in a table,but there can b multiple unique
constarints.

What is the difference between having and where clause?

having is a condition for a group or aggregate function used in select stmt. where
clause cannot have aggregate func.

having clause selects rows after grouping. where clause selects before grouping.

select student,score from marks where score>=40

select student,sum(score) as total from marks group by student having total > 70

How to print duplicate rows in a table?

select name,section from tb1 group by name,section having count(*)>1

join query:
select sc.courseid,s.studentname from sc inner join s on sc.enrollno=s.enrollno
order by sc.courseid;

what is a view?

1) view is a virtual table formed by joining multiple tables.

2) A user having the permission can only query the view.it hides the complexity of
data of underlying base tables.
3) view takes little space to store.database contains only definition of the
view,not the copy of all data.

create view view1 as


select coulmn_name
from table_name
where condition

trigger - trigger is a code associated with insert,update and delete operations.the


code is executed automatically when the associated quey is executed on
table.triggers are used to maintain integrity in database.

stored procedure - contains set of operations compiled together to perform common


databse tasks

stored proc can b called directly. but triggers cannot b. they can only b
associated with queries.

Threads Using Anonymous Classes:

Thread th=new Thread(new Runnable(){

@Override
public void run(){
}
});
th.start();

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 reenters the pool
of ready tasks. The scheduler then determines which task should execute next, based
on priority and other factors.

What happens if we call the run() method instead of start() method ?

each thread starts in a separate call stack.invoking run() from main thread causes
it to go to current call stack instead of beginning of call stack. besides that
there will b no context switching between threads and thread objects will b treated
as normal obj

jvm shutdown hook:


this allows the developer to execute a piece of code when jvm is shutting down

public class Shutdownhook{


psvm(){
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
syso("shut down hook running");
}
});
syso("application terminating");
}
}

What is the difference between synchronized method and synchronized block ?

1) sync block locks only the critical section of code like locking in singleton
pattern.instead of locking the whole getInstance(),we lock only the critical
section of code which is used to create singleton instance.

2)sync block throws nullpointer exception if the parameter provided to the block is
null but this is not the case with sync methods.

public class syncexample{

public static synchronized void lockedByClassLock{


syso("");
}

public void lockedByBlock{


Object obj=String.class;
synchronized(obj){
syso("");
}
}
}

class Account{

synchronized static void showAccount(String accountName){


System.out.println("My account name is "+accountName+" Holder Name is
"+Thread.currentThread().getName());
try{
Thread.sleep(500);
}catch(Exception e){}
}
}

class MyThread1 extends Thread{


public void run(){
Account.showAccount("Dineshonjava.com");
}
}

class MyThread2 extends Thread{


public void run(){
Account.showAccount("Linkedin.com");
}
}

class MyThread3 extends Thread{


public void run(){
Account.showAccount("Facebook.com");
}
}

class MyThread4 extends Thread{


public void run(){
Account.showAccount("Twitter.com");
}
}

class StaticSyncDemo{
public static void main(String t[]){
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
MyThread4 t4 = new MyThread4();
t1.setName("DAV JavaServices");
t2.setName("dinesh.rajput");
t3.setName("dineshonjava");
t4.setName("admin@dineshonjava.com");
t1.start();
t2.start();
t3.start();
t4.start();
}
}

synchronized block:

static void showAccount(String accname)


{
synchronized(Account.class){
}
}

public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.

database transaction - set of database operations to b executed wholly or not at


all
ACID

What are clustered and non-clustered Indexes?

Clustered - data is physically stored on disk.only one clustered index can b


created on a database table

non clustered index defines logical ordering.

index - a data structure which improves data rerieval operations in database table
but consumes more storage space on the disk

t1.setDaemon(true);//now t1 is daemon thread

t1.start();//starting threads
t1.start();
t1.setDaemon(true);//will throw exception here

public class ThreadGroupDemo implements Runnable{


public void run(){
syso(Thread.currentThread().getName());
}
psvm(){
ThreadGroupDemo runnable=new ThreadGroupDemo();
ThreadGroup tg1=new ThreadGroup("parent group");
Thread t1=new Thread(tg1,runnable,"one");
t1.start();
Thread t2=new Thread(tg1,runnable,"two");
t2.start();

tg1.getName();
tg1.list();
}
}

How can an object be unreferenced?

1) by nulling the reference

Employee e=new Employee();


e=null;

2)by assigning a reference to another

Employee e1=new Employee();

Employee e2=new Employee();

e1=e2;

3)by anonymous object:


new Employee();

Simple Example of garbage collection in java

public class TestGarbage1{


public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

class Table{

synchronized static void printTable(int n){


for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}

public class TestSynchronization5 {


public static void main(String[] args) {

Thread t1=new Thread(){


public void run(){
Table.printTable(1);
}
};

Thread t2=new Thread(){


public void run(){
Table.printTable(10);
}
};

Thread t3=new Thread(){


public void run(){
Table.printTable(100);
}
};

Thread t4=new Thread(){


public void run(){
Table.printTable(1000);
}
};
t1.start();
t2.start();
t3.start();
t4.start();

}
}

static void printTable(int n){


synchronized(Table.class){

}
}
example of deadlock:

public class TestDeadlockExample1 {


public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");

try { Thread.sleep(100);} catch (Exception e) {}

synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};

t1.start();
t2.start();
}
}

Difference between wait and sleep?

Let's see the important differences between wait and sleep methods.

wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or notifyAll() methods after the specified amount of
time, sleep is completed.
2 examples of interthread commnication:

class Customer{
int amount=10000;

synchronized void withdraw(int amount){


if(this.amount<amount)
{
try{
wait();
}catch(){}

this.amount-=amount;
}

synchronized void deposit(int amount)


{
this.amount+=amount;
notify();
}

class Test{
psvm(){

final Customer c=new Customer();


new Thread(){
public void run(){
c.withdraw(15000);
}.start();

new Thread(){
public void run(){
c.deposit(10000);
}.start();
}}

producer-consumer prob is an example of synchronization prob. both of them share a


common buffer used as a queue.
the producer go to sleep state if the buffer is full.the consumer removes the item
from the buffer and notifies the producer who starts filling buffer again.
similarly consumer goes to sleep state if buffer is empty.producer fills in the
buffer and notifies consumer who woke up from sleep state and remove item from
buffer.

public class ThreadExample{


psvm(){

//object of a class that has both produce n consume methods


final PC pc=new PC();

//create producer thread


Thread t1=new Thread(new Runnable()
{
public void run(){
pc.produce();
}
});

//create consumer thread


Thread t2=new Thread(new Runnable()
{
public void run(){
pc.consume();
}
});

t1.start();
t2.start();

//t1 finishes before t2


t1.join();
t2.join();
}

public static class PC{

//create a list shared by producer and consumer


//size of list is 2
LinkedList<Integer> list=new LinkedList<>();
int capacity=2;

public void produce() throws InterruptedException{


int value=0;
while(true)
{
synchronized(this){

//producer waits till list is full


while(list.size==capacity){
wait();

//inserting values in the list


list.add(value++);

//notifies the consumer that it can start consuming


notify();
Thread.sleep(1000);
}
}
}

public void consume() throws InterruptedException{


while(true)
{
synchronized(this){

//consumer waits while list is empty


while(list.size()==0)
{
wait();

int val = list.removeFirst();


notify();
Thread.sleep(1000);
}
}
}
}
}

If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked),


calling the interrupt() method on the thread, breaks out the sleeping or waiting
state throwing InterruptedException.

If you define any data member as transient, it will not be serialized.If you
deserialize the object, you will get the default value for transient variable.

How to call private method from another class in java?

by java.lang.Class class and java.lang.reflect.Method class,we can call private


method from another class.

e.g.:

public class A{
private void messgae(){
syso("hello");

}
}

public class MethodCall{


psvm(){
Class c=Class.forName("A");
Object o=c.newInstance();
Method m=c.declaredMethod("message",null);
m.setAccessible(true);
m.invoke(o,null);
}
}

call parametrized private method from another class:

class A{
private void cube(int n)
{
syso(n*n*n);
}
}

class M{
psvm(){
Class c=A.class;
Object o=c.newInstance();
Method m=c.getDeclaredMethod("cube",new Class[]{int class});
m.setAccessible(true);
m.invoke(o,4);
}}

o/p 64

Get Current Date and Time: java.text.SimpleDateFormat


The SimpleDateFormat class is also used for formatting date and time. But it is old
approach.

import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentDateTimeExample2 {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(formatter.format(date));
}
}

Date date=java.util.Calendar.getInstance().getTime();
syso(date);

class demo10 {
public static void main(String args[])
{
String str = "JavaProgramming";
String str1 = "Java";

System.out.println(str.compareTo(str1));
System.out.println(str1.compareTo(str));
}
}
Run on IDE
Output:

11
-11

int to string:

int i=10;
String s=String.valueOf(i);//Now it will return "10"

or

String s=Integer.toSTring(i);

String.format() - it format the arguments into string.

public static String format(String format,Object... args)

int i=200;
String s=String.format("%d",i);
o/p:200

Collections is a framework that store and manipulate the group of objects.

What are the two ways to iterate the elements of a collection ?

public final class A{

psvm(String... args)
{
List<String> flavors=new ArrayList<>();
flavors.add("vanilla");
flavors.add("choc");

useWhileLoop(flavors);
useForLoop(flavors);

private static void useWhileLoop(Collection<String> aFlavors){

Iterator<String> itr=aFlavors.iterator();
while(itr.hasNext())
{
syso(itr.next());
}
}

private static void useForLoop(Collection<String> aFlavors){


for(Iterator<String> itr=aFlavors.iterator();itr.hasNext();){
syso(itr.next());
}}}

class Outer {
class Inner {
public
void m1()
{
System.out.println("Hii");
}
} public static void main(String[] args)
{
Outer o = new Outer();
o.m1();
}
}
Run on IDE
Options:
1.Hii
2.Compile time error
3.Run time error
4.No Output
Output:

The answer is option (3)


Explanation : As we know that compiler is not responsible to check whether class
contains main() method or not. But during the time of execution JVM check whether
class contains main() method or not. If the class does not contain main() method
then we will get Run time error saying NoSuchMethodError:main.

class Outer {
class Inner {
public
static void main()
{
System.out.println("Hii");
}
} Outer o = new Outer();
o.main();
}
Run on IDE
Options:
1.Hii
2.Run time
3.Compile time error
4.No Output

Output:

The answe is option (3)


Explanation : In the above program, we will get compile time error saying �Inner
classes can�t have static declaration� and here in the program we declare a static
method.

class Outer {
class Inner {
public
void m1()
{
System.out.println("Hii");
}
} public static void main(String[] args)
{
Line - 1
}
}
Run on IDE
Options:
1.Outer o=new Outer();
Outer.Inner i=o.new Inner();
i.m1();
2.Outer.Inner i=new Outer().new Inner();
i.m1();
3.new Outer().new Inner().m1();
4.None

Output:
The answer is option (1), (2), (3)

class Test {
public final int a;
} class Example {
public static void main(String args[])
{
Test obj = new Test();
System.out.println(obj.a);
}
}
Run on IDE
Option
A. 0
B. Garbage value
C. Compile time error : variable is not initialized
D. Run time error : a is the blank variable
Output:

C. Compile time error : variable is not initialized

there r 3 ways to initialize final variable.


1) at the time of variable declaration
2)using constructor
3)initialization block

ArrayList grow by half of its size when resized while Vector doubles the size of
itself by default when grows.

iterator and list iterator returned by arraylist is fail fast but enumeration
returned by vector is fail-safe.

similarities:
1) both use growable array structure
2) allows duplicate and null values
3) maintains insertion order
4) both grows n shriks automatically
5) iterator and list iterator returned by Arraylist n vector is fail fast

How to make ArrayList synchronized?

List list=Collections.synchronizedList(new ArrayList());


....
....

synchronized(list){

Iterator iterator = list.iterator();


while (iterator.hasNext())
...
iterator.next();
...
}
Difference betwn hashset n hashmap:

1) hashset implements set interface


.hashmap map interface

2) hashset stores elements/values in it.e.g. {"hello","hi"}


hashmap stores key value pair.{1->"hello",2->"bye",3->"hi"}

3)hashset allows no duplicate values but hashmap allows duplicate values but no
duplicate keys

4)hashset can have a single null value


hashmap have single null key n multiple null value

hashmap n hashset r not synchronized but they can b synchronized by:

Set s=Collections.synchronizedSet(new HashSet());

hashset internally uses hashmap for its operations

hashset to arraylist:

hashSet.add("1");
hashSet.add("2");

List<String> list=new ArrayList<String>(hashSet);

hashSet.to array:

hashSet.add("1");
hashSet.add("2");

String[] arr=new String[hashSet.size()];


hashSet.toArray(arr);

for(String temp:arr){
syso(temp);
}

Adding element to front of LinkedList in Java

LinkedList<String> list = new LinkedList<String>();

// Add elements
list.add("AA");
list.add("BB");
list.add("CC");
list.add("DD");

list.offerFirst("new");
o/p- [new,aa,bb,cc,dd]

class Test implements Runnable {


public
void run()
{
System.out.println("Run");
}
} class Myclass {
public
static void main(String[] args)
{
Thread t1 = new Thread();
t1.start();
System.out.println("Main");
}
}
Run on IDE
Options:
1. Run
2. Main
3. Compile time error
4. Run Main

Output:

The answer is option (2)

HashMap vs Hashtable:

hashmap -not synchronizzed

HashMap allows one null key and any number of null values.
Hashtable doesn�t allow null keys and null values.

hashmap and hashtable do not maintain insertion order


LinkedHashMap maintains the insertion order and TreeMap sorts the mappings based on
the ascending order of keys.

iterator of hashmap is fail-fast


enumerator for hashtable is not fail-fast

HashMap hm=new HashMap();

Set keys= hm.keySet();


for(Object key:keys){
hm.put(key,value);
}

Hashtable ht=new Hashtable();

Enumeration en=ht.keys();
for(Enumeration en=ht.elements();en.hasMoreElements();en.nextElement(){
ht.put(key,value);
}

Copy all the elements of one Vector to another Vector example:

Vector<String> va = new Vector<String>();


//Adding elements to the first Vector
va.add("AB");
va.add("BC");
va.add("CD");
va.add("DE");

//Second Vector
Vector<String> vb = new Vector<String>();
//Adding elements to the second Vector
vb.add("1st");
vb.add("2nd");
vb.add("3rd");
vb.add("4th");
vb.add("5th");
vb.add("6th");

//copying all elements from va to vb


Coll
ections.copy(vb,va);

o/p: [AB, BC, CD, DE, 5th, 6th]

HashMap Sorting by Keys:

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


hmap.put(5, "A");
hmap.put(11, "C");

Set set=hm.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry me=(Map.Entry) itr.next();
syso(me.getKey());
syso(me.getValue());

Map<Integer, String> map = new TreeMap<Integer, String>(hmap);


System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
}

HashMap Sorting by Values:

public class HMapSortingByvalues {


public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(5, "A");
hmap.put(11, "C");
hmap.put(4, "Z");
hmap.put(77, "Y");
hmap.put(9, "P");
hmap.put(66, "Q");
hmap.put(0, "R");
System.out.println("Before Sorting:");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}

Map<Integer,String> map=sortByValues(hmap);

Set set2=map.entrySet();

Iterator itr=set2.iterator();

while(itr.hasNext()){

Map.Entry me2=(Map.Entry) itr.next();


syso(me2.getKey());

syso(me2.getValue());

}
}
}

private static HashMap sortByValues(HashMap map){

List list=new LinkedList(map.entrySet());

Collections.sort(list,new Comparator(){
public int compare(Object o1,Object o2){
return ((Comparable)((Map.Entry) (o1)).getValue().compareTo((Map.Entry)
(o2)).getValue());
}
});

//copying sorted list in hashmap using linked hash map to preserve insertion order

HashMap sortedHashMap=new LinkedHashMap();


for(Iterator it=list.iterator();it.hasNext();){
Map.Entry me=(Map.Entry)it.next();
sortedHashMap.put(me.getKey(),me.getValue());
}

return sortedHashMap;
}
}

ConcurrentHashMap:

this is used when we want to modify our map at run time.

public class Test{


psvm(){
Map<String,String> map=new ConcurrentHashMap<String,String>();
map.put("1","1");
map.put("2","2");
map.put("3","3");

Iterator<String> itr=map.keySet().iterator();
while(itr.hasNext()){
String key=it.next();
if(key.equals("3")){
map.put(key+"new","new3");
}

But if we use HashMap instaed of ConcurrentHashMap,it will throw


ConcurrentModificationException.so add break statement after put call.

if(key.equals("3")){
map.put(key+"new3","new3");
break;
}

if we don't want to add a new entry but update existing key- value pair.

map.put(key,"new3");

Question 4. What is the output of this question?

class Test1 {
static int i = 1;
public static void main(String[] args)
{
static int i = 1;
for (Test1.i = 1; Test1.i < 10; Test1.i++) {
i = i + 2;
System.out.print(i + " ");
}
}
}
Run on IDE
Option
A)Error
B)1 3 9
C)3 5 7 9 11 13 15 17 19
D)1 2 3 � 9

Output: A
Explanation : We can not declare the static variable inside the block. If we
declare static variable inside the block, then we will get the compile time error :
illegal start of expression.

Question 2. what is the output of this question?

class Test1 {
int x = 10;
public
static void main(String[] args)
{
System.out.println(x);
}
static
{
System.out.print(x + " ");
}
}
Run on IDE
Option
A) 10 10
B) Error
C) Exception
D) none

Output: B
Explanation : If we are trying to print the instance variable inside the static
block or static method without creating class instance then it will give the
error : non-static variable x cannot be referenced from a static context.

Question 4. What is the output of this question?

class Test1 {
static int i = 1;
public static void main(String[] args)
{
static int i = 1;
for (Test1.i = 1; Test1.i < 10; Test1.i++) {
i = i + 2;
System.out.print(i + " ");
}
}
}
Run on IDE
Option
A)Error
B)1 3 9
C)3 5 7 9 11 13 15 17 19
D)1 2 3 � 9
Output: A
Explanation : We can not declare the static variable inside the block. If we
declare static variable inside the block, then we will get the compile time error :
illegal start of expression.

class Test1 {
public static void main(String[] args)
{
static int arr1[] = { 11, 22, 33 };
static int arr2[] = { 11, 22, 33, 44, 55 };
static int ptr[];
ptr = arr1;
arr1 = arr2;
arr2 = ptr;
System.out.print(arr1.length + " ");
System.out.println(arr2.length);
}
}
Run on IDE
Option
A)Error
B)5 5
C)5 3
D)3 5

Output: A
Explanation :Here we are trying to declare array as static type but we can not
declare the local array as static type. If we will try to declare the local
variable as static, then will get error : illegal start of expression.

Differences Between Enumeration And Iterator In Java :

1) through Enumeration we can only traverse through the collection object,we cannot
do any modification while through iterator we can remove the element using remove()
while traversing the collection object.remove() is not present in enumeration
interface.

2) Enumeration is a legacy interface used to traverse only the legacy classes like
Vector, HashTable and Stack. Where as Iterator is not a legacy code which is used
to traverse most of the classes in the collection framework. For example,
ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap,
TreeMap etc.

3) iterator is fail-fast in nature,it throws concurrentmodification exception if


collection is modified, other than its own remove() method,during iteration.but
enumeration is fail-safe and and does not hrow any exception if collection is
modified during iteration.

4) as iterator is fail-fast it does not allow other threads to modify the


collection object while iterating,so it is safe and secure than enumeration.

5) Methods in enumeration: hasMoreElements() and nextElement() Methods in


iterator: hasNext(), next() and remove()

Question 5. what is the output of this question?


class Test1 {
static int x = 10;
public
static void main(String[] args)
{
Test1 t1 = new Test1();
Test1 t2 = new Test1();

t1.x = 20;
System.out.print(t1.x + " ");
System.out.println(t2.x);
}
}
Run on IDE
Option
A) 10 10
B) 20 20
C) 10 20
D) 20 10

Output: B
Explanation : static variable is class level variable. if we do update in any
reference then automatically all pointing reference value are changed.

Q 3. What is the output of this program?

class Example {
public static void main(String args[])
{
try {
return;
}
finally
{
System.out.println("Hello India");
}
}
}
Run on IDE
Option
A. Hello India
B. Code run with no output
C. Compile time error
D. Run time error
Output:

A. Hello India
Explanation : In the case of try, catch, finally it is sure that finally block will
run only few cases finally block will not run. Few cases are like �System.exit(0)�
system call in try.

Q 5.What is the output of this program?

class String_Test {
public static void main(String args[])
{
String str1 = new String("Hello World");
String str2 = new String("Hello World");

if (str1 == str2)
System.out.println("Hello Ingland");
else
System.out.println("Hello India");
}
}
Run on IDE
Option
A. Hello India
B. Hello Ingland
C. Compiler time error
D. Run time error
Output:

A. Hello India
Explanation : If we use the new keyword then a new object created, if we use the
double quote then only one object is created and all string reference point to this
object. Here equal() check the string is equal or not and �==� check the reference
point.

1. What will be the output of the following program?

class Geeks
{
public static void main(String[] args)
{
try
{
System.out.println(1/0);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
Run on IDE
Options:
1. java.lang.ArithmeticExcetion
2. / by zero
3. java.lang.ArithmeticExcetion:/ by zero
4. ArithmeticExcetion

The answer is option (2)


Explanation: In the above program, we are calling getMessage() method to print the
exception information. We know that getMessage() method will always be printed as
the description of the exception which is / by zero.

sort an array:

String[] fruits=new String[]{"pineapple","apple","orange",'banana"};


Arrays.sort(fruits);

sort an arraylist:

List<String> fruits = new ArrayList<String>();


fruits.add("Pineapple");
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");

Collections.sort(fruits);

int i=0;
for(String temp: fruits){
System.out.println("fruits " + ++i + " : " + temp);
}

sort an object with comparable:

public class Fruit{

private
String name;
private String desc;
private int qty;

public Fruit(String name,String desc,int qty){


super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}

public String getFruitName() {


return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitDesc() {
return fruitDesc;
}
public void setFruitDesc(String fruitDesc) {
this.fruitDesc = fruitDesc;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}

public int compareTo(Fruit f){


int compQty =((Fruit) f).getQuantity();

//ascending
return this.quantity-compQty;

//descending
return compQty-this.quantity;
}
public class SortObj{

psvm(){
Fruit[] fruits=new Fruit[4];
Fruit pineapple=new Fruit("pineapple", "Pineapple description",70);
Fruit apple = new Fruit("Apple", "Apple description",100);
Fruit orange = new Fruit("Orange", "Orange description",80);
Fruit banana = new Fruit("Banana", "Banana description",90);

fruits[0]=pineappale;
fruits[1]=apple;
fruits[2]=orange;
fruits[3]=banana;

Arrays.sort(fruits);

for(Fruit temp:fruits){
syso("fruits"+temp.getFruitName()+Quantity : " + temp.getQuantity());
}

}
}

sort an object with comparator:

public class Fruit implements Comparable<Fruit>{


private String fruitName;
private String fruitDesc;
private int quantity;

public Fruit(String fruitName, String fruitDesc, int quantity) {


super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}

public String getFruitName() {


return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public String getFruitDesc() {
return fruitDesc;
}
public void setFruitDesc(String fruitDesc) {
this.fruitDesc = fruitDesc;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}

public int compareTo(Fruit f){


int compQty=((Fruit) f).getQuantity();

return this.quantity - compQty;

public static Comparator<Fruit> fruitNmaeComparator=new Comparator<Fruit>(){


public int compare(Fruit f1,Fruit f2)
{
return f1.getFruitName().compareTo(f2.getFruitName();
}
};
}

how to generate serialversionUID?

private static final long serialVersionUID = 1L;

class Geeks
{
public static void main(String[] args)
{
try
{
System.out.println(1/0);
}
System.out.println("Hello GEEKS");
catch(ArithmeticException e)
{
System.out.println("Welcome");
}
}
}
Run on IDE
Options:
1. Hello Geeks
2. Hello Geeks
Welome
3. Run-time Exception
4. Compile-time error

The answer is option (4)


Explanation: In the above program, we are declaring a try block and also a catch
block but both are separated by a single line which will cause compile time error:

Question 1. What is the output of this question?

class Test1 {
public
static void main(String[] args)
{
int arr[] = { 11, 22, 33 };
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");

System.out.println();

int arr2[] = new int[3];


arr2[] = { 11, 22, 33 };
for (int i = 0; i < arr2.length; i++)
System.out.print(arr2[i] + " ");
}
}
Run on IDE
Option
A) 11 22 33
11 22 33
B) Error
C) Exception
D) None

Output: B
Explanation : It�s not a valid Syntax for array declarations. It will give compile
time error : not a statement arr2[] = {11, 22, 33}

Question 2. What is the output of this question?

class Test2 {
public
static void main(String[] args)
{
String str[] = { "Geeks", "for", "Geeks" };
for (int i = 0; i < str.length; i++)
System.out.print(str[i]);
}
}
A)GeeksforGeeks
B)Error
C)Geeks
D)GfG
Run on IDE
Option

Output: A
Explanation : It is a simple one dimension string type array.

what does hashcode method do in java?

hashcode method is defined by object class.this method converts internal address of


object into integer.

If two objects have the same hashcode then they are NOT necessarily equal. ... It
is not required that if two objects are unequal according to the
equals(java.lang.Object) method, then calling the hashCode method on each of the
two objects must produce distinct integer results.

What is the difference between java collection and java collections ?


collection interface is a member of java.util package.List and set are sub
interfaces of collection.Iterable is root interface of collection hierarchy.

collections is an utility class in java.util package.it consists of static methods


which operate on Collection objects.e.g. arraylist and hashset

1) Collections.max()
2) Collections.min()
3) Collections.sort()
4) Collections.synchronizedCollection()

import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}

public class Test{


psvm(){

List<Book> list=new ArrayList<Book>();

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);


Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

list.add(b1);
list.add(b2);
list.add(b3);

for(Book b:list){
syso(b.name+b.author);

}
}
}

treeset maintains ascending order and contain unique elements like hashset.

hashmap:

1) null key ,multiple null values


2) it contain unique elements
3) it maintains no order

import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {

this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}

public class Test{


psvm(){
Map<Integer,Book> map=new HashMap<Integer,Book>();

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);


Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

map.put(1,b1);
map.put(2,b2);
map.put(3,b3);

for(Map.Entry<Integer,Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();

syso(b.id+b.name);

}
}
}

LinkedHashMap: 1 null key,multiple null values

maintains insertion order

contain unique elements

Treemap: 1 null key,multiple null values

maintains ascending order

contain unique elements


What is difference between HashMap and TreeMap?

1) hashmap contains one null key


treemap cannot contain null key

2)hashmap maintains no order


3) treemap maintains ascending order

hashtable also contains unique elements.


it does not have null key and null value
it is synchronized

hashmap and hashtable:

hashmap traversed by iterator.


hashtable traversed both by iterator and enumarator

iterator in hashmap is fail-fast.


enumerator in hashtable is not fail-fast

hashmap extends abstractMap class


hashtable extends Dictionary class

Collections.addAll(list,strArr);

Collections.max(list)

Collections.min(list)

Sorting in collection:

we can sort
1)string objects
2)wrapper class objects
3)user defined class objects

import java.util.*;
class TestSort1{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();


al.add("Viru");
al.add("Saurav");
al.add("Mukesh");
al.add("Tahir");

Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
Output:Mukesh
Saurav
Tahir
Viru

Example of Sorting the elements of List that contains Wrapper class objects
import java.util.*;
class TestSort2{
public static void main(String args[]){

ArrayList al=new ArrayList();


al.add(Integer.valueOf(201));
al.add(Integer.valueOf(101));
al.add(230);//internally will be converted into objects as Integer.valueOf(230)

Collections.sort(al);

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

java comparable interface - it is used to sort the elements on the basis of single
data member-name,age,roll no etc

class Student implements Comparable<Student>


{
int roll;
String name;
int age;

Student(int r,String n,int a){


this.roll=r;
this.name=n;
this.age=a;

public int compareTo(Student st)


{
if (this.age==st.age)
reurn 0;
else if(age>st.age)
return 1;
else
return -1;
}

public class Test{


psvm(){
ArrayList<String> al=new ArrayList<String>();
al.add(new Student(106,"vijay",23);
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

Collections.sort(al);
for(Student st:al)
{
syso(st.name+st.age+st.roll);
}
}
}

java Comparator interface:

class Student {
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}

class AgeComparator implements Comparator{


public int compare(OBject o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;

if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}

class NameComparator implements Comparator{


public int compare(Object o1,Object o2)
{
Student s1=(Student)o1;
Student s2=(Student) o2;

return s1.name.compareTo(s2.name);
}
}

class Simple{
psvm(){
ArrayList al=new ArrayList();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student) itr.next();
syso(st.roll+st.age+st.name);
}

Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}

}
}

db.properties
user=system
password=oracle

psvm(){
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);

syso(p.getProperty("user"));
syso(p.getProperty("password");
}
}

// Main.java
public class Main
{
public static void gfg(String s)
{
System.out.println("String");
}
public static void gfg(Object o)
{
System.out.println("Object");
}

public static void main(String args[])


{
gfg(null);
}
} //end class
Run on IDE
Output:

String
// Main.java
public class Main
{
public static void gfg(String s)
{
System.out.println("String");
}
public static void gfg(Object o)
{
System.out.println("Object");
}
public static void gfg(Integer i)
{
System.out.println("Integer");
}

public static void main(String args[])


{
gfg(null);
}
} //end class
Run on IDE
Output:

Compile Error at line 19.


Explanation: In this case of method Overloading, the most specific method is
choosen at compile time.
As �java.lang.String� and �java.lang.Integer� is a more specific type than
�java.lang.Object�,but between �java.lang.String� and �java.lang.Integer� none is
more specific.
In this case the Java is unable to decide which method to call.

// Main.java
public class Main
{
public static void main(String args[])
{
String s1 = "abc";
String s2 = s1;
s1 += "d";
System.out.println(s1 + " " + s2 + " " + (s1 == s2));

StringBuffer sb1 = new StringBuffer("abc");


StringBuffer sb2 = sb1;
sb1.append("d");
System.out.println(sb1 + " " + sb2 + " " + (sb1 == sb2));
}
} //end class
Run on IDE
Output:

abcd abc false


abcd abcd true
Explanation : In Java, String is immutable and string buffer is mutable.
So string s2 and s1 both pointing to the same string abc. And, after making the
changes the string s1 points to abcd and s2 points to abc, hence false. While in
string buffer, both sb1 and sb2 both point to the same object. Since string buffer
are mutable, making changes in one string also make changes to the other string. So
both string still pointing to the same object after making the changes to the
object (here sb2).

class Geeks throws ArithmeticException {


public
static void main(String[] args) throws ArithmeticException
{
System.out.printl(10 / 0);
System.out.println("Hello Geeks");
}
}
Run on IDE
Options:
1. Hello Geeks
2. No Output
3. Run-time Exception
4. Compile time error

Output:

The answer is option (4)


Explanation : In the above program, we are throwing ArithmeticException from the
class. But we have to take care of the convention when we are using throws keyword
that we can use throws keyword for methods and constructors but not for classes.

class Test {
public
static void main(String[] args)
{
fun();
}
public
static void fun()
{
moreFun();
}
public
static void moreFun() throws InterruptedException
{
Thread.sleep(10000);
System.out.println("GEEKS");
}
}
Run on IDE
Options:
1. GEEKS
2. No Output
3. Compile time error
4. Run-time Exception
Output:

The answer is option (3)


Explanation : In the above program, we are throwing InterruptedException from a
method where exception may be rise. But we will get compile time error saying
error: unreported exception InterruptedException; must be caught or declared to be
thrown because moreFun() method is called by fun() method and fun() method is
called by main() method. Thats why we have to use throws keyword for every caller.

class Test {
public
static void main(String[] args)
{
final int a = 10, b = 20;
while (a > b) {
System.out.println("Hello");
}
System.out.println("GEEKS");
}
}
Run on IDE
Options:
1. Compile time error
2. GEEKS
3. Hello
4. No Output

The answer is option (1)


Explanation: In the above program, we declare two variables as final. In the while
loop, it always returns false and the control does not go inside while loop and it
does not get the chance in the entire program. Thats why we will get compile time
error saying error: unreachable statement.

Vector example:

Vector<String> v=new Vector<String>();

v.add("umesh");
v.addElement("irfan");
v.addElement("kumar");

Enumeration e=v.elements();
while(e.hasMoreElemnts()){
e.nextElement();

}
}

API is a document that contains description of all the features of product or


software.it contains classes and interfaces by which programs can communicate with
each other.API can b created for applications,libraries,operating systems etc

JDBC driver: enables java application to interact with database.

1)jdbc-odbc bridge driver


2) native-api driver(partially java driver)
3) network protocol driver(fully java driver)
4) thin driver(fully java driver)
1) jdbc-odbc bridge driver- uses odbc driver to connect to the database.converts
jdbc method calls to odbc function calls.

java application..... refer to javatpoint for details.

how to ensure thread safety?

by synchronization,using volatile keyword,immutable classes, Thread safe classes.

Abstract class and interface can't b instantiated.


they don't have constructors.

packages are used to avoid naming conflicts,control access protection and search
classes,enumerations,interfaces and annotations easily.

In the below example, what will be the output?

public class superclass {


public void displayResult() {
system.out.println("Printing from superclass");
}
}
public class subclass extends superclass {
public void displayResult() {
system.out.println("Displaying from subClass");
super.displayResult();
}
public static void main(String args[]) {
subclass obj=new subclass();
obj.displayResult();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class superclass {

public void displayResult() {

system.out.println("Printing from superclass");

public class subclass extends superclass {

public void displayResult() {

system.out.println("Displaying from subClass");

super.displayResult();

public static void main(String args[]) {

subclass obj=new subclass();

obj.displayResult();

Ans: Output will be:

Displaying from subclass

Displaying from superclass

In the below example, how many String Objects are created?

String s1="I am Java Expert";


String s2="I am C Expert";
String s3="I am Java Expert";
1
2
3
4
5
String s1="I am Java Expert";

String s2="I am C Expert";

String s3="I am Java Expert";

Ans: In the above example, two objects of Java.Lang.String class are created. s1
and s3 are references to same object.

Why Strings in Java are called as Immutable?

Ans: In java, string objects are called immutable as once value has been assigned
to a string, it can�t be changed and if changed, a new object is created.

In below example, reference str refers to a string object having value �Value one�.

String str="Value One";


1
String str="Value One";

When a new value is assigned to it, a new String object gets created and the
reference is moved to the new object.

Java

str="New Value";
1
str="New Value";

How garbage collection is done in Java?

System.gc() and runtime.gc()

Can we call the constructor of a class more than once for an object?

Ans: Constructor is called automatically when we create an object using new


keyword. It�s called only once for an object at the time of object creation and
hence, we can�t invoke the constructor again for an object after its creation.

What�s the benefit of using inheritance?

1) code reusability

2) extensibility or polymorphism- new functionalities can b introduced without


affecting existing classes

Can we use a default constructor of a class even if an explicit constructor is


defined?
Ans: Java provides a default no argument constructor if no explicit constructor is
defined in a Java class. But if an explicit constructor has been defined, default
constructor can�t be invoked and developer can use only those constructors which
are defined in the class.

Can we override a method by using same method name and arguments but different
return types?

Ans: The basic condition of method overriding is that method name, arguments as
well as return type must be exactly same as is that of the method being overridden.
Hence using a different return type doesn�t override a method.

main method is an entry point of Java class and is required for execution of the
program however; a class gets compiled successfully even if it doesn�t have a main
method. It can�t be run though.

Can we call a non-static method from inside a static method?

Ans: Non-Static methods are owned by objects of a class and have object level scope
and in order to call the non-Static methods from a static block (like from a static
main method), an object of the class needs to be created first. Then using object
reference, these methods can be invoked.

What are the two environment variables that must be set in order to run any Java
programs?

1) path variable
2) classpath variable

JDK is development Kit of Java and is required for development only and to run a
Java program on a machine, JDK isn�t required. Only JRE is required.

Java ThreadLocal:

ThreadLocal is used to create thread local variables. all thread objects share its
variables,so the variables r not thread safe.for thread safety, we can use
synchronization but if we r avoiding synchnization ,we can use threadlocal
variables.

every thread has its own threadlocal variable and we can use get() and set()
methods to get the value or change the value local to thread.

package com.journaldev.threads;

import java.text.SimpleDateFormat;
import java.util.Random;

public class ThreadLocalExample implements Runnable{


// SimpleDateFormat is not thread-safe, so give one to each thread
private static final ThreadLocal<SimpleDateFormat> formatter = new
ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue()
{
return new SimpleDateFormat("yyyyMMdd HHmm");
}
};

public static void main(String[] args) throws InterruptedException {


ThreadLocalExample obj = new ThreadLocalExample();
for(int i=0 ; i<10; i++){
Thread t = new Thread(obj, ""+i);
Thread.sleep(new Random().nextInt(1000));
t.start();
}
}

@Override
public void run() {
System.out.println("Thread Name= "+Thread.currentThread().getName()+"
default Formatter = "+formatter.get().toPattern());
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
//formatter pattern is changed here by thread, but it won't reflect to
other threads
formatter.set(new SimpleDateFormat());

System.out.println("Thread Name= "+Thread.currentThread().getName()+"


formatter = "+formatter.get().toPattern());
}

what is thread dump?

thread dump is a list of active threads in JVM.it is used to analyze bottlenecks


and deadlock situation in application.

we can create thread dump by - Profiler,kill-3 command and jstack tool.jstack tool
is easy to use and comes along with jdk installation.

Explain the usage of this() with constructors?


It is used with variables or methods and used to call constructer of same class.

JAR files is Java Archive fles and it aggregates many files into one. It holds Java
classes in a library. JAR files are built on ZIP file format and have .jar file
extension.

What are the ways in which a thread can enter the waiting state?
by wait() or sleep()

Does it matter in what order catch statements for FileNotFoundException and


IOException are written?
Yes, it does. The FileNoFoundException is inherited from the IOException.
Exception's subclasses have to be caught first.

What is the difference between yielding and sleeping?


When a task invokes its yield() method, it returns to the ready state. When a task
invokes its sleep() method, it returns to the waiting state.

Can you write a Java class that could be used both as an applet as well as an
application?
Yes, just add a main() method to the applet.

Can a variable be local and static at the same time?

Ans: No a variable can�t be static as well as local at the same time. Defining a
local variable as static gives compilation error.

In a class implementing an interface, can we change the value of any variable


defined in the interface?

Ans: No, we can�t change the value of any variable of an interface in the
implementing class as all variables defined in the interface are by default public,
static and Final and final variables are like constants which can�t be changed
later.

I want my class to be developed in such a way that no other class (even derived
class) can create its objects. How can I do so?

Ans: If we declare the constructor of a class as private, it will not be accessible


by any other class and hence, no other class will be able to instantiate it and
formation of its object will be limited to itself only.

In java, there is no way to find out the exact size of an object on the heap.

Which of the following classes will have more memory allocated?

Class A: Three methods, four variables, no object

Class B: Five methods, three variables, no object

Ans: Memory isn�t allocated before creation of objects. Since for both classes,
there are no objects created so no memory is allocated on heap for any class.

Although String and StringBuffer both represent String objects, we can�t compare
them with each other and if we try to compare them, we get an error.
No, we can neither cast any other primitive type to Boolean data type nor can cast
Boolean data type to any other primitive data type.

What�s the order of call of constructors in inheritiance?

Ans: In case of inheritance, when a new object of a derived class is created, first
the constructor of the super class is invoked and then the constructor of the
derived class is invoked.

java.util.Timer task is an abstract class that implements Runnable interface .it is


used to schedule a task to run one -time or at regular intervals

a thread pool manages a pool of worker threads.executors provide implementation of


executor interface to create thread pool in java.
Creating a lot many threads with no bounds to the maximum threshold can cause
application to run out of heap memory. So, creating a ThreadPool is a better
solution as a finite number of threads can be pooled and reused. Executors
framework facilitate process of creating Thread pools in java.

nothing will happen if we don�t override the run() method.

BlockingQueue supports producer-consumer problem.


this doesn't allow null values and throws null pointer exception if queue stores
null values.blockingqueue is thread-safe.

CopyOnWriteArrayList or concurrenthashmap makes the collection classes fail safe.

The code sleep(2000); puts thread aside for exactly two seconds. The code
wait(2000), causes a wait of up to two second. A thread could stop waiting earlier
if it receives the notify() or notifyAll() call. The method wait() is defined in
the class Object and the method sleep() is defined in the class Thread.

The garbage collector invokes an object's finalize() method when it detects that
the object has become unreachable.

What will happen if static modifier is removed from the signature of the main
method?
Program throws "NoSuchMethodError" error at runtime.

When a thread is created and started, what is its initial state?


A thread is in the ready state as initial state after it has been created and
started.
Why deletion in LinkedList is fast than ArrayList?

Deletion in linked list is fast because it involves only updating the next pointer
in the node before the deleted node and updating the previous pointer in the node
after the deleted node.

Where and how can you use a private constructor?


Private constructor is used if you do not want other classes to instantiate the
object and to prevent subclassing.

No, Java does not allow Default Arguments.

jQuery is not a programming language but a well written JavaScript code. It is a


JavaScript code, which do document traversing, event handling, Ajax interactions
and Animations.

What are the methods used to provide effects?

Some of the effects methods are:

Show()
Hide()
Toggle()
FadeIn() and
FadeOut()

Improve the performance of an application


Very fast and extensible

if minimized version of jquery is used, min.js will b more than 50 percent less
than normal js file.reduction in file size makes web page faster.

jquery is a single javascript file.it is a javascript library file which contains


DOM,event effects and ajax functions in it.

Mac, Windows and Linux are more compatible with the jQuery.

Find method is used to find all levels down the DOM tree but children find single
level down the DOM tree.

A � jQuery connect� is a plugin used to connect or bind a function with another


function. Use $.connect function to connect a function to another function.

what are basic selectors in jquery?

element id, tag name,css name, DOM hierachy

What is the use jQuery.data method?


jquery.data is used to associate data with DOM nodes and objects.

What is the use of each function in jQuery?

each function is used to iterate each and every element of an object, arrays or DOM
elements.

What is the difference between size and length of jQuery?

size and length both returns no. of elements in an object. length is faster than
size becoz length is a property and size is a method.

Can we add more than one �document.ready� function in a page?

Yes, we can add more than one document.ready function in a page. But, body.onload
can be added once in a page.

What is the use of jQuery load method?

jquery load method is used to load data from server and assign data to the element
without loading the page.

Whether our own specific characters are used in place of $ in jQuery?


var sample = $.noConflict()

What are the four parameters used for jQuery Ajax method?

url- specify url to send the request


type- type of request(GET/POST)
data- data to b sent to server

jquery filter - is used to filter certain values from the object list based on
criteria

Which sign is used as a shortcut for jQuery?


dollar($) sign

jQuery is a client scripting.It is a javascript file that contains DOM, event


effects and Ajax functions.

jquery.ajax is used for asynchronous HTTP requests.

Where can we download JQuery?


it can b downloaded from jquery.com

Is jQuery is a replacement of JavaScript?no

What is called chaining?


chaining is used to connect multiple events and functions in a selector.
What are the advantages of jQuery?
it is a javascript enhancement
coding is simple and reusable

What is the difference between onload() and document.ready()?

we can have one onload() function but more than one document.ready() function.
document.ready is called when DOM is loaded but onload function is called when DOM
and images are loaded on the page.

How method can be called inside code behind using jQuery?

$.ajax can b called and by declaring WebMethod inside code behind using jquery.

Which is the fastest selector in jQuery?


id and element

What is the slowest selector in jQuery?


class selectors

Where jQuery code is getting executed?


it is executed on client browser

What is the method used to define the specific character in place of $ sign?
NoConflict

Why jQuery is better than JavaScript?


jquery is a library used for developing ajax application and helps us to write
clean and concise code.it is also used for ajax interactions,event handling and
animation.

What are the types of selectors in jQuery?


CSS selector
custom selector
xpath selector

benefits of collections framework are:

1) reduced development effort by using core collection classes instaed of our own
collection classes

2) code quality is enhanced by using collection framework classes

3)reusability

What is currentThread()?
it is a public static method used to obtain a reference to the current thread

Explain main thread under Thread class execution?

main thread executes automatically when program starts.it is a thread from which
all other child threads originate.

Why Generics are used in Java?


Generics provide compile-time type safety,avoid classcast exception at run time

What is Nested top-level class?

Nested top-level class is inner class.


if a class is declared within a class and it has a static modifier,then the
compiler treat it like any other top-level class.

What is Externalizable interface?

this class contains two methods- readExternal and writeExternal.this gives u a


control on serialization mechanism.

Which method must be implemented by all threads?

run()

What is Ajax?
ajax-asynchronous javascript and xml.it is not a programming language. it is used
to create faster,better and interactive web applications.this uses asynchronous
data transfer between browser n server.

What are all the controls of Ajax?

scriptmanager
scriptmanagerproxy
updatepanel
updateprogress
timer

What is the name of the DLL that contains Ajax control tool kit?
ajaxcontroltoolkit.dll is used for ajax control tool kit and can b downloaded from
internet.

How many types of triggers are present in update panel?


postbacktrigger
asyncpostbacktrigger

How to control the duration of an Ajax request?

asyncpostbacktimeout is used to control duration of ajax request. default is 90


seconds.

What are the advantages of Ajax?

more interactive
faster
retrieval of data
saves memory when data is fetched from same page
What are the disadvantages of Ajax?

1) ajax is dependant on javascript.if there is some javascript problem in the


browser or in the OS,Ajax will not support.
2) it can cause problem in search engines as it mostly uses javascript

3)ajax source code is human readable.so this may cause security issues

4)increases size of requests

5) slow or unreliable network


6) problem with browser back button becoz of ajax enabled pages
7) debugging is difficult

What is update panel?


it is a server control.it is used to update specified portion of web page.script
manager is used whenever update panel is used.using update panel,user cannot handle
outside controls.

What are all the technologies used by Ajax?

javascript,xhtml,css,DOM,xmlhttprequest

What is JSON in Ajax?


javascript object notation.it is data interchange format in javascript

What are the components of Struts Framework?

java servlets,jsp,custom tags,message resources

What�s the role of a handler in MVC based applications?

handler is used to transfer requests to appropriate models.they get mapping


information from configuration files for transferring requests.

What�s the flow of requests in Struts based applications?

based on MVC design pattern.


user interacts with view by clicking on link or submitting the form.
request is passed to controller
controller passes request to appropriate action
action calls a function in model where all business logic is implemented.
response from model is received back by action which passes to the view where user
can see the response.

Which file is used by controller to get mapping information for request routing?
strutsconfig.xml

How an actionForm bean is created?

by extending org.apache.struts.action.actionform

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
public class testForm extends ActionForm {
private String Id=null;
private String State=null;
public void setId(String id){
this.Id=id;
}
public String getId(){
return this.Id;
}
public void setState(String state){
this.State=state;
}
public String getState(){
return this.State;
}

What are the two types of validations supported by Validator FrameWork?

client side
server side

What are the steps of Struts Installation?

add struts.jar in development environment.once jar file is available in


classpath,we can use struts framework and develop struts based aplications

How client side validation is enabled on a JSP form?

by using validator plug-in in struts-config.xml.

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-
INF/validation.xml"/>

then validation rules r defined in validation.xml file.if a form contains email


field and want to enable client side validation for this field:

<form name="testForm">
<field property="email" depends="required">
<arg key="testForm.email"/>
</field>
</form>

How action-mapping tag is used for request forwarding in Struts configuration file?

<action path="/test" forward="/pages/testing.jsp">

In Struts, how can we access Java beans and their properties?

bean tag library is a struts library used for accessing java beans

Which configuration file is used for storing JSP configuration information in


Struts?

web.xml
What�s the purpose of Execute method of action class?
used for execution of business logic.this method returns actionforward object which
passes application to appropriate page.

Java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class actionExample extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("exampleAction");
}
}

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class actionex extends Action{


public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("exampleAction");
}
}

What�s the difference between validation.xml and validator-rules.xml files in


Struts Validation framework?

in validation.xml,we define validation rules for any java bean while in validator-
rules.xml,standard and generic validation rules r defined.

How can we display all validation errors to user on JSP page?

by <html:errrors/> in jsp page

What�s declarative exception handling in Struts?

<global-exceptions>
<exception key="test.key" type="java.lang.NullPointerException" path="/web-
inf/errors/error_page.jsp">
</g-e>
What�s DynaActionForm?

Collection is the root of the collection hierarchy.

enumeration is twice as fast as iterator and uses ver less memory.

listiterator inherits from iterator interface and has some extra functionalities
like adding element,replacing elemnt,getting index position for previous n next
element.

all the collection classes in java.util package are fail-fast whereas collection
classes in java.util.concurrent are fail-safe.

UnsupportedOperationException indicates that operation is not supported.this is


thrown for add n remove operations.

HashMap initial default capacity is 16 and load factor is 0.75.threshold is


capacity*load factor.when we try to add an entry and map size is greater than
threshold,then contents of hashmap are rehashed into a new array with larger
capacity.capacity is always a power of 2.

If o1.equals(o2), then o1.hashCode() == o2.hashCode()should always be true.


If o1.hashCode() == o2.hashCode is true, it doesn�t mean that o1.equals(o2) will be
true.

What is the importance of hashCode() and equals() methods?

If these methods are not implemented correctly, two different Key�s might produce
same hashCode() and equals() output and in that case rather than storing it at
different location, HashMap will consider them same and overwrite them.

Can we use any class as Map key?

No,only immutable keys.if the keys r not immutable,hashcode() and equlas() for the
key will change.and when we will try to look for the key in the same index, there
will b no match as the key is mutated and it will return null.

e.g.

//MyKey name argument passed is used for equals() and hashCode()


MyKey key = new MyKey("Pankaj"); //assume hashCode=1234
myHashMap.put(key, "Value");

// Below code will change the key hashCode() and equals()


// but it's location is not changed.
key.setName("Amit"); //assume new hashCode=7890

//below will return null, because HashMap will try to look for key
//in the same index as it was stored but since key is mutated,
//there will be no match and it will return null.
myHashMap.get(new MyKey("Pankaj"));

This is the reason why String and Integer are mostly used as HashMap keys.

What are different Collection views provided by Map interface?


entrySet(),keySet() and values().

hashmap is fail-fast but hashtable is fail-safe.

Vector, Hashtable, Properties and Stack are synchronized classes,

What is Queue and Stack, list their differences?

stack-lifo

queue-fifo

stack is a class which extends vector but queue is an interface

What is Collections Class?

it is a utility classconsisting of methods that operate on collections.


class A {
A() {
System.out.println("class A");
}
}
class B extends A {
B() {
System.out.println("class B");
}
}
class C extends B {
public static void main(String args[]) {
C c = new C(); //
}
}

How many number of Object is created in this case.


When you create an instance of Class C by C cInstance = new C(); a single
instance(Object) of Class C is creates(None of A and B). However since C extends B
and B extends A, C will have all the methods of Class A and B(Actually depends on
access modifiers used but lets say for this case they are public or default).

If one object is created then how internally Super() is calling Parent class
Constructor
. How Super is able to call parent class constructor.
That is how inheritance works. When a new object is created it will call it's super
class constructor and that super class will call it's super class constructor and
so on. In other ordinary function you have to explicitly call super(). So calling
super class constructor goes bottom-up fashion while execution goes top-down
fashion of the inheritance hierarchy tree
What is the difference between inner class and nested class?

when a class is defned within scope of another class ,it is inner class.if the
inner class has static modifier ,it is nested class.

How does a try statement determine which catch clause should be used to handle an
exception?

When an exception is thrown within the body of a try statement, the catch clauses
of the try statement are examined in the order in which they appear. The first
catch clause that is capable of handling the exception is executed. The remaining
catch clauses are ignored.

What are the difference between AJAX and Javascript?

ajax- it sends request to server and does not wait for response.it do some other
operations on the page during that time.

js- sends request to server and waits for response.

ajax minimizes load on server as it sends the request once.


js- js posts a request which updates script every time.

Where AJAX cannot be used?

if browser does not support javascript.


if we want to create secure application

How can you find out that an AJAX request has been completed?
if readyState property is equal to 4,then request has been completed and data is
available.

Is javascript knowledge is required to do Ajax?


yes

internet explorer support ajax

How can you test the Ajax code?


jsunit which is a part of junit.jsunit is client side jvascript code

Ajax supports both technology and as architectural style.

Abort() method can be called to cancel the XMLHttpRequest in Ajax.

XmlHttpRequest object is used for Ajax requests.

Script Manager is pre-requisite to use Update Panel controls.

There are no restrictions on the number of update panels per page.


What is Script Manager?
as ajax depends on javascript,script manager acts as a mediator.all the pages that
uses ajax has a script manager for enabling ajax libraries

How Ajax objects can be created?

var sample=new AjaxObject('path of page');

What are the protocols used by Ajax?


http's get/post method
xmlhttprequest
json to communicate betwn client n server
url encoded data

What�s DynaActionForm?

it is an actionform class used for dynamically creating form beans.

What configuration changes are required to use Tiles in Struts?

<plug-in className="org.apache.struts.tiles.TilesPlugin">
<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/>
<set-property property="moduleAware" value="true"/>
</plug-in>

How tag libraries are defined in Struts?


<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</>
<taglib-location>/WEB-INF/struts-bean.tld</>

</taglib>

You might also like