Tuesday, October 15, 2013

580 - Critical Mass UVA Online Judge

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=714&page=show_problem&problem=841



#include <cmath>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
#include<cstdio>
#include<cstdlib>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<sstream>
#include<cstring>
#define For(i,n) for(int i=0;(i)<n;i++)
#define mp make_pair
#define pb push_back
#define MOD 10000007
using namespace std;

int main(){

    int p[]={3,6};
    int *t=p;
    int x=*t++;
    cout<<*t<<x;
   long long  int dp[101][4];
    memset(dp,0,sizeof(dp));
    dp[1][0]=1;dp[1][1]=1;
    dp[2][0]=2;dp[2][1]=1;dp[2][2]=1;
    For(i,101){
        if(i<3)continue;
        For(j,3){
            dp[i][0]+=dp[i-1][j];
        }
        dp[i][1]=dp[i-1][0];
        dp[i][2]=dp[i-1][1];
        dp[i][3]=dp[i-1][2]+2*dp[i-1][3];

    }
    int n;
    cin>>n;
    while(n!=0){
        cout<<dp[n][3]<<endl;
        cin>>n;
    }
}

Sunday, March 10, 2013

Best Practices Common and Important Architecture for Web Application Using Java


An architecture is the most important part for any software. The whole software depends on the architecture, you follow initially. It is very difficult or almost impossible, to change the architecture of any software application which is already build. A good architecture is utmost requirement of good Quality Attribute.

Today I will discuss the architecture for the web application. This architecture will help for new comers and also for others. This architecture is not only for Java based web application, but also for Web application built in PHP, dotnet , etc. I am here to design the general architecture. Generally if a good architecture is not followed, then at the end we try to fix issues according to our requirement and the application finally becomes too complex, to make changes. Please do read about Software Architecture http://en.wikipedia.org/wiki/Software_architecture

This blog is for people who want to design good architecture in their web applications. This architecture is the layered architecture. There are different frameworks available in java like struts,spring,etc. The Struts and Spring are themselves following MVC patterns. So, if you are using these framework, almost you are half-way to good architecture. But if you are not using these frameworks, then you need good architecture. Following is the general architecture which I generally follow.


Now, the question is "How can we implement them in any language". I will discuss this in terms of J2EE. In my next blog I will list some some of my classes for PHP which might be useful for all.

Views are JSP's and Controllers are Sevlets. Every new request goes to the servlet. Servlet will interact to Service or Business layer and then it forward the request to the desired JSP(view). Following are some of the guidelines, which are preferred.

  • Keep all the configurable parameters in the properties files. With properties file we can easily keep (key,value) pair.The simplest example is to keep SQL Connection properties in connection.properties file. The advantage of this approach is that, when we want  to change any value, in that case, we don't have to touch code, we can directly change in these files and also it can be easily maintained by non technical guys. These properties file are kept in a separate folder( this folder should be in classpath).
  • Create Interfaces for each property file. As we know, interfaces variables are "public static final". Now link each property (key) with a interface variable. The advantage of this approach is that you can directly use these variables, just by name of interfaces, irrespective of the fact that the value can change in near future. Also create a separate package for these interfaces.
  • Create POJO's. These POJO's are generally called Transfer Objects. These Transfer Objects are used to pass values from one layer to another. Create a package for POJO's
  •  Create useful utilities. The utilities are the objects which are commonly used. For example make a class of Database utility. The Database utility contains methods like getConnection(), closeConnection(). So, if tomorrow you want to switch to a different database you can just change the getConnection() method, without affecting other layers. Create a separate package for utilities.
  • Create separate package for controllers, exceptions(your own Exception handling), business logic
  • In case of JSP's make a separate folder for css, images, java script. If possible try to use Apache tiles. The advantage of using tiles is that you can make your layout. The layout may contain a header and footer. So, if in future you want to change the layout, you have to change in your layout JSP's and whole layout of your web-application gets changed.

Following diagram show the package wise architecture diagram.



Following is the sample application.Click here to download sample architecture

 Please give your valuable feedback and also tell the ways to improve the architecture.







Tuesday, October 23, 2012

How to include custom jar into your Maven repository?

Still you will find jars which are not there in Maven repository. Classic example is suppose you create a common utility jar and you want to use it across projects or it could be a third party jar which has private licence and so cannot be there in Maven central repository. In above cases, you can actually put the required jar easily in the Maven local repository. For demonstration purpose, we are using Kaptcha.
Here is the command:
mvn install:install-file 
-Dfile=c:\kaptcha-2.3.2.jar 
-DgroupId=com.google 
-DartifactId=kaptcha 
-Dversion=2.3.2 
-Dpackaging=jar

Remember to remove the newlines from above command incase you are copying and pasting.
Below is the result from command line after executing the command:
C:\>mvn install:install-file -Dfile="c:\kaptcha-2.3.2.jar" -DgroupId=com.google
-DartifactId=kaptcha -Dversion=2.3.2 -Dpackaging=jar
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install-file (default-cli) @ standalone-po
m ---
[INFO] Installing c:\kaptcha-2.3.2.jar to C:\Users\dharmvir.singh\.m2\repository
\com\google\kaptcha\2.3.2\kaptcha-2.3.2.jar
[INFO] Installing C:\Users\DHARMV~1.SIN\AppData\Local\Temp\mvninstall71581647865
23828175.pom to C:\Users\dharmvir.singh\.m2\repository\com\google\kaptcha\2.3.2\
kaptcha-2.3.2.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.587s
[INFO] Finished at: Tue Oct 23 15:23:57 IST 2012
[INFO] Final Memory: 3M/15M
[INFO] ------------------------------------------------------------------------
Job is done. You can now specify the dependency of this jar as shown:

      com.google
      kaptcha
      2.3.2

Monday, October 15, 2012

Configuring Maven inside proxy network

Maven version I used is 3.0.4 and environment is windows 7 enterprise edition.

Well, it is pretty simple,

