You are on page 1of 29

PAG

PAGE
2

Contents
JAVA INTERVIEW QUIZ AND ANSWER

CORE JAVA QUESTION AND ANSWER

JAVACODEHELPS

PAGE
3

QUESTION AND ANSWER

Core Java Interview Questions Answers in Finance domain


Q-1. What is immutable object? Can you write immutable object?
A- Immutable classes are Java classes whose objects can not be modified once created. Any
modification in Immutable object result in new object. For example String is immutable in Java.
Mostly Immutable classes are also final in Java, in order to prevent sub classes from overriding methods,
which can compromise Immutability. You can achieve same functionality by making member as non
final but private and not modifying them except in constructor. Apart form obvious, you also need to
make sure that, you should not expose internals of Immutable object, especially if it contains a mutable
member. Similarly, when you accept value for mutable member from client e.g. java.util.Date,
use clone() method keep separate copy for yourself, to prevent risk of malicious client modifying
mutable reference after setting it. Same precaution needs to be taken while returning value for a mutable
member, return another separate copy to client, never return original reference held by Immutable class.

Q-2. What is the difference between creating String as new() and literal?
A- When we create string with new() Operator, its created in heap and not added into
string pool while String created using literal are created in String pool itself which exists
in PermGen area of heap.
String str = new String("Test");
does not put the object str in String pool , we need to call String.intern() method
which is used to put them into String pool explicitly. its only when you create String object as
String literal e.g. String s = "Test" Java automatically put that into String pool. By the
way there is a catch here, Since we are passing arguments as "Test", which is a String
literal, it will also create another object as "Test" on string pool.

PAGE
4

Q- 3. How does substring () inside String works?


A-Another good Java interview crack question, I think answer is not sufficient but here it is
Substring creates new object out of source string by taking a portion of original
string. This question was mainly asked to see if developer is familiar with risk of memory
leak, which substring can create. Until Java 1.7, substring holds reference of original character
array, which means even a substring of 5 character long, can prevent 1GB character array
from garbage collection, by holding a strong reference. This issue is fixed in Java 1.7, where
original character array is not referenced any more, but that change also made creation of
substring bit costly in terms of time. Earlier it was on the range of O(1), which could be O(n) in
worst case on Java 7.

Q-4. Where does equals and hashcode method comes in picture during get
operation?
A-This core Java interview question is follow-up of previous Java question and candidate
should know that once you mention hashCode, people are most likely ask, how they are used
in HashMap.When you provide key object, first it's hashcode method is called to calculate
bucket location. Since a bucket may contain more than one entry as linked list, each of those
Map.Entry object are evaluated by using equals() method to see if they contain the
actual key object or not.

Q- 5. What is difference between Executor.submit() and


Executer.execute() method ?
There is a difference when looking at exception handling. If your tasks throws an exception and if it
was submitted with execute this exception will go to the uncaught exception handler
(when you don't have provided one explicitly, the default one will just print the stack trace to
System.err). If you submitted the task with submit any thrown exception, checked exception or not,
is then part of the task's return status. For a task that was submitted with submit and that terminates
with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

Q- 6. What is Singleton? is it better to make whole method synchronized or only


critical section synchronized ?

PAGE
5

A-Singleton in Java is a class with just one instance in whole Java application, for example
java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5
introduced Enum its very easy.

Q- 7. What will be the problem if you don't override hashcode() method ?


A-If you don't override equals method, than contract between equals and hashcode will not
work, according to which, two object which are equal by equals() must have same
hashcode. In this case other object may return different hashcode and will be stored on that
location, which breaks invariant of HashMap class, because they are not supposed to allow
duplicate keys. When you add object using put() method, it iterate through all Map.Entry
object present in that bucket location, and update value of previous mapping, if Map already
contains that key. This will not work if hashcode is not overridden

Q- 8. Give a simplest way to find out the time a method takes for execution
without using any profiling tool?
A- Read the system time just before the method is invoked and immediately after method
returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println (Time taken for execution is + (end start));
Remember that if the time taken for execution is too small, it might show that it is taking zero
milliseconds for execution. Try it on a method which is big enough, in the sense the one which
is doing considerable amount of processing

