Monday, April 9, 2012

Different ways to create objects in Java

This is a trivia. Yeah, it’s a bit tricky question and people often get confused. I had searched a lot to get all my doubts cleared.
There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:
1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
 3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject(); 
MyObject object = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); 
MyObject object = (MyObject) inStream.readObject();
Now you know how to create an object. But its advised to create objects only when it is necessary to do so.

Saturday, April 7, 2012

Finding Second largest number in an Array

Below given is the Java code example to find second largest element in an array.

1. Using two temporary variable.

Class SecondLargest{
public static void main(String[] args){
int array[] = {5, 3, 2, 1, 4};
max1 = max2 = array[0];
for(int i = 1; i if ( array[i] > max1 ) {
max2 = max1;
max1 = array[i];
}else if ( array[i] > max2 && array[i] < max1 ){
max2 = array[i];
}
System.out.println("Second largest No. : " + max2);
}

2. Sorting
We can sort the array in descending order. The second largest element will be second element in the array.

3. Bubbling through the array twice.
We can use the bubble sort algrithm to sort the array in descending order, but instead of running the complete bubble sort algorithm we bubble just twice through the array, hence bringing the second largest element to the second position in the array.

Compiled Languages vs Interpreted languages

A compiled language is one where you have to compile the source code before it can be executed. The compilation process transforms the source code into machine executable code, which is stored in a separate file. The machine executable code is invoked to actually run the application. Thus in compiled language the source code needs to be compiled before it can be executed. Eg. C, C++

An interpreted language is one where you can execute the source code directly without compilation, by the help of an interpreter. The interpreter reads the source code and executes. Eg. Php, Perl, Python

Compiled programs generally run faster than interpreted ones because interpreted ones must be reduced to machine instructions at runtime. However, it is easier to develop applications in an interpreted environment as you don't have to recompile the source code each time to test it.

Where does Java come?
Java is both compiled and interpreted language. The source code is first compile and converted to byte code - which is stored in .class files. The byte code is then interpreted by the JVM during execution time.

What are JIT compilers?
JIT stands for Just-In-Time compiler. They are used in interpreters (specially in Java VM) to improve the runtime performance. They convert the byte code into native instructions before executing them, so that they can take full advantage of underlying architecture.

why wait and notify methods are in Object class not in thread?

These two links provide the most comprehensive explaination for this question:

http://geekexplains.blogspot.com/2009/10/why-waitnotify-and-notifyall-in-object.html

http://javaqna.wordpress.com/2008/07/07/why-wait-and-notify-methods-are-in-object-class-not-in-thread/

X-----X

Below are some snippets from the above links:-

1. Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java not only with threads.

2. wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other.

3. Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java language considered it wise to put them in Object class instead of putting them in Thread class.

4. The usage of the 'object' is the particular object's prerogative and not that of the required threads. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way ...

5. the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it.

Marker Interface in Java: what, why, uses, etc.

Why is Java not a pure Object based language

The most satisfying answer to this question is :

Java supports primitive datatypes such as int, float, double etc which are not objects. Hence Java is not pure Object based language.

Also, Java has static fields and method which are not part of any object.

Can we clone a Singleton object?

This might seem a tricky question, can we use object.clone() to create a new object of the class and break our Singleton pattern.

Well the answer to this is NO.

The clone method has protected access on the Object class - meaning it is available in the Object class and to the extending classes (which is our Singleton class). Thus any attempt to invoke clone() method on any object will give compile time exception.

This is illegal:-
SingletonClass instance = SingletonClass.getInstance();
SingletonClass newInstance = (SingletonClass)instance.clone();

Hence to create a clone of an object, the object must override the clone() method of the Object class. Thus our SingletonClass can only be cloned if it explicitly implements the clone() method.

How many different types of JDBC drivers are present?

Type 1: JDBC-ODBC Bridge plus ODBC Driver: The first type of JDBC driver is the JDBC-ODBC Bridge. It is a driver that provides JDBC access to databases through ODBC drivers. The ODBC driver must be configured on the client for the bridge to work. This driver type is commonly used for prototyping or when there is no JDBC driver available for a particular DBMS.

Type 2: Native-API partly-Java Driver: The Native to API driver converts JDBC commands to DBMS-specific native calls. This is much like the restriction of Type 1 drivers. The client must have some binary code loaded on its machine. These drivers do have an advantage over Type 1 drivers because they interface directly with the database.

Type 3: JDBC-Net Pure Java Driver: The JDBC-Net drivers are a three-tier solution. This type of driver translates JDBC calls into a databaseindependent network protocol that is sent to a middleware server. This server then translates this DBMSindependent protocol into a DBMS-specific protocol, which is sent to a particular database. The results are then routed back through the middleware server and sent back to the client. This type of solution makes it possible to implement a pure Java client. It also makes it possible to swap databases without affecting the client.

Type 4: Native-Protocol Pur Java Driver: These are pure Java drivers that communicate directly with the vendor's database. They do this by converting JDBC commands directly into the database engine's native protocol. This driver has no additional translation or middleware layer, which improves performance tremendously.

What are wrapper classes?

Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances e.g. a boolean data type can be represented as a Boolean class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper class instance cannot be changed further.

Wrapper Classes are used broadly with Collection classes in the java.util package and with the classes in the java.lang.reflect reflection package.

HashMap Vs HashTable

Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.

The key difference between the two is that access to the Hashtable is synchronized (by default) while access to the HashMap isn't.

Another difference is that iterator in the HashMap is fail-safe while the iterator for the Hashtable isn't. If you change the map while iterating, you'll know.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn't.

whats the difference between concat and append?

Concat is used to add a string at the end of another string.But append() is used with String Buffer to append character sequence or string.

When we concatinate a string with another string a new string object is created. But in case of StringBuffer append() that is not the case.

Difference between instanceof and isInstance() ?

First difference:


instanceof is a reserved word of Java, but isInstance() is a method of java.lang.Class.


Other differences:

you could use instanceof on types (which are known on compile time), and isInstance() could only be called on an instance fo java.lang.Class.

if (obj instanceof MyType) {
...
}

if (MyType.class.isInstance(obj)) {
...
}

so you can have dynamism using isInstane() like this:

Class x = Integer.class;

if (x.isInstance(obj)) {
...
}

x = String.class;

if (x.isInstance(obj)) {
...
}

as you see you could check the type of an object with an unknown class during compile time!

Serializable Vs Externalizable in Java

JVM vs JRE

Technically, the term "JVM" specifies the Java Virtual Machine. I.e., the "JVM" is the definition of the abstract, stack-based computational engine used to execute Java bytecodes. The term "JRE" stands for the Java Runtime Environment (if you follow Sun's nomeclature) or, interchangeably,Java Runtime Engine. I.e., a JRE is a specific implementation of the the JVM, including the core libaries. 

Alas, in practice, many people use "JVM" for both cases. So, be careful to understand the context that people are talking about when using the term "JVM" to distinguish between the abstract definition and a specific implementation. 


The Java Virtual Machine forms part of a large system, the Java Runtime Environment (JRE). Each operating system and CPU architecture requires a different JRE. The JRE comprises a set of base classes, which are an implementation of the base Java API, as well as a JVM. The portability of Java comes from implementations on a variety of CPUs and architectures. Without an available JRE for a given environment, it is impossible to run Java software.

Refer this link for more details:-
http://www.javacoffeebreak.com/articles/inside_java/insidejava-jan99.html 

http://www.javabeat.net/qna/67-wat-is-the-difference-between-jrejvm-and-jdk/

Can we override a static method ?

We can not override a static method.

Static method are associated with class and not the object, hence inheritance does not apply to static methods. Even though we can write a static method in the child class with same signature as the parent class but it will not be counted as overriding as a reference of the Parent class will always invoke the static method of the Parent class.

Example:

ClassA a = new ClassB();
a.someStaticMethod();

This type of method invocation will always invoke the definition in the parent class, and not the object instance of ClassB. Hence the two methods will exist separately.

Iterator in HashTable Vs Iterator inHashMap

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.




The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.



Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

What happens when thread is not able to aquire lock?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

Thread yield() vs sleep()

yield() tells the JVM Thread Scheduler that it's OK to give other threads time slices. Usually the JVM uses this call to activate another thread of the same thread priority. In a good preemptive multithreading environment, yield() is a no-op. However, it is important in a cooperative multithreading environment, since without yield(), one thread can eat up all of the CPU.
sleep(x) tells the JVM Thread Scheduler to actively put this thread to sleep and not run it again until at least x milliseconds have elapsed.

Neither sleep() nor yield() change anything about the status of synchronization locks. If your thread has a lock, and you call sleep(1000), then at least a second will elapse before your thread wakes up. When it wakes up it may decide to release the lock -- or it may hold on to it longer.

What is the difference between "green" threads and "native" threads?

Both green and native threads are mechanisms to support multithreaded execution of Java programs. Some JDK distributions (such as Blackdown's) include the option to run with either type of threading.



Native threads use the operating system's native ability to manage multi-threaded processes - in particular, they use the pthread library. When you run with native threads, the kernel schedules and manages the various threads that make up the process.



Green threads emulate multithreaded environments without relying on any native OS capabilities. They run code in user space that manages and schedules threads; Sun wrote green threads to enable Java to work in environments that do not have native thread support.


There are some important differences between using the two in a Linux environment:


Native threads can switch between threads pre-emptively, switching control from a running thread to a non-running thread at any time. Green threads only switch when control is explicitly given up by a thread (Thread.yield(), Object.wait(), etc.) or a thread performs a blocking operation (read(), etc.).



On multi-CPU machines, native threads can run more than one thread simultaneously by assigning different threads to different CPUs. Green threads run on only one CPU.


Native threads create the appearance that many Java processes are running: each thread takes up its own entry in the process table. One clue that these are all threads of the same process is that the memory size is identical for all the threads - they are all using the same memory.



Unfortunately, this behavior limits the scalability of Java on Linux. The process table is not infinitely large, and processes can only create a limited number of threads before running out of system resources or hitting configured limits.

What is the priority of main thread in Java program?

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.


When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:


* The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.

* All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method. 

Can you get a lock on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.


You get a lock for the class by declaring the method to be synchronized, but the method also has to be a static method. a static method that is synchronized ensures a class level lock. whereas synchronizing a non-static method gives a lock on the object of that class.

Why Java doesn't allow pointers?

The Java Language the referencing and dereferencing of objects is handled for you automatically. Java does not allow you to manipulate pointers or memory addresses of any kind. It does not allow you to cast object or array references into integers and It does not allow you to do pointer arithmetic. It does not allow you to compute the size in bytes of any primitive type or object. There are two reasons for these restrictions:

Pointers are a notorious source of bugs. Eliminating them simplifies the language and eliminates many potential bugs. Pointers and pointer arithmetic could be used to sidestep Java's run-time checks and security mechanisms. Removing pointers allows Java to provide the security guarantees that it does.

To a C programmer, the lack of pointers and pointer arithmetic may seem an odious restriction in Java. But once you get used to the Java object-oriented programming model, it no longer seems like a serious restriction at all. The lack of pointers does mean that you probably can't do things like write UNIX device drivers in Java (at least not without using native methods written in C). But big deal--most of us never have to do this kind of low-level programming anyway. 

How many JVM could be run on an operating system? If only one, then what is the logical reason?

We can run as many JVM instances as we want on an OS. When ever we start a new java process by invoking java.exe (i.e. java [class-name] ) a new instance of JVM is created. Each java process executes in its separate JVM environment - we can specify different JVM parameter for each process.

If it was not possible to execute more than one JVM instance or in other words if all java processes were made share the same JVM instance, then we would not have been able to specify separate JVM options for every processes.

Also, this provides a security feature for each java process, as it executes in its separate environment controlled by the JVM options provided during its start.

A good example of it is Java RMI. RMI is used for communication between two JVMs. Even on a single machine we need to use RMI to communicate between different java processes, that explains that they are not sharing the same JVM instance.

Now, many people are of the opinion that we can have only one JVM as we can install only one JVM type on an OS. This is same as saying that we can open only one MS-Word document coz we can install only one office suit. (Well, not exactly, we can have multiple office suits installed - in different directories).

Also to say, whenever we do a java install, we do not install a JVM, we either install a JRE or JDK. And we can install multiple JRE/JDK on the same machine and also use them simultaniously run our programs - by providing specific paths during program start.

So, this simply explains that we can have more than one JVM instance running on an OS.