collect your proxy server and port configuration and if username and password  are there then them too and save them in your settings.xml.
Settings.xml can be found either in <userhome>/.m2/settings.xml (Apache documentation tells about this path but I couldn't find it in this location, link to proxy config doc.. proxy config mini guide) or (I found them in this path <maven unzipped directory>/config/settings.xml, in my case path was D:/apache-maven-3.0.4/config/settings.xml)
Now, you have to uncomment this section from settings.xml and save the correct info here as shown:
 
    
    
      optional
      true
      http
      proxyuser
      proxypass
      Your Proxy server IP Here
      Your proxy server port numbere here
      local.net|some.host.com
    
    
  

Related Articles

Eclipse proxy setting

Thursday, June 28, 2012

5.JAVA BASICS..CONCEPT OF STATIC

Here you will learn about the static keyword which in itself a very useful concept.

What do you understand by static? 
  By seeing the word static three things come to our mind
 1) Class Global variable- It means that it is global to the class. No object copy.
 2) One copy in memory - Only one copy exists in memory.
 3) It exists in memory even before creation of objects.

We will take some examples of objects and their memory allocation.

class Test
{
int a;
float b;
int d=10;
}

class TestMain
{
public static void main(String[] args)
{
Test obj1=new Test();
Test obj2=new Test();
Test obj3=new Test();
obj3.d=15;
obj3.b=5.0;
obj2.a=5;
obj3=new Test();       //Line 7
obj3.d=16;
}
}
Following is the heap diagram with objects.

In the above figure you will find that all the objects are created in the heap memory. obj1,obj2,obj3 are the references which points to these objects. The references obj1,obj2,obj3 are defined inside the method, we can say that these references are using stack memory. In the above objects,you will also  find that all the objects have their own copy of variables. Each object have different value of variables. In short all objects have their own variables.
Obj3 firstly refers to other object and after line-7 it points to different object.

Example of static:
class Test
{
int a;
float b;
static int c
int d=10;
}

class TestMain
{
public static void main(String[] args)
{
Test obj1=new Test();
Test obj2=new Test();
Test obj3=new Test();
obj3.d=15;
obj3.b=5.0;
obj2.a=5;
obj3=new Test();       //Line 7
obj3.d=16
obj1.c=6;
obj3.c=10;
obj2.c=15;
Test.c=20;
}
}

In the above example 'c' is the static variable,so there exists only one copy of variable c and is not inside any of the object area,instead it has a separate memory space which is accessible by any of the objects and even by the class. This is how the static works.

static in broader terms:

Following are the different ways of using keyword static
  • Variables
  • Methods
  • Classes
  • Block

Variables:
A static variable have one copy and any instance can change its value.
Use of Static variables: Whenever you fell a resource should be accessible by all the instances and you need only one copy. Take a simple example of a basket of chocolates, take 'N' students who can take chocolate from this basket.Student will act as an object. When a student takes a chocolate from basket then the number of chocolates decreases. In these types of examples, take count_of_chocolate as a static variable and when an object takes it the count of chocolate decreases.

Static variables exist in memory even before the instances are created. By this statement don't misunderstand that it will always exist in memory. It will only exist in memory when a class gets loaded( you will learn class loading later).

Difference between static variables and normal variables
  • static variables- Class global
    normal variables- Object specific
  • static variables- Only one copy
    normal variables- copies are equal to the number of objects that exist in memory
  • static variables- Exist when class gets loaded
    normal variables- Exist when instance get created, each object has different copy
  • static variables- Every object have access to this variable,also accessed by class name
    normal variables- Object able to access its own copy.

Static methods:
Prefixing static before a method name makes a method static.
Where the normal methods exist in memory?
There is only one copy of normal methods,it does not depend on the number of objects. The methods are stored in Method area. Method area is a separate memory in Heap which stores the class methods.Methods are executed from this area.
Static Methods- They are also stored in the same area and only one copy exist in memory.

Difference between static method and normal method
Both have one copy in memory. Static method exist in memory even when there is no object while the normal method exist only after instance is created.
Can static method access non static variable???..
No. Static method and variable exist in memory when a class gets loaded while the non static variable and method exist only after instance is created. This is the reason why static method cannot access non static variable.

Static Classes:
Remember an outer class can never be static as there is no point in declaring an outer class an static class. Only the nested classes are allowed to be static. Technically, inner classes are not called static, inner classes are local and anonymous classes. Static classes are same as normal classes, the only difference is that static classes cannot access not static member variables and methods of the parent class.
Static class behaves like normal classes.
  Nested Classes: Nested classes are of 2 types
  a) static nested classes
  b) Non-static Nested Classes- These classes are called Inner Class.