Q- 9. How do you know if an explicit object casting is needed ?.

PAGE
6
A- If you assign a superclass object to a variable of a subclass's data type, you need to do
explicit casting. Whereas, When you assign a subclass to a variable having a supeclass type,
the casting happens automatically.

Q- 10.Describe the wrapper classes in Java ?

A- Wrapper class is wrapper around a primitive data type. An instance of a wrapper class
contains, or wraps, a primitive value of the corresponding type and creates an Object.
Ex: java.lang.Boolean is the Wrapper for boolean, java.lang.Long is the wrapper for long etc.

JSP INTERVIEW QUESTIONS


1. What is JSP?
A-JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to
web applications in a portable, secure and well-defined way. The JSP Technology allows us to use
HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User
Interface components for Web Applications.

2. What do you understand by JSP Actions?


A-JSP actions are XML tags that direct the server to use existing components or control the behavior of
the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon,
followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:
< jsp : include / >
< jsp : forward / >
< jsp : plugin / >

PAGE
7

< jsp : usebean / >


< jsp : setProperty / >
< jsp : getProperty / >

3. What is the difference between < jsp : include page = ... > and < % @ include file
= ... >?
A-Both the tags include information from one JSP page in another. The differences are:
< jsp : include page = ... >
This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and
the generated html content is included in the content of calling jsp) each time the client page is accessed
by the client. This approach is useful while modularizing a web application. If the included file changes
then the new content will be included in the output automatically.
< % @ include file = ... >
In this case the content of the included file is textually embedded in the page that have < % @ include
file=".."> directive. In this case when the included file changes, the changed content will not get
included automatically in the output. This approach is used when the code from one jsp file required to
include in multiple jsp files.

4. What is the difference between < jsp : forward page = ... > and
response.sendRedirect(url)?
A-The element forwards the request object containing the client request information from one JSP file to
another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the
same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new
request to go the redirected page. The response.sendRedirect also kills the session variables.

5. Name one advantage of JSP over Servlets?


A-Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code,
making JSPs more flexible and powerful than Servlets.
However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They
have their strengths too which cannot be overseen.

PAGE
8

SERVLET INTERVIEW QUESTION


1. What is a Servlet?
A-Java Servlets are server side components that provides a powerful mechanism for developing server
side of web application. Earlier CGI was used to provide server side capabilities for web applications.
Although CGI played a major role in the explosion of the Internet, its performance, scalability and
reusability issues made it less and less desirable among people who wanted enterprise class scalable
applications. Java Servlets was the solution to all of CGIs problems. Built from ground up using Sun's
java technology, servlets provide excellent framework for server side processing. They are an integral
part of almost all J2EE applications.

2. What are the types of Servlet?


A-There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic
or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides http protocl
specific functionality.

3. What are the differences between HttpServlet and Generic Servlets ?


A- GenericServlet defines a generic, protocol-independent servlet whereas HttpServlet Provides an
abstract class to be subclassed to create an HTTP servlet suitable for a Web site that uses the Http
Protocol.

4. What are the differences between a Servlet and an Applet ? .


A-Servlets are server side components that executes on the server whereas applets are client side
components and executes on the web browser.
* Applets have GUI interface but there is no GUI interface in case of Servlets.
* Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety
of operations
* Servlets can perform operations like interacting with other servlets, JSP Pages, connect to
databases etc while Applets cannot do all this.

PAGE
9

5. What are the different methods present in a HttpServlet ?


A-The methods of HttpServlet class are :
* doGet() - To handle the GET, conditional GET, and HEAD requests
* doPost() - To handle POST requests
* doPut() - To handle PUT requests
* doDelete() - To handle DELETE requests
* doOptions() - To handle the OPTIONS requests and
* doTrace() - To handle the TRACE requests
Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and
destroy the servlet respectively. They are not any operation specific and are available in all Servlets for
use during their active life-cycle.

Hibernate Interview Questions


