Monday, 16 December 2013

Java Basics




                                          JAVA BASICS



Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
As of December 2008, the latest release of the Java Standard Edition is 6 (J2SE). With the advancement of Java and its widespread popularity, multiple configurations were built to suite various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.
Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.

History of Java:
James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name Green and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.
Java is:
·         Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.

·         Platform independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

·         Simple:Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be easy to master.
·         Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

·         Architectural-neutral :Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system.

·         Portable:Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset.

·         Robust:Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.

·         Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.

·         Interpreted:Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.

·         High Performance: With the use of Just-In-Time compilers, Java enables high performance.

·         Distributed:Java is designed for the distributed environment of the internet.

·         Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time. 
Java Basics
Java is an Object-Oriented Language. When we consider a Java program it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.
·         Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.

·         Class - A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support.

·         Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

·         Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

First Java Program:
Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram {

   /* This is my first java program. 
    * This will print 'Hello World' as the output
    */

    public static void main(String []args) {
       System.out.println("Hello World"); // prints Hello World
    }
}
 Java Servlet - A servlet is a Java class processing incoming user HTTP requests and returning a result.
JSP (JavaServer Page) - A text based HTML document (i.e., a kind of template) processed to produce static content. It can contain snippets of script code which is executed to render the final static documents.

JMS (Java Message Service) - An API allowing exchanges of messages reliably and asynchronously between application and services over the internet. ActiveMQ implements JMS.

JDBC (Java Database Connectivity) - This API lets an application perform SQL transaction directly with databases. 

JNDI (Java Naming and Directory Interface) - A mean to store and retrieve resources or access to resources using their name. See this post for more details.




Java Fundamentals



1)Give a few reasons for using Java?

 Built-in support for multi-threading, socket communication, and memory management (automatic garbagecollection).
Object Oriented (ooo), Better portability than other languages across operating systems.
 Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI, EJB etc)and network protocols (HTTP, JRMP etc) with the help of extensive standardized APIs (Application
Programming Interfaces).

 2)What is the main difference between the Java platform and the other software platforms?
 Java platform is a software-only platform, which runs on top of other hardware-based platforms like UNIX, NT etc.
The Java platform has 2 components:
a)Java Virtual Machine (JVM) – ‘JVM’ is a software that can be ported onto various hardware platforms. Byte codes are the machine language of the JVM.
b)Java Application Programming Interface (Java API) – set of classes written using the Java language and runon the JVM.


3) What is the difference between C++ and Java?

A Both C++ and Java use similar syntax and are Object Oriented, but:
Java does not support pointers. Pointers are inherently tricky to use and troublesome.
Java does not support multiple inheritances because it causes more problems than it solves. Instead Java
supports multiple interface inheritance, which allows an object to inherit many method signatures from
different interfaces with the condition that the inheriting object must implement those inherited methods. The multiple interface inheritance also allows an object to behave polymorphically on those methods.
Java does not support destructors but adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means
you do not know when the objects are going to be finalized. Avoid using finalize() method to release nonmemory resources like file handles, sockets, database connections etc because Java has only a finite
number of these resources and you do not know when the garbage collection is going to kick in to release All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions.
 C++ requires explicit memory management, while Java includes automatic garbage collection.

4)How does Java allocate stack and heap memory? Explain re-entrant, recursive and idempotent
methods/functions?
Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack (i.e. Last In First Out queue), if they are local variables and in the heap if they are member variables (i.e. fields of a class). In Java methods and local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed. In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space.
The stack is thread-safe because each threadwill have its own stack with say 1MB RAM allocated for each thread but the heap is not thread-safe unless guarded with synchronization through your code. The stack space can be increased with the –Xss option.
All Java methods are automatically re-entrant. It means that several threads can be executing the same method at once, each with its own copy of the local variables. A Java method may call itself without needing any special declarations. This is known as a recursive method call. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive methods are useful in removing iterations from manysorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server (i.e. scalable).

