Search This Blog

Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Tuesday, 21 June 2016

How to start eclipse with different version of Java?

After Installing required JRE if you require to upgrade Eclipse version then kindly follow following step to upgrade eclipse java version:

You can add the -vm option to eclipse.ini:
-vm
c:/<path>/java/<javaName>/bin/javaw.exe
path : directory where Java is installed
javaName:Name of JDK/JRE installed.
 After updating eclipse.ini file, eclipse.ini file may look like this :
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:\Program Files (x86)\Java\jre7\bin\javaw.exe
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx512m

Thursday, 18 February 2016

Split String at Space ,Except if it is not in double qoutes


Split String at Space ,Except if it is not in double qoutes


 public class Main {
    public static void main(String[] args) {
        String str= "abc \"peter micheal\" Jean \"Patrick David\" Richards";
        String[] tempArr = str.split("[ ]+(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
       for(String string : tempArr) {
         System.out.println(string);
      }
  }
}

You can use online java compiler such as THIS to verify usability.
This will help you to avoid chances of using wrong solution and save your time.

Output: 

abc
"peter micheal"
Jean
"Patrick David"
Richards

Sunday, 10 May 2015

HashMap example in Java


HashMap example in Java

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.
The following constructors are defined: HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)

The first form constructs a default hash map. The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments. The meaning of capacity and fill ratio is the same as for HashSet, described earlier.
HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.
The following program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used.
 


import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Raj", new Double(3434.34));
hm.put("Arun", new Double(123.22));
hm.put("Avi", new Double(1378.00));
hm.put("Paresh", new Double(99.22));
hm.put("Jonan", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("Raj", new Double(balance + 1000));
System.out.println("Raj's new balance: " +
hm.get("Raj"));
}
}


Output from this program is shown here:
Raj: -19.08 
Arun: 123.22
Avi: 3434.34
Paresh: 99.22 

Jonan: 1378.0
Raj's current balance: 4434.34

Thursday, 7 May 2015

Java Collection Introduction

Java Collection Introduction


 A collection is an object that contains a group of objects.
Each object in a collection is called an element. Every collection contains a group of objects.
Each different type of collection manages their elements in its own way.
The Collections Framework consists of interfaces, implementation classes, and some utility classes to handle most types of collections.
Java Collections are designed to work only with objects.
All collection classes in Java are declared generic.

Architecture of the Collection Framework

The Java Collections Framework has three main components:
  • Interfaces
  • Implementation Classes
  • Algorithm Classes
An interface in Java Collections Framework represents a specific type of collection.
For example, the List interface represents a list. The Set interface represents a set. The Map interface represents a map.
The data structures defined by interfaces rather than a class has the following advantages: we can provide different implementation for the same interfaces.
The Java Collections Framework also provides implementations of collection interfaces.
We should always try to define the type of the class using interfaces, rather than using their implementation classes.
The following code shows how to use the implementation class ArrayList to create a list:
List<String> names = new ArrayList<>();
If possible we should avoid using the following way to create a list object.
ArrayList<String> names = new ArrayList<>();



Operations

We can perform different actions on a collection.
  • searching through a collection
  • converting a collection of one type to another type
  • copying elements from one collection to another
  • sorting elements of a collection in a specific order

Tuesday, 15 July 2014

File Upload Example in Struts

 

 

Required JAR file

Before we start, we need to make sure commons-io.jar file is present in the classpath. Following are the list of required Jar files.
struts2-file-upload-jar-files

Getting Started

In order to add file upload functionality we will add an action class FileUploadAction to our project. Create file FileUploadAction.java in package com.blogspot.rajvishwakarma15.struts2.
FileUploadAction.java
package com.blogspot.rajvishwakarma15.struts2;
 
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
 