1. Does Hibernate implement its functionality using a minimal number of database
queries to ensure optimal output ?
A-Hibernate can make certain optimizations all the time:
Caching objects - The session is a transaction-level cache of persistent objects. You may also enable a
JVM-level/cluster cache to memory and/or local disk.
Executing SQL statements later, when needed - The session never issues an INSERT or UPDATE
until it is actually needed. So if an exception occurs and you need to abort the transaction, some
statements will never actually be issued. Furthermore, this keeps lock times in the database as short as
possible (from the late UPDATE to the transaction end).
Never updating unmodified objects - It is very common in hand-coded JDBC to see the persistent
state of an object updated, just in case it changed.....for example, the user pressed the save button but
may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as
you are inside the same (possibly very long) unit of work.

PAGE
10
Efficient Collection Handling - Likewise, Hibernate only ever inserts/updates/deletes collection rows
that actually changed.
Rolling two updates into one - As a corollary to (1) and (3), Hibernate can roll two seemingly
unrelated updates of the same object into one UPDATE statement.
Updating only the modified columns - Hibernate knows exactly which columns need updating and, if
you choose, will update only those columns.
Outer join fetching - Hibernate implements a very efficient outer-join fetching algorithm! In addition,
you can use subselect and batch pre-fetch optimizations.
Lazy collection initialization
Lazy object initialization - Hibernate can use runtime-generated proxies (CGLIB) or interception
injected through byte code instrumentation at build-time

2. Why not implement instance-pooling in Hibernate ?


A-Firstly, it would be pointless. There is a lower bound to the amount of garbage Hibernate creates
every time it loads or updates and object - the garbage created by getting or setting the object's
properties using reflection.
More importantly, the disadvantage of instance-pooling is developers who forget to reinitialize fields
each time an instance is reused. We have seen very subtle bugs in EJBs that don't reinitialize all fields in
ejbCreate.
On the other hand, if there is a particular application object that is extremely expensive to create, you
can easily implement your own instance pool for that class and use the version of Session.load() that
takes a class instance. Just remember to return the objects to the pool every time you close the session.

3. How do I use Hibernate in an EJB 2.1 session bean ?


A-1. Look up the SessionFactory in JNDI.
2. Call getCurrentSession() to get a Session for the current transaction.
3. Do your work.
4. Don't commit or close anything, let the container manage the transaction.

PAGE
11

4. What is Middlegen ?
A-Middlegen is an open source code generation framework that provides a general-purpose databasedriven engine using various tools such as JDBC, Velocity, Ant and XDoclet

5. How can I place a condition upon a collection size ?


A-If your database supports subselects:
from User user where size(user.messages) >= 1
or:
from User user where exists elements(user.messages)
If not, and in the case of a one-to-many or many-to-many association:
select user
from User user
join user.messages msg
group by user
having count(msg) >= 1
Because of the inner join, this form can't be used to return a User with zero messages, so the following
form is also useful
select user
from User as user
left join user.messages as msg
group by user
having count(msg) = 0

JAVA SPRING AND HIBERNATE


INTERVIEW QUESTION
1. Explain DI or IOC pattern.
A-Dependency injection (DI) is a programming design pattern and architectural model, sometimes also
referred to as inversion of control or IOC, although technically speaking, dependency injection

PAGE
12
specifically refers to an implementation of a particular form of IOC. Dependency Injection describes the
situation where one object uses a second object to provide a particular capacity. For example, being
passed a database connection as an argument to the constructor method instead of creating one inside the
constructor. The term "Dependency injection" is a misnomer, since it is not a dependency that is
injected; rather it is a provider of some capability or resource that is injected. There are three common
forms of dependency injection: setter, constructor and interface-based injection.
Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way
in which an object obtains references to its dependencies. This is often done by a lookup method. The
advantage of inversion of control is that it decouples objects from specific lookup mechanisms and
implementations of the objects it depends on. As a result, more flexibility is obtained for production
applications as well as for testing.

2. What are the different types of dependency injection? Explain with examples.

