You are on page 1of 9

http://www.itassistant.

org/diverse/interviu/java/intrebari-si-raspunsuri-pentru-i
nterviurile-java/
http://www.landofcode.com/java-quiz/
purile de join
cum se face o relatie many-to many
ce`i foreign key sa stii
ce`i primary key
cum se fac relatiile
one-to-one
one-to-many
many-to-many
sa stii ce e group by
cum faci un insert,un update
http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhas
hmap/
sa stii care-i treaba cu exceptiile
cu try/catch/finally
clase abstracte, interfata
sa stii poliformism(daca o clasa mosteneste alta ce se intampla)
tutorialul oficial
de la oracle
are si exemplu de cod
numai ca e in engleza
1.What is Java Virtual Machine and how it is considered in context of Javas plat
form independent feature?
When Java is compiled, it is not compiled into platform specific machine, rathe
r into platform independent byte code. This byte code is distributed over the we
b and interpreted by virtual Machine (JVM) on whichever platform it is being run
.
2.Class Variable = variables declared with in a class, outside any method, with
the static keyword.
3. Steps for Object creation = Object is first declared, then instantiated and t
hen it is initialized;
4. Variables used in a switch statement can be used with which datatypes?
Variables used in a switch statement can only be a byte, short, int, or char
5.Why is StringBuffer called mutable?
The String class is considered as immutable, so that once it is created a String
object cannot be changed. If there is a necessity to make alot of modifications
to Strings of characters then StringBuffer should be used.
6.What is the difference between StringBuffer and StringBuilder class?
Use StringBuilder whenever possible because it is faster than StringBuffer. But,
if thread safety is necessary then use StringBuffer objects.
7.What is finalize() method?

It is possible to define a method that will be called just before an object s f


inal destruction by the garbage collector. This method is called finalize( ), an
d it can be used to ensure that an object terminates cleanly.
8.Java programming language does not require methods to catch or to specify unch
ecked exceptions (RuntimeException, Error, and their subclasses) . Runtime excep
tions represent problems that are the result of a programming problem, and as su
ch, the API client code cannot reasonably be expected to recover from them or to
handle them in any way. The Exception class has two main subclasses : IOExcepti
on class and RuntimeException Class.
9.When super keyword is used?
If the method overrides one of its superclass s methods, overridden method can
be invoked through the use of the keyword super. It can be also used to refer to
a hidden field
10.What are the two ways in which Thread can be created?
Thread can be created by: implementing Runnable interface, extending the Threa
d class.
11. Explain Set Interface?
It is a collection of element which cannot contain duplicate elements. The Se
t interface contains only methods inherited from Collection and adds the restric
tion that duplicate elements are prohibited.
12.Explain TreeSet?
It is a Set implemented when we want elements in a sorted order.
13.What is Comparable Interface?
It is used to sort collections and arrays of objects using the collections.s
ort() and java.utils. The objects of the class implementing the Comparable inter
face can be ordered.
14. Define JRE i.e. Java Runtime Environment?
Java Runtime Environment is an implementation of the Java Virtual Machine w
hich executes Java programs. It provides the minimum requirements for executing
a Java application;
15.What is JAR file?
JAR files is Java Archive fles and it aggregates many files into one. It holds J
ava classes in a library. JAR files are built on ZIP file format and have .jar f
ile extension.
16.What is a WAR file?
This is Web Archive File and used to store XML, java classes, and JavaServer pag
es. which is used to distribute a collection of JavaServer Pages, Java Servlets,
Java classes, XML files, static Web pages etc.
17.What is static block?
It is used to initialize the static data member, It is excuted before main metho
d at the time of classloading.
18.What is function overloading?
If a class has multiple functions by same name but different parameters, it is k
nown as Method Overloading.
19. What is final class?
Final classes are created so the methods implemented by that class cannot be ov

erridden. It cant be inherited.


20.What are the ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blockin
g on IO, by unsuccessfully attempting to acquire an object s lock, or by invokin
g an object s wait() method. It can also enter the waiting state by invoking its
(deprecated) suspend() method.
21.What invokes a thread s run() method?
After a thread is started, via its start() method of the Thread class, the JVM
invokes the thread s run() method when the thread is initially executed.
22.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.
23.Why Vector class is used?
The Vector class provides the capability to implement a growable array of object
s. Vector proves to be very useful if you don t know the size of the array in ad
vance, or you just need one that can change sizes over the lifetime of a program
.
24.How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 charact
ers?
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 char
acters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patte
rns.
25. What is the purpose of File class?
It is used to create objects that provide access to the files and directories o
f a local file system.
26.What is the difference between the Reader/Writer class hierarchy and the Inp
utStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/Ou
tputStream class hierarchy is byte-oriented
27.: Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object s design and java
.lang.Class class instance represent classes, interfaces in a running Java appli
cation.
28.What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream
. Deserialization is the process of restoring these objects.
29.What s the difference between the methods sleep() and wait()?
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 t
he class Object and the method sleep() is defined in the class Thread.