To know more about Inner and nested class please read http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Static Blocks:
A class can have number of static block and normal block.
All normal block will be executed each time a instance is created in the order they are exist in class and are executed before the constructor is called while the static block is executed only once on class loading (it's execution does not depend on the number of instance). As the static block is executed on class loading, it is executed before normal blocks gets executed.

Here is a simple example to understand the difference between static and normal block

public class StaticBlockExp {

 static{
  System.out.println("1.static block");
 }
 static{
  System.out.println("2.static block");
 }
 {
  System.out.println("Welcome to Java");
 }
 {
  System.out.println("Welcome to world of java");
 }
 public StaticBlockExp()
 {
  System.out.println("Constructor");
 }
 public static void main(String[] args) {
  new StaticBlockExp();
  new StaticBlockExp();
 }
}

Output of above program:
1.static block
2.static block
Welcome to Java
Welcome to world of java
Constructor
Welcome to Java
Welcome to world of java
Constructor

From this it is clear that static blocks are executed only once while normal blocks are executed each time an instance is created.


Thursday, June 21, 2012

Spring 3.2 M1 released...

Spring 3.2 comes with a lot of new stuff. Below is a brief listing of the features that are in 3.2 version:
  1. Initial support for asynchronous @Controller methods
  2. Early support for JCache-based cache providers
  3. Significant performance improvements in autowiring of non-singleton beans
  4. Initial delay support for @Scheduled
  5. Ability to choose between multiple executuors with @Async
  6. Enhanced bean profile selection using the not (!) operator
  7. 47 bugs fixed, 8 new features and 36 improvements implemented
There are a lot of other stuff.. checkout Spring source website ...

Tuesday, June 12, 2012

System.out.println(), What is it?

System is a class in java.lang package. It is a system related class and most of times make native calls. As far as out is concerned. System class declares it something like this:
  public final static InputStream in = null; 
  public final static PrintStream out = null; 
  public final static PrintStream err = null; 
As shown above both err and out are instances of PrintStream class (java.io.PrintStream). System class has setters for all the three mentioned above but no getters. InputStream is again from java.io package. Setters are written something like as shown:
  public static void setOut(PrintStream out) { 
    checkIO(); 
    setOut0(out); 
 }
Summarizing above, System is class in java.lang package and out is the instance of PrintStream class from java.io package and println() is a method from the PrintStream class obviously.

Friday, May 18, 2012

JAXB: XSD datatypes mapping to Java DataTypes

Below is the list of mappings from XSD data types to Java data types
XSD types Java DataTypes
bytebyte
intint
integerjava.math.BigInteger
decimaljava.math.BigDecimal
longlong
floatfloat
doubledouble
durationjavax.xml.datatype.Duration
datejavax.xml.datatype.XMLGregorianCalendar
dateTimejavax.xml.datatype.XMLGregorianCalendar
stringjava.lang.String
nonNegativeIntegerjava.math.BigInteger
nonPositiveIntegerjava.math.BigInteger
unsignedByteshort
unsignedIntlong
unsignedLongjava.math.BigInteger
unsignedShortint
anyURIjava.lang.String
base64Binarybyte [] (byte array)
booleanboolean
ENTITIESList
ENTITYjava.lang.String
timejavax.xml.datatype.XMLGregorianCalendar
gDayjavax.xml.datatype.XMLGregorianCalendar
gMonthjavax.xml.datatype.XMLGregorianCalendar
gYearjavax.xml.datatype.XMLGregorianCalendar
gMonthDay javax.xml.datatype.XMLGregorianCalendar
gYearMonthjavax.xml.datatype.XMLGregorianCalendar
Whatever data types are not there in Java JAXB has created appropriate datatypes in their API, for example, XMLGregorainCalendar. Now the question is how to convert it our facourite dataypes like java.util.Date or java.sql.Date or java.util.Calendar etc. You can probably write an Adaptor class which has static methods to do all these conversion.

Thursday, May 3, 2012

Why to prefer static factory methods over constructors to get the object of a class?

Instead of creating objects using new operator you can also use static method to instantiate a class. Code listing:
// instantiating a class using constructor
Dog dog = new Dog(); 
..........................................

// instantiating the class using static method
Class Dog{
  private Dog(){
  }
  // factory method to instantiate the class
  public static Dog getInstance(){
    return new Dog();
  }
}
Using static factory methods have both advantages as well as disadvantages. Advantages:
  1. Static factory methods can have different name than class whereas constructors cannot: As methods have names, they convey their purpose clearly as opposed to constructors. A class can have only one constructor with a given signature, developers get around this restriction by changing the order of parameters passed to constructors; In case of methods you can give a different name to resolve the issue.
  2. Static methods support conditional instantiation: Each time you invoke a constructor an object will get created but you might not want that. (for example, in singleton class you will maintain a single object). Or suppose you want to check some condition only then you want to create a new object.
  3. Methods can return subtypes of return type: Suppose there is a class Animal and it has subclass Dog. We have static method with signature
      public static Animal getInstance(){
       ...
      }
    }
    
    then method can return Both objects of type Animal and Dog which provides great flexibility.
Disadvantages:
  1. If constructor of the class is not public or protected then the class cannot be sub classed: If you ask if there is a workaround to this, there is not. But honestly, it is better as you cannot use inheritance and so you have to use composition which is always better than inheritance any day.
  2. Another disadvantage is you cannot differentiate between static factory methods and regular factory methods: There is no syntactical difference but if you follow some naming convention then it is easy to identify. For example, getInstance() is used in many frameworks to provide the instance of a class (java.util.Calendar, ).
Examples of static factory methods in Java:
  1. Pattern.compile
  2. Calendar.getInstance
  3. Collections.synchronizeCollection
List is very big. References

Monday, February 20, 2012

JAR to JAVA converter

I went through many websites,but i did not find any converter for jar file to .java files at one go.
So, I thought of writing a script for this conversion. This script also keeps the package structure same as in the jar file

Following are the prerequisites
  • This is restricted to windows platform
  • Unzip utility should be installed in the system
  • jad decompiler should be installed.
    If you don't have jad installed, you can find from the following link
    click here to download
  • Unzip the jad.zip downlaoded in step2,set the jad.exe in the systems path variable.
  • Run the command prompt in the administrator mode

Steps to run the batch file
  • cd "path to which batch file is placed"
  • jar2java.bat "jar file name/jar file path with jar file name"
  • Note: Give jar file name without extension
Download the batch file from here

Note:Remove the extention .txt to make it .bat file.

Example:
Step 1) >cd D:\jartojava (Copy the above downloaded batch file in this folder)
Step 2) jartojava> jar2java.bat abc (copy abc.jar in this folder)
Here a folder named abc is created with all the java files found in abc.jar.

Friday, December 16, 2011

Difference between ServletConfig and ServletContext

Following table lists down the main differences and others things are discussed afterwords:
ServletConfigServletContext(It should have been ApplicationContext)
One ServletConfig object is created per servlet One ServletContext object is created per Application
Can be used to pass deployment time information to the Servlet. Information is stored as parameters in the deployment descriptor(web.xml) Can be used to share Application level information across servlets and is this information is also stored in the web.xml as well as parameters (So it kind of acts as GlobalContext or Application Context)
Provides a set of methods to set and get the initialization configuration information Provides a set of methods to the servlet so that servlet can communicate with the Container
------------------------Servlet can access a ServletContext object only through ServletConfig object

Working with ServletConfig:

We will explaing here how to declare the Servlet init Parameters in in the Deployment Descriptor(web.xml) and how to retrieve them in the servlet also how to get the object of Servlet Context from ServletConfig.
web.xml: Declaring init parameters for a specific servlet

    
    SampleServ
    SampleServ
    in.javaespresso.web.SampleServ
    
     Sample Init Parameters
     servParamservValue
  
Servlet Code: Getting init parameters inside the servlet
getServletConfig().getInitParameter("servParam");
Servlet Code: Getting ServletContext object using ServletConfig
ServletContext context = getServletConfig().getServletContext();

Working with ServletContext:

Let us get the context paramteres declared in the web.xml in the servlet and jsp
web.xml: Declaring context parameters

    Sample context parameters
    emailjava.espresso@gmail.com
Servlet Code: Accessing context params in Servlet
getServletContext().getInitParameter("email")
JSP code: Accessing context params in JSP
<%
getServletContext().getInitParameter("email");
%>

Please find the code for the article attached here

Monday, November 14, 2011

Remote Method Invocation(RMI) Example

