Вы находитесь на странице: 1из 15

Interview questions from our panel experts

What are OOP’s principal

Or Explain
• polymorphism,
• abstraction
• inheritance
• encapsulation
think from your project point of view

here are three types of oops in java.


1.Encapsulation:Encapsulation is mechanism,that binds
together data and code its manipulates.
Ex:suppose we are writing one bean.we declaring two private
variables.we are providing setters and getters methods of
two variables.These variables are accessed in that class.
2.Inheritance:To acquire the base class properties into
derived class.
Ex:class A{
m1(){
System.out.println("m1 method");
}
}
class B extends A{
m2(){
System.out.println("m2 method");
}
public static void main(String args[]){
B b = new B();
System.out.println(b.m1);
System.out.println(b.m2);
}
}
O/p is:m1 method
m2 method.
Polymorphism:one Interface to be used for a general class of
actions.
There are two types of polymorphisms.
1.Compile-time polymorphism:what object will be assigned to
the present variable.This will be evaluated at compile time.
This is known as compile-time polymorphism.
2.Run-time polymorphism:what object will be assigned to the
present variable.This will be evaluated at runtime depending
on condition.This is known as Run-time polymorphism.

what is polymorphism

Or
explain method overloading and overriding, give practical scenario for both

e.g. from capital market point of view – there can be cash market and Futures and Options

spread method although being spread has a different behaviour


e.g user wants register on web portal.. on the web application would choose - corporate user, normal user - bank
guarantee is required..
user would be parent calss
corporate and normal user would be two child class -

Why Over riding is Run Time Polymorphism?


Answer Overriding method resolution always take care
# 1 by JVM based
on runtime object. Hence overriding is
consider as runtime
or dynamic orlatebinding

There are 2 methods in a class. Both have the same method signature except
for return types. Is this overloading or overriding or what is it?
Answer It is not overloading because overloading
# 6 must have different parameters, no matter
what ever may be the return type is.
And for overriding inheritance should be
used between 2 classes.
so it is neither overriding nor overloading.

It just show compilation error as method is


already defined in
same class

• Explain encapsulation
• please give encapsulation example from your project

data abstraction is one of the two major aspects of encapsulation (the other is information
hiding).

When you encapsulate something you get an outside and an inside. Take any encapsulated unit,
like a primitive or an object for example. The way you can use it and how it behaves is the data
abstraction. Hidden inside is the implementation.

In Java you usually define your own data abstraction by putting together a set of non-private
methods in the form of a class or an interface.

Encapsulation is the concept that an object should totally separate its interface from its
implementation. All the data and implementation code for an object should be entirely hidden behind
its interface.
The idea is that we can create an interface (Public methods in a class) and, as long as that interface
remains consistent, the application can interact with our objects. This remains true even if we entirely
rewrite the code within a given method thus the interface is independent of the implementation

e.g

variables as private - expose the same via public method..


practical scenario.
Form Bean -
data ..Get methods and set methods...

/Example of Encapsulation

class Box {
// what are the properties or fields
private int length;
private int width;
private int height;

// what are the actions or methods


public void setLength(int p)
{length = p;}

public void setWidth(int p)


{width = p;}

public void setHeight(int p)


{height = p;}

public int displayVolume()


{return (length*width*height);}
}

class BoxVol {
public static void main (String args[]) {

Box ob1 = new Box();

double vol;

ob1.setLength(120);
ob1.setWidth(100);
ob1.setHeight(90);

vol = ob1.displayVolume();
System.out.println("Volume is : " + vol);
}
}

**************************************…
private keyword use top specifies encapsulated.

By keeping your data private(encapsulated)out side entity(other methods and data) can not misuse it
or alter it with out your permission. you can only allow them to use it but you will not allow them to
alter it.

Can you explain the difference b/n abtract and interface


with a good example,?In what cases we have use abtract
and what case interface?
Interfaces are used to create prototype of classes. Interfaces would be
using high-level access specifiers(public).

Abstraction is a mechanism in Java to expose the essential features of the


class. Different levels of abstraction is achieved through Access
specifiers.

abstract class:-- abstract class contains abstract methods


and concreat methods,abstract class may have Zero(0)
abstract methods also, for example HttpServlet class is
best example for abstract class, HttpServlet class contains
Zero abstract methods, The SUN People declared HttpServlet
as abstract,B'ecz out side people unable to create object
for HttpServlet(abstract class)and due to security reasons
HttpServlet declared as abstract class.

If you are declared abstract methods in a abstract class,


we should provide the implementation in child classes.

we can't create Object for abstract class, we can create


refrence for abstract class.

In real-time, we can use abstract classes depends on


requirement only.

Interface:---

By default all the methods in Interface are public abstract


methods.Variables are by default public static final.
All the methods are non-implemented in interface and we
need to provide the implemantation for abstract methods in
interface implemented class(child class)

For example Servlet is a interface, if MyServlet class


implements Servlet, then we should provide the
implementation for Servlet interface methods like init
(),service(), destroy(),servletConfig(),etc..

Explain IS A and HAS A relationships


is a