30. What is a transient variable?


A transient variable is a variable that may not be serialized during Serializat
ion and which is initialized by its default value during de-serialization,
31. Under what conditions is an object s finalize() method invoked by the garba
ge collector?
The garbage collector invokes an object s finalize() method when it detects tha
t the object has become unreachable.
32.The default value of the boolean type is false.
33. What is the Locale class?
The Locale class is used to tailor program output to the conventions of a parti
cular geographic, political, or cultural region.
34.What is runtime polymorphism or dynamic method dispatch?
Runtime polymorphism or dynamic method dispatch is a process in which a call t
o an overridden method is resolved at runtime rather than at compile-time. In th
is process, an overridden method is called through the reference variable of a s
uperclass.
35.What are the advantages of ArrayList over arrays?
ArrayList can grow dynamically and provides more powerful insertion and search
mechanisms than arrays.
36.Why deletion in LinkedList is fast than ArrayList?
Deletion in linked list is fast because it involves only updating the next po
inter in the node before the deleted node and updating the previous pointer in t
he node after the deleted node.
37. How do you decide when to use ArrayList and LinkedList?
If you need to frequently add and remove elements from the middle of the list a
nd only access the list elements sequentially, then LinkedList should be used. I
f you need to support random access, without inserting or removing elements from
any place other than the end, then ArrayList should be used.
38. What is a Values Collection View ?
It is a collection returned by the values() method of the Map Interface, It co
ntains all the objects present as values in the map.
39.Where and how can you use a private constructor?
Private constructor is used if you do not want other classes to instantiate th
e object and to prevent subclassing.
40.The life cycle of a thread include:
Newborn state
Runnable state
Running state
Blocked state
Dead state

41.Which number is denoted by leading zero in java?


Octal Numbers are denoted by leading zero in java, example: 06
42.Which number is denoted by leading 0x or 0X in java?
Hexadecimal Numbers are denoted by leading 0x or 0X in java, example: 0XF
43. What is a Socket?
Sockets provide the communication mechanism between two computers using TCP. A c
lient program creates a socket on its end of the communication and attempts to c
onnect that socket to a server.
44.Disadvantages of Java Sockets?
Socket based communications allows only to send packets of raw data between appl
ications. Both the client-side and server-side have to provide mechanisms to mak
e the data useful in any way.
45.Which class is used by server applications to obtain a port and listen for cl
ient requests?
java.net.ServerSocket class is used by server applications to obtain a port and
listen for client requests
46.What is Nested top-level class?
If a class is declared within a class and specify the static modifier, the comp
iler treats the class just like any other top-level class. Nested top-level clas
s is an Inner class.
47. If System.exit (0); is written at the end of the try block, will the finall
y block still execute?
No in this case the finally block will not execute because when you say System.
exit (0); the control immediately goes out of the program, and thus finally neve
r executes.
48.What is daemon thread?
Daemon thread is a low priority thread, which runs intermittently in the back g
round doing the garbage collection operation for the java runtime system.
49.: Which method must be implemented by all threads?
All tasks must implement the run() method
50.What is the difference between the size and capacity of a Vector?
The size is the number of elements actually stored in the vector,
while capacity is the maximum number of elements it can store at a given instan
ce of time.
51.Can a vector contain heterogenous objects?
Yes a Vector can contain heterogenous objects. Because a Vector stores everythi
ng in terms of Object.
52. What is difference between Path and Classpath?
Path and Classpath are operating system level environment variales. Path is def
ines where the system can find the executables(.exe) files and classpath is used

to specify the location of .class files.


53.What are order of precedence and associativity and how are they used?
Order of precedence determines the order in which operators are evaluated in ex
pressions.
Associatity determines whether an expression is evaluated left-to-right or rig
ht-to-left.
54. What is the difference between inner class and nested class?
When a class is defined within a scope of another class, then it becomes inner
class.
If the access modifier of the inner class is static, then it becomes nested cl
ass.
55. What is constructor chaining and how is it achieved in Java?
A child object constructor always first needs to construct its parent.
In Java it is done via an implicit call to the no-args constructor as the firs
t statement.