public class FileUploadAction extends ActionSupport implements
        ServletRequestAware {
    private File userImage;
    private String userImageContentType;
    private String userImageFileName;
 
    private HttpServletRequest servletRequest;
 
    public String execute() {
        try {
            String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”);
            System.out.println("Server path:" + filePath);
            File fileToCreate = new File(filePath, this.userImageFileName);
 
            FileUtils.copyFile(this.userImage, fileToCreate);
        } catch (Exception e) {
            e.printStackTrace();
            addActionError(e.getMessage());
 
            return INPUT;
        }
        return SUCCESS;
    }
 
    public File getUserImage() {
        return userImage;
    }
 
    public void setUserImage(File userImage) {
        this.userImage = userImage;
    }
 
    public String getUserImageContentType() {
        return userImageContentType;
    }
 
    public void setUserImageContentType(String userImageContentType) {
        this.userImageContentType = userImageContentType;
    }
 
    public String getUserImageFileName() {
        return userImageFileName;
    }
 
    public void setUserImageFileName(String userImageFileName) {
        this.userImageFileName = userImageFileName;
    }
 
    @Override
    public void setServletRequest(HttpServletRequest servletRequest) {
        this.servletRequest = servletRequest;
 
    }
}
In above class file we have declared few attributes:
  • private File userImage; -> This will store actual uploaded File
  • private String userImageContentType; -> This string will contain the Content Type of uploaded file.
  • private String userImageFileName; -> This string will contain the file name of uploaded file.
The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also follow the naming standard if you providing the content type and file name string. The name should be ContentType and FileName. For example if the file attribute in action file is private File uploadedFile, the content type will be uploadedFileContentType and file name uploadedFileFileName.
Also note in above action class, we have implemented interface org.apache.struts2.interceptor.ServletRequestAware. This is to get servletRequest object. We are using this path to save the uploaded file in execute() method. We have used FileUtil.copyFile() method of commons-io package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user.

The JSPs

Create two JSP file in WebContent folder. UserImage.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server. User will be sent to SuccessUserImage.jsp file where File details will be displayed. Copy following code into it.
UserImage.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
 
<body>
<h2>Struts2 File Upload & Save Example</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
    <s:file name="userImage" label="User Image" />
    <s:submit value="Upload" align="center" />
</s:form>
</body>
</html>
SuccessUserImage.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>
</head>
<body>
    <h2>Struts2 File Upload Example</h2>
    User Image: <s:property value="userImage"/>
    <br/>
    Content Type: <s:property value="userImageContentType"/>
    <br/>
    File Name: <s:property value="userImageFileName"/>
    <br/>
    Uploaded Image:
    <br/>
    <img src="<s:property value="userImageFileName"/>"/>
</body>
</html>

Struts.xml entry

Add following entry for FileUploadAction class to struts.xml file.
<action name="userImage"
    class="com.blogspot.rajvishwakarma15.struts2.FileUploadAction">
    <interceptor-ref name="fileUpload">
        <param name="maximumSize">2097152</param>
        <param name="allowedTypes">
            image/png,image/gif,image/jpeg,image/pjpeg
        </param>
    </interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <result name="success">SuccessUserImage.jsp</result>
    <result name="input">UserImage.jsp</result>
</action>
Note that in above entry we have specified two parameter to fileUpload interceptor, maximumSize and allowedTypes. These are optional parameters that we can specify to interceptor. The maximumSize param will set the maximum file size that can be uploaded. By default this is 2MB. And the allowedTypes param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file (image/png,image/gif,image/jpeg,image/pjpeg).
The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:
  • struts.messages.error.uploading – error when uploading of file fails
  • struts.messages.error.file.too.large – error occurs when file size is large
  • struts.messages.error.content.type.not.allowed – when the content type is not allowed

That’s All Folks

Compile and Execute the project in eclipse and goto link http://localhost:8080/StrutsHelloWorld/UserImage.jsp
Image Upload Screen
struts2-file-upload-example
Image Upload Screen in case of error
struts2-file-upload-error
Image Upload Screen on success
struts2-file-upload-success

Download Source Code

Click here to download Source Code without JAR files (20KB)


Friday, 27 June 2014

Why multiple inheritance is not supported in Java !!!

Why Java doesn't support multiple inheritance

1) First reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below

           A play()
           / \
          /   \
play() B     C play()
          \   /
           \ /
            D
           play()

In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.

Some times if you give this reason to interviewer he asks if C++ can support multiple inheritance than why not Java. hmmmmm in that case I would try to explain him the second reason which I have given below that its not because of technical difficulty but more to maintainable and clearer design was driving factor though this can only be confirmed by any of java designer and we can just speculate. Wikipedia link has some good explanation on how different language address problem arises due to diamond problem while using multiple inheritances.

2) Second and more convincing reason to me is that multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

Java Collections - List