rose is a flower
Parent - child relationship
corporate user is a user

has a relationship

rose has petals

corporate user has trade data


string s1 = "abc"
string s2 = "abc"
new string ("abc")

s1==s2
would be true

s1== s3
would be false

s3.equals(s2) = true
would be true

String builder is faster than String Buffer and last one is threadsafe.please tell
another important difference.
Answer String is immutable whereas StringBuffer and
# 2 StringBuilder
can change their values.

The only difference between StringBuffer and


StringBuilder
is that StringBuilder is unsynchronized
whereas
StringBuffer is synchronized. So when the
application needs
to be run only in a single thread then it is
better to use
StringBuilder. StringBuilder is more
efficient than
StringBuffer.

Criteria to choose among String, StringBuffer


and
StringBuilder

If your text is not going to change use a


string Class
because a String object is immutable.
If your text can change and will only be
accessed from a
single thread, use a StringBuilder because
StringBuilder is
unsynchronized.
If your text can changes, and will be
accessed from
multiple threads, use a StringBuffer because
StringBuffer
is synchronous.
System.out.println(101/14) what is the output? a)6 b)14 c)7.14 d)0
Answer Answer is 7,
# 6 as int is the default datatype for numeric
values.. Not float.

can one interface extend another interface.

Yes

difference in string and stringbuffer

string is immutable class v/s mutable.

String are read only and immutable. The StringBuffer class


is used to represent characters that can be modified.
StringBuffer is faster than String when performing simple
concatenations.

exceptions.

Difference betwn checked exception and unchecked


(compile time)

run time exception - array index out of bound...

what is the use of finally block.

finally always gets executed.

even after final exception

closing the connections etc.. shud be there in finally..

what are the differences between final,finally,finalize methods?


Answer final is used for making a class no-
# 1 subclassable, and making
a member variable as a constant which cannot
be modified.
finally is usually used to release all the
resources
utilized inside the try block. All the
resources present in
the finalize method will be garbage collected
whenever GC is
called. Though finally and finalize seem to
be for a similar
task there is an interesting difference
here.This is because
the code in finally block is guaranteed of
execution
irrespective of occurrence of exception,
while execution of
finalize is not guarenteed.finalize method is
called by the
garbage collector on an object when the
garbage collector
determines that there are no more references
to the object.

------------------------------------------------

what are the best practices in exception handling.


never follow the exception - dont leave empty catch - log it and throw custom exception
always from sub class to super class.

order of exception:: sqlexception and then exception...

can there be zero catch block..


u have to write catch..

------------------------------------------

how do u create ur own custom exception classes.

by extending Exception class..

what is difference in exception and error

- exception can be handled.


- method cannot recover from error.
What is diff in vector and arraylist

vector is synchronized.. arraylist it is not


only one thread can access

ArrayList is non synchronized.Vector is


synchronized.ArrayList is very fast because non
synchronized.we can specify the increment size with the
vector and with arrayList we cannot

If method a() is synchronized and method b() is not synchronized.

there are two threads t1 and t2

t1 is access a, and t2 wants to access b... is it allowed = YES

t1 wants to acces a, and t2 wants to access a at the same time - NO

thread priorities..

default - round robin,

t.setpriority.

what are different ways to create thread.

by extending thread.
override run interface

by implementing runnable interface.

----------------------------------------

thread t.start

how do u start thread

starting
------------------------------------------

what is a synhronized block.

- it will do a class level block


--------------------------------------

thread life cycle

no state
ready to run state
running
destroyed
or sleep -> ready to run ->

The thread states are:

- New (created but start mtd not called)


- Runnable (Ready to run, waiting for CPU cycles)
- Running (allocated CPU cycle)
- Suspended (timed sleeping)
- Wait (waiting for a notify)
- Stopped (Completed)

-------------------------------------------------------------

write a program to run a thread.

================================================================

JDBC connectivity..

how to obtain a connection object.

application server

data source and connection pooling is configured

jndi look up has to be done to get the datasource and the from there the connection object

- data source.get connection()

-----------------------------------------
what is adv of connection pooling.

better performance -

ready to use - registering - unregistering


memory management etc..

-----------------------------------

what is scrollable resultset..

normal resultset - u can move ahead but not back


--------------------------------------

how to execute a stored procedure

by use of callable statement

----------------------------------------

what is servelet lifecyle

- init()
- instance getting initialized. first request from webbrowser. init will only be called once. opening of file etc.
- service
doget
dopost

- destroy

is servelet thread safe - not

they have to implement single thread model interface. marker - which will server one request.

what is http -
request and response.
how do u maintain session
session object

using session object.


cookies
by passing the parameters thru url

------------------------------------------------

By default jsp gets converted to servelet


- can i override init - YES

how to override init


_jsp.init

by default this gets extended.

------------------------------------

what are the implicit object of jsp

request
response
session
out
pagecontext
applicationcontext

--------------------------------------

hibernate

what is hibernate
- It is an orm tool

what is ORM

what is object relation mapping.

primary key / foreign keys are there in Databaswe

using hibernate we can map oject hierarch cann be mapped to table.