A-There are two types of dependency injection: setter injection and constructor injection.
Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the
value of property as follows:
public class namebean {
String name;
public void setName(String a) {
name = a; }
public String getName() {
return name; }
}
We will create an instance of the bean 'namebean' (say bean1) and set property as
bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration
file as shown below:
< bean id="bean1" class="namebean" >
< property name="name" >
< value > tom < / value >
< / property >
< / bean >
The subelement < value > sets the 'name' property by calling the set method as setName("tom"); This
process is called setter injection.
To set properties that reference other beans , subelement of is used as shown below,
< bean id="bean1" class="bean1impl" >
< property name="game" >

PAGE
13
< ref bean="bean2" / >
< / property >
< / bean >
< bean id="bean2" class="bean2impl" / >
Constructor injection: For constructor injection, we use constructor with parameters as shown below,
public class namebean {
String name;
public namebean(String a) {
name = a;
}
}
We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 =
new namebean("tom");
Here we use the < constructor-arg > element to set the property by constructor injection as
< bean id="bean1" class="namebean" >
< constructor-arg >
< value > My Bean Value < / value >
< / constructor-arg >
< / bean > -

3. What is spring? What are the various parts of spring framework? What are the
different persistence frameworks which could be used with spring ?
A-Spring is an open source framework created to address the complexity of enterprise application
development. One of the chief advantages of the Spring framework is its layered architecture, which
allows you to be selective about which of its components you use while also providing a cohesive
framework for J2EE application development. The Spring modules are built on top of the core container,
which defines how beans are created, configured, and managed. Each of the modules (or components)
that comprise the Spring framework can stand on its own or be implemented jointly with one or more of
the others. The functionality of each component is as follows:
The core container: The core container provides the essential functionality of the Spring framework. A
primary component of the core container is the BeanFactory, an implementation of the Factory pattern.
The BeanFactory applies the Inversion of Control (IOC) pattern to separate an applications
configuration and dependency specification from the actual application code.
Spring context: The Spring context is a configuration file that provides context information to the
Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail,
internalization, validation, and scheduling functionality.
Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly

PAGE
14
into the Spring framework, through its configuration management feature. As a result you can easily
AOP-enable any object managed by the Spring framework. The Spring AOP module provides
transaction management services for objects in any Spring-based application. With Spring AOP you can
incorporate declarative transaction management into your applications without relying on EJB
components.
Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for
managing the exception handling and error messages thrown by different database vendors. The
exception hierarchy simplifies error handling and greatly reduces the amount of exception code you
need to write, such as opening and closing connections. Spring DAOs JDBC-oriented exceptions
comply to its generic DAO exception hierarchy.
Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object
Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Springs
generic transaction and DAO exception hierarchies.
Spring Web module: The Web context module builds on top of the application context module,
providing contexts for Web-based applications. As a result, the Spring framework supports integration
with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding
request parameters to domain objects.
Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC
implementation for building Web applications. The MVC framework is highly configurable via strategy
interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and
POI.

4. What is AOP? How does it relate with IOC? What are different tools to utilize
AOP ?

A- Aspect-oriented programming, or AOP, is a programming technique that allows programmers to


modularize crosscutting concerns, or behaviour that cuts across the typical divisions of responsibility,
such as logging and transaction management. The core construct of AOP is the aspect, which
encapsulates behaviours affecting multiple classes into reusable modules. AOP and IOC are
complementary technologies in that both apply a modular approach to complex problems in enterprise
application development. In a typical object-oriented development approach you might implement
logging functionality by putting logger statements in all your methods and Java classes. In an AOP
approach you would instead modularize the logging services and apply them declaratively to the
components that required logging. The advantage, of course, is that the Java class doesn't need to know
about the existence of the logging service or concern itself with any related code. As a result, application
code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is
AspectJ. However AspectJ works at the byte code level and you need to use AspectJ compiler to get the
aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the
Spring context for transaction management, logging, and various other features. In general any AOP
framework control aspects in three possible ways:

PAGE
15

Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific
methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific context at those points
Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message
before executing a joinpoint.

5. Explain the role of ApplicationContext in spring.


