Professional Documents
Culture Documents
Entry class objects are stored in an array, not as key value pair.
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.
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".
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.
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 HashSet()
{
map=new HashMap<>();
}
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>
e.g.
<message name="EmpNameRequest">
<part name="EmpId"type="xsd:number">
</message>
<message name="EmpNameResponse">
<part name="EmpName" type="xsd:string"/>
</message>
For binding:
class Animal{
public void animalSound(){
System.out.println("Default Sound");
}
}
public class Dog extends Animal{
Woof
Animal obj = new Animal();
obj.animalSound();
// This would call the Animal class method
Constructors
Static methods
Private methods
Methods that are declared �final�
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.
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.
psvm(){
t1.start();
t2.start();
t1.join();
t2.join();
synchronized(this)
{
wait();
}
Thread.sleep(1000);
synchronized(this)
{
notify();
Thread.sleep(1000);
}
}
class Sender{
public void send(String msg){
Thread.sleep(1000);
}
}
Thread1(String m,Sender s)
{
msg=m;
sender=s;
}
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();
}
}
synchronized(this){
while(list.size()==capacity)
{
wait();
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
int val=list.removeFirst();
notify();
}}}
Thread pools:
Thread.sleep(1000);
}
}
ExecutorService pool=Executors.newFixedThreadPool(MAX_T);
pool.execute(r1);
pool.execute(r2);
pool.execute(r3);
pool.execute(r4);
pool.execute(r5);
pool.shutdown();
}
}
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.
deadlock:
class Util{
static void sleep(long millis)
{
Thread.sleep(millis);
}
}
class Shared{
synchronized void test1(Shared s2){
Utils.sleep(1000);
s2.test2(this);
}
t1.start();
t2.start();
Utils.sleep(2000);
}
}
1)avoid nested locks - avoid giving lock to multiple threads when u have given to
one.
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.
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:
http://localhost:7779/ws/hello?wsdl
helloworldclient.java
Service service=Service.create(url,qname);
HelloWorld hello=service.getPort(HelloWorld.class);
sop(hello.getHelloWorldAsString("javatpoint rpc"));
}
}
Op o=new O("okay")
String s1="java";
String s2="java";
1 object only
jax-rs example:
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
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-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();
}
}
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>
t=null;
System.gc();
}
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
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
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
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
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.
interface Showable{
void show();
interface Message{
void msg();
}
}
psvm(){
Showable.Message message=new Test();
mesaage.msg();
}
}
Example of nested interface which is declared within the class:
class A{
interface Message{
void msg();
}
}
psvm(){
A.Message msg=new Test();
msg.msg();
}
}
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.
You can use set intersection operations with your ArrayList objects.
l1.add(1);
l1.add(2);
l1.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 :
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:
SQL constaints:
syntax:
1) not null:
2) unique
3) primary key
4)foreign key
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).
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'));
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.
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.
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,sum(score) as total from marks group by student having total > 70
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?
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.
stored proc can b called directly. but triggers cannot b. they can only b
associated with queries.
@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.
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
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.
class Account{
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:
public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
index - a data structure which improves data rerieval operations in database table
but consumes more storage space on the disk
t1.start();//starting threads
t1.start();
t1.setDaemon(true);//will throw exception here
tg1.getName();
tg1.list();
}
}
e1=e2;
class Table{
}
}
}
}
example of deadlock:
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
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;
this.amount-=amount;
}
class Test{
psvm(){
new Thread(){
public void run(){
c.deposit(10000);
}.start();
}}
t1.start();
t2.start();
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.
e.g.:
public class A{
private void messgae(){
syso("hello");
}
}
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
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);
int i=200;
String s=String.format("%d",i);
o/p:200
psvm(String... args)
{
List<String> flavors=new ArrayList<>();
flavors.add("vanilla");
flavors.add("choc");
useWhileLoop(flavors);
useForLoop(flavors);
Iterator<String> itr=aFlavors.iterator();
while(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:
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:
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:
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
synchronized(list){
3)hashset allows no duplicate values but hashmap allows duplicate values but no
duplicate keys
hashset to arraylist:
hashSet.add("1");
hashSet.add("2");
hashSet.to array:
hashSet.add("1");
hashSet.add("2");
for(String temp:arr){
syso(temp);
}
// Add elements
list.add("AA");
list.add("BB");
list.add("CC");
list.add("DD");
list.offerFirst("new");
o/p- [new,aa,bb,cc,dd]
Output:
HashMap vs Hashtable:
HashMap allows one null key and any number of null values.
Hashtable doesn�t allow null keys and null values.
Enumeration en=ht.keys();
for(Enumeration en=ht.elements();en.hasMoreElements();en.nextElement(){
ht.put(key,value);
}
//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");
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=sortByValues(hmap);
Set set2=map.entrySet();
Iterator itr=set2.iterator();
while(itr.hasNext()){
syso(me2.getValue());
}
}
}
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
return sortedHashMap;
}
}
ConcurrentHashMap:
Iterator<String> itr=map.keySet().iterator();
while(itr.hasNext()){
String key=it.next();
if(key.equals("3")){
map.put(key+"new","new3");
}
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");
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 {
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.
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.
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.
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.
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.
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.
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
sort an array:
sort an arraylist:
Collections.sort(fruits);
int i=0;
for(String temp: fruits){
System.out.println("fruits " + ++i + " : " + temp);
}
private
String name;
private String desc;
private int qty;
//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());
}
}
}
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
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();
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}
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.
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.
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;
}
}
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:
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;
}
}
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);
}
}
}
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[]){
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[]){
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
Collections.sort(al);
for(Student st:al)
{
syso(st.name+st.age+st.roll);
}
}
}
class Student {
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
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");
}
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");
}
// 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));
Output:
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:
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
Vector example:
v.add("umesh");
v.addElement("irfan");
v.addElement("kumar");
Enumeration e=v.elements();
while(e.hasMoreElemnts()){
e.nextElement();
}
}
packages are used to avoid naming conflicts,control access protection and search
classes,enumerations,interfaces and annotations easily.
super.displayResult();
obj.displayResult();
Ans: In the above example, two objects of Java.Lang.String class are created. s1
and s3 are references to same object.
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�.
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";
Can we call the constructor of a class more than once for an object?
1) code reusability
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.
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;
@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());
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.
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()
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.
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.
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?
In java, there is no way to find out the exact size of an object on the heap.
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.
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.
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.
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.
Show()
Hide()
Toggle()
FadeIn() and
FadeOut()
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.
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.
each function is used to iterate each and every element of an object, arrays or DOM
elements.
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.
Yes, we can add more than one document.ready function in a page. But, body.onload
can be added once in a page.
jquery load method is used to load data from server and assign data to the element
without loading the page.
What are the four parameters used for jQuery Ajax method?
jquery filter - is used to filter certain values from the object list based on
criteria
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.
$.ajax can b called and by declaring WebMethod inside code behind using jquery.
What is the method used to define the specific character in place of $ sign?
NoConflict
1) reduced development effort by using core collection classes instaed of our own
collection classes
3)reusability
What is currentThread()?
it is a public static method used to obtain a reference to the current thread
main thread executes automatically when program starts.it is a thread from which
all other child threads originate.
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.
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.
more interactive
faster
retrieval of data
saves memory when data is fetched from same page
What are the disadvantages of Ajax?
3)ajax source code is human readable.so this may cause security issues
javascript,xhtml,css,DOM,xmlhttprequest
Which file is used by controller to get mapping information for request routing?
strutsconfig.xml
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;
}
client side
server side
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-
INF/validation.xml"/>
<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?
bean tag library is a struts library used for accessing java beans
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;
in validation.xml,we define validation rules for any java bean while in validator-
rules.xml,standard and generic validation rules r defined.
<global-exceptions>
<exception key="test.key" type="java.lang.NullPointerException" path="/web-
inf/errors/error_page.jsp">
</g-e>
What�s DynaActionForm?
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.
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.
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.
//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.
stack-lifo
queue-fifo
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.
ajax- it sends request to server and does not wait for response.it do some other
operations on the page during that time.
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.
What�s DynaActionForm?
<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>
</taglib>