5.What do you know about the Java garbage collector? When does the garbage collection occur? Explain different types of references in Java?

Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (i.e. background) thread. You can nicely ask the garbage collector to collect garbage by calling System.gc() but you can’t force it.
An object’s life has no meaning unless something has reference to it. If you can’t reach it then you can’t ask it to do anything. Then the object becomes unreachable and the garbage collector will figure it out. Java automatically collects all the unreachable objects periodically and releases the memory consumed by those unreachable objects to be used by the future reachable objects.
We can use the following options with the Java command to enable tracing for garbage collection events.
java -verbose:gc //reports on each garbage collection event.

6)What is the difference between processes and threads?

A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety. 

7)Briefly explain high-level thread states?
Runnable — waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should not be used very frequently.
Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method:Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
Blocked on synchronization: Will move to Runnable when a lock is acquired.

Dead: The thread is finished working.

8)What is a daemon thread?
 Daemon threads are sometimes called "service" or “background” threads. These are threads that normally run at a low priority and provide a basic service to a program when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. The JVM exits whenever all no daemon threads have completed, which means that all daemon threads are automatically stopped. To make a thread as a daemon thread in Java  myThread.setDaemon (true);

9)How can threads communicate with each other? How would you implement a producer (one thread) and a consumer (another thread) passing data (via stack)?
The wait(), notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate with each other. This communication solves the ‘consumer-producer problem’. This problem occurs when the producer thread is completing work that the other thread (consumer thread) will use.

10)What is a socket? How do you facilitate inter process communication in Java?
A socket is a communication channel, which facilitates inter-process communication (For example
communicating between two JVMs, which may or may not be running on two different physical machines). A socket is an endpoint for communication. There are two kinds of sockets, depending on whether one wishes to use a connectionless or a connection-oriented protocol. The connectionless communication protocol of the Internet is called UDP. The connection-oriented communication protocol of the Internet is called TCP. UDP sockets are also called datagram sockets. Each socket is uniquely identified on the entire Internet with two numbers. The first number is a 32-bit (IPV4 or 128-bit is IPV6) integer called the Internet Address (or IP address).
The second number is a 16-bit integer called the port of the socket. The IP address is the location of the machine, which you are trying to connect to and the port number is the port on which the server you are trying to connect is running. The port numbers 0 to 1023 are reserved for standard services such as e-mail, FTP, HTTP etc.

The lifetime of the socket is made of 3 phases: Open Socket,   Read and Write to Socket ,  Close Socket To make a socket connection you need to know two things: An IP address and port on which to listen/connect. In Java you can use the Socket (client side) and ServerSocket (Server side) classes.

11)How will you call a Web server from a stand-alone Java application/Swing client/Applet?
Using the java.net.URLConnection and its subclasses like HttpURLConnection and JarURLConnection.
URLConnection HttpClient (i.e. a browser)
Supports HEAD, GET, POST, PUT, DELETE, TRACE and
OPTIONS
Supports HEAD, GET, POST, PUT, DELETE, TRACE and
OPTIONS.
Does not support cookies. Does support cookies.
Can handle protocols other than http like ftp, gopher, mailto and file. Handles only http.

12)How will you initialize an applet?
By writing your initialization code in the applet’s init() method or applet’s constructor.

What is the order of method invocation in an applet?
 The Applet’s life cycle methods are as follows:
• public void init() : Initialization method called only once by the browser.
• public void start() : Method called after init() and contains code to start processing. If the user leaves the page and returns without killing the current browser session, the start () method is called without being preceded by init ().
• public void stop() : Stops all processing started by start (). Done if user moves off page.
• public void destroy() : Called if current browser session is being terminated. Frees all resources used by the applet.

13)How would you communicate between applets and servlets?
  We can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection and “tunnel” to a Web server. The server then passes this information to the servlet. Basically, the applet pretends to be a Web browser, and the servlet doesn’t know the difference. As far as the servlet is concerned, the applet is just another HTTP client. Applets can communicate with servlets using GET or POST methods.