e.g
employee / department,

insurance

policy

coporate - group or individual

- parent child relationship


how to obtain session
sessionfactory
cfg.xml

If you are reviewing the code of your team members, what points will
you look at, assuming the performance of the application is not so
great
Answer UNNECASARY OB JECT CREATION shud b 0 Sandhya
# 1 avoided..REUSABILITY OF
CODE SHUD B THER.network calls shud be
less..beter to use
connection pooling.gud exceptional
handling.

Is This Answer Correct ? 9 Yes 0 No

Re: If you are reviewing the code of your team members, what points
will you look at, assuming the performance of the application is not so
great
Answer To boost performance:
# 2 1) Use trim() meaningfully.
2) Operation on String Object should be
on check.
3) Network calls should be put on check.
4) Keep a look on loops.
5) Use static methods for utility
purposes. Like Math class.
6) Use logging only for important tasks

Interview questions from http://www.techinterviews.com/core-java-interview-questions

1.
2. Can there be an abstract class with no abstract methods in it? - Yes
3. Can an Interface be final? - No
4. Can an Interface have an inner class? - Yes.
public interface abc

static int i=0; void dd();

class a1

a1()
{

int j;

System.out.println("inside");

};

public static void main(String a1[])

System.out.println("in interfia");

5. Can we define private and protected modifiers for variables in interfaces? - No


6. What is Externalizable? - Externalizable is an Interface that extends Serializable Interface. And
sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out)
and readExternal(ObjectInput in)
7. What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers
are allowed for methods in interfaces.
8. What is a local, member and a class variable? - Variables declared within a method are “local”
variables. Variables declared within the class i.e not within any methods are “member” variables (global
variables). Variables declared within the class i.e not within any methods and are defined as “static” are
class variables
9. What are the different identifier states of a Thread? - The different identifiers of a Thread are: R
- Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW -
Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock
10. What are some alternatives to inheritance? - Delegation is an alternative to inheritance.
Delegation means that you include an instance of another class as an instance variable, and forward
messages to the instance. It is often safer than inheritance because it forces you to think about each
message you forward, because the instance is of a known class, rather than a new class, and because it
doesn’t force you to accept all the methods of the super class: you can provide only the methods that
really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it
is not a subclass).
11. Why isn’t there operator overloading? - Because C++ has proven by example that operator
overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method
overloading in Java, but it was thought that this was too useful for some very basic methods like print().
Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and
writeByte().
12. What does it mean that a method or field is “static”? - Static variables and methods are
instantiated only once per class. In other words they are class variables, not instance variables. If you
change the value of a static variable in a particular object, the value of that variable changes for all
instances of that class. Static methods can be referenced with the name of the class rather than the name
of a particular object of the class (though that works too). That’s how library methods like
System.out.println() work. out is a static field in the java.lang.System class.
13. How do I convert a numeric IP address like 192.18.97.39 into a hostname like
java.sun.com?
14. String hostname = InetAddress.getByName("192.18.97.39").getHostName();

15. Difference between JRE/JVM/JDK?


16. Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other
threads may execute while the I/O operation is performed.
17. What is synchronization and why is it important? - With respect to multithreading,
synchronization is the capability to control the access of multiple threads to shared resources. Without
synchronization, it is possible for one thread to modify a shared object while another thread is in the
process of using or updating that object’s value. This often leads to significant errors.
18. Is null a keyword? - The null value is not a keyword.
19. Which characters may be used as the second character of an identifier,but not as the first
character of an identifier? - The digits 0 through 9 may not be used as the first character of an
identifier but they may be used after the first character of an identifier.
20. What modifiers may be used with an inner class that is a member of an outer class? - A
(non-local) inner class may be declared as public, protected, private, static, final, or abstract.
21. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? -
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is
usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses
16-bit and larger bit patterns.
22. What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed
as objects.
23. What restrictions are placed on the location of a package statement within a source code
file? - A package statement must appear as the first line in a source code file (excluding blank lines and
comments).
24. What is the difference between preemptive scheduling and time slicing? - 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.
25. What is a native method? - A native method is a method that is implemented in a language other
than Java.
26. What are order of precedence and associativity, and how are they used? - Order of
precedence determines the order in which operators are evaluated in expressions. Associatity
determines whether an expression is evaluated left-to-right or right-to-left
27. What is the catch or declare rule for method declarations? - If a checked exception may be
thrown within the body of a method, the method must either catch the exception or declare it in its
throws clause.
28. Can an anonymous class be declared as implementing an interface and extending a
class? - An anonymous class may implement an interface or extend a superclass, but may not be
declared to do both.
29. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1
Singleton

also

How to make a method thread safe without using synchronized


keyword?

public class Singleton {


// Private constructor prevents instantiation from other classes
private Singleton() {}

/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {


return SingletonHolder.INSTANCE;
}
}

How can you reverse a string?


Answer String str="how r u";
# 1 int length=str.length();
System.out.print("The reverse String is:");
while(len>0)
{
System.out.print(str.charAt(len-1));
len--;
}

Вам также может понравиться