A-While Bean Factory is used for simple applications; the Application Context is spring's more
advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and
dispense beans upon request. It also provide
1) A means for resolving text messages, including support for internationalization.
2) A generic way to load file resources.
3) Events to beans that are registered as listeners.
Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when
the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used
implementation of 'Application Context' are
1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the
classpath, treating context definitions as classpath resources. The application context is loaded from the
application's classpath by using the code
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem.
The application context is loaded from the file system by using the code
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web
application.

PAGE
16

EXCEPTION HANDLING INTERVIEW


QUESTION
1. How could Java classes direct messages to a file instead of the Console?
A-The System class has a variable "out" that represents the standard output, and the variable "err" that
represents the standard error device. By default, they both point at the system console.
The standard output could be re-directed to a file as follows:
Stream st = new Stream(new FileOutputStream("output.txt"));
System.setErr(st);
System.setOut(st);

2. Does it matter in what order catch statements for FileNotFoundException and


IOException are written?
A-Yes, it does. The child exceptions classes must always be caught first and the "Exception" class
should be caught last.

3. What is user-defined exception in java ?


A-User-defined expections are the exceptions defined by the application developer which are errors
related to specific application. Application Developer can define the user defined exception by inheriting
the Exception class. Using this class we can create & throw new exceptions.

4. What is the difference between checked and Unchecked Exceptions in Java ?


A-Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you
dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions.

PAGE
17

5. What is the catch or declare rule for method declarations?


A-If a checked exception may be thrown within the body of a method, the method must either catch that
exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions
that are not handled by any method.

COLLECTION INTERVIEW QUESTIONS


1. What's the main difference between a Vector and an ArrayList
A-Java Vector class is internally synchronized and ArrayList is not. Hence, Vectors are thread-safe
while ArrayLists are not. On the Contrary, ArrayLists are faster and Vectors are not. ArrayList has no
default size while vector has a default size of 10.

2. What's the difference between a queue and a stack?


A-Stacks works by last-in-first-out rule (LIFO), while queues use the first-in-first-out (FIFO) rule

3. what is a collection?
A-Collection is a group of objects.
There are two fundamental types of collections they are Collection and Map.

PAGE
18
Collections just hold a bunch of objects one after the other while Maps hold values in a key-value pair.
Collections Ex: ArrayList, Vector etc.
Map Ex: HashMap, Hashtable etc

4. What is the Collections API?


A-The Collections API is a set of classes and interfaces that support operation on collections of objects.
The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday
programming using the collections.
The purpose of the Collection API is to:
o Reduces programming efforts. - Increases program speed and quality.
o Allows interoperability among unrelated APIs.
o Reduces effort to learn and to use new APIs.
o Reduces effort to design new APIs.
o Encourages & Fosters software reuse.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

5. What is the List interface?


A-The List interface provides support for ordered collections of objects.
Ex: ArrayList

PAGE
19

GARBAGE COLLECTION INTERVIEW


QUESTIONS

1. How can you force garbage collection?


A-You cannot force Garbage Collection, but could request it by calling System.gc(). Though you
manually call this command from your program, the JVM does not guarantee that GC will be started
immediately.

2. How can you minimize the need of garbage collection and make the memory use
more effective?
A-Use object pooling and weak object references. We need to ensure that all objects that are no longer
required in the program are cleared off using finalize() blocks in your code.

3. Explain garbage collection ?


A-Garbage collection is an important part of Java's security strategy. Garbage collection is also called
automatic memory management as JVM automatically removes the unused variables/objects from the
memory. The name "garbage collection" implies that objects that are no longer needed or used by the
program are "garbage" and can be thrown away to create free space for the programs that are currently
running. A more accurate and up-to-date term might be "memory recycling." When an object is no
longer referenced by the program, the heap space it occupies must be recycled so that the space is
available for subsequent new objects. The garbage collector must determine which objects are no longer
referenced by the program and make available the heap space occupied by such unreferenced objects.
This way, unused memory space is reclaimed and made available for the program to use.