Here, we will learn basics of RMI and will implement a small example

Remote Method Invocation Basics
As the name suggests,it is a system to call remote method,which may be on other JVM or other computer. It is built on top of Sockets. But,you don't have to deal with sockets and protocols directly. You can directly call a method on some other machine and it works,as if you have called it locally. To achieve this it passes the objects over the network(objects should be Serializable).

Drawback: RMI can only be used in java. Interaction with other language platform is not possible.

Requirements of RMI
Client Requirement
Let us suppose there is a server Object which is registered.
* Client Object have to find the Server Object(by looking it up in registry)
* Serialize the parameters and send
* Deserialize the response from the server

Server Requirement
* Server should be a remote object
* The remote object should be registered(rmiregistry is used for registration)

Example

HelloInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface HelloInterface extends Remote {
 public String sayHello() throws RemoteException;
 }

Hello.java
import java.rmi.RemoteException;
public class Hello implements HelloInterface 
{

private String message; 
public Hello (String msg) throws RemoteException {
message = msg;
 }
public String sayHello() throws RemoteException {
 return message;  
 }
}
HelloServer.java
import java.net.MalformedURLException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

class HelloServer {

 public static void main(String[] argv)  throws RemoteException, MalformedURLException {
  
  try{
   Hello remoteObj=new Hello("This is test RMI");
    Remote obj = UnicastRemoteObject.exportObject(remoteObj, 9502);
          Registry r = LocateRegistry.createRegistry(9502);
          r.bind("RemoteHelloServer", obj);
   System.out.println("Hello Server is ready.");
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  
 }
}

Steps for compilation:
1)javac HelloInterface.java
2)javac Hello.java
3)javac HelloWorld.java
4)rmiregistry //In a separate command prompt
5)rmic -vcompat Hello //will generate Hello_Stub.class and Hello_Skel.class
6)java HelloWorld

After step 6,Server is up

Steps for client code:
* Copy the HelloInterface.java and Hello_Stub.class file in client area
* Write a client program HelloClient.java, which looks up in registry.

HelloClient.java
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

class HelloClient {
 public static void main(String[] args) {
  try {
   Registry registry;
  HelloInterface hello;
  registry=LocateRegistry.getRegistry(
                "localhost",(new Integer(9502)).intValue());
  String name = "RemoteHelloServer";
  
   hello = (HelloInterface) registry.lookup(name);
   System.out.println(hello.say());
  } catch (Exception e) {
   System.out.println("HelloClient exception: " + e);
  }
 }
}

Compile and run the client code.
After this it is easy to expose your methods with RMI.

Monday, October 31, 2011

Base64 encoding and decoding in Java

What is Base 64 Encoding Scheme?
Wiki says -
"Base64 is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The Base64 term originates from a specific MIME content transfer encoding."

In simple terms Base64 encoding is a Binary to ASCII text conversion technique. Other such techniques available are quoted-printable, hexadecimal, BinHex, etc.

Binary to text encoding/decoding techniques are used when there is doubt that the transmission protocol/channel might not be capable of handling the non-textual data, best examples are email sent via MIME, Usenet. For example, many browser normally convert a space in URLs to %20D or such like characters and you might be in trouble if your server doesn't reconvert them but you can't possible crack down every such possible case. So better is use an encoding scheme that converts your data to text based characters.

your data => [ Base64 Encoding System ] => Textual Data
Image      => [ Base64 Encoding System ] => Image converted to text data

Is Base64 Encoding scheme a Encryption technique? NO, don't even think like an idiot. it is simply converting data from one form to another so that no modification happens due to the limitation in my transmission protocol/channel but there is not concept of cryptography involved at all.

How Base64Encoding works? Well, look at Wiki example, it is pretty much straight forward and clear.
Same example is given below as well..
Text content M a n
ASCII 77 97 110
Bit pattern 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 1 1 0 1 1 1 0
Index 19 22 5 46
Base64-encoded T W F u

Since in Base64 you can have totally 64 different characters so your output can have characters only from the set given below:
A-Z, a-z, 0-9, +, /
Note: last two character might change depending on the implementation, for example, in variant Base64 with URL and Filename Safe Alphabet (RFC 4648 'base64url' encoding) -(hyphen) and _ (underscore) are used.

There are many variants of base64 are available, Some are listed below:
  1. RFC 1421
  2. RFC 2045- org.apache.commons.codec.binary.Base64 class does encoding and decoding as per this standard.
  3. RFC 3548
See more exhaustive list here(Wiki).

Last thing we will cover in theory is padding.. Now padding is adding extra bits/bytes/characters etc. when required. In Base64encoding also, padding is required some times.

When does padding is done in Base64Encoding and what characters are inserted for padding?
I will not explain how padding is done. this is clearly explained on Wiki site of Base64(See Relevant References) here. Padding is done when the number of bytes to encode is not divisible by 3, that is there are only one or two bytes of input for the last block. The '==' sequence indicates that the last group contained only 1 byte, and '=' indicates that it contained 2 bytes (you'll like that there are implementations available which doesn't require padding at all).

There are various implementations available as I mentioned earlier but being a good developer you should open your eyes and decide which implementation to choose depending on the requirement. Some Common applications of Base64 are given below:
  1. URL:
    • To encode the URL query parameters
    • To encode data in hidden form fields
    • Just to obfuscate the URL data
  2. File names: Variant Modified Base64 for file name uses '-' instead of '/', because Unix and Windows file names cannot contain '/'.
Checkout the other applications also.

Let us jump to Base64 Encoding in Java: There are many implementations available. I will list them down first (not all):
  • Apache commons: org.apache.commons.codec.binary.Base64. Usage of this implementation is recommended.
  • Sun misc package: sun.misc.BASE64Decoder. Avoid using it as misc package is never officially released by SUN, this is one thing. Another thing is Oracle might be tempted to remove all packages with names having SUN and you see that code suddenly stopped working in future releases of Java.
  • Base64 class shipped with JAXB framework. Use this if your project is already using JAXB.
  • javax.mail.internet.MimeUtility: This class also has encode and decode methods and can do the job for you. But use them when your code is dealing with emails as this implementation follows MIME protocol guidelines.
There are many others also available. You can write your own as well (all the best if you are doing.)

Now it's time for demo code:
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;

/**
 * @author java-espresso
 * This class has two methods one encodes a string in Base64Encoding 
 * and other decodes the same.
 */