The parameters can be passed between the applet and the servlet as name value pairs.
http://www.foo.com/servlet/TestServlet?LastName=Jones&FirstName=Joe).
Objects can also be passed between applet and servlet using object serialization. Objects are serialized to and from the inputstream and outputstream of the connection respectively.

14) How will you communicate between two Applets?
All the applets on a given page share the same AppletContext. We obtain this applet context as follows:
AppletContext ac = getAppletContext();
AppletContext provides applets with methods such as getApplet(name), getApplets(), getAudioClip(url),
getImage(url), showDocument(url) and showStatus(status).

Java – Performance and Memory issues


How would you improve performance of a Java application?
1  Pool valuable system resources
2  CPU context switching
3  Minimize network overheads
4  Optimize your I/O operations:
5  Establish whether you have a potential memory problem and manage your objects efficiently:
Pool valuable system resources like threads, database connections, socket connections etc. Emphasize on
reuse of threads from a pool of threads. Creating new threads and discarding them after use can adversely
affect performance. Also consider using multi-threading in your single-threaded applications where possible to
enhance performance. Optimize the pool sizes based on system and application specifications and
requirements. Having too many threads in a pool also can result in performance and scalability problems
due to consumption of memory stacks (i.e. each thread has its own stack.)
and CPU context switching (i.e. switching between threads as opposed to doing real computation.).

 Minimize network overheads by retrieving several related items simultaneously in one remote invocation if
possible. Remote method invocations involve a network round-trip, marshaling and unmarshaling of
parameters, which can cause huge performance problems if the remote interface is poorly designed.

Most applications need to retrieve data from and save/update data into one or more databases. Database calls
are remote calls over the network. In general data should be lazily loaded (i.e. load only when required as
opposed to pre-loading from the database with a view that it can be used later) from a database to conserve
memory but there are use cases (i.e. need to make several database calls) where eagerly loading data and
caching can improve performance by minimizing network trips to the database. Data can be eagerly loaded
with a help of SQL scripts with complex joins or stored procedures and cached using third party frameworks or
building your own framework. At this point your interviewer could intercept you and ask you some pertinent
questions relating to caching like:

Optimize your I/O operations: use buffering (Refer Q25 in Java section) when writing to and reading from
files and/or streams. Avoid writers/readers if you are dealing with only ASCII characters. You can use streams
instead, which are faster. Avoid premature flushing of buffers. Also make use of the performance and
scalability enhancing features such as non-blocking and asynchronous I/O, mapping of file to memory etc
offered by the NIO (New I/O).
Establish whether you have a potential memory problem and manage your objects efficiently: remove
references to the short-lived objects from long-lived objects like Java collections etc, to minimize any potential memory leaks. Also reuse objects where possible. It is cheaper to recycle

Where applicable apply the following performance tips in your code:
1. Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc where possible. This is because the
methods in ArrayList, HashMap etc are not synchronized (Refer Q15 in Java Section). Even better is to
use just arrays where possible.
2.Set the initial capacity of a collection (e.g. ArrayList, HashMap etc) and StringBuffer/StringBuilder
appropriately. This is because these classes must grow periodically to accommodate new elements. So,
if you have a very large ArrayList or a StringBuffer, and you know the size in advance then you can speed
things up by setting the initial size appropriately. (Refer Q17, Q21 in Java Section).
3.Minimize the use of casting or runtime type checking like instanceof in frequently executed methods or
in loops. The “casting” and “instanceof” checks for a class marked as final will be faster. Using
instanceof” construct is not only ugly but also unmaintainable. Look at using visitor pattern (Refer Q11
in How would you go about…? section) to avoid “instanceof” constructs in frequently accessed methods.
4. Do not compute constants inside a large loop. Compute them outside the loop. For applets compute it in
the init() method. Avoid nested loops (i.e. a “for” loop within another “for” loop etc) where applicable and
make use of a Collection class as discussed in “How can you code better without nested loops ?” --
Q17 in Java section.
5. Exception creation can be expensive because it has to create the full stack trace. The stack trace is
obviously useful if you are planning to log or display the exception to the user. But if you are using your
exception to just control the flow, which is not recommended, then throw an exception, which is precreated.
An efficient way to do this is to declare a public static final Exception in your exception class
itself.
6.Avoid using System.out.println and use logging frameworks like Log4J etc, which uses I/O buffers (Refer
Q25 in Java section).
7.Minimize calls to Date, Calendar, etc related classes
8. Minimize JNI calls in your code.