4. Does garbage collection guarantee that a program will not run out of memory?
A-Garbage collection does not guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It is also possible for
programs to create objects that are not subject to garbage collection as well. Hence, the Garbage

PAGE
20
Collection mechanism is a "On Best Effort Basis" system where the GC tries to clean up memory as
much as possible to ensure that the system does not run out of memory but it does not guarantee the
same.

5. Can an object's finalize() method be invoked while it is reachable?


A-An object's finalize() method cannot be invoked by the garbage collector while the object is still
reachable. However, an object's finalize() method may be invoked by other objects.

6. What is the purpose of garbage collection?


A-The purpose of garbage collection is to identify and discard objects that are no longer needed by a
program so that their resources may be reclaimed and reused.

7. Can an unreachable object become reachable again?


A-An unreachable object may become reachable again. This can happen when the object's finalize()
method is invoked and the object performs an operation which causes it to become accessible to
reachable objects.

CORE JAVA INTERVIEW QUESTION


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

PAGE
21

2. Explain the usage of Java packages.


A-This is a way to organize files when a project consists of multiple modules. It also helps resolve
naming conflicts when different packages have classes with the same names. Packages access level also
allows you to protect data from being used by the non-authorized classes.

3. If a class is located in a package, what do you need to change in the OS


environment to be able to use it?
A-You need to add a directory or a jar file that contains the package directories to the CLASSPATH
environment variable. Once the class is available in the CLASSPATH, any other Java program can use
it.

4. What's the difference between J2SDK 1.5 and J2SDK 5.0?


A-There's no difference, Sun Microsystems just re-branded this version.

5. What are the static fields & static Methods ?


A-If a field or method defined as a static, there is only one copy for entire class, rather than one copy for
each instance of class. static method cannot accecss non-static field or call non-static methods

6. How are Observer and Observable used?


A-Objects that subclass the Observable class maintain a list of observers. When an Observable object is
updated it invokes the update() method of each of its observers to notify the observers that it has
changed state. The Observer interface is implemented by objects that observe Observable objects.

PAGE
22

7. Is null a keyword?
A-No, the null value is not a keyword.

8. Which characters may be used as the second character of an identifier, but not as
the first character of an identifier?
A-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.

9. How does Java handle integer overflows and underflows?


A-It uses those low order bytes of the result that can fit into the size of the type allowed by the
operation.

10. What is the difference between the >> and >>> operators?
A-The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted
out.

11. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters?
A-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.

PAGE
23

12. Is sizeof a keyword?


A-No, the sizeof operator is not a keyword.

13. What restrictions are placed on the location of a package statement within a
source code file?
A-A package statement must appear as the first line in a source code file (excluding blank lines and
comments). It cannot appear anywhere else in a source code file.

14. What value does readLine() return when it has reached the end of a file?
A-The readLine() method returns null when it has reached the end of a file.

15. What is a native method?


A-A native method is a method that is implemented in a language other than Java.

16. Can a for statement loop indefinitely?


A-Yes, a for statement can loop indefinitely.
Ex:
for(;;) ;

17. What are order of precedence and associativity, and how are they used?
A-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

PAGE
24

18. What is the range of the short type?


A-The range of the short data type is -(2^15) to 2^15 - 1.

19. What is the range of the char type?


A-The range of the char type is 0 to 2^16 - 1.

20. What is the difference between the Boolean & operator and the && operator?
A-&& is a short-circuit AND operator - i.e., The second condition will be evaluated only if the first
condition is true. If the first condition is true, the system does not waste its time executing the second
condition because, the overall output is going to be false because of the one failed condition.
& operator is a regular AND operator - i.e., Both conditions will be evaluated always.

21. What is the GregorianCalendar class?


The GregorianCalendar provides support for traditional Western calendars.

22. What is the purpose of the Runtime class?


The purpose of the Runtime class is to provide access to the Java runtime system.

23. What is the argument type of a program's main() method?


A program's main() method takes an argument of the String[] type. (A String Array)

PAGE
25

24. Which Java operator is right associative?


The = operator is right associative.

25. What is the Locale class?