HIBERNATE
=======================================
FetchType.LAZY = Doesnt load the relationships unless explicitly asked for via gett
er
FetchType.EAGER = Loads ALL relationships
In the case of one-to-one relationships , in the owner entity(the one that has t
he foreign key) we add the annotation @PrimaryJoinColumn and in the other entity
we add tHe mapped by attribute.In generaly we add the mapped by attribute to sp
ecift that this entity is not the owner of the foreign key
HOW TO ADD RECORDS USING HIBERNATE
====================================
session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//Create new instance of Contact and set values in it by reading them from form
object
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName(imran)
session.save(contact);
tx.commit();
HOW TO QUERY USING HSQL
=============================
Query query = session.createQuery("update Stock set stockName = :stockName" +
" where stockCode = :stockCode");
query.setParameter("stockName", "DIALOG1");
query.setParameter("stockCode", "7277");
int result = query.executeUpdate();
ABSTRACT CLASSES AND INTERFACES
==========================================
It is possible, however, to define a class that does not implement all of the in
terface s methods, provided that the class is declared to be abstract.

With interfaces, all fields are automatically public, static, and final, and all
methods that you declare or define (as default methods) are public.
METHOD HIDING
==================================================
Method hiding means subclass has defined a class method(static method) with the
same signature as a class method in the superclass.
The version of a method that is executed will NOT be determined by the object th
at is used to invoke it. In fact it will be determined by the type of the refere
nce variable used to invoke the method.
A Class Variable Shadows the Inherited Variable from Its Parent Classes
==========================================================================
When an instance variable in a subclass has the same name as an instance variab
le in a super class,
then the instance variable is chosen in the class that is the reference type.
Because variables names in Java are resolved by the reference type,
not the object they are referencing.
A class can declare a variable with the same name as an inherited variable from
its parent class,
thus "hiding" or shadowing the inherited version.
NESTED CLASSES
============================================================================
Nested classes are divided into two categories: static and non-static.
Nested classes that are declared static are called static nested classes.
Non-static nested classes are called inner classes
Non-static nested classes (inner classes) have access to other members of the en
closing class, even if they are declared private.
Static nested classes do not have access to other members of the enclosing clas
s. As a member of the OuterClass, a nested class can be declared private, public
, protected, or package private.
(Recall that outer classes can only be declared public or package private.)
A static nested class cannot refer directly to instance variables or methods de
fined in its enclosing class: it can use them only through an object reference.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
INNER CLASS
=============
An inner class is associated with an instance of its enclosing class and has
direct access to that object s methods and fields.
Also, because an inner class is associated with an instance, it cannot define
any static members itself.
An instance of InnerClass can exist only within an instance of OuterClass and
has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
You can use the same modifiers for inner classes that you use for other membe
rs of the outer class

ANONYMOUS CLASS
============================
Anonymous classes are expressions, which means that you define the class in an
other expression.
An anonymous class has access to the members of its enclosing class.
An anonymous class cannot access local variables in its enclosing scope that a
re not declared as final or effectively final.
Like a nested class, a declaration of a type (such as a variable) in an anonym
ous class shadows any other declarations in the
enclosing scope that have the same name.
You cannot declare static initializers or member interfaces in an anonymous cl
ass.
An anonymous class can have static members provided that they are constant var
iables.
YOU can have the following in anonymous classes:
Fields
Extra methods (even if they do not implement any methods of the supertype)
Local classes
Instance initializers
You cannot declare constructors in an anonymous class
this KEYWORD
===========================
From within a constructor, you can also use the this keyword to call another c
onstructor in the same class.
If present, the invocation of another constructor must be the first line in th
e constructor.
If a constructor does not explicitly invoke a superclass constructor, the Java c
ompiler automatically inserts a call to the no-argument constructor of the super
class. If the super class does not have a no-argument constructor, you will get
a compile-time error. Object does have such a constructor, so if Object is the o
nly superclass, there is no problem.
Contract between equals() and hashcode()
====================================================
hashcode() method is supported for the benefit of hashtables such as those provi
ded by java.util.Hashtable
Rules of contract:
1.Firstly, it states that the hash code returned by the hashCode method must be
consistently the same for multiple invocations during the same execution of the
application as long as the object is not modified to affect the equals method.
2.The second requirement of the contract is the hashCode counterpart of the requ
irement specified by the equals method.
It simply emphasizes the same relationship - equal objects must produce the same
hash code. However, the third point elaborates that unequal objects need not pr
oduce distinct hash codes.

Collections
===============================================================================

Map-interface most used implementations


================================================================================
===========
HASHMAP
================
HashMap is implemented as a hash table, and there is no ordering on keys or valu
es.
If we are using self-defined objects as keys we need to override the equals and
hashcode method
TreeMap
=====================
Sorted by keys. If self-defined defined object is used as key then it needs to i
mplement the Comparable interface
Hashtable
================
Almost the same as HashMap except it is unsynchronized and permits nulls
LinkedHashMap
=====================
LinkedHashMap is a subclass of HashMap.
That means it inherits the features of HashMap. In addition, the linked list pre
serves the insertion-order.

LIST-Interface
==========================================================
ArrayList vs LinkedList
===============================
arraylist has O(1) for get while linkedList has O(n)
linkedlist fares better at the insertion/removal of elements