73: How would you detect and minimize memory leaks in Java? FAQ
A 73: In Java, memory leaks are caused by poor program design where object references are long lived and the
garbage collector is unable to reclaim those objects.
Detecting memory leaks:
 Use tools like JProbe, OptimizeIt etc to detect memory leaks.
 Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat, netstat etc on
UNIX systems.
Write your own utility class with the help of totalMemory() and freeMemory() methods in the Java Runtime
class. Place these calls in your code strategically for pre and post memory recording where you suspect to be
causing memory leaks. An even better approach than a utility class is using dynamic proxies
or Aspect Oriented Programming (AOP) for pre and post memory
recording where you have the control of activating memory measurement only when needed.

Minimizing memory leaks:
In Java, typically memory leak occurs when an object of a longer lifecycle has a reference to objects of a short life cycle.
This prevents the objects with short life cycle being garbage collected. The developer must remember to remove the references
to the short-lived objects from the long-lived objects. Objects with the same life cycle do not cause any issues because the
garbage collector is smart enough to deal with the circular references (Refer Q38 in Java section).
1 Design applications with an object’s life cycle in mind, instead of relying on the clever features of the JVM.
Letting go of the object’s reference in one’s own class as soon as possible can mitigate memory problems.
Example: myRef = null;
2 Unreachable collection objects can magnify a memory leak problem. In Java it is easy to let go of an entire
collection by setting the root of the collection to null. The garbage collector will reclaim all the objects (unless
some objects are needed elsewhere).
3 Use weak references (Refer Q37 in Java section) if you are the only one using it. The WeakHashMap is a
combination of HashMap and WeakReference. This class can be used for programming problems where you
need to have a HashMap of information, but you would like that information to be garbage collected if you are
the only one referencing it.
4 Free native system resources like AWT frame, files, JNI etc when finished with them. Example: Frame,
Dialog, and Graphics classes require that the method dispose() be called on them when they are no longer
used, to free up the system resources they reserve.

Why does the JVM crash with a core dump or a Dr.Watson error?
Any problem in pure Java code throws a Java exception or error. Java exceptions or errors will not cause a core
dump (on UNIX systems) or a Dr.Watson error (on WIN32systems). Any serious Java problem will result in an
OutOfMemoryError thrown by the JVM with the stack trace and consequently JVM will exit. These Java stack
traces are very useful for identifying the cause for an abnormal exit of the JVM. So is there a way to know that
OutOfMemoryError is about to occur? The Java J2SE 5.0 has a package called java.lang.management which
has useful JMX beans that we can use to manage the JVM. One of these beans is the MemoryMXBean.
An OutOfMemoryError can be thrown due to one of the following 4 reasons:
JVM may have a memory leak due to a bug in its internal heap management implementation. But this is highly
unlikely because JVMs are well tested for this.
1The application may not have enough heap memory allocated for its running. You can allocate more JVM
heap size (with –Xmx parameter to the JVM) or decrease the amount of memory your application takes to
overcome this. To increase the heap space:
java -Xms1024M -Xmx1024M
Care should be taken not to make the –Xmx value too large because it can slow down your application. The
secret is to make the maximum heap size value the right size.
2 Another not so prevalent cause is the running out of a memory area called the “perm” which sits next to the
heap. All the binary code of currently running classes is archived in the “perm” area. The ‘perm’ area is
important if your application or any of the third party jar files you use dynamically generate classes. For
example: “perm” space is consumed when XSLT templates are dynamically compiled into classes, J2EE
application servers, JasperReports, JAXB etc use Java reflection to dynamically generate classes and/or
large amount of classes in your application. To increase perm space:
java -XX:PermSize=256M -XX:MaxPermSize=256M
3The fourth and the most common reason is that you may have a memory leak in your application as
discussed in Q73 in Java section.
[Good read/reference: “Know your worst friend, the Garbage Collector” http://java.syscon.
com/read/84695.htm by Romain Guy]

