1) Factory Pattern Example:
Shape
Circle
Rectangle
Triangle
package others;
interface Shape {
public
void draw();
}
class Circle implements
Shape {
public
void draw() {
System.out.println("circle..");
}
}
class Triangle implements
Shape {
public
void draw() {
System.out.println("tringle..");
}
}
class Rectangle implements
Shape {
public
void draw() {
System.out.println("Rectangle..");
}
}
class ShapeFactory
{
public
Shape getShape(String type)
{
if(type
== null)
return
null;
if(type.equalsIgnoreCase("circle"))
return
new Circle();
if(type.equalsIgnoreCase("rectangle"))
return
new Rectangle();
if(type.equalsIgnoreCase("Triangle"))
return
new Triangle();
else
return
null;
}
}
public class
FactoryImpl {
public
static void main(String s[])
{
ShapeFactory
sf = new ShapeFactory();
Shape
s1 = sf.getShape("circle");
s1.draw();
Shape
s2 = sf.getShape("triangle");
s2.draw();
Shape
s3 = sf.getShape("rectangle");
s3.draw();
Shape
s4 = sf.getShape(null);
s4.draw();
}
}
2)
Function overriding rules:
1)
If
we are overriding a method, and making object of child class and assign it in
parent ref variable, then the method call will always execute method of child
(or we can say method of class for which object is created). If the method does
not exist in child them it will execute the class of parent.
2)
We
cannot reduce the visibility of overridden method, means a public method cannot
be overridden as private or protected.
3)
We
cannot override private methods; if we do so then it will automatically make it
as local method, so no override.
4)
If
we put throws in parent method then, we are allowed to omit it in child
overridden method.
5)
If
we put throws in parent method and in child method also, then child throwing
exception will always be lower than parent one for example if parent is
IOException then we cannot put Exception in child class.
package others;
import java.io.IOException;
import java.util.HashSet;
class A {
public void printTest(int i) throws
IOException {
System.out.println("A");
}
}
public class OverrideTest extends
A {
@Override
public void printTest(int j) {
System.out.println("B");
}
public
static void main(String s[]) {
OverrideTest a = new
OverrideTest();
a.printTest(10);
}
4) What is class loader?
The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine.[1] Usually classes are only loaded on demand. The Java run time system does not need to know about files
and file systems because of classloaders. Delegation is an important concept to understand when learning about classloaders.
Java ClassLoader loads a java class file
into java virtual machine. It is as simple as that. It is not a huge
complicated concept to learn and every java developer must know about the java
class loaders and how it works.
Types (Hierarchy) of Java
Class Loaders
Java class loaders can be broadly classified
into below categories:
- Bootstrap
Class Loader
Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs. - Extensions
Class Loader
JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader. - System
Class Loader
Java classes that are available in the java classpath are loaded using System class loader.
You can see more class loaders like
java.net.URLClassLoader, java.security.SecureClassLoader etc. Those are all
extended from java.lang.ClassLoader
10) String s =
“a^b^c~1^2^3~k^l^m……”;
Print above result in
following format:
a
b c
1
2
3
K
l
m
Answer:
package
others;
public
class StringPattern {
public static void
main(String s[])
{
String str =
"a^b^c~1^2^3~k^l^m~5^6^7";
for(int
i=0;i<str.length();i++)
{
if(str.charAt(i) ==
'^')
{
System.out.print(str.charAt(i-1)
+ " ");
}
if(str.charAt(i) ==
'~')
{
System.out.print(str.charAt(i-1)
+ " ");
System.out.println();
}
if(i==str.length()-1)
{
System.out.print(str.charAt(i)
+ " ");
}
}
}
}
7) System.out.println() –
is it overloaded – go inside to check.
Ans:
yes it is overloaded, println() function further calls println().
6) how json is internally
formed from a class object in restful webservice.
@RequestMapping(value="/getuserrole",method
= RequestMethod.GET)
public @ResponseBody
Map<String,Map<String,List<String>>> getUserRoleList(@RequestParam("sso") String sso) {
List<String> lstAvailableRoles = new ArrayList<String>();
List<String> lstAssignedRoles = new ArrayList<String>();
Map<String,List<String>> mpRoles = new HashMap<String,List<String>>();
Map<String,Map<String,List<String>>> result = new HashMap<String,Map<String,List<String>>>();
lstAvailableRoles = usrRoleService.getAvailableRoleList(sso);
lstAssignedRoles = usrRoleService.getAssignedRoleList(sso);
mpRoles.put(AppConstant.AVAILABLE_ROLE, lstAvailableRoles);
mpRoles.put(AppConstant.ASSIGNED_ROLE, lstAssignedRoles);
result.put(AppConstant.RESULTS,mpRoles);
return result;
}
public @ResponseBody
Map<String,Map<String,List<String>>> getUserRoleList(@RequestParam("sso") String sso) {
List<String> lstAvailableRoles = new ArrayList<String>();
List<String> lstAssignedRoles = new ArrayList<String>();
Map<String,List<String>> mpRoles = new HashMap<String,List<String>>();
Map<String,Map<String,List<String>>> result = new HashMap<String,Map<String,List<String>>>();
lstAvailableRoles = usrRoleService.getAvailableRoleList(sso);
lstAssignedRoles = usrRoleService.getAssignedRoleList(sso);
mpRoles.put(AppConstant.AVAILABLE_ROLE, lstAvailableRoles);
mpRoles.put(AppConstant.ASSIGNED_ROLE, lstAssignedRoles);
result.put(AppConstant.RESULTS,mpRoles);
return result;
}
9) how annotation works
internally.
Ans:
The first main distinction between kinds of annotation is
whether they're used at compile time and then discarded (like
@Override
) or placed in the compiled class file and available at
runtime (like Spring's @Component
). This is
determined by the @Retention policy of
the annotation. If you're writing your own annotation, you'd need to decide
whether the annotation is helpful at runtime (for autoconfiguration, perhaps)
or only at compile time (for checking or code generation).
When compiling code with annotations, the compiler sees
the annotation just like it sees other modifiers on source elements, like
access modifiers (
public
/private
) or final
. When it
encounters an annotation, it runs an annotation processor, which is like a
plug-in class that says it's interested a specific annotation. The annotation
processor generally uses the Reflection API to inspect the elements being
compiled and may simply run checks on them, modify them, or generate new code
to be compiled. @Override
is an
example of the first; it uses the Reflection API to make sure it can find a
match for the method signature in one of the superclasses and uses the Messager
to cause a compile error if it can't.
There are a number of tutorials available on writing
annotation processors; here's a useful one. Look
through the methods on the
Processor
interface for how the
compiler invokes an annotation processor; the main operation takes place in the process
method,
which gets called every time the compiler sees an element that has a matching
annotation.
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodInfo{
String
author() default "Pankaj";
String
date();
int revision() default 1;
String
comments();
}
·
Annotation methods can’t have parameters.
·
Annotation methods return types are limited
to primitives, String, Enums, Annotation or array of these.
·
Annotation methods can have default values.
·
Annotations can have meta annotations
attached to them. Meta annotations are used to provide information about the
annotation. There are four types of meta annotations:
1.
@Documented – indicates
that elements using this annotation should be documented by javadoc and similar
tools. This type should be used to annotate the declarations of types whose
annotations affect the use of annotated elements by their clients. If a type
declaration is annotated with Documented, its annotations become part of the
public API of the annotated elements.
2.
@Target – indicates
the kinds of program element to which an annotation type is applicable. Some
possible values are TYPE, METHOD, CONSTRUCTOR, FIELD etc. If Target
meta-annotation is not present, then annotation can be used on any program
element.
3.
@Inherited – indicates
that an annotation type is automatically inherited. If user queries the
annotation type on a class declaration, and the class declaration has no
annotation for this type, then the class’s superclass will automatically be
queried for the annotation type. This process will be repeated until an
annotation for this type is found, or the top of the class hierarchy (Object)
is reached.
4.
@Retention – indicates
how long annotations with the annotated type are to be retained. It takes
RetentionPolicy argument whose Possible values are SOURCE, CLASS and RUNTIME
Java Built-in
Annotations
Java Provides three built-in annotations.
1.
@Override – When we want to override a method of
Superclass, we should use this annotation to inform compiler that we are
overriding a method. So when superclass method is removed or changed, compiler
will show error message. Learn why we should always use java override annotation while overriding a method.
2.
@Deprecated – when we want the compiler to know
that a method is deprecated, we should use this annotation. Java recommends
that in javadoc, we should provide information for why this method is deprecated
and what is the alternative to use.
3.
@SuppressWarnings – This is just to tell compiler to
ignore specific warnings they produce, for example using raw types in java generics. It’s retention policy is SOURCE and
it gets discarded by compiler.
Calling above defined
custom annotation – MethodInfo
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class AnnotationExample
{
public static void main(String[] args) {
}
@Override
@MethodInfo(author
= "Pankaj", comments = "Main method", date = "Nov 17
2012", revision = 1)
public String toString() {
return "Overriden toString method";
}
@Deprecated
@MethodInfo(comments
= "deprecated method", date = "Nov 17 2012")
public static void oldMethod() {
System.out.println("old
method, don't use it.");
}
@SuppressWarnings({
"unchecked", "deprecation" })
@MethodInfo(author
= "Pankaj", comments = "Main method", date = "Nov 17
2012", revision = 10)
public static void genericsTest() throws FileNotFoundException
{
List
l = new ArrayList();
l.add("abc");
oldMethod();
}
}
Parsing above annotation
defined:
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class AnnotationParsing
{
public static void main(String[] args) {
try {
for (Method method : AnnotationParsing.class
.getClassLoader()
.loadClass(("com.journaldev.annotations.AnnotationExample"))
.getMethods())
{
//
checks if MethodInfo annotation is present for the method
if (method
.isAnnotationPresent(com.journaldev.annotations.MethodInfo.class))
{
try {
//
iterates all the annotations available in the method
for (Annotation anno : method.getDeclaredAnnotations()) {
System.out.println("Annotation
in Method '"
+
method + "' : " + anno);
}
MethodInfo
methodAnno = method
.getAnnotation(MethodInfo.class);
if (methodAnno.revision() == 1) {
System.out.println("Method
with revision no 1 = "
+
method);
}
}
catch (Throwable ex) {
ex.printStackTrace();
}
}
}
}
catch (SecurityException | ClassNotFoundException
e) {
e.printStackTrace();
}
}
}
19) what is JMS:
Ans:
JMS Tutorial
JMS (Java
Message Service) is an API that provides the facility to create, send and read
messages. It provides loosely coupled, reliable and asynchronous communication.
Requirement of JMS
Generally,
user sends message to application. But, if we want to send message from one
application to another, we need to use JMS API.
Consider a
scenario, one application A is running in INDIA and another application B is
running in USA. To send message from A application to B, we need to use JMS.
Advantage of JMS
1) Asynchronous: To receive the message, client is not
required to send request. Message will arrive automatically to the client.
2) Reliable: It provides assurance that message is
delivered.
1)
Point-to-Point (PTP) Messaging Domain
In PTP
model, one message is delivered
to one receiver only. Here, Queue is used as a message oriented
middleware (MOM).
The Queue
is responsible to hold the message until receiver is ready.
In PTP
model, there is no timing
dependency between sender and
receiver.
2)
Publisher/Subscriber (Pub/Sub) Messaging Domain
In Pub/Sub
model, one message is delivered
to all the subscribers. It is like broadcasting. Here, Topic is used as a message oriented
middleware that is responsible to hold and deliver messages.
In PTP
model, there is timing
dependency between publisher
and subscriber.
JMS Programming Model
JMS Queue Example
To develop
JMS queue example, you need to install any application server. Here, we are
using glassfish3 server where we are creating two JNDI.
- Create connection factory named myQueueConnectionFactory
- Create destination resource named myQueue
After
creating JNDI, create server and receiver application. You need to run server
and receiver in different console. Here, we are using eclipse IDE, it is opened
in different console by default.
1)
Create connection factory and destination resource
Open
server admin console by the URL http://localhost:4848
Login with
the username and password.
Click on
the JMS Resource ->
Connection Factories -> New, now write the pool name and select the
Resource Type as QueueConnectionFactory then click on ok button.
Click on
the JMS Resource ->
Destination Resources -> New, now write the JNDI name and physical
destination name then click on ok button.
2)
Create sender and receiver application
Let's see
the Sender and Receiver code. Note that Receiver is attached with listener
which will be invoked when user sends message.
File: MySender.java
1.
import java.io.BufferedReader;
2.
import java.io.InputStreamReader;
3.
import javax.naming.*;
4.
import javax.jms.*;
5.
6.
public class MySender {
7.
public static void main(String[] args) {
8.
try
9.
{ //Create and start connection
10.
InitialContext ctx=new InitialContext();
11.
QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");
12.
QueueConnection con=f.createQueueConnection();
13.
con.start();
14.
//2) create queue session
15.
QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
16.
//3) get the Queue object
17.
Queue t=(Queue)ctx.lookup("myQueue");
18.
//4)create QueueSender object
19.
QueueSender sender=ses.createSender(t);
20.
//5) create TextMessage object
21.
TextMessage msg=ses.createTextMessage();
22.
23.
//6) write message
24.
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
25.
while(true)
26.
{
27.
System.out.println("Enter Msg, end to terminate:");
28.
String s=b.readLine();
29.
if (s.equals("end"))
30.
break;
31.
msg.setText(s);
32.
//7) send message
33.
sender.send(msg);
34.
System.out.println("Message successfully sent.");
35.
}
36.
//8) connection close
37.
con.close();
38.
}catch(Exception e){System.out.println(e);}
39.
}
40.
}
File: MyReceiver.java
1.
import javax.jms.*;
2.
import javax.naming.InitialContext;
3.
4.
public class MyReceiver {
5.
public static void main(String[] args) {
6.
try{
7.
//1) Create and start connection
8.
InitialContext ctx=new InitialContext();
9.
QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");
10.
QueueConnection con=f.createQueueConnection();
11.
con.start();
12.
//2) create Queue session
13.
QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
14.
//3) get the Queue object
15.
Queue t=(Queue)ctx.lookup("myQueue");
16.
//4)create QueueReceiver
17.
QueueReceiver receiver=ses.createReceiver(t);
18.
19.
//5) create listener object
20.
MyListener listener=new MyListener();
21.
22.
//6) register the listener object with receiver
23.
receiver.setMessageListener(listener);
24.
25.
System.out.println("Receiver1 is ready, waiting for messages...");
26.
System.out.println("press Ctrl+c to shutdown...");
27.
while(true){
28.
Thread.sleep(1000);
29.
}
30.
}catch(Exception e){System.out.println(e);}
31.
}
32.
33.
}
File: MyListener.java
1.
import javax.jms.*;
2.
public class MyListener implements MessageListener {
3.
4.
public void onMessage(Message m) {
5.
try{
6.
TextMessage msg=(TextMessage)m;
7.
8.
System.out.println("following message is received:"+msg.getText());
9.
}catch(JMSException e){System.out.println(e);}
10.
}
11.
}
Printed till here
11) read a file and count
number of words start from vowel.
Ans:
import
java.io.BufferedReader;
import
java.io.FileNotFoundException;
import
java.io.FileReader;
import
java.io.IOException;
public
class ReadVowelFromFile {
public static void
main(String...s)
{
BufferedReader br = null;
int counter = 0;
try {
br = new
BufferedReader(new FileReader("e:\\vowel.txt"));
String currLine = null;
while((currLine =
br.readLine())!=null)
{
System.out.println(currLine);
String t[] = currLine.split("
");
for(String
c:t)
{
if(c.toLowerCase().charAt(0)
== 'a' || c.toLowerCase().charAt(0) == 'e' || c.toLowerCase().charAt(0) == 'i'
|| c.toLowerCase().charAt(0) == 'o' || c.toLowerCase().charAt(0) == 'u')
{
counter++;
}
}
}
System.out.println("Vowels:
" + counter);
} catch
(FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
if(br!=null)
try {
br.close();
} catch (IOException
e) {
e.printStackTrace();
}
}
}
}
10) explaination of inner
join, left and right join.
Ans:
create table stock
(stock_id number(10) primary key not null, stock_code varchar2(20), stock_name
varchar2(50));
create table stock_detail (
stock_id number(10), comp_name varchar2(20), comp_desc varchar2(1000), FOREIGN
KEY (stock_id) REFERENCES stock(stock_id));
insert into stock
values(101,'A','AOAO');
insert into stock
values(102,'B','BOBO');
insert into stock
values(103,'C','COCO');
insert into stock
values(104,'D','DODO');
insert into stock
values(105,'E','EOEO');
insert into stock_detail
values(101,'BSL','noida sec 62');
insert into stock_detail
values(102,'IBM','noida sec 64');
insert into stock_detail
values(106,'IBM','noida sec 64');
inner join:
select * from stock s,
stock_detail sd where s.stock_id = sd.stock_id;
select * from stock s inner
join stock_detail sd on s.stock_id = sd.stock_id;
this will pull all matching
records
left join:
select * from stock s,
stock_detail sd where s.stock_id = sd.stock_id(+);
select * from stock s left
join stock_detail sd on s.stock_id = sd.stock_id;
this will pull all records
from stock table and only matching records from stock_detail
(101,102,103,104,105)
right join:
select * from stock s,
stock_detail sd where s.stock_id(+) = sd.stock_id;
select * from stock s right
outer join stock_detail sd on s.stock_id = sd.stock_id;
this will pull only
matching records 101 and 102 if there is foreign key defined between these
tables, if ther is no define foreign key then
all records from
stock_detail and only matching records from stock table will be returned.
11) explain indexing in DB.
Ans:
Indexes are special lookup tables that the database
search engine can use to speed up data retrieval. Simply put, an index is a
pointer to data in a table. An index in a database is very similar to an index
in the back of a book.
Single-Column
Indexes:
A single-column index is one that is created
based on only one table column. The basic syntax is as follows:
CREATE INDEX index_name
ON table_name (column_name);
Unique
Indexes:
Unique indexes are used not only for
performance, but also for data integrity. A unique index does not allow any
duplicate values to be inserted into the table. The basic syntax is as follows:
CREATE UNIQUE INDEX index_name
on table_name (column_name);
Unique
index does not allow duplicate entries.
Composite
Indexes:
A composite index is an index on two or more
columns of a table. The basic syntax is as follows:
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a
composite index, take into consideration the column(s) that you may use very
frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a
single-column index should be the choice. Should there be two or more columns
that are frequently used in the WHERE clause as filters, the composite index
would be the best choice.
Implicit
Indexes:
Implicit indexes are indexes that are
automatically created by the database server when an object is created. Indexes
are automatically created for primary key constraints and unique constraints.
When
should indexes be avoided?
Although indexes are intended to enhance a
database's performance, there are times when they should be avoided. The
following guidelines indicate when the use of an index should be reconsidered:
·
Indexes should not be used on small tables.
·
Tables that have frequent, large batch update
or insert operations.
·
Indexes should not be used on columns that
contain a high number of NULL values.
·
Columns that are frequently manipulated
should not be indexed.
14) Explain overall spring
MVC flow.
Ans:
15) is there any other
method of threading. except 2.
Ans: third way is using executor framework
(java.util.concurrent package):
Example:
Task.java:
package
executors;
import
java.util.concurrent.TimeUnit;
public
class Task implements Runnable
{
private String name;
public Task(String name)
{
this.name = name;
}
public String getName() {
return name;
}
@Override
public void run() {
// TODO Auto-generated
method stub
Long duration = (long)
(Math.random() * 10);
System.out.println("Doing a
task during : " + name);
try {
TimeUnit.SECONDS.sleep(duration);
} catch
(InterruptedException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
BasicThreadPoolExecutorExample.java:
package
executors;
import
java.util.concurrent.Executors;
import
java.util.concurrent.ThreadPoolExecutor;
public
class BasicThreadPoolExecutorExample
{
public static void
main(String[] args)
{
ThreadPoolExecutor executor =
(ThreadPoolExecutor) Executors.newCachedThreadPool();
for (int i = 0; i
<= 5; i++)
{
Task task = new
Task("Task " + i);
System.out.println("A
new task has been added : " + task.getName());
executor.execute(task);
}
executor.shutdown();
}
}
Output:
A new task has
been added : Task 0
A new task has
been added : Task 1
A new task has
been added : Task 2
A new task has
been added : Task 3
A new task has
been added : Task 4
A new task has
been added : Task 5
Doing a task
during : Task 0
Doing a task
during : Task 5
Doing a task
during : Task 4
Doing a task
during : Task 3
Doing a task
during : Task 2
Doing a
task during : Task 1
If object1 and object2
are equal according to their equals() method, they must also have the same hash
code.
If object1 and object2
have the same hash code, they do NOT have to be equal too.
In shorter words:
If equal, then same
hash codes too.
Same hash codes no
guarantee of being equal.
12) how Set is stored
internally and how it ensures uniqueness.
13) how can you create
annotation.
16) How JSon is converted
internally.
17) how you ensure session
timeout after few seconds?
5) How can you implement security In rest webservice.
18) what spring @Component annotation
do?
8) how HashMap works
internally (hashing algorithm)
18) explain Maven:
What
is Maven?
Maven is a project management and
comprehension tool. Maven provides developers a complete build lifecycle
framework. Development team can automate the project's build infrastructure in
almost no time as Maven uses a standard directory layout and a default build
lifecycle.
No comments:
Post a Comment