Tuesday, July 15, 2014

Constructor multiple choice questions in Java

Constructor in Java with examples
In this post, I have created a few questions on understanding of constructors in Java. If you are new to constructor concept in Java and you want to read about constructor before taking this test please check constructor article or otherwise you can refer to it later after the test. Please let me know your feedback after the test. All the Best!


1. What is the return type of Constructors?
    int
    float
    void
    None of the above
The correct answer is the None of the above. Constructors does not have any return type, not even void.

2. Which operator is used by Java to free the memory of an object when it is no longer needed?
    null
    free
    new
    None of the above
The correct answer is the None of the above. Garbage collection take care of memory management in java.

3. Predict the output of the following program?


class employee{
private String name;
public employee(String name) {
this.name=name;
}
}

public class Constructor1 {

public static void main(String[] JavaLatte) {
employee e = new employee("JavaDeveloper");
System.out.println("Emp Name : "+e.name);
}
}
    Emp Name : JavaDeveloper
    JavaDeveloper
    Compile time error
    Run time error
The correct answer is the Compile time error because String name is private.

4. Predict the output of the following program?


class person{
person(){
System.out.println("Hello constructor!");
return;
}
}

public class Constructor2 {

public static void main(String[] JavaLatte) {
person p = new person();
}
}
    Hello constructor!
    No output
    Compile time error
    Run time error
The correct answer is the Hello constructor! because we are not returning anything from constructor

5. Predict the output of the following program?

class Animal{
}

public class Constructor4 {

public static void main(String[] JavaLatte) {
Animal a = new Animal();
}
}
    Run with error
    Run without error
    Compile time error
    Run time error
The correct answer is the Run without error because default constructor will be created if we are thinking that constructor is not there

6. Predict the output of the following program?

class manager{
String name;
public manager(String name) {
this.name=name;
}
void welcomeMessage(){
System.out.println("Welcome to Java-Latte");
}
}

public class Constructor3 {

public static void main(String[] args) {
manager m = new manager();
}
}
    Welcome to Java-Latte
    No output
    Compile time error
    Run time error
The correct answer is the Compile time error because in this case default constructor in not created.

7. Will this class compile?


class Overloaded{
Overloaded(){
System.out.println("Constructor is initialised");
}
protected Overloaded(){
System.out.println("Constructor is initialised");
}
}
    Yes
    No
The correct answer is the No because Overloaded constructors can’t be defined by just a change in the access modifiers

8. Predict the output of the following program?

class Rectangle{
int len;
int width;
void Rectangle(int len, int width){
this.len=len;
this.width=width;
}
}
public class Constructor5 {

public static void main(String[] JavaLatte) {

Rectangle r = new Rectangle();
r.Rectangle(5, 7);
System.out.println(r.width+" "+r.len);
}
}
    5 7
    7 5
    0 0
    Error
The correct answer is the 7 5.

9. Can we define a constructor using all four access modifiers: public,protected, default, and private.
    Yes
    No
The correct answer is the Yes.

10. Predict the output of the following program?

class Square{
Square(){
System.out.println("Constructor is initialised");
}
{
System.out.println("Square is initialised");
}
}

public class Constructor6 {

public static void main(String[] JavaLatte) {
new Square();
}
}
    Square is initialised
         Constructor is initialised
    Constructor is initialised
         Square is initialised
    Compile time error
    Run time error
The correct answer is the A An initializer block is defined within a class, not as a part of a method. It executes for every object that’s created for a class

11. Predict the output of the following program?

class Square{
Square(){
System.out.println("Constructor is initialised");
}
{
System.out.println("Square is initialised");
}
}

public class Constructor7 {

public static void main(String[] JavaLatte) {
new Square();
new Square();
}
}
    Square is initialised
         Square is initialised
         Constructor is initialised
         Constructor is initialised
    Constructor is initialised
         Constructor is initialised
         Square is initialised
         Square is initialised
    Square is initialised
         Constructor is initialised
         Square is initialised
         Constructor is initialised
    Square is initialised   
         Constructor is initialised
The correct answer is the C because An initializer block is defined within a class, not as a part of a method. It executes for every object that’s created for a class

12. Predict the output of the following program?

class Employe{
String name;
Employe(){
Employe("JavaLatte");
}
Employe(String name){
this.name = name;
}
}