This class is used in conjunction with DateFormat and NumberFormat to format dates, numbers and
currency for specific locales. With the help of the Locale class youll be able to convert a date like
10/10/2005 to Segunda-feira, 10 de Outubro de 2005 in no time. If you want to manipulate dates
without producing formatted output, you can use the Locale class directly with the Calendar class.

CORE JAVA QUIESTIONS-2


1. Are true and false keywords?
A-The values true and false are not keywords.

2. What is a void return type?


A-A void return type indicates that a method does not return a value after its execution.

3. What is the difference between the File and RandomAccessFile classes?


A-The File class encapsulates the files and directories of the local file system. The RandomAccessFile
class provides the methods needed to directly access data contained in any part of a file.

4. Which package is always imported by default?


A-The java.lang package is always imported by default in all Java Classes.

PAGE
26

5. What restrictions are placed on method overriding?


A-Overridden methods must have the same name, argument list, and return type. The overriding method
may not limit the access of the method it overrides but it can expand it. The overriding method may not
throw any exceptions that are not thrown by the overridden method.

6. Which arithmetic operations can result in the throwing of an


ArithmeticException?
A-Integer / and % can result in the throwing of an ArithmeticException.

7. What is the ResourceBundle class?


A-The ResourceBundle class is used to store locale-specific resources that can be loaded by a program
to tailor the program's appearance to the particular locale in which it is being run.

8. What is numeric promotion?


A-Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that
integer and floating-point operations may take place. In numerical promotion, byte, char, and short
values are converted to int values. The int values are also converted to long values, if necessary. The
long and float values are converted to double values, as required.

9. To what value is a variable of the boolean type automatically initialized?


A-The default value of the boolean type is false.

10. What is the difference between the prefix and postfix forms of the ++ operator?
A-The prefix form performs the increment operation and returns the value of the increment operation.
The postfix form returns the current value to the expression and then performs the increment operation
on that value.

PAGE
27

11. What is the purpose of a statement block?


A-A statement block is used to organize a sequence of statements as a single statement group.

12. What is the difference between an if statement and a switch statement?


A-The if statement is used to select among two alternatives. It uses a boolean expression to decide which
alternative should be executed. The switch statement is used to select among multiple alternatives. It
uses an int expression to determine which alternative should be executed.
A Switch statement with 5 Case blocks can be compared to an if statement with 5 else-if blocks.

13. What do you mean by object oreiented programming


A-In object oreinted programming the emphasis is more on data than on the procedure and the program
is divided into objects. Some concepts in OO Programming are:
* The data fields are hidden and they cant be accessed by external functions.
* The design approach is bottom up.
* The Methods operate on data that is tied together in data structure

14. What are 4 pillars of object oreinted programming


A-1. Abstraction - It means hiding the details and only exposing the essentioal parts
2. Polymorphism - Polymorphism means having many forms. In java you can see polymorphism when
you have multiple methods with the same name
3. Inheritance - Inheritance means the child class inherits the non private properties of the parent class
4. Encapsulation - It means data hiding. In java with encapsulate the data by making it private and even
we want some other class to work on that data then the setter and getter methods are provided

15. Difference between procedural and object oreinted language


A-In procedural programming the instructions are executed one after another and the data is exposed to

PAGE
28
the whole program
In Object Oriented programming the unit of program is an object which is nothing but combination of
data and code and the data is not exposed outside the object

A-16. What is the difference between parameters and arguments


A-While defining method, variables passed in the method are called parameters. While using those
methods, values passed to those variables are called arguments.

A-17. What is reflection in java


A-Reflection allows Java code to discover information about the fields, methods and constructors of
loaded classes and to dynamically invoke them. The Java Reflection API covers the Reflection features.

18. What is a cloneable interface and how many methods does it contain
A-The cloneable interface is used to identify objects that can be cloned using the Object.clone() method.
IT is a Tagged or a Marker Interface and hence it does not have any methods.

THE END
EMAIL SAHILYADAV761@GMAIL.COM
WEBSITE- http://javacodehelps.blogspot.com
Fb page- www.fb.com/javacodehelps

You might also like