Q. So why does the JVM crash with a core dump or Dr.Watson error?
Both the core dump on UNIX operating system and Dr.Watson error on WIN32 systems mean the same thing. The
JVM is a process like any other and when a process crashes a core dump is created. A core dump is a memory
map of a running process. This can happen due to one of the following reasons:
1 Using JNI (Java Native Interface) code, which has a fatal bug in its native code. Example: using Oracle OCI
drivers, which are written partially in native code or JDBC-ODBC bridge drivers, which are written in non Java
code. Using 100% pure Java drivers (communicates directly with the database instead of through client
software utilizing the JNI) instead of native drivers can solve this problem. We can use Oracle thin driver,
which is a 100% pure Java driver.
2 The operating system on which your JVM is running might require a patch or a service pack.
3The JVM implementation you are using may have a bug in translating system resources like threads, file
handles, sockets etc from the platform neutral Java byte code into platform specific operations. If this JVM’s
translated native code performs an illegal operation then the operating system will instantly kill the
process and mostly will generate a core dump file, which is a hexadecimal file indicating program’s state
in memory at the time of error. The core dump files are generated by the operating system in response to
certain signals. Operating system signals are responsible for notifying certain events to its threads and
processes. The JVM can also intercept certain signals like SIGQUIT which is kill -3 < process id > from the
operating system and it responds to this signal by printing out a Java stack trace and then continue to run.
The JVM continues to run because the JVM has a special built-in debug routine, which will trap the signal -3.
On the other hand signals like SIGSTOP (kill -23 <process id>) and SIGKILL (kill -9 <process id>) will cause
the JVM process to stop or die. The following JVM argument will indicate JVM not to pause on SIGQUIT
signal from the operating system.
java –Xsqnopause






________________________________________________________________________________________
Firewall
Internet firewalls could be either software or hardware, which protect your computer from outside internet attacks that might pose threats to your internet security as well as files on your computer. The firewall functionality allows you to set up rules to either permit or deny passage of internet traffic.
Operating System
A generic term for the software that manages the basic tasks of your computer’s resources and which programmers use to access those resources. The most common desktop operating systems include Linux, Mac OS X, Microsoft Windows and Solaris. 
Physical Memory
Most often in the java.com site, this term refers to a form of semiconductor storage in computers known as random access memory (RAM). 
Process
A general term to describe a program that is running to execute a specific task – often in concurrence with other programs. 
Proxy Server
An intermediary computer between the user's computer and the Internet. It can be used to log Internet usage and also to block access to a web site. The firewall at the proxy server blocks some web sites or web pages for various reasons. As a result, users may be unable to download Java or to run some Java applets without configuring certain proxy settings in the computer’s web browser. 


Proxy Setting
Correctly configured proxy settings allow users to connect to the Internet when a proxy server is involved. As a rule, users would need to contact their network administrator to get the necessary information to configure the proxy settings. 
Workaround
A workaround is typically a temporary fix that bypasses an identified system problem pending a more permanent solution.
Patch
Refers to incremental changes to a software installation. May include fixes to address general performance and security issues. 
Java Plug-in
Java plug-in technology is part of the Java Runtime Environment and establishes a connection between popular browsers and the Java platform. This connection enables applets on Web sites to be run within a browser on the desktop. 
__________________________________________________________________________________
This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Java.

Q: What do you know about Java?
A: Java is an Object-Oriented Language .Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Q: What do you mean by Object?
A: Object is a runtime entity and it’s state is stored in fields and behavior is shown via methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.

Describe what happens when an object is created in Java.

Several things happen in a particular order to ensure the object is constructed properly: 

