HIBERNATE
1. What is Hibernate?
§ Object/Relational (OR) Mapping Tool.
Object-relational mapping is, mapping object-oriented programming objects to relational databases managed by MYSQL, Oracle, DB2, Sybase, and other relational database managers (RDBMS).
§ Helps in Transparent Persistence.
Object-relational mapping products have the ability to directly manipulate the data stored in the relational database using object oriented programming. This is in contrast to the database sub-language used by Embedded SQL or call interface used by JDBC or ODBC.
§ An object-relational mapping product is likely to reduce programmer code and, through caching, improve performance.
2. Why use Hibernate?
Hibernate provides a lot of advantages over the traditional method of interacting with the database.
§ Ease of interaction with the Database:
Hibernate maps plain old java objects(that have simple getter/setter methods for the attributes in the table) to the tables already created in the database using the .hbm.xml files (also called mapping files), provides queries to insert, update, delete etc. data in the tables though it does not help in creating tables.
§ JDBC Calls not required:
A hibernate. properties file, which has details about the database, needs to be created. While configuring Hibernate, this properties file is looked up for connecting to the database without the user having to make the JDBC calls and thereby avoids the hard coding of IP, port, username, password etc in the code. The driver for the database needs to be included.
§ The Hibernate Query Language (HQL):
Database related queries should be written in this language and Hibernate converts it to a query that is supported by the underlying Database.
Advantages of using HQL:
o HQL facilitates writing database independent queries. These are converted to SQL queries specific to the underlying database at runtime. Learning SQL specific to the database is not a must.
o Makes the application program very loosely coupled with the underlying database.
3. Tools that support Hibernate:
XDoclet
AndroMDA
Middlegen
Spring FrameWork
All these tools help us generate the objects and/or mapping documents used in Hibernate.
4. Using Hibernate:
To use Hibernate the following documents need to be in place.
Note:-Samples of these files can be found in the attachment named source.zip
§ The jar files specific to Hibernate. (details are given below)
§ Hibernate.properties file.
§ Bean Class which is a POJO (Plain Old Java Object) which represents the Table.
§ Mapping Document which is a XML.
§ The Application Program.
4.1 The Jar files:
Having obtained the Hibernate package, include the following jar files in the Classpath. The jar files are:
§ hibernate2.jar ;
§ ehcache-0.7.jar ;
§ cglib-full-2.0.1.jar ;
§ xerces-2.4.0.jar ;
§ dom4j-1.5.jar ;
§ jta.jar ;
§ j2ee.jar ;
§ commons-collections-2.1.jar ;
§ mysql-connector-java-3.0.14-production-bin.jar ;
Most of these jar files can be found in the lib folder of the package. MySQL-connector and J2EE .jar files need to be procured. MySQL Connector is being used since the DB used in the application is MYSQL. The driver for the MySQL Database can be found in this jar. Hence depending on the Database that the application demands, corresponding driver needs to be procured.
4.2 Table in the Database:
Tables need to be created before running the application. Hibernate does not help in creating tables. Its main purpose is to make the transient data persistent with least trouble. The table that is used in the example has the following fields:
§ SerialNo: - Serial Number, which is the primary key and is an auto increment.
§ FirstName:- First name of the employee
§ LastName: - Last name of the employee.
Note: - The database that is used is MySQL. The database is not on the local machine. It is in the network.
The DDL used for creating the Table is:
“Create table tblEmpDetails (
SerialNo int primary key auto_increment,
FirstName varchar (15),
LastName varchar (15));”
4.3 Hibernate. properties file:
Databases usually have various details linked to them. All these are reflected in the file hibernate.properties. This file holds details like:
§ IP Address of the Database.
§ User ID.
§ Password
§ Dialect( This is specific to the database , and can be obtained from the hibernate API)
§ Other details like connection-pool, show-sql, etc.
This file comes with the Hibernate package in the folder src. It needs to be modified to suit the applications requirements.
4.4 Defining Persistent Domain Object:
This is basically the bean class that has simple getter/setter methods for the attributes that are specified in the table. Inorder to persist data, the bean class is instantiated and using the setter methods, data is set. The object is then saved to the database. The Persistent Domain object in the example is EmpDetails.java. Mapping of the bean class to the table happens in the .hbm.xml file also called the mapping file explained next.
4.5 Hibernate mapping File:
Mapping files in Hibernate are basically XML files. The various tags and their functions are given below. An xml file corresponding to the bean and the table is given in the attachment (EmpDetails.hbm.xml). The DTD-(Document Type Definition)-for the xml file is predefined and can be found in the hibernate package in the folder src\net\sf\hibernate. While compiling the XML document, the application searches for the DTD in the URL specified. If it fails to locate it then it searches for it in the hibernate package itself. The various tags that were used are given below.
Tuesday, November 6, 2007
Posted by
Real Time Questions
at
3:06 AM
0
comments
Labels: HIBERNATE
EJB
1.1 UNDERSTANDING THE EJB ARCHITECTURE
There should be a tight coupling between the Web Tier and the EJB Tier.
This is accomplished by the IService and the ServiceImpl.
All the EJB calls must be in the IService interface. These methods in the Interface must be implemented in the ServiceImpl class.
The constructor of the ServiceImpl, gets the handle to the remote through the BusinessServiceFactory and the ServiceLocator classes. The ServiceLocator gets the handle through the JNDI name. ServiceLocator looks up and reads the services-config.xml file and retrieves the JNDI Name of the Services corresponding to the name. From the JNDI name it gives the handle to the EJB. If the handle is in cache, then it is returned from cache. Otherwise, a new handle is created. This handle is used by the rest of all methods to contact the EJB Tier (Façade). Façade gives the handle to the FacadeEJB.
The EJBHelper will help to create handles to the LocalEJBs. There can be more than one LocalEJB. Every ‘LocalEJB’ will have its corresponding ‘Local’. The EJBHelper gets a handle to the Local which in turn gives a call to the LocalEJB. Every method in the FacadeEJB gets the handle to the appropriate Local via the EJBHelper. And then corresponding call is made with this handle. There can also be many Helper classes for every LocalEJB so that the functionalities are split up and diversified.
When the number of EJB methods is finite or limited, we need not go for LocalEJB. The functionalities can b accomplished by having one EJB. In that case, the Façade becomes the Remote and all the functionalities are implemented in the EJB(only one created).
The LocalEJBs and the Helper classes can have private methods for simplification of the work to be performed. These private methods are explicitly for those classes that implement.
Flow is like this.
IService à ServiceImpl à Façade à FacadeEJB à Local à LocalEJB à Helper Classes (if any)
Façade pattern is followed when the redirection of EJB calls are required.
There can be more than one LocalEJb. Different calls can be in different Ejbs. Different LocalEJBs can be created for different purposes. From FacadeEJB, the calls can be made to the appropriate EJB.
There can be many EJB calls. Instead of mounting all the EJB calls, in one Local EJB, they can be split and more LocalEJBs and helper classes can be created.
1.2 CREATION OF ISERVICE
Create a new Java interface in util package named as I
Ex.
public interface IWorkFlowService
extends IService
{
}
1.3 CREATION OF SERVICEIMPL
Create a new Java class in web package named as
Ex. Text written in
public WorkFlowServiceImpl()
{
//Get the instance of Service Locator
_serviceLocator = ServiceLocator.getInstance();
//Initialize the service Locator
try
{
_serviceLocator.init();
}
catch (ServiceLocatorException e2)
{
e2.printStackTrace();
}
try
{
//Get the handle to the Home
_workflowHome =
(WorkFlowFacadeHome) _serviceLocator
.getRemoteHome(WorkFlowServiceImpl.SERVICE_NAME,
WorkFlowFacadeHome.class);
}
catch (ServiceLocatorException e1)
{
if (_log.isDebugEnabled())
{
_log.debug("Service Exception: Service" +
" not located");
}
e1.printStackTrace();
}//handle Exception
//Obtain the Remote Interface from the Home Reference
try
{
_workflowRemote = _workflowHome.create();
}
catch (RemoteException e)
{
// e.printStackTrace();
//To be Replaced with Logging Code
}
catch (CreateException e)
{
// e.printStackTrace();
//To be replaced with Logging code
}
}
1.4 CREATION OF FACADE
Create a new Java class in the ejb package named as
Copy the code from the existing UserFacade and paste it in the newly created class. Change the name of the class. Except for the EJB methods, remove all the other methods.
All your methods in Facade must throw RemoteException.
Ex.
public ProcessTO fetchAllSteps()
throws RemoteException,WorkFlowException;
1.5 CREATION OF FAÇADE EJB
Create a new Java class in the ejb package named as
If you need to create LocalEJBs, then do the following. If you need to go for ServiceDelegates go to section 1.10.
1.6 CREATION OF LOCAL
Create a new Java class in the ejb package named as
Copy the existing code from the UserLocal to the newly created class. Change the name of the class. Remove all the methods.
1.7 CREATION OF LOCAL EJBs
Create a new class in the ejb package named as
1.8 CREATION OF FAÇADE HOME
Create a new class in the ejb package named as
Ex.
public WorkFlowFacade create()
throws RemoteException, CreateException;
1.9 CREATION OF EJBHELPER
Create the Java class in the ejb package named as
Copy the code from UserEJBHelper and paste it. Change the name of the newly created class. Modify the existing method appropriately.
Ex.
localHome = (WorkFlowLocalHome)
ServiceLocator.getInstance()
getLocalHome(WorkFlowConstants.
WORKFLOW_LOCAL_SERVICE);
Note: WorkFlowConstants is a constants file created in util package.
1.10 CREATION OF META-INF, ejb-jar.xml and weblogic-jar.xml
Create a new folder under the ejb package “META-INF”.
Create a new XML file named as weblogic-jar.xml.
Copy the code in weblogic-jar.xml of ejb package of User module.
Paste it in the newly created xml file. Change the entries in the xml file, for the EJB being created by replacing the UserLocalEJB entries and remove the entries for TeamLocalEJB.
Ex.
FACADEEJB
WorkFlowFacadeEJB
WorkFlowFacadeEJB
LOCALEJB
WorkFlowLocalEJB
WorkFlowLocalEJB
Create a new XML file named as ejb-jar.xml
Copy the code in ejb-jar.xml of ejb package of User module.
Paste it in the newly created xml file. Change the entries in the xml file, for the EJB being created by replacing the UserLocalEJB entries and remove the entries for TeamLocalEJB.
Create 2 new
Ex.
FACADEEJB
WorkFlowFacadeEJB
com.gm.pqms.domain.workflow.ejb.WorkFlowFacadeHome
com.gm.pqms.domain.workflow.ejb.WorkFlowFacade
com.gm.pqms.domain.workflow.ejb.WorkFlowFacadeEJB
Stateless
Bean
LOCALEJB
WorkFlowLocalEJB
com.gm.pqms.domain.workflow.ejb.WorkFlowLocalHome
com.gm.pqms.domain.workflow.ejb.WorkFlowLocal
com.gm.pqms.domain.workflow.ejb.WorkFlowLocalEJB
Stateless
Bean
Open the BusinessServiceFactory.java in arch.util package for editing. Add a new constant to the existing constants for
Ex.
public static final String WORKFLOW_SERVICE = "WORKFLOW_SERVICE";
Add a new entry in the file for ServiceImpl as follows .
Ex.
classMap.put(BusinessServiceFactory.WORKFLOW_SERVICE, "com.gm.pqms.domain.workflow.web.WorkFlowServiceImpl");
1.11 MODIFICATION OF EXISTING XML FILES
Open build.xml in WebRoot/WEB-INF package for editing.
Add a new
Ex.
Open application.xml in the same package for editing.
Add a new entry
Ex.
Open service-config.xml file in the arch.util package for editing.
Add a new entry for the ejb created.
Ex.
-- END --
P.S : Every method in the FacadeEJB must be included in IService, ServiceImpl, Façade, FacadeEJB, Local and LocalEJB.
Posted by
Real Time Questions
at
3:02 AM
0
comments
Labels: EJB
JVM FAQs
1.What is JVM?
A Java Virtual Machine is a runtime environment required for execution of a Java application.Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM.It is JVM which is crux of 'platform independent' nature of the language.
2.What is a JVM consisted of?
Each time a Java Application is executed then an instance of JVM ,responsible for its running,is created.A JVM instance is described in terms of subsystems, memory areas, data types, and instructions.The block diagram given below,depicts a view of Internal Architecture of JVM :
3.What is a class loader and what is its responsibilities?
The Class loader is a subsystem of a JVM which is responsible,predominantly for loading classes and interfaces in the system.Apart from this,a class loader is responsible for the following activities:-Verification of imported types(classes and interfaces)-Allocating memory for class variables and initializing them to default values.Static fields for a class are created and these are set to standard default values but they are not explicitly initialized.The method tables are constructed for the class.-Resolving symbolic references from type to direct references The class loaders can be of two types: a bootstrap or primordial class loader and user defined class loaderEach JVM has a bootstrap class loader which loads trusted classes , including classes from Java API.JVM specs do not tell how to locate these classes and is left to implementation designers.A Java application with user defined class loader objects can customize class loading.These load untrustworthy classes and not an intrinsic part of JVM.They are written in Java,converted to class files and loaded into the JVM and installed like any other objects.If you want to read this in more details then read Chapter 8,"The Linking Model" of Inside Java 2 Virtual Machine by Bill Venners.
4. What is heap and stack?
The heap is the part of memory of JVM where all objects reside.The stack is consisted of stack frames.When a thread invokes a method,the JVM pushes a new frame onto that thread's Java stack.Each stack frame is consisted of operand stack and the local variable array.All arguments,local variables,intermediate computations and return values if any are kept in these stack corresponding to the method invoked.The stack frame on the top of the stack is called the active stack frame,which is the current place of execution.When the method completes, the virtual machine pops and discards the frame for that method.
5. How is your Java program executed inside JVM?
When JVM executes a Java application, a runtime instance of JVM is born.This runtime instance invoke main() method of Java application.The main() method of an application serves as the starting point for that application's initial thread. The initial thread can in turn fire off other threads.This thread has a program counter(PC) and Java stack.Whenever main() method is invoked, a stack frame is pushed onto the stack,this then becomes the active tack frame.The program counter in the new Java stack frame will point to the beginning of the method.If there are more method invocations within main() method then this process of pushing new stack frame onto the stack for each method call is repeated as and when they are invoked.When a method returns, the active frame is popped from the stack and the one below becomes the active stack frame.The PC is set to the instruction after the method call and the method continues.There is only one heap corresponding to an instance of JVM and all objects created are stored here.This heap is shared by all threads created in an application.Inside the Java virtual machine, threads come in two flavors: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application--the one that begins at main()--is a non- daemon thread.A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.When main() returns,it terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.
6. What is Java class file's magic number?
A Magic Number of a class file is a unique identifier for tools to quickly differentiate class files from non class files.The first four bytes of each Java class file has the magic value as 0xCAFEBABE.And the answer to why this number,I do not actually know but there may be very few sensible and acceptable options possible constructed from letters A-F which can surely not be 'CAFEFACE' or 'FADECAFE'....
7. How JVM performs Thread Synchronization?
JVM associates a lock with an object or a class to achieve mutilthreading. A lock is like a token or privilege that only one thread can "possess" at any one time. When a thread wants to lock a particular object or class, it asks the JVM.JVM responds to thread with a lock maybe very soon, maybe later, or never. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.If a thread has a lock,no other thread can access the locked data until the thread that owns the lock releases it.The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.Each monitor is associated with an object reference. It is the responsibility of monitor to watch an arriving thread must obtain a lock on the referenced object.When the thread leaves the block,it releases the lock on the associated object.A single thread is allowed to lock the same object multiple times.JVM maintains a count of the number of times the object has been locked. An unlocked object has a count of zero. When a thread acquires the lock for the first time, the count is incremented to one. Each time the thread acquires a lock on the same object, a count is incremented. Each time the thread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads.In Java language terminology, the coordination of multiple threads that must access shared data is called synchronization. The language provides two built-in ways to synchronize access to data: with synchronized statements or synchronized methods.The JVM does not use any special opcodes to invoke or return from synchronized methods. When the JVM resolves the symbolic reference to a method, it determines whether the method is synchronized. If it is, the JVM acquires a lock before invoking the method. For an instance method, the JVM acquires the lock associated with the object upon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs. After a synchronized method completes, whether it completes by returning or by throwing an exception, the lock is released.Two opcodes, monitorenter and monitorexit are used by JVM for accomplishing this task.When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If the thread already owns the lock for that object, a count is incremented. Each time monitorexit is executed for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.
8.How JVM performs Garbage Collection?
Whenever a reference to an object on heap lies dangling or no longer in use then it becomes eligible for being garbage collected by JVM.JVM specifications do not force any specific kind of garbage collection algorithm though there are several algorithms like reference counting,tracing,compacting,copying,generational etc. in place.It is very important that garbage collection should be efficient and non interfering in execution of Java programs.There is a trade off between ease of implementation versus better performance while implementing garbage collection feature for a JVM.
9. How to profile heap usage?
Try using -Xaprof to get a profile of the allocations (objects and sizes) of your application.Also try -agentlib:hprof=heap=all (or other option, try -agentlib:hprof=help for a list).
10. What will you do if VM exits while printing "OutOfMemoryError" and increasing max heap size doesn't help?
The Java HotSpot VM cannot expand its heap size if memory is completely allocated and no swap space is available. This can occur, for example, when several applications are running simultaneously. When this happens, the VM will exit after printing a message similar to the following.Exception java.lang.OutOfMemoryError: requested bytesIf you see this symptom, consider increasing the available swap space by allocating more of your disk for virtual memory and/or by limiting the number of applications you run simultaneously. You may also be able to avoid this problem by setting the command-line flags -Xmx and -Xms to the same value to prevent the VM from trying to expand the heap. Note that simply increasing the value of -Xmx will not help when no swap space is available.
11. Should one pool objects to help Garbage Collector?Should one call System.gc() periodically?
The answer is No!Pooling objects will cause them to live longer than necessary. The garbage collection methods will be much more efficient if you let it do the memory management. The strong advice is taking out object pools.Don't call System.gc(), HotSpot will make the determination of when its appropriate and will generally do a much better job.
12. An application has a lot of threads and is running out of memory, why?
You may be running into a problem with the default stack size for threads. In Java SE 6, the default on Sparc is 512k in the 32-bit VM, and 1024k in the 64-bit VM. On x86 Solaris/Linux it is 320k in the 32-bit VM and 1024k in the 64-bit VM.On Windows, the default thread stack size is read from the binary (java.exe). As of Java SE 6, this value is 320k in the 32-bit VM and 1024k in the 64-bit VM.You can reduce your stack size by running with the -Xss option. For example:java -server -Xss64kNote that on some versions of Windows, the OS may round up thread stack sizes using very coarse granularity. If the requested size is less than the default size by 1K or more, the stack size is rounded up to the default; otherwise, the stack size is rounded up to a multiple of 1 MB.64k is the least amount of stack space allowed per thread.
13. If your program is I/O bound or running in native methods, do these activities engage JVM?
The answer is 'No'.If the program is I/O bound or running in native methods, then the VM is not involved in the consumption of CPU time. The VM technology will engage CPU for running bytecodes. Typical examples of time spent not running bytecode are graphical operations that make heavy use of native methods, and I/O operations such as reading and writing data to network sockets or database files.
14. What is the difference between interpreted code and compiled code?
An interpreter produces a result from a program, while a compiler produces a program written in assembly language and in case of Java from bytecodes.The scripting languages like JavaScript,Python etc. require Interpreter to execute them.So a program written in scripting language will directly be executed with interpreter installed on that computer,if it is absent then this program will not execute.While in case of compiled code,an assembler or a virtual machine in case of Java is required to convert assembly level code or bytecodes into machine level instructions/commands.Generally, interpreted programs are slower than compiled programs, but are easier to debug and revise.
15. Why Java based GUI intensive program has performance issues?
GUI intensive Java application mostly run underlying OS specific native libraries which is time and more CPU cycles consuming.
The overall performance of a Java application depends on four factors:
The design of the application
The speed at which the virtual machine executes the Java bytecodes
The speed at which the libraries that perform basic functional tasks execute (in native code)
The speed of the underlying hardware and operating system
The virtual machine is responsible for byte code execution, storage allocation, thread synchronization, etc. Running with the virtual machine are native code libraries that handle input and output through the operating system, especially graphics operations through the window system. Programs that spend significant portions of their time in those native code libraries will not see their performance on HotSpot improved as much as programs that spend most of their time executing byte codes.
16. What is 64 bit Java ?
A 64-bit version of Java has been available to Solaris SPARC users since the 1.4.0 release of J2SE. A 64-bit capable J2SE is an implementation of the Java SDK (and the JRE along with it) that runs in the 64-bit environment of a 64-bit OS on a 64-bit processor. The primary advantage of running Java in a 64-bit environment is the larger address space.This allows for a much larger Java heap size and an increased maximum number of Java Threads, which is needed for certain kinds of large or long-running applications. The primary complication in doing such a port is that the sizes of some native data types are changed. Not surprisingly the size of pointers is increased to 64 bits. On Solaris and most Unix platforms, the size of the C language long is also increased to 64 bits. Any native code in the 32-bit SDK implementation that relied on the old sizes of these data types is likely to require updating.Within the parts of the SDK written in Java things are simpler, since Java specifies the sizes of its primitive data types precisely. However even some Java code needs updating, such as when a Java int is used to store a value passed to it from a part of the implementation written in C.
17. What is the difference between JVM and JRE?
A Java Runtime Environment (JRE) is a prerequisite for running Java applications on any computer.A JRE contains a Java Virtual Machine(JVM),all standard,core java classes and runtime libraries. It does not contain any development tools such as compiler, debugger, etc. JDK(Java Development Kit) is a whole package required to Java Development which essentially contains JRE+JVM,and tools required to compile and debug,execute Java applications
Posted by
Real Time Questions
at
2:58 AM
0
comments
Labels: JVM faqs2
CORE JAVA faqs2
- Why stop and suspend method are deprecated?
Stop() terminates the thread abruptly while suspend() method blocks a thread until another thread calls resume () on it.
Stop () method will leave an object in inconsistent state because it immediately gives up locks on all other object that it has locked. For example, during transfer of money from one account to other account if the transfer thread is stopped, the bank account object is damaged. When a thread wants to stop another thread, it doesn’t know when it is safe to stop that thread. So it has been deprecated.
Suspend () method frequently leads to deadlocks .It can be invoked on a thread externally at any point of time without the threads consent which is not desired. For this reason it has been deprecated. - What is difference between sleep() ,wait()and suspend() of a Thread ?
Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has acquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt () it will wake up the sleeping thread.
Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptible it is deadlock prone.
object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object. - What is "starvation" when used in the context of the Java threading model?
· Starvation is when the Java runtime (JVM) doesn't allocate time to a thread to execute. This may be due to a poor scheduling algorithm (like green Threads under Solaris, where a for loop from 1 to 1 million doing something CPU intensive wouldn't yield the CPU under Solaris but would under Windows), poor programming practice (not returning from the paint() method in an applet), or a hostile attack (like hitting a host with a denial of service attack where the CPU is busy outside the Java process). - What is a daemon thread?
· Daemon is a thread that has only purpose in life is to serve others.
· When only daemon threads remain, the program exits. - What is the difference between a “Green thread” and “Native thread”
· Green Threads" are the default threads that are provided in the JDK, while the "Native Threads" are the one provided by the native Operating System.Normally "Native Threads" provide better performance because they are controlled by the kernel of the system, allowing the JVM to better use the resources offered by the system itself.For example, in a multiprocessor system "Green Threads" will never be able to use Solaris or Linux or Windows specified kernel calls to optimize the use of the processors. - What is an object graph?
· When used in connection with serialization, an object graph is a tree structure rooted at the object you have written to the ObjectOutputStream. The branches and leaves of the tree are all the objects, which are reachable by following references from the root object. This structure is maintained by the ObjectOutputStream in order to ensure that the complete reachable state of the given object is serialized and to handle cyclic dependencies. The graph is computed on the fly, during the serialization process.
A side-effect of maintaining this graph is that an object which has already been written to the stream will not be written again - it will be replaced by an object stream identifier, simply a number used to point at the previously object. To force a changed object to be written in its entirety, you need to reset() the stream, which clears the object graph - Can a Vector or a Hashtable be serialized and deserialized?
· Both these classes implement Serializable, and have been designed for serialization. So yes, they can be serialized.
· In order to serialize a collection like Vector or Hashtable, you must also be able to serialize all of the objects contained in these collections. Otherwise, the collection would not be able to be completely restored. Your program will throw a NotSerializableException unless all objects stored in the Vector or Hashtable are also serializable. - Is writing an object to an ObjectOutputStream a thread-safe operation?
· Absolutely not. Serialization, i.e. passing an object reference to the writeObject () method of ObjectOutputStream, is not an atomic operation. Serialization involves traversing a graph of objects, each of which contributes to the state of the object being serialized, saving the state of each object in turn. This is a time-consuming procedure. If other threads are allowed to concurrently access or modify any one of the objects in the graph you could get undefined and unwanted results. - What is the advantage of using Externalizable over Serializable?
· Externalization allows a class to specify the methods to be used to write the object's contents to a stream and to read them back. By implementing Externalizable you can win performance at the cost of flexibility and extra code to maintain. If you implement Externalizable you stream the data directly without the need for reflection, which is used in the case of Serializable. - What is JNDI and what is its use?
· JNDI is Java Naming and Directory Services provides a standard interface to locate users, machines, networks, objects and services. - Define a naming service?
· Associates names with objects, which is otherwise called binding.
· It provides a facility to find objects based on names, which is otherwise known as look-up.
· When it is required to locate a machine on the network, DNS is used to translate the machine name to IP Address. - What is a directory object? Is it different from naming object?
· A directory object can store attributes with it. A directory metadata contains how the directory is structured. - What are the standard naming and directory services available?
· LDAP, NIS (Network Information services) and NDS (Novell Directory Services).
61. What are the advantages of using JNDI?
· It is unified to system to access all sorts of directory service information.
· It is single API to access different directories with different protocols.
· It insulates application from protocol and implementation details.
· It is extensible. Future provider of directories can plug in their particular directory services to JNDI without affecting client code.
Posted by
Real Time Questions
at
2:55 AM
0
comments
Labels: CORE JAVA faqs2
CORE JAVA faqs
- What is the difference between an Interface and Abstract class ?
· A class may implement several interfaces where as it can extend only one abstract class.
· An interface cannot provide any code at all, much less default code where as an abstract class can provide complete code, default code, and/or just stubs that has to be overridden.
· Static final constants can use the interfaces without qualification in classes that implement the interface where as both static constants and instance variables can use the abstract classes.
· Interface implementation can be added to any existing third part classes where as third party classes must be rewritten to extend from the abstract classes.
· Interfaces are used to often represent peripheral ability of a class, not central identity where as abstract class defines core identity of its descendants.
· If various implementations share is method signature then Interface works best where as If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.
· Interface is slow where as abstract class is fast in performance.
· If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method where as in case of an abstract class if you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.
· You can put shared code into an abstract class, where you cannot into an interface. - How do you write user-defined exceptions in Java?
· To write user-defined exception in java, you exception class should extend Exception base class have call the super class methods in your own methods.
What is multiple inheritance? Is it supported in java?
· This means one object having multiple parents, which is not truly supported in java but supported in C++. But overall design of java suggests that we can implement multiple inheritances in java using interfaces. - What is difference between an inner class and static inner class?
· A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.
What is an inner class and what is its advantage?
· Inner class is class, which is defined inside a class as private class and always bears a reference to the outer class.
o Inner classes can be nested within the body of a method.
· Scope of inner class is the entire enclosing class in which the inner class is nested.
· Inner classes can access attributes and methods in nesting class.
· Each inner class is compiled into a separate. class file labeled:NestingClass$InnerClass.
· Inner classes can contain methods that return handles to inner class instances.
· Major advantage of inner classes is the ability to create adaptor classes that implement an interface.
o Make all inner classes private to ensure hidden implementation.
o Rather than handle classes returning inner classes, they return interfaces.
· Inner classes frequently used with event handling in applets. - What is a transient variable?
o The variable, which cannot be serialized, is known as transient variable.
What are wrapped classes?
o Wrapped classes are classes that allow primitive types to be accessed as objects.
What is an immutable object and what are its advantages?
· An immutable object is an object and any object it references that does not change after construction. The object is, therefore, immutable for its lifetime.
· Immutable classes are commonly used to represent strings, colors, and numeric values.
Advantage:
· They guarantee that their state cannot change after construction, they are inherently thread-safe. - What are basic rules, which govern creation of immutable classes?
· Declare the class final.
· Declare all data private.
· Provide only getter methods and no setter methods.
· Set all instance data in the constructor.
· Clone mutable objects for which a reference to them is returned.
· Clone mutable objects for which a reference to them is received.
· Implement a deep clone if the default shallow clone is not correct for a properly behaved immutable object.
What is a Java package and how is it used?
· A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces- What restrictions are placed on method overriding?
· 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.
· The overriding method may not throw any exceptions that may not be thrown by the overridden method. - What is use of this and super key words?
· ‘this’ is used for referring to current instance of the object where as ‘super’ is used to refer to variables and methods of its super class.
· Incase of constructors, this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. - What is the difference between a static and non-static variable?
· A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
What is polymorphism and what are different types of polymorphism?
· One name, different form and there are three forms.
1. Method overloading
2. Method overriding through Interfaces
3. Method overriding through java interfaces.
What is the essence of run-time polymorphism behavior?
With runtime polymorphism based on method overriding, the decision as to which version of a method will be executed is based on the actual type of object whose reference is stored in the reference variable, and not on the type of the reference variable on which the method is invoked.
The decisions as to which version of the method to invoke cannot be made at compile time. That decision must be deferred and made at runtime. This is sometimes referred to as late binding.
What is a singleton class and how to implement it? What are the advantages of Singleton class?
Singleton classes are created to have only one instance.
A singleton may be used to represent some unique system.
It is generally implemented by keeping the constructor private.
It should have static members and methods.
The main advantage of singleton class is memory management( Garbage collection)
Why java prohibits use of ‘synchronized’ inside a constructor ?
because other threads cannot get a reference to the object until construction of the object completes. This has got a performance overhead.
What do you mean by Garbage collection and what are its advantages and disadvantages?
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.
An object is eligible for garbage collection when its reference is set to null. Method variables or local variables are eligible for Garbage collection when they go out of scope.
Garbage Collection cannot be forced explicitly. JVM may do garbage collection if it is running short of memory.The call System.gc() does NOT force the garbage collection but only suggests that the JVM may make an effort to do garbage collection.
It frees up the heap space and takes care of heap fragmentation.
It also helps to ensure program integrity as programmers are unable to crash the JVM by incorrectly freeing the memory accidentally or purposefully.
The only disadvantage is garbage-collected heap is a performance overhead.
What do you mean by conservative garbage collector?
The garbage collectors that cannot distinguish between genuine object references and look-alikes.
Can an object's finalize () method be invoked while it is reachable?
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.
How many times may an object's finalize() method be invoked by the garbage collector and when it is invoked ?
An object's finalize() method may only be invoked once by the garbage collector when the object is unreachable. - Does garbage collection guarantee that a program will not run out of memory?
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. - How does the distributed garbage collection work in java?
· The RMI subsystem implements a reference counting-based distributed garbage collection (DGC) algorithm to provide automatic memory management facilities for remote server objects.
· Basically, DGC works by having the remote server keep track of all external client references to it at any given time. When a client obtains a remote reference, it is addded to the remote object's referenced set. The DGC then marks the remote object as dirty and increases its reference count by one. When a client drops a reference, the DGC decreases its reference count by one, and marks the object as clean. When the reference count reaches zero, the remote object is free of any live client references. It is then placed on the weak reference list and subject to periodic garbage collection. - What is the priority of Garbage collection thread in java ?
This is a low-priority thread in java. - How many applications can be run by one run-time instance of JVM ?
One run-time instance of java application can run only one instance.
When the JVM terminates ?
The Java Virtual machine terminates when all the non-daemon threads of java application terminates.
If permitted by the security manager it can also call System.runtime.ext () for terminating the JVM. - Is it possible to know from the content of a class file whether it is a java class file or not?
The first four bytes of every java class file is a magic number “0xCAFEBABE”. So it is very easy to identify whether it is a java class file or not. - Name the process thru which JVM makes the types available to the running program?
The Java Virtual Machine makes types available to the running program through a process of loading, linking, and initialization. - Define loading, linking and initialization of java class ?
Loading : Loading is the process of bringing a binary form for a type into the Java Virtual Machine.
Linking : Linking is the process of incorporating the binary type data into the runtime state of the virtual machine. Linking is divided into three sub-steps: verification, preparation, and resolution.
Initialization: During initialization the class variables are their proper initial values. - What do you mean by first active use of a class in JVM?
· The invocation of a constructor on a new instance of the class.
· The creation of an array that has the class as its an element type.
· The invocation of a method declared by the class (not inherited from a super class) .
· The use or assignment of a field declared by the class (not inherited from a superclass or super interface), except for fields that are both static and final, and are initialized by a compile-time constant expression. - What are steps involved in loading of a class file into JVM?
· Produce a stream of binary data that represents the type.
· Parse the stream of binary data into internal data structures in the method area.
· Create an instance of class java.lang.Class that represents the type.
Is it possible to detect a malformed class file during early loading by the class loader?
No it is not possible. If a class loader encounters a missing or malformed class file during early loading, it must wait to report that error until the class is first active use by the program.
What are the different stages of linking after the class is loaded?
Verification, prepare and resolve are the three phases of linking. - What is verification stage and what are steps involved during verification?
It ensures that the types obey the semantics of java language and doesn’t violate the integrity of JVM.
The entire process of detecting any kind of problem with loaded types is placed under the category of verification.
Verification of symbolic references and converting them to direct references.
· checking that final classes are not sub classed
· checking that final methods are not overridden
· if the type being checked is a non-abstract class, checking that all the methods declared in any interfaces implemented by the class are indeed implemented by the class
· Making sure no incompatible method declarations (such as two methods that have the same name, the same number, order, and types of parameters, but different return types) appear between the type and its supertypes. - What is done during Preparation Stage?
The Java Virtual Machine allocates memory for the class variables and sets them to default initial values. The class variables are not initialized to their proper initial values until the initialization phase.
Java Virtual Machine implementations may also allocate memory for data structures that are intended to improve the performance of the running program. - What happens during Resolution Phase?
Resolution is the process of locating classes, interfaces, fields, and methods referenced symbolically from a types constant pool, and replacing those symbolic references with direct references. - How the initialization of class is is different from initialization of interface?
Initialization of class requires initialization of its super classes but initialization of interfaces doesn’t require initialization of it super interfaces. - What is a JIT compiler?
JIT compilers are used to convert the java byte codes to native types on the fly. - What is the difference between instance method and class method ?
· Instance methods require an instance before they can be invoked; class methods do not.
· Instance methods use dynamic (late) binding; class(static methods) methods use static (early) binding. - What is the difference between a process and Thread?
A process is a self-contained running program within its own address space while a Thread is a single sequential flow of control within a process.
Each process has its own set of variables where as Threads share the same data.
Inter-process communication is much slower and restrictive as compared to inter-thread communication is faster.
Creating and destroying Thread is much cheaper in terms of performance overhead as compared to launching a new process. - What is the difference between pre-emptive multi-tasking and co-operative multi-tasking?
In case of pre-emptive multitasking, the program is interrupted without consulting first where as in case of co-operative multitasking; programs are interrupted only when they are willing to yield control.
Windows 95,NT – pre-emptive multi-tasking where Windows 3.1 is co-operative multitasking.
Pre-emptive multi-tasking is more effective as compared co-operative multitasking. - What is difference between creating a thread by extending Thread class and implementing Runnable?
Explain the four different states of a thread
The four different states of a thread are
new: When a thread is created with new operator .It is not yet running.
Runnable: Once you invoke the start method on the thread it becomes runnable. It is up to the OS to decide when to give time to the thread to run. A runnable thread may or may not be running.
Blocked : Thread enters this state under the following condition.
Someone calls sleep () on the thread.
Thread calls an operation that blocks on input/output.
Thread calls wait() method.
Thread tries to lock an object that is currently locked by another thread.
Dead : The Thread is dead for one of two reasons.
It dies a natural death because the run method exits normally.
It dies abruptly because an uncaught exception terminates the run method. - What happens when there are more than one highest priority threads having same priority?
In that case only one of the thread is picked up. It is up to the thread Scheduler to arbitrate between threads of same priority.
There is no guarantee that all the same priority threads will be fairly treated. - Why do threads block on I/O ?
Threads block on I/O so that other threads may execute while the I/O operation is performed. - What are the methods which can only be called from within a Synchronized method or block ?
Notify (): unblocks one randomly selected thread among the threads that called wait() on this object.
NoitifyAll() : unblocks the threads that called wait() on this object.
Wait (): causes the thread to wait until it is notified.
What is the difference between yield and sleep methods of Thread?
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.
Posted by
Real Time Questions
at
2:52 AM
0
comments
Labels: CORE JAVA faqs
COLLECTIONS
Q:What is the Collections API?
A:The Collections API is a set of classes and interfaces that support operations on collections of objects.
Q:
What is the List interface?
A:
The List interface provides support for ordered collections of objects.
Q:
What is the Vector class?
A:
The Vector class provides the capability to implement a growable array of objects.
Q:
What is an Iterator interface?
A:
The Iterator interface is used to step through the elements of a Collection .
Q:
Which java.util classes and interfaces support event handling?
A:
The EventObject class and the EventListener interface support event processing.
Q:
What is the GregorianCalendar class?
A:
The GregorianCalendar provides support for traditional Western calendars
Q:
What is the Locale class?
A:
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region .
Q:
What is the SimpleTimeZone class?
A:
The SimpleTimeZone class provides support for a Gregorian calendar .
Q:
What is the Map interface?
A:
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
Q:
What is the highest-level event class of the event-delegation model?
A:
The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.
Q:
What is the Collection interface?
A:
The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
Q:
What is the Set interface?
A:
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
Q:
What is the typical use of Hashtable?
A:
Whenever a program wants to store a key value pair, one can use Hashtable.
Q:
I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?
A:
The existing object will be overwritten and thus it will be lost.
Q:
What is the difference between the size and capacity of a Vector?
A:
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 instance of time.
Q:
Can a vector contain heterogenous objects?
A:
Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
Q:
Can a ArrayList contain heterogenous objects?
A:
Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.
Q:
What is an enumeration?
A:
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
Q:
Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList?
A:
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
Q:Can a vector contain heterogenous objects?
A:Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
Posted by
Real Time Questions
at
2:49 AM
0
comments
Labels: Core JAVA4
Core JAVA
Q:What method must be implemented by all threads?
A:
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.
Q:
What are synchronized methods and synchronized statements?
A:
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
Q:
What is Externalizable?
A:
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)
Q:
What modifiers are allowed for methods in an Interface?
A:
Only public and abstract modifiers are allowed for methods in interfaces.
Q:
What are some alternatives to inheritance?
A:
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).
Q:
What does it mean that a method or field is "static"?
A:
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.
Q:
What is the difference between preemptive scheduling and time slicing?
A:
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.
Q:
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 the exception or declare it in its throws clause.
Q:
Is Empty .java file a valid source file?
A:
Yes, an empty .java file is a perfectly valid source file.
Q:
Can a .java file contain more than one java classes?
A:
Yes, a .java file contain more than one java classes, provided at the most one of them is a public class.
Q:
Is String a primitive data type in Java?
A:
No String is not a primitive data type in Java, even though it is one of the most extensively used object. Strings in Java are instances of String class defined in java.lang package.
Q:
Is main a keyword in Java?
A:
No, main is not a keyword in Java.
Q:
Is next a keyword in Java?
A:
No, next is not a keyword.
Q:
Is delete a keyword in Java?
A:
No, delete is not a keyword in Java. Java does not make use of explicit destructors the way C++ does.
Q:
Is exit a keyword in Java?
A:
No. To exit a program explicitly you use exit method in System object.
Q:
What happens if you dont initialize an instance variable of any of the primitive types in Java?
A:
Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0, a boolean will be initialized to false.
Q:
What will be the initial value of an object reference which is defined as an instance variable?
A:
The object references are all initialized to null in Java. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references.
Q:
What are the different scopes for Java variables?
A:
The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.1. Instance : - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.2. Local : - These are the variables that are defined within a method. They remain accessbile only during the course of method excecution. When the method finishes execution, these variables fall out of scope.3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.
Q:
What is the default value of the local variables?
A:
The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain abt the local varaible not being initilized..
Q:
How many objects are created in the following piece of code?MyClass c1, c2, c3;c1 = new MyClass ();c3 = new MyClass ();
A:
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.
Q:
Can a public class MyClass be defined in a source file named YourClass.java?
A:
No the source file name, if it contains a public class, must be the same as the public class name itself with a .java extension.
Q:
Can main method be declared final?
A:
Yes, the main method can be declared final, in addition to being public static.
Q:What will be the output of the following statement?System.out.println ("1" + 3);
A:It will print 13.
Q:What will be the default values of all the elements of an array defined as an instance variable?
A:If the array is an array of primitive types, then all the elements of the array will be initialized
to the default value corresponding to that primitive type. e.g. All the elements of an array of int will be initialized to 0, while that of boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.
Posted by
Real Time Questions
at
2:43 AM
0
comments
Labels: Core JAVA3
Core JAVA
Q:Why do we need wrapper classes?
A:
It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.
Q:
What are checked exceptions?
A:
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.
Q:
What are runtime exceptions?
A:
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
Q:
What is the difference between error and an exception?
A:
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
Q:
How to create custom exceptions?
A:
Your class should extend class Exception, or some more specific type thereof.
Q:
If I want an object of my class to be thrown as an exception object, what should I do?
A:
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
Q:
If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
A:
One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
Q:
How does an exception permeate through the code?
A:
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.
Q:
What are the different ways to handle exceptions?
A:
There are two ways to handle exceptions, 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and 2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.
Q:
What is the basic difference between the 2 approaches to exception handling.1> try catch block and 2> specifying the candidate exceptions in the throws clause?When should you use which approach?
A:
In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
Q:
Is it necessary that each try block must be followed by a catch block?
A:
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
Q:
If I write return at the end of the try block, will the finally block still execute?
A:
Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.
Q:
If I write System.exit (0); at the end of the try block, will the finally block still execute?
A:
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 never executes.
Q:
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.
Q:
What is synchronization and why is it important?
A:
With respect to multithreading, synchronization is the capability to controlthe 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.
Q:
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.
Q:
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.
Q:
What is the difference between preemptive scheduling and time slicing?
A:
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.
Q:
When a thread is created and started, what is its initial state?
A:
A thread is in the ready state after it has been created and started.
Q:
What is the purpose of finalization?
A:
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
Q:
What is the Locale class?
A:
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
Q:
What is the difference between a while statement and a do statement?
A:
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
Q:
What is the difference between static and non-static variables?
A:
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
Q:
How are this() and super() used with constructors?
A:
This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
Q:
What are synchronized methods and synchronized statements?
A:
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
Q:
What is daemon thread and which method is used to create the daemon thread?
A:
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
Q:
Can applets communicate with each other?
A:
At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable. An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members. It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.
Q:
What are the steps in the JDBC connection?
A:
While making a JDBC connection we go through the following steps : Step 1 : Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");
Step 4 : Exceute the query :
stmt.exceuteUpdate();
Q:
How does a try statement determine which catch clause should be used to handle an exception?
A:
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.
Q: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.
Posted by
Real Time Questions
at
2:40 AM
0
comments
Labels: Core JAVA2
Core JAVA
Q:What is the difference between an Interface and an Abstract class?
A:
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods..
Q:
What is the purpose of garbage collection in Java, and when is it used?
A:
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
Q:
Describe synchronization in respect to multithreading.
A:
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Q:
Explain different way of using thread?
A:
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
Q:
What are pass by reference and passby value?
A:
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
Q:
What is HashMap and Map?
A:
Map is Interface and Hashmap is class that implements that.
Q:
Difference between HashMap and HashTable?
A:
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.
Q:
Difference between Vector and ArrayList?
A:
Vector is synchronized whereas arraylist is not.
Q:
Difference between Swing and Awt?
A:
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.
Q:
What is the difference between a constructor and a method?
A:
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Q:
What is an Iterator?
A:
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
Q:
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A:
public : Public class is visible in other packages, field is visible everywhere (class must be public too)private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.
Q:
What is an abstract class?
A:
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
Q:
What is static in java?
A:
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
Q:
What is final?
A:
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
Q:
What if the main method is declared as private?
A:
The program compiles properly but at runtime it will give "Main method not public." message.
Q:
What if the static modifier is removed from the signature of the main method?
A:
Program compiles. But at runtime throws an error "NoSuchMethodError".
Q:
What if I write static public void instead of public static void?
A:
Program compiles and runs properly.
Q:
What if I do not provide the String array as the argument to the method?
A:
Program compiles but throws a runtime error "NoSuchMethodError".
Q:
What is the first argument of the String array in main method?
A:
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
Q:
If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
A:
It is empty. But not null.
Q:
How can one prove that the array is not null but empty using one line of code?
A:
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
Q:
What environment variables do I need to set on my machine in order to be able to run Java programs?
A:
CLASSPATH and PATH are the two variables.
Q:
Can an application have multiple classes having main method?
A:
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
Q:
Can I have multiple main methods in the same class?
A:
No the program fails to compile. The compiler says that the main method is already defined in the class.
Q:
Do I need to import java.lang package any time? Why ?
A:
No. It is by default loaded internally by the JVM.
Q:
Can I import same package/class twice? Will the JVM load the package twice at runtime?
A:
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
Q:
What are Checked and UnChecked Exception?
A:
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch theexception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
Q:
What is Overriding?
A:
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
Q:
What are different types of inner classes?
A:
Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement amore publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.
Q:
Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
A:
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbolsymbol : class ABCDlocation: package ioimport java.io.ABCD;
Q:
Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
A:
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
Q:
What is the difference between declaring a variable and defining a variable?
A:
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
Q:
What is the default value of an object reference declared as an instance variable?
A:
null unless we define it explicitly.
Q:
Can a top level class be private or protected?
A:
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
Q:
What type of parameter passing does Java support?
A:
In Java the arguments are always passed by value .
Q:
Primitive data types are passed by reference or pass by value?
A:
Primitive data types are passed by value.
Q:
Objects are passed by value or by reference?
A:
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
Q:
What is serialization?
A:
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
Q:
How do I serialize an object to a file?
A:
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
Q:
Which methods of Serializable interface should I implement?
A:
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
Q:
How can I customize the seralization process? i.e. how can one have a control over the serialization process?
A:
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
Q:
What is the common usage of serialization?
A:
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
Q:
What is Externalizable interface?
A:
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
Q:
When you serialize an object, what happens to the object references included in the object?
A:
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
Q:
What one should take care of while serializing the object?
A:
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
Q:
What happens to the static fields of a class during serialization?
A:
There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are1. Serialization ignores static fields, because they are not part of ay particular state state.2. Base class fields are only hendled if the base class itself is serializable.3. Transient fields.
Q:
Does Java provide any construct to find out the size of an object?
A:
No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.
Q:
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 amout of processing.
Q:What are wrapper classes?
A:
Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.
Posted by
Real Time Questions
at
2:37 AM
0
comments
Labels: Core JAVA1