The java.util.List interface is a subtype of the java.util.Collection interface. It represents an ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index too. You can also add the same element more than once to a List.
Here is a list of the topics covered in this text:
  1. List Implementations
  2. Adding and Accessing Elements
  3. Removing Elements

List Implementations

Being a Collection subtype all methods in the Collection interface are also available in the List interface.
Since List is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following List implementations in the Java Collections API:
  • java.util.ArrayList
  • java.util.LinkedList
  • java.util.Vector
  • java.util.Stack
There are also List implementations in the java.util.concurrent package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a List instance:
List listA = new ArrayList();
List listB = new LinkedList();
List listC = new Vector();
List listD = new Stack();    

Adding and Accessing Elements

To add elements to a List you call its add() method. This method is inherited from the Collection interface. Here are a few examples:
List listA = new ArrayList();

listA.add("element 1");
listA.add("element 2");
listA.add("element 3");

listA.add(0, "element 0");
The first three add() calls add a String instance to the end of the list. The last add() call adds a String at index 0, meaning at the beginning of the list.
The order in which the elements are added to the List is stored, so you can access the elements in the same order. You can do so using either the get(int index) method, or via the Iterator returned by the iterator()method. Here is how:
List listA = new ArrayList();

listA.add("element 0");
listA.add("element 1");
listA.add("element 2");

//access via index
String element0 = listA.get(0);
String element1 = listA.get(1);
String element3 = listA.get(2);


//access via Iterator
Iterator iterator = listA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}


//access via new for-loop
for(Object object : listA) {
    String element = (String) object;
}
When iterating the list via its Iterator or via the for-loop (which also uses the Iterator behind the scene), the elements are iterated in the same sequence they are stored in the list.

Removing Elements

You can remove elements in two ways:
  1. remove(Object element)
  2. remove(int index)
remove(Object element) removes that element in the list, if it is present. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1.
remove(int index) removes the element at the given index. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1.

Tuesday, 10 June 2014

Jsp Interview Questions and Answers

 

JSP Interview Questions and Answers

 
 
 
Download Link
 
 

Servlet Interview Questions and Answers

 

            Servlet Interview Questions and Answers

 
                     

Core Java Interview Questions and Answers

                                    

   Core Java Interview Questions and Answers





   

   Core java Interview Questions and Answers


Saturday, 12 April 2014

How Volatile in Java works ? Example of volatile keyword in Java



Any way  Volatile keyword in Java is used as an indicator to Java compiler and  Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like AutoboxingEnumGenericsand Variable arguments ,  Java introduces some change in Java Memory Model (JMM),  Which  guarantees visibility of changes made by one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatilekeyword also  guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.



Example of volatile keyword in Java:

To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java.

/**
 * Java program to demonstrate where to use Volatile keyword in Java.
 * In this example Singleton Instance is declared as volatile variable to ensure
 * every thread see updated value for _instance.
 *
 * @author Javin Paul
 */

public class Singleton{
private static volatile Singleton _instance; //volatile variable 

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}

If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of first request comes.

If we do not make _instance variable volatile then Thread which is creatininstance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.


Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads.



Let’s see another example of volatile keyword in Java:
Volatile variable example in Javamost of the time while writing game we use a variable bExist to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread , So if we don't  use volatile keyword with this variable , Game Thread might miss update from event handler thread if its not synchronized in java already. volatile keyword in java guarantees that value of volatile variable will always be read from main memory  and  "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads.

 private boolean bExit;

 while(!bExit) {
    checkUserPosition();
    updateUserPosition();
 }

In this code example One Thread (Game Thread) can cache the value of "bExit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable "bExit" as volatile in java ensures this will not happen.


When to use Volatile variable in Java



1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many  platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java.

2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation  completed, without volatile keyword different reader thread may see different values.

3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like following example withoutvolatile variable may result in infinite loop

private boolean isActive = thread;
public void printMessage(){
  while(isActive){
     System.out.println("Thread is Active");
  }
} 

without volatile modifier its not guaranteed that one Thread see the updated value of isActive from other thread. compiler is also free to cache value of isActive instead of reading it from main memory in every iteration. By making isActive a volatile variable you avoid these issue.

4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.

Important points on Volatile keyword in Java
1. volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.

2. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.

3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).

4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.

5. From Java 5 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 in java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.

6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without use of volatile keyword in Java.

7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.

8. Java volatile variable that is an object reference may be null.

9. Java volatile keyword doesn't means atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.