public class Constructor8 {

public static void main(String[] JavaLatte) {
new Employe();
}
}
    JavaLatte
    No output
    Compile time error
    Run time error
The correct answer is the Won’t compile—you can’t invoke a constructor within a class by using the class’s name. Because a constructor is defined using the name of its class, it’s a common mistake to try to invoke a constructor from another constructor using the class’s name


13.  Predict the output of the following program?
class Employe{
String name;
Employe(){
System.out.println("JavaLatte");
}
Employe(String name){
this.name = name;
this();
}
}

public class Constructor9 {
public static void main(String[] JavaLatte) {
new Employe();
}
}

    JavaLatte
    No output
    Compile time error
    Run time error
The correct answer is the Won’t compile— the call to the overloaded constructor must be the first statement in a constructor.


Show me the answers!

You are suppose to answer all the question!

Well done! You answered them all right!

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Monday, July 14, 2014

How Java program works

How Java program works
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java applications are typically compiled to bytecode (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture. In this post, we'll see the basic five phase of Java program life cycle.

Virtual Machine
The heart of the Java platform is the concept of a "virtual machine" that executes Java bytecode programs. This bytecode is the same no matter what hardware or operating system the program is running under. There is a JIT (Just In Time) compiler within the Java Virtual Machine, or JVM. The JIT compiler translates the Java bytecode into native processor instructions at run-time and caches the native code in memory during execution.
The use of bytecode as an intermediate language permits Java programs to run on any platform that has a virtual machine available. The use of a JIT compiler means that Java applications, after a short delay during loading and once they have "warmed up" by being all or mostly JIT-compiled, tend to run about as fast as native programs.


Primary goals in the creation of the Java language
  1. It should be "simple, object-oriented and familiar"
  2. It should be "robust and secure"
  3. It should be "architecture-neutral and portable"
  4. It should execute with "high performance"
  5. It should be "interpreted, threaded, and dynamic"

Types of Java
There are many types of Java programs which run differently:
  • Java Applet - is usually stored on a website and is downloaded and run on a client computer from within a web browser
  • Application - can only be run on the computer. If online, it has to be downloaded before being run.
  • JAR File - is used to package Java files together into a single file. (Almost exactly like a .zip file.)
  • Servlet - runs on a web server and helps to display web pages.
  • Swing application - is used to build an application that has a GUI (windows, buttons, menus, etc.)
  • EJB - runs on a web server and is used to develop large, complex websites


Java programs go through five phases

Edit
Programmer writes program using an editor; stores program on disk with the .java file name extension

Compile
Use javac (the Java compiler) to create bytecodes from source code program; bytecodes stored in .class files. To compile a program called Welcome.java, type
javac Welcome.java


Load 
Class loader reads bytecodes from .class files into memory.
The program must first be placed in memory before it can be executed. This is  done by the class loader, which takes the .class file (or files) containing the bytecodes and transfers it to memory. The .class file can be loaded from a disk on your system or  over a network

Verify
Bytecode verifier examines bytecodes to ensure that they are valid and do not violate security restrictions.

The JVM verifies all bytecode before it is executed. This verification consists primarily of three types of checks:

  • Branches are always to valid locations
  • Data is always initialized and references are always type-safe
  • Access to private or package private data and methods is rigidly controlled

The first two of these checks take place primarily during the verification step that occurs when a class is loaded and made eligible for use. The third is primarily performed dynamically, when data items or methods of a class are first accessed by another class.
The bytecode verifier traverses the bytecodes, constructs the type state information, and verifies the types of the parameters to all the bytecode instructions.



Execute
Java Virtual Machine (JVM) uses a combination of interpretation and just- in-time compilation to translate bytecodes into machine language

Summary of above phases in picture


Through the Java VM , the same application is capable of running on multiple platforms.






If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Sunday, July 13, 2014

Object declaration and creation in Java

Object declaration creation Initialization Java
Unlike some other programming languages, such as C, Java doesn't allow you to allocate or deallocate memory yourself when you create or destroy objects. Java manages memory for allocating objects and reclaiming the memory occupied by unused objects. The task of reclaiming unused memory is taken care of by Java’s garbage collector, which is a low-priority thread. It runs periodically and frees up space occupied by unused objects. In this post, we'll see the terms Declaration, Instantiations and Initialization of an object.

Object is born
An object comes into the picture when you use the keyword operator new. You can initialize a reference variable with this object. Note the difference between declaring a variable and initializing it. The following is an example of a class Person and another class ObjectLifeCycle:


In the previous code, no objects of class Person are created in the class ObjectLifeCycle; it declares only a variable of type Person. An object is created when a reference variable is initialized:

The difference in variable declaration and object creation can be easy understood with this image. where you can compare a baby name to a reference variable and a real baby to an object.

The left box in figure represents variable declaration, because the baby hasn’t been born yet. The right box in figure represents object creation.

Object creation can be understood with these 3 steps:

Declaration of an object
Declarations can appear as part of object creation as you saw above
Person person;
Declarations simply notify the compiler that you will be using name to refer to a variable whose type is type. Declarations do not instantiate objects. To instantiate a Person  object, or any other object, use the new operator.

Instantiation of an object

The new operator instantiates a new object by allocating memory for it. new requires a single argument: a constructor method for the object to be created. The constructor method is responsible for initializing the new object.

Initialization of an object
Classes provide constructor methods to initialize a new object of that type. In out case, default constructor or Person class do the initialization of object
Person()
A constructor such as the one shown, that takes no arguments, is known as the default constructor. Like Person, most classes have at least one constructor, the default constructor. However, classes can have multiple constructors, all with the same name but with a different number or type of arguments.



If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Saturday, July 12, 2014

Enhanced for each loop in Java

For-each loop in Java
The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readableThe enhanced for loop is also called the for-each loop, and it offers some advantages over the regular for loop. It also has some limitations.

To start with, the regular for loop is cumbersome to use when it comes to iterating through a collection or an array. You need to create a looping variable and specify the start and end positions of the collection or the array, even if you want to iterate through the complete collection or list. The enhanced for loop makes the previously mentioned routine task quite a breeze, as the following example demonstrates for an ArrayList myList:

You can read the colon (:) in a for-each loop as “in”.

The for-each loop is a breeze to implement: there’s no code clutter, and the code is easy to write and comprehend. In the previous example, the for-each loop is read as “for each element val in collection myList, print the value of val.”
You can also easily iterate through nested collections using the enhanced for loop. In this example, assume that an ArrayList of exams, levels, and grades are defined as follows:
The output of this code is as follows:
Java
Oracle
Basic
Advanced
Pass
Fail

The nestedArrayList can be compared to a multidimensional array


For-each with arrays
The enhanced for loop is again a breeze to use to iterate through nested or non-nested arrays. For example, you can use the following code to iterate through an array of elements and calculate its total:



Modification within for-each loop
What happens when you try to modify the value of the loop variable in an enhanced for loop? The result depends on whether you’re iterating through a collection of primitive values or objects
If you’re iterating through an array of primitive values, manipulation of the loop variable will never change the value of the array  being iterated because the primitive values are passed by value to the loop variable in an enhanced for loop.
When you iterate through a collection of objects, the value of the collection is passed by reference to the loop variable. Therefore, if the value of the loop variable is manipulated by executing methods on it, the modified value will be reflected in the collection of objects being iterated:
Sample Output:
Java
Lattte
JavaOracle
LattteOracle

Let’s modify the previous code. Instead of calling the method append on the loop variable val, let’s assign to it another StringBuilder object. In this case, the original elements of the array being iterated will not be affected and will remain the same:



Sample Output:
Java
Lattte
Java
Lattte

Limitations of the enhanced for loop
Though a for-each loop is a good choice for iterating through collections and arrays, it can’t be used in some places.

CAN’T BE USED TO INITIALIZE AN ARRAY AND MODIFY ITS ELEMENTS
Can you use an enhanced for loop in place of the regular for loop in the following code?

The simple answer is “no.” Although you can define a “counter” outside of the enhanced for loop and use it to initialize and modify the array elements, this approach defeats the purpose of the for-each loop. The existing for loop is easier to use in this case.

CAN’T BE USED TO DELETE OR REMOVE THE ELEMENTS OF A COLLECTION
Because the for loop hides the iterator used to iterate through the elements of a collection, you can’t use it to remove or delete the existing collection values because you can’t call the remove method.
If you assign a null value to the loop variable, it won’t remove the element from a collection

CAN’T BE USED TO ITERATE OVER MULTIPLE COLLECTIONS OR ARRAYS IN THE SAME LOOP
Though it’s perfectly fine for you to iterate through nested collections or arrays using a for loop, you can’t iterate over multiple collections or arrays in the same for-each loop because the for-each loop allows for the creation of only one looping variable. Unlike the regular for loop, you can’t define multiple looping variables in a for-each loop.

Use the for-each loop to iterate arrays and collections. Don’t use it to initialize, modify, or filter them.

Advantages enhanced for loop

  • Makes the code more readable
  • Elimnates the possibility of programming errors


Download CodeLoopAndForEach.java NestedForEach.java ForEachArray.java ModificationForEach.java ModificationForEach1.java 


If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Sunday, June 29, 2014

Optimize way to check empty String in Java

In this post, we'll see the best practice and optimize way to check empty String in Java. Every developer know how to check empty String but here we'll look into the optimized method of checking empty String. 

Most of us always prefer to use equals() method to check for empty String such as



However, this equals() method is overkill to test for an empty String. It is quicker to test if the length of the String is 0. So, the best way to check for empty String is 



How to prove that second option is the optimized way to check for empty String? 
For this, I have done micro-tuning. Micro-tuning should always start with a baseline measurement. The most basic tool in the tuner's armory is the System.currentTimeMillis() method, which returns the current time in milliseconds, as a long data item. This method returns the time offset from some starting time, but we don't actually care what that starting time is because we will use the currentTimeMillis() method to measure a time difference, the elapsed time between the start and end of our test



5 test result : 
Test run 1
Time in Mili Sec to length : 60
Time in Mili Sec to equals : 120
Test run 2
Time in Mili Sec to length : 53
Time in Mili Sec to equals : 98
Test run 3
Time in Mili Sec to length : 62
Time in Mili Sec to equals : 101
Test run 4
Time in Mili Sec to length : 54
Time in Mili Sec to equals : 89
Test run 5
Time in Mili Sec to length : 65
Time in Mili Sec to equals : 118

String.equals() is expensive if you are only testing for an empty string. It is quicker to test if the length of the string is 0.
Reason is that, since String class is immutable so there length is cached where in case of equals() a lot of statements need to be executed to know whether string is empty or not.
Onward Java 6, isEmpty() method of String is use for the same purpose.

What about if String is NULL?
In this case, you can add one condition of null check before checking length of the String. For instance,


Download CodeEmptyString EmptyStringWithNull



If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Friday, June 27, 2014

How CopyOnWriteArrayList works internally in Java

CopyOnWriteArrayList | ArrayList Java
In this article, we will see one of the most important concurrent collection class CopyOnWriteArrayList and we also look into the working of CopyOnWriteArrayList class including its comparison with ArrayList and in which situation CopyOnWriteArrayList should be preferred over ArrayList.


Few Drawbacks of ArrayList
  • If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.Means whenever there is access or modification we need synchronization that is a overhead.
  • The iterator will throw a ConcurrentModificationException


What is copy-on-write concept
Copy-on-write is an optimization strategy used in computer programming. Copy-on-write stems from the understanding that when multiple separate tasks use identical copies of the same information, it is not necessary to create separate copies of that information for each process, instead they can all be given pointers to the same resource. When there are many separate processes all using the same resource it is possible to make significant resource savings by sharing resources this way. However, when a local copy has been modified, the copy-on-write paradigm has no provision that the shared resource has in the meantime not been updated by another task or tasks.
So Copy-on-write is therefore only suggested if only the latest update is important and occasional use of a slightly stale value is not harmful. Copy-on-write is the name given to the process of identifying when a task attempts to make a change to the shared information, creating a separate (private) copy of that information for the task and redirecting the task to making changes to the private copy to prevent its changes from becoming visible to all the other tasks


CopyOnWriteArrayList
As the name suggest, "copy on write" means whenever there is write operation such as add, set and so on. it copies the underlying array. So it is a thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array. So basic idea is whenever we add or remove to the CopyOnWriteArrayList, the underlying array is copied with the modification. Remember this point, we'll see shortly in the code how CopyOnWriteArrayList do this.
It means, whenever there is modification done by thread that update the ArrayList, all other threads holding an older copy of different array. This is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don't want to synchronize traversals, yet need to preclude interference among concurrent threads.

This completes our basic understanding what is the need CopyOnWriteArrayList compared to ArrayList. Now we'll look into the code of CopyOnWriteArrayList to see how it implements the same concept.


Working of CopyOnWriteArrayList



If you see the underlying array reference is marked as volatile so that readers do not need to use a lock to see changes to the referenced array which means array update is an atomic operation and hence reads will always see the array in a consistent state. When a write operation occurs this volatile reference is only updated in the final statement via setArray() method. Up until this point any read operations will return elements from the old copy of the array. 
Also, the write lock is required to prevent concurrent modification, which may result the array holding inconsistent data or changes being lost

Advantage of volatile
Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change. Here volatile only applies to the array reference itself, not to the content of the array.

add(E e) method


If you notice in the above code, lock is acquired before adding the element in line 415 and getArray() is called which returned the underlying array which is declared volatile. After copying and modification the array is updated using the setArray() method, finally release the lock. This same concept applies to all the modification operations.

Iterator of CopyOnWriteArrayList
Iterator use "snapshot" style method uses a reference to the state of the array at the point that the iterator was created. Iterator of CopyOnWriteArrayList is fail-safe and doesn't throw ConcurrentModificationException even if underlying CopyOnWriteArrayList is modified once iteration begins because iterator is operating on separate copy of ArrayList. Consequently all the updates made on CopyOnWriteArrayList is not available to iterator.

How to get the most updated version of array
To get the most updated version do a new read like list.iterator(). Let's have a look to understand it more


In the above code, if you notice it call the getArray() method to return the iterator which always return the updated version of array. COWIterator implements the ListIterator.

How ArrayList throw ConcurrentModificationException
First, we will see the code of iterator of both ArrayList and CopyOnWriteArrayList from that we analyzed how ArrayList throw exception.

CopyOnWriteArrayList  Iterator




ArrayList Iterator








Here modCount is the ArrayList variable that holds the modification count and every time we use add, remove or trimToSize method, it increments. expectedModCount is the iterator variable that is initialized when we create iterator with same value as modCount. This explains why we don’t get exception if we use set method to replace any existing element. So basically iterator throws ConcurrentModificationException if list size is changed. Which is not the case with next() function of CopyOnWriteArrayList because we have the copy of array and no other thread will modify the same array.
Sometimes we want to add or remove elements from the list if we find some specific element, in that case we should use Concurrent Collection class – CopyOnWriteArrayList. 

When CopyOnWriteArrayList is preferred
A CopyOnWriteArrayList is preferable to a synchronized ArrayList when the expected number of reads and traversals greatly outnumber the number of updates to a list.


Examples of CopyOnWriteArrayList and ArrayList













If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Thursday, June 26, 2014

Linked List implementation of Queue Data Structure in Java

Linked List implementation of Queue Data Structure in Java
A Queue is a data structure for storing data similar to Linked List and Stack. In Queue, the order in which data arrives is important. In general, a queue is a line of people or things waiting to be served in sequential order stating at the beginning of the line.

A queue is an ordered list in which insertions are done at one end (rear) and deletion done at other end (front). The first element to be inserted is the first one to be deleted. Hence, it is called as First in First Out(FIFO) or Last in Last Out (LILO).

This is some what similar to Stack. When an element is inserted in a queue, the concept is called EnQueue and when an element is removed from the queue, the concept is called DeQueue.Trying to DeQueue an empty Queue is called as underflow and trying to EnQueue an full queue is called overflow. Generally, we treat them as exceptions.

Queue Operations
Main Operations

  • enQueue(int data) : Insert an element at the end of the queue
  • deQueue() : Removes and element an element at the front of the queue
Auxiliary Operations
  • int Front() : Returns the element at the front without removing it.
  • int QueueSize() : Returns the queue size.
  • int isEmpty() : Indicates whether element are stored.


Implementation of Queue
Linked List is one of the implementation of Queue, in which EnQueue operation is implemented by inserting element at the end of the list and DeQueue operation is implemented by deleting an element from the beginning of the list.


Source : wikipedia


Queue Exception class


For ListNode class refer Linked List

Queue




Demo 
4
4
8
2

Complexity
Space Complexity : O(n)
Time Complexity : enQueue and deQueue operations O(1)

Download Code : QueueException Queue QueueDemo


If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...