public class CommonUtil {

 public static String base64Encode(String stringToEncode){
  byte [] stringToEncodeBytes = stringToEncode.getBytes();
  return Base64.encodeBase64String(stringToEncodeBytes);
 }
 
 public static String base64Decode(String stringToDecode){
  byte [] decodedBytes = Base64.decodeBase64(stringToDecode);
  return new String(decodedBytes);
 }
 
}
Test class for the above code:
public class TestBase64 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  String testString1 = "test String"; //Total bytes=11 divide by 3  and 2 bytes are in remainder so '=' is appended in the encoded string
  String testString2 = "TestString"; //Total bytes=10 divide by 3  and 1 bytes are in remainder so '==' is appended in the encoded string
  String testString3 = "Test string."; // Total bytes=12 divide by 3  and 0 bytes are in remainder so nothing is appended
  
  String encoded1= CommonUtil.base64Encode(testString1);
  String encoded2= CommonUtil.base64Encode(testString2);
  String encoded3= CommonUtil.base64Encode(testString3);
  
  System.out.println("====== Encoded Strings =======================================");
  System.out.println(testString1+" > Encoded > "+encoded1);
  System.out.println(testString2+" > Encoded > "+encoded2);
  System.out.println(testString3+" > Encoded > "+encoded3);
  
  System.out.println("====== Decoded Strings =======================================");
  System.out.println(encoded1+" > Decoded > "+CommonUtil.base64Decode(encoded1));
  System.out.println(encoded2+" > Decoded > "+CommonUtil.base64Decode(encoded2));
  System.out.println(encoded3+" > Decoded > "+CommonUtil.base64Decode(encoded3));
 }

}
output on executing the above code:
====== Encoded Strings =======================================
test String > Encoded > dGVzdCBTdHJpbmc=
TestString > Encoded > VGVzdFN0cmluZw==
Test string. > Encoded > VGVzdCBzdHJpbmcu
====== Decoded Strings =======================================
dGVzdCBTdHJpbmc= > Decoded > test String
VGVzdFN0cmluZw== > Decoded > TestString
VGVzdCBzdHJpbmcu > Decoded > Test string.
Please find the source of the application attached here.
Related Article

Relevant References

Thursday, October 13, 2011

Threads Part1: An introduction

A thread in computer science is short for a thread of execution. A thread is a single sequential flow of control within a program (i.e., process). Threads are a way for a process to split itself into multiple simultaneously running tasks. Threads are lightweight processes because they run within the context of a full-blown program and takes advantage of the resources allocated for that program and the program's environment. Threads are similar to process, but differ in the way that they share resources.
Java virtual machine can support many threads of execution at once. These threads independently execute code that operates on values and objects residing in a shared main memory. Threads may be supported by having many hardware processors (where threads are executed on separate processors), by time-slicing a single hardware processor (where a single processor switches between different threads giving the illusion that they are all executing at the same time), or by time-slicing many hardware processors. There is always at least one thread within every Java program: the main() method of the class which was given as a parameter to the Java interpreter.

Difference between a user thread and daemon thread. The daemon threads purpose is to give services to the user threads which are created by the user to perform the long running task (mostly for not blocking the ui or to do something in background ).The main() method of the application is a user thread. Threads created by a user are user thread ,you can also create the Daemon thread by explicitly calling the setDaemon(true) on a Thread object.One important point here is that setDaemon() method must be called before the thread is started .Once all the user threads are terminated then only JVM will terminate not in the other way if there are Daemon threads running but no user threads then JVM will close the running application .There should be atleast one user thread(main thread is a user thread )running for the JVM not to close the application.


There are two ways of implementing threading in JAVA
1) By extending java.lang.Thread class, or
2) By implementing java.lang.Runnable interface.
Before we go into implementation details I just like to cover when we use thread? so we use thread if we want some part of code is executed parallel and we put that code inside run() method of either Thread class or Runnable interface.
Actually public void run () method is defined in Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically.


//implementing Thread by extending Thread class
class MyThread extends Thread{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());
}
}

//implementing Thread by implementing Runnable interface
class MyRunnable implements Runnable{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());
}
}
//starting Thread
Thread mythread = new MyThread();
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable(),"T2");
mythread.start();
myrunnable.start();


Thread will not start until you call the start() method of java.lang.Thread class. When we call start () method Java Virtual machine execute run () method of that Thread class into separate Thread other than calling thread. Anybody guess what will happen if we call the run() method directly instead of calling start() method ?
run() method will simply be executed in the same Thread and new Thread will not be created. Another follow up question would be what will happen if you call start () method twice in same Thread object e.g

mythread.start();
mythread.start();// this line will throw IllegalThreadStateException


Difference between mythread.start() & mythread.run()?
• If we call mythread.start(), it will create a new Thread and that thread is responsible for execution of run().
• If we call mythread.run(), no new thread will create, the main thread only will execute run(), just like a normal method.
• In case of mythread.start() output we can’t expect
• In case of mythread.run() output first it ll run the code in the run function in the main thread .
Thread class start():-

public void start()
{
1. Registering our thread with the thread scheduler then only thread scheduler allocate CPU and memory type of resources for this new thread also.
2. calls run() // you can think of it as a call back invoked by the jvm
}



The thread is in the "new" state, once it is constructed. In this state, it is merely an object in the heap, without any system resources allocated for execution. From the "new" state, the only thing you can do is to invoke the start() method, which puts the thread into the "runnable" state. Calling any method besides the start() will trigger an IllegalThreadStateException.

The start() method allocates the system resources necessary to execute the thread, schedules the thread to be run, and calls back the run() once it is scheduled. This put the thread into the "runnable" state. However, most computers have a single CPU and time-slice the CPU to support multithreading. Hence, in the "runnable" state, the thread may be running or waiting for its turn of the CPU time.
The thread enters the "not-runnable" state when one of these events occurs:
The sleep() method is called to suspend the thread for a specified amount of time and yield control to the other threads.

The wait() method is called to wait for a specific condition to be satisfied.
The thread is blocked and waiting for an I/O operation to be completed.
For the "non-runnable" state, the thread becomes "runnable" again:
If the thread was put to sleep, the specified sleep time expired or the sleep was interrupted via a call to the interrupt() method.
If the thread was put to wait via wait(), its notify() or notifyAll() method was invoked to inform the waiting thread that the specified condition had been fulfilled and the wait was over.
If the thread was blocked for an I/O operation, the I/O operation has been completed.
A thread is in a "dead" state, only when the run() method terminates naturally and exits.