* Memory allocation: To hold all instance variables and implementation-specific data of the object and its super classes. 
* Initialization: the objects are initialized to their default values. 
* Constructor: Constructors call the constructors for its super classes. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. 
* Execution: Before the body of the constructor is executed all instance variable initializes and initialization blocks must get executed. Then the body of the constructor is executed.

Q: Define class?
A: A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.

Q: What kind of variables a class can consist of?
A: A class consist of Local variable, instance variables and class variables.

Q: What is a Local Variable
A: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.

Q: What is a Instance Variable
A: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.

Q: What is a Class Variable
A: These are variables declared with in a class, outside any method, with the static keyword.

Q: What is JAR file?
A: JAR files is Java Archive fles and it aggregates many files into one. It holds Java classes in a library. JAR files are built on ZIP file format and have .jar file extension.

Q: What is a WAR file?
A: This is Web Archive File and used to store XML, java classes, and JavaServer pages. which is used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages etc.

Q: What is the difference between error and an exception?
A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.

Can you explain Native methods in Java?

The Java native method is used to merge the power of C or C++ programming into Java.

  • To enhance to high performance language, when efficient native Java compilers are not fully implemented, use of native method boosts the performance to at least the speed of C compiled code.
Java applications can call code written in C, C++, or assembler. This is sometimes done for performance and sometimes to access the underlying host operating system or GUI API using the JNI.

Q: What is an Exception?
A: An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread's method invocation stack.

Q: What do you mean by Checked Exceptions?
A: It is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Q: Explain Runtime Exceptions?
A: It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

Q: What is NullPointerException?
A: A NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object etc.

Q: Which are the two subclasses under Exception class?
A: The Exception class has two main subclasses : IOException class and RuntimeException Class.

Q: When throws keyword is used?
A: If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method's signature.

Q: When throw keyword is used?
A: An exception can be thrown, either a newly instantiated one or an exception that you just caught, by using throw keyword.

Q: How finally used under Exception Handling?
A: The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.

Q: What is Java Virtual Machine and how it is considered in context of Java’s platform independent feature?
A: When Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

Q: What are the ways in which a thread can enter the waiting state?
A: A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

2. What is the purpose of garbage collection in Java, and when is it used?
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.

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.

What is the disadvantage of garbage collector?

Garbage Collector runs in its own thread which affects the performance of the system. It increases the workload of JVM because it constantly monitor the object which is not referenced.. The two main disadvantages of garbage collector are:
  • TIME: to collect all those no referenced object JVM spends a considerable amount of time by scanning the entire heap.
  • Mark and sweep: some time it is difficult to implement mark and sweep in the application.



Q: Explain garbage collection in Java?
A: It uses garbage collection to free the memory. By cleaning those objects that is no longer reference by any of the program.

3. Why do threads block on I/O?
Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

Q: Describe life cycle of thread?
A: A thread is a execution in a program. The life cycle of a thread include:
·         Newborn state
·         Runnable state
·         Running state
·         Blocked state
·         Dead state

Q: What is difference between Path and Classpath?
A: Path and Classpath are operating system level environment variales. Path is defines where the system can find the executables(.exe) files and classpath is used to specify the location of .class files.

Q: What is 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.

Q: What is a Socket?
A: Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server

How does a 3 tier application differ from a 2 tier one?

Tiers are the physical units of separation or deployment, while layers are the logical units of separation. Imagine that you’re designing an e-commerce website. A 3 tier architecture would consist of web pages, a web server and a database, with the corresponding 3 layers being the “Presentation”, “Business Logic” and “Database” layers. If you take the database tier and layer out then your have a 2 tier architecture.
What is the difference between JAR and WAR files?

JAR files (Java ARchive) allows aggregating many files into one, it is usually used to hold Java classes in a library. WAR files (Web Application aRchive) stores XML, java classes, and JavaServer pages for Web Application purposes.

What is JMS in Java?

Java Message Service (JMS) is used for creating the communication interface between two clients by using the message passing services. This helps the application to interact with other components irrespective of components location whether they rely on same system or connect to the main system through LAN or internet.




No comments:

Post a Comment