The method isAlive() can be used to test whether the thread is alive. isAlive() returns false if the thread is "new" or "dead". It returns true if the thread is "runnable" or "not-runnable".
JDK 1.5 introduces a new Thread.getState() method. This method returns an enum of type Thread.State, which takes a constant of {NEW, BLOCKED, RUNNABLE, TERMINATED, WAITING}.
NEW: the thread has not yet started.
RUNNABLE:
WAITING:
BLOCKED: the thread is blocked waiting for a monitor lock.
TIMED_WAITING: the thread is waiting with a specified waiting time.
TERMINATED:

Methods in Thread Class
The methods available in Thread class include:
public void start(): Begin a new thread. JVM calls back the run() method of this class. The current thread continues.
public void run(): to specify the execution flow of the new thread. When run() completes, the thread terminates.
public static sleep(long millis) throws InterruptedException: Temporarily suspend the thread and yield control to other thread for the given milliseconds. Method sleep() is thread-safe as it does not release its monitors. The method throws InterruptedException if it is awaken before the specified timing (via a call to interrupt() method). This is a static method and commonly used to pause the current thread so that the other threads can have a chance to execute. For example:
try {
// suspend for 0.1 sec and give other threads a chance to run
sleep(100);
} catch (InterruptedException ex) {}
public void interrupt(): Interrupt the sleep() method.
public boolean isAlive(): Return false if the thread is new or dead. Returns true if the thread is "runnable" or "not runnable".
public void setPriority(int p): Set the priority-level of the thread, which is implementation dependent.
public void yield(): suspend the current thread to allow other threads to run.
The stop(), suspend(), and resume() methods have been deprecated in JDK 1.4, because they are not thread-safe, due to the release of monitors. See JDK API documentation for more discussion.

What is the difference between implementing Runnable and extending Thread?
One difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance.
"Which way of implementing Thread is better? Extending Thread class or implementing Runnable method?

In my opinion implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us.
Second reason which make sense to me is more on OOPS concept according to OOPS if we extend a class we provide some new feature or functionality , So if the purpose is just to use the run() method to define code its better to use Runnable interface.
e.g


public class Espresso {
public static void main (String[] args) {
Runner r = new Runner();

Thread t1 = new Thread(r, "Thread A");
Thread t2 = new Thread(r, "Thread B");
Thread s1 = new Mythread("Thread C");
Thread s2 = new Mythread("Thread D");

t1.start();
t2.start();
s1.start();
s2.start();

}
}

class Runner implements Runnable {
private int counter;
public void run() {
try {
for (int i = 0; i != 2; i++) {
System.out.println(Thread.currentThread().getName() + ": "
+ counter++);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}

class Mythread extends Thread {
private int counter;
Mythread(String name) {
super(name);
}
public void run() {
try {
for (int i = 0; i != 2; i++) {
System.out.println(Thread.currentThread().getName() + ": "
+ counter++);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}


output
Thread A: 0
Thread B: 1
Thread C: 0
Thread D: 0
Thread C: 1
Thread B: 2
Thread A: 3
Thread D: 1

Tuesday, October 11, 2011

JQuery Tutorial 1: Showing alert popup

Let me put the code first then we will do the post mortem

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
</head>
<body>
<input type="button" value="Trigger Alert" id="btn_trig">
<script type="text/javascript">
/* $('#btn_trig') gives reference to the html element whose id is passed,
 * similiar to getElementById() function. On that reference a callback function is defined
 *  syntax of callback functions is like this event( function(){ //thing you want to do on event happening}). Callback functions are called when event happens.
 *  
 */
$('#btn_trig').click(function(){
 alert("Hello World!");
} 
);
</script>
</body>
</html>

Try for yourself:



Thursday, September 29, 2011

Configuring SSL in tomcat

What is SSL?
SSL or Secure Socket Layer is a technology which allows web browsers and web servers to communicate over a secured connection. The data being sent is encrypted by one side, transmitted, then decrypted by the other side before any further processing. Essentially, it is a two way process, Browser encrypts its requests before sending them to the server and server decrypts them then server encrypts the response and the browser decrypts it.

There is one more thing we should understand about SSL is certificates used for Authentication. When the Browser places the first request to a web server over a secure connection, that server will respond to your web browser with two things, one is your page (for example ICICI Loginpage,CitiBank login page) and other is a set of credentials, in the form of a Certificate; This certificate gives information to the browser about the authenticity of the website.

Certificates and SSL
In order to implement SSL, a web server must have an associated certificate for each external IP address that accepts secure connections. Certificate acts as a identity proof for the website like your passport for you. This certificate is signed by the issuer (you can also create your self-signed certificates as well, but do not use them in production). Issuer is normally a well recognized authority like VeriSign, Thawte, Go Daddy, etc.

Why shouldn't you use Self-signed certificates?
Hackers normally utilize the weakness of your certificate to attack and the weakness is that it is self-signed. The attack might happen, something like this, when the client attempts to connect to the server the hacker hijacks the connection(means that now your requests will go to the hacker not the server). He then sends the client his own self-signed certificate(seeing which you feel happy and say, wow, now I can fill my credit card info without any prob.) which has the same name as the one present in the server's self-signed certificate. The hacker then connects to the real server himself. When the client sends data to the server the attacker reads it(might change it as well) and then sends it along to the real server. So, your credit card information might get leaked.
Let us start with tomcat:
  1. You need to create a keystore file to store the private key of the server using the following command.
    Windows:

    Unix:

    Same is shown below:
    The file will get created under the directory from which you are running the command, for example, as shown in image, the file will get created under following path: C:\Users\dharmvir.singh

    To specify a different location to store the keystore file(keystore in the last of the path), just modify the above command as shown below:
    Windows:

    same way you can do in unix.
    Sample is shown below:
    Password used in both the example screens shots is "changeit" as it is the default password for tomcat.
    The certificate can be obtained from authorities like Verisign and others.
  2. Uncomment the following section from $CATALINA_HOME/conf/server.xml:
    
    
    $Catalina_Home here represents path of your tomcat home folder
To test it I created a sample TestServer app (I have attached tomcat with that application to download). Here is how it will look like on accessing it on localhost.
Tips on SSL:
  1. SSL has encryption/decryption which is expensive so do not configure entire application on SSL. For example, Website home, adds, banners pages, sitemap page, about us page might not be put on SSL.
  2. using name-based virtual hosts on a secured connection can be problematic. This is a limitation of SSL protocol. So you can use only one certificate for one IP address.

Apache-Troubleshooting SSL in tomcat

tomcat with SSL enabled can be downloaded from here, It contains the TestServer App as well, so just download and start the server and test it.

Relevant References

Note from Author: Please leave appreciation comment, if you like the article or else please leave your questions, suggestions or feedback.
Thanks,
java-espresso

Wednesday, September 28, 2011

JAVA BASICS.. JAVA A DIFFERENT APPROACH TO START.. JAVA PLATFORM INDEPENDENT. HOW JAVA IS PORTABLE?


Must read for a good start of JAVA

All of us know that JAVA is portable i.e JAVA is platform independent.Let us try to figure out the reason how Java is platform independent. Java has used a slogan Write Once Run anywhere.

Explanation:
Some language generate .obj or .exe file after compiling. These generated file will not work in other Operating system. There was a need to have something which will not depend on operating system. Hence they came with new concept of JAVA VIRTUAL MACHINE(JVM). Running a java program was divided into 2 parts. First part makes .class file and in the second part this .class file will be run on JVM.
For the generation of .class file from .java file,compiler was written which will always generate the same .class file for any of the operating systems. Half of the work is over for getting platform independency.

.java ----Compile---->.class(Byte Code)---Interpreter(Platform Dependent)--->machineCode


For running the same .class file in different OS, they made a difference in JVM for different operating system. JVM depends on the hardware and OS architecture. It will take .class file as input and interpret it. So for the same .class file it will generate the same output. It is the difference in JVM which has made java a platform independent language.

Now in the next post we will learn basics of java taking memory into consideration.

Friday, September 23, 2011

web.xml servlet Understanding <url-pattern>/*</url-pattern>

Understanding the <url-pattern>/*</url-pattern>

Other Questions of similar pattern:
1) How to exclude from url-pattern in servlet mapping?
2) To exclude content from url-pattern

While developing web.xml in application, do take care of the <url-pattern>.
Try not to give a generic url-pattern ie., <url-pattern>/*</url-pattern>.The disadvantage of this URL Pattern is, any request coming to the server will fall in this URL PATTERN(except for those you have explicitly defined). Suppose browser is requesting a page which has images,css,etc then you will find page will load with the servlet response,while the images,css,js,etc are not getting loaded and it will be very difficult to find the reason for this type of behaviour.

The reason is as:-
Our browser requests in the following steps
Step1: The browser requests the page and gets back the response which contains all other path.
Step2: The browser again requests all the other path to the server and these path contains the images,css,etc

What happens in our problem is in step 2,the browser's request goes to the server and now the images,etc also falls in the <url-pattern >/*</url-pattern>,which redirects to a servlet and this is the problem. This is the reason why we don't get images and other files in our web page.

Let us solve this with the help of example:
web.xml

 TestUrlPattern
 
   ServletDefault
   com.test.ServletDefault
   
  
    ServletDefault
    /*
  
  
  abcd
  /abc.jsp
  
  
   abcd
    /abc.jsp
  


abc.jsp
<html>
<head>
<title>TestUrlPattern</title>
</head>
<body>
Sample text
<img src="Desert.jpg" >
</body>
</html>


Whenever a request comes as localhost:8080/TestApp/abc.jsp, the abc.jsp loads and images are not getting loaded. The images goes to the SevletDefault mapping. You can see this by printing any text in doGet or doPost method of ServletDefault class.
Reason is,all files other than abc.jsp will go to ServletDefault.

Solution for /* type pattern in web.xml

I found two approaches to solve this problem
Approach 1:

Make a common servlet which consumes all the files which have the pattern for images,css,javascript,etc
web.xml  (modified)

  TestUrlPattern
  
      CommonServlet
      com.test.CommonServlet
    
  
      Servlet
      com.test.Servlet
    
    
        Servlet
        /*
    
    
    abcd
    /abc.jsp
  
    
    
      abcd
        /abc.jsp
    
        
        CommonServlet
        /images/
    
    
        CommonServlet
        /stylesheet.css
    
    
        CommonServlet
        /javascript.js
      


Keep the images in the 'images' folder. For a new request to the servlet, you will find,all the images,css,js requests goes to CommonServlet. Write a CommonServlet which retuns back the file itself in the response.

CommonServlet.java

public class CommonServlet extends HttpServlet  {
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  ServletContext sc = getServletContext();
  String path=req.getRequestURI().substring(req.getContextPath().length()+1, req.getRequestURI().length());
     String filename = sc.getRealPath(path);

     // Get the MIME type of the image
     String mimeType = sc.getMimeType(filename);
     if (mimeType == null) {
         sc.log("Could not get MIME type of "+filename);
         resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
         return;
     }
     // Set content type
     resp.setContentType(mimeType);

     // Set content size
     File file = new File(filename);
     resp.setContentLength((int)file.length());

     // Open the file and output streams
     FileInputStream in = new FileInputStream(file);
     OutputStream out = resp.getOutputStream();

     // Copy the contents of the file to the output stream
     byte[] buf = new byte[1024];
     int count = 0;
     while ((count = in.read(buf)) >= 0) {
         out.write(buf, 0, count);
     }
     in.close();
     out.close();
 }
}

The above servlet write the contents of file in the response and our problem is solved.

Approach 2:

This approach sets the context in jboss server.xml file.
server.xml is found at Jboss_home\server\default\deploy\jboss-web.deployer path.
Open server.xml in edit mode
Add the context in server.xml.
Find text similar to the following code in server.xml
<Host name="localhost" autoDeploy="false" deployOnStartup="false" deployXML="false"configClass="org.jboss.web.tomcat.security.config.JBossContextConfig" >
Below the above code add the context as:



set docBase,path according to your path.This will solve your problem.

These were the two approaches which i found out for this problem. Please let me know if you know any more approach.

4.JAVA BASICS.. IS JAVA A PURE OBJECT ORIENTED LANGUAGE..PROBLEM SOLVING.


As you all know java is a pure Object Oriented language.
Is java Really a pure Object Oriented Language?

The answer is NO..Java is not a pure object oriented language.
1)The main reason for this is it does not always deal with objects.
int,char,float,etc are not in the form of objects and java uses them. So this is the main reason why java is not object oriented language.
2)The other reason is that java does not support Multiple inheritance in case of classes,but a pure object oriented language supports multiple inheritance.

Now let us see some of the basic thing in java which is to be noted. Those who already know java can skip this.

What is the default value of Byte?
Ans: NULL

Now a question may arise in your mind,that the default value of byte is false.Your question is correct.
If you observe clearly,then you will find that default value of Byte is asked not byte.And Byte is a class that means it will store reference. Remember in the first java basic, i told to see the data types start with lower case.

Point to be remembered: In java a class is always declared with first letter as Upper case letter(This is not a rule but it is a best practice so that you never make mistake).

Similarly you will find some more class which may confuse you like Boolean with boolean ,Float with float,Double with double. So don't get confuse with these classes.

 Now a question may arise in your mind that why they have made these confusing classes.What is the use of these classes.Your question is correct,following is the explanations for this.

Sometimes we need objects of these primitive data types,for this Java has made WRAPPER CLASSES for these primitive data types. All the primitive data types have Wrapper Class. Now by using these Wrapper classes,we can convert these data types to Objects and can use them.
Following are the wrapper classes of the primitive data types
1)int    --> Integer
2)byte   -->Byte
3)short   ---> Short
4)char    --->Character
5)boolean  --> Boolean
6)float    --->Float
7)double   --->Double
8)long     --->Long
9)void    ---> Void

Compilation of program:
The java compiler search for a particular signature in the main function.
The signature is
public static void main(String[] args)
This is the signature,that should exist in a program to run ,otherwise it will not run.

Example for the above concept
Class A
{
public static void main(String[] args)
{
     main('x');
     System.out.println("my string");
}
public static void main(char b)
{
     System.out.println(b);
}
}

Output: x
            my string

Reason: It will only treat the first main method as the main method as it is having proper signature and treats 2nd method like a normal java method.

Example2:Count how many objects are created and how many references exist:

Eg:
Customer a=new Customer();
Customer b=new Customer();
Customer c=a;
Customer d= b;
new Customer();

Ans: 3 Objects 4 references

In these types of questions just count the number of new keywords that will give you the number of objects.
and count the number of references by the class name count and in some examples please make the heap and object diagram which we made earlier and then there will be no mistakes.

In next we will learn the concept of static in java..So keep reading...

3.JAVA BASICS.. CLASS AND OBJECTS WITH APPROACH OF MEMORY

What is a class?
We can say class is a template of an object. Objects exists in memory. Class is just a way to define a structure of object.

Now we start with discussion of memory.
Four segments of memory
1)Data segment
2)Code segment
3)Stack segment
4)Heap segment

In C we have seen the use of code and data segment. But in java we will be dealing with Stack Segment and Heap Segment.

See the example below

When we write using new keyword, a new object is created and new Customer() returns the hashcode of the created object. The variable used to store the hash code value is called reference variable.It is called reference because it has the hash code value,which refers to an object.

In short we can say that obj(the variable used above) stores the hash code,where hash code is not the actual address(it is changed to hash code by some hash algorithm). Java does not deal with direct memory,it deals with hash code and the hash code  indirectly refers to a memory. This is the reason why java is called secure. Unlike C,it has no pointers or depointers which can take you to the actual memory address.

Suggestions: 
When ever dealing with output problems,always make a heap by making a square and see the code for how many objects are there. Count and make that many ovals inside the square and point these objects by an arrow of reference. I assure you by using this method,you will not make any mistakes. Example is below

Now an important note,to be always kept in mind and will solve all your problems.
         Local Variables   ------->  STACK
         Global Variables  ------->   HEAP
Keep the above note always in your mind and there will never be a chance of mistake.Here global refers to be a part of class definition.
Stack Variables do not have any default value
Heap variables have default value. If there is any variable in Stack and you try to use that variable without initialization then it will result in a compile time error.
All the objects which are created using new keyword,goes to heap memory,while the location of these references depends,whether they are local or global.
    Take a simple example::
  Sample sample=new Sample();
Here the object of class Sample will always be in heap memory,while the reference(sample here)  location depends on whether it is declared locally or global. We can say that if sample is inside a method then it will be in stack,and if it is inside a class(but outside methods) then it will be stored in heap memory.

Default values of all the variables(only Heap Variables)
int       ---> 0
byte     --->0
short    --->0
boolean -->false
long    ---->0
float     ---->0.0f
double  ---->0.0
char     ----->'\0'
Reference Variable   ---> NULL

NOTE: From above,keep in mind,all variables  keep 0 as the default value.. false(boolean) can be related with 0,NULL can be related with 0,'\0' can be related with 0. Keep in mind a default value of 0.

By seeing any class you can relate the variables with stack and heap.

We will do some examples and then proceed
Class Sample{
int a;                //   Global Variable =>heap              
void printVariable()
{
int b;               //     Local Variable => Stack                 
System.out.println(a);
System.out.println(b);                         ///Error
}
}

Why Error?
The reason is that b is a local variable. We are trying to use a local variable,which is not initialized,and stack variable don't have  default value so it gives error. 
Comparison with C language: In C also,global variables prints 0 while the local variable gives Garbage Value.
Java does not want to have these garbage values because that will make your code buggy,so Java compiler is checking for this at compile time only and thus ,doesn't allow the code to compile.

Example 2:
Class Sample{
Test obj;            //   suppose Test is another class
int a;
void printVariables()
{
System.out.println("value of a is:"+a);
System.out.println("value of reference:"+obj);
}
}
Ans: As we can see that both are global variables,means both use heap memory.
None of them is initialized,so default value is printed.
    value of a is: 0
    value of reference: NULL

Example 3:
class Sample{
void printArea()
{
 int a;
int b=1;
if(b==1)
{
a=10;
}
System.out.println(a);
}
Ans: Compile Time Error
Now the question that come in your mind, the local variable is initialized before using,then why it gives compile time error.
Reason: Even though you have initialized the variable,but at compile time, the compiler does not know in advance if it will enter the loop or not at run time. If suppose,at run time it does not enter the loop and the variable will not get initialized. To avoid these type of situations at run time,java is designed such a way,if a variable is not initialized and gets initialized in inner loops,it does not matter. So if any variable is initialized in inner loop but not in the loop where it is declared,and we use the variable in the declaration loop,the code will not compile.