Read QRCode in JAVA

Hello Friends,

As in earlier post we had learn what is QR code and how can we generate QR code in java and servlet.

Now here today we will learn how can we read QR Code in java.

Here again i had use same jar file as we had previuos. ZXing- Zibra Corossing

Here is code to read QR Code.


import java.io.FileInputStream;
import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class QRReader {

public static void main(String args[]){

Result result = null;
BinaryBitmap binaryBitmap;

try{

binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream("D:/Generated_QR.PNG")))));
result = new MultiFormatReader().decode(binaryBitmap);
System.out.println("QR Code : "+result.getText());

}catch(Exception ex){
ex.printStackTrace();
}
}
}

 

Hope you like it. Cheers… 🙂

 

 

Advertisements

Difference Between Stack and Heap

What Is Stack?

Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread. A Java virtual machine stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated. The memory for a Java virtual machine stack does not need to be contiguous.

The Java virtual machine specification permits Java virtual machine stacks either to be of a fixed size or to dynamically expand and contract as required by the computation. If the Java virtual machine stacks are of a fixed size, the size of each Java virtual machine stack may be chosen independently when that stack is created. A Java virtual machine implementation may provide the programmer or the user control over the initial size of Java virtual machine stacks, as well as, in the case of dynamically expanding or contracting Java virtual machine stacks, control over the maximum and minimum sizes.

The following exceptional conditions are associated with Java virtual machine stacks:

  • If the computation in a thread requires a larger Java virtual machine stack than is permitted, the Java virtual machine throws a StackOverflowError.
  • If Java virtual machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java virtual machine stack for a new thread, the Java virtual machine throws an OutOfMemoryError

The Stack section of memory contains methods, local variables and reference variables.

What Is Heap?

The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated.

The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor’s system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.

The heap mainly store objects create using or class level variables.

The following exceptional condition is associated with the heap:

  • If a computation requires more heap than can be made available by the automatic storage management system, the Java virtual machine throws an OutOfMemoryError

The Heap section contains Objects (may also contain reference variables).

Points to Remember:

  • When a method is called , a frame is created on the top of stack.
  • Once a method has completed execution , flow of control returns to the calling method and its corresponding stack frame is flushed.
  • Local variables are created in the stack
  • Instance variables are created in the heap & are part of the object they belong to.
  • Reference variables are created in the stack.

What if Object has a reference as its instance variable?


public static void main(String args[]){

A parent = new A();
//more code

}

class A{

B child = new B();
int e;
//more code

}

class B{

int c;
int d;
//more code

}

In this case , the reference variable “child” will be created in heap ,which in turn will be pointing to its object, something like the diagram shown below.

HashMap vs Hashtable vs HashSet

I was reading about collection framework of Java. And was studying Hashtable, HashMap and HashSet. Its quite interesting to know the differences between them. In this post I will discuss these three with examples.

Hashtable

Hashtable is basically a datastructure to retain values of key-value pair.

  • It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
  • It is synchronized. So it comes with its cost. Only one thread can access in one time
Hashtable<Integer,String>; cityTable = new Hashtable<Integer,String>();
cityTable.put(1, "Lahore");
cityTable.put(2, "Karachi");
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/

System.out.println(cityTable.get(1));
System.out.println(cityTable.get(2));
System.out.println(cityTable.get(3));

HashMap

Like Hashtable it also accepts key value pair.

  • It allows null for both key and value
  • It is unsynchronized. So come up with better performance
HashMap<Integer,String> productMap = new HashMap<Integer,String>();
productMap.put(1, "Keys");
productMap.put(2, null);

HashSet

HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.

HashSet<String> stateSet = new HashSet<String>();
stateSet.add ("CA");
stateSet.add ("WI");
stateSet.add ("NY");

if (stateSet.contains("PB")) /* if CA, it will not add but shows following message*/
System.out.println("Already found");
else
stateSet.add("PB");

Generate Capatcha in JAVA


package com.project.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

/**
* Action implementation class CaptchaAction
*/
public class CaptchaGeneration {
private static final Logger log = Logger.getLogger(CaptchaGeneration.class);

private String captchValue;
private String prevImageName;
private String currentImageName;

public CaptchaGeneration(){

}
public CaptchaGeneration(String prevImageName){
       this.prevImageName = prevImageName;
}

public String getCaptchValue() {
        return captchValue;
}

public void setCaptchValue(String captchValue) {
        this.captchValue = captchValue;
}
public String getPrevImageName() {
return prevImageName;
}
public void setPrevImageName(String prevImageName) {
this.prevImageName = prevImageName;
}
public String getCurrentImageName() {
return currentImageName;
}
public void setCurrentImageName(String currentImageName) {
this.currentImageName = currentImageName;
}
public void refresh(String tempFolderPath) throws Exception {
log.info("Inside execute of CaptchaAction");
int height = 30;
int width = 120;
File f = null;
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = image.createGraphics();
Random r = new Random();
String token = Long.toString(Math.abs(r.nextLong()), 36);
String ch = token.substring(0, 6);
GradientPaint gp = new GradientPaint(30, 30, Color.gray, 15, 25, Color.GRAY, true);
graphics2D.setPaint(gp);
Font font = new Font("Verdana", Font.CENTER_BASELINE, 26);
graphics2D.setFont(font);
graphics2D.drawString(ch, 2, 24);
graphics2D.dispose();
setCaptchValue(ch);
StringBuffer fileName = null;
//String path = null;
FileOutputStream fout = null;
try {
fileName = new StringBuffer("Captcha").append(System.nanoTime()).append(".jpeg");
//path = req.getRealPath(CommonConstant.TEMPFILES_FOLDER_NAME);
log.info("path : " + tempFolderPath);
if(getPrevImageName()!=null){
f = new File(tempFolderPath + "/" + getPrevImageName());
log.info("File to delete : " + getPrevImageName());
if(f.exists()){
boolean isDeletd = f.delete();
log.info("FIle deleted ::::::::::::: " + isDeletd);
}
}
f = null;
f = new File(tempFolderPath + "/" + fileName.toString());
fout = new FileOutputStream(f);
ImageIO.write(image, "jpeg", fout);
log.info("file name is :: " + fileName.toString());
setCurrentImageName(fileName.toString());
setPrevImageName(fileName.toString());
} catch (Exception e) {
log.error("CaptchaGeneration : refresh() : Exception : " , e);
throw e;
}finally{
fileName = null;
f = null;
if(fout!=null){
fout.close();
}
fout = null;
}

}

}

Vector or ArrayList — which is better?

 Vector or ArrayList — which is better and why?

Sometimes Vector is better; sometimes ArrayListis better; sometimes you don’t want to use either. I hope you weren’t looking for an easy answer because the answer depends upon what you are doing. There are four factors to consider:

  • API
  • Synchronization
  • Data growth
  • Usage patterns

Let’s explore each in turn.

API

In The Java Programming Language (Addison-Wesley, June 2000) Ken Arnold, James Gosling, and David Holmes describe the Vector as an analog to the ArrayList. So, from an API perspective, the two classes are very similar. However, there are still some major differences between the two classes.

Synchronization

Vectors are synchronized. Any method that touches the Vector‘s contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don’t need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It’s always best to set the object’s initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don’t know how much data you’ll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

Usage patterns

Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time — O(1). However, adding and removing elements from any other position proves more expensive — linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean?

It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time — O(1). However, indexing an element is a bit slower — O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.

Finally, in “PRAXIS 41” from Practical Java (Addison-Wesley, Feb. 2000) Peter Haggar suggests that you use a plain old array in place of either Vector or ArrayList — especially for performance-critical code. By using an array you can avoid synchronization, extra method calls, and suboptimal resizing. You just pay the cost of extra development time.

Why main method is public static in Java?

Main method in Java

Main method in Java is the first programming method a Java programmer knows when he starts learning Java programming language.have you ever thought about why main method in Java is public, static and void, of-course Yes, since most of us first learn C and C++ than we move to Java in our programming path we familiar with main method but in Java main method is slightly different it doesn’t return any value like in C it returns int, main method is public static and void Why? In this post we will try to find answer of these questions and have an idea of one of the most popular questions in Java why main method is declared Static.

What is main method in Java?

Main method in Java is entry point for any core Java program. Remember we are not talking about Servlet, MIDlet or any other container managed Java program where life cycle methods are provided to control the execution. In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[]) method in that class and if it doesn’t find that method it throws error NoSuchMethodError:main and terminates.

Signature of main method in Java
Main method has to strictly follow its syntax; other wise JVM will not be able to locate it and your program will not run. Here is the exact signature of main method
public static void main(String args[])
This signature is classic signature and there from start of Java but with introduction of  variable argument or varargs in Java5 you can also declare main method in Java using varargs syntax as shown in below example:
public static void main(String… args)
Remember varargs version of java main method will only work in Java 1.5 or later version. Apart from public, static and void there are certain keywords like final, synchronized and strictfp which are permitted in signature of java main method.

Why main method is static in Java

Now come to the main point “Why main method is static in Java”, there are quite a few reasons around but here are few reasons which make sense to me:
1. Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.
2. If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
3. Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
Why main mehtod is public in Java
Java specifies several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessible from outside of that class. Since main method is public in Java, JVM can easily access and execute it.
Why main method is void in Java
Since main method in Java is not supposed to return any value, its made void which simply means main is not returning anything.
Summary:
1. Main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.
2. JVM throws NoSuchMethodException:main if it doesn’t find main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.
3. Main method is entry point for any Core Java program. Execution starts from main method.
4. Main method is run by a special thread called “main” thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from main method is running.
5. When you see “Exception in Thread main” e.g.
Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.
6. You can declare main method using varargs syntax from Java 1.5 onwards e.g.
public static void main(String… args)
7. Apart from static, void and public you can use final, synchronized and strictfp modifier in signature of main method in Java.
8. Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature specified above.
9. You can use throws clause in signature of main method and can throw any checked or unchecked Exception.
10. Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.
Source  : Javarevisited

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

What are Marker Interfaces in Java?

An empty interface having no methods or fields/constants is called a marker interface or a tag interface. This of course means if the interface is extending other interfaces (directly or indirectly) then the super interfaces must not have any inheritable member (method or field/constant) as otherwise the definition of the marker interface (an entirely empty interface) would not be met. Since members of any interface are by default ‘public’ so all members will be inheritable and hence we can say for an interface to be a marker interface, all of its direct or indirect super interfaces should also be marker. (Thanks marco for raising the point. I thought it was obvious, but mentioning all this explicitly would probably help our readers.)

There are few Java supplied marker interfaces like Cloneable, Serializable, etc. One can create their own marker interfaces the same way as they create any other interface in Java.

Purpose of having marker interfaces in Java i.e., why to have marker interfaces?

The main purpose to have marker interfaces is to create special types in those cases where the types themselves have no behavior particular to them. If there is no behavior then why to have an interface? Because the implementor of the class might only need to flag that it belongs to that particular type and everything else is handled/done by some other unit – either internal to Java (as in the case of Java supplied standard marker interfaces) or an app specific external unit.

Let’s understand this by two examples – one in which we will discuss the purpose of a standard Java interface (Cloneable) and then another user-created marker interface.

What purpose does the Cloneable interface serve?

When JVM sees a clone() method being invoked on an object, it first verifies if the underlying class has implemented the ‘Cloneable’ interface or not. If not, then it throws the exception CloneNotSupportedException. Assuming the underlying class has implemented the ‘Cloneable’ interface, JVM does some internal work (maybe by calling some method) to facilitate the cloning operation. Cloneable is a marker interface and having no behavior declared in it for the implementing class to define because the behavior is to be supported by JVM and not the implementing classes (maybe because it’s too tricky, generic, or low-level at the implementing class level). So, effectively marker interfaces kind of send out a signal to the corresponding external/internal entity (JVM in case of Cloneable) for them to arrange for the necessary functionality.

How does JVM support the ‘cloning’ functionality – probably by using a native method call as cloning mechanism involves some low-level tasks which are probably not possible with using a direct Java method. So, a possible ‘Object.clone’ implementation would be something like this:-

public Object clone() throws CloneNotSupportedException {

 if (this implements Cloneable)

 return nativeCloneImpl();

 else

 throw new CloneNotSupportedException();

}

 

Anyone wondered as to why and when do we get ‘CloneNotSupportedException’ exception at compile-time itself? Well… that’s no trick. If you see the signature of the ‘Object.clone()’ method carefully, you will see a throws clause associated with it. I’m sure how can you get rid of it: (i) by wrapping the clone-invocation code within appropriate try-catch (ii) throwing the CloneNotSupportedException from the calling method.

What purpose does a user-defined marker interface serve? It can well serve the same purpose as by any standard marker interface, but in that case the container (the module controlling the execution of the app) has to take the onus of making sure that whenever a class implements that interface it does the required work to support the underlying behavior – the way JVM does for Cloneable or any other standard marker interface for that matter.

Defining an user-defined marker interface in Java

Let’s define a user-defined marker interface. Let’s say there is an app suporting a medical store inventory and suppose you need a reporting showing the sale, revenue, profit, etc. of three types of medicines – allopathic, homeopathic, and ayurvedic separately. Now all you need is to define three marker interfaces and make your products (medicines) implement the corresponding ones.

public interface Allopathic{}
public interface Homeopathic{}
public interface Ayurvedic{}

In your reporting modules, you can probably get the segregation using something similar to below:-

for (Medicine medicine : allMedicines) {
if (medicine instanceof Allopathic) {
//... update stats accordingly
}
else if (medicine instanceof Homeopathic) {
//... update stats accordingly
}
else if (medicine instanceof Ayurvedic) {
//... update stats accordingly
}
else {
//... handle stats for general items
}
}

As you can see the medicines themselves don’t need to implement any specific behavior based on whether they are allopathic, homeopathic, or ayurvedic. All they need is to have a way of reflecting which category they belong to, which will in turn help the reporting modules to prepare the stats accordingly.

Now this can be done by having a flag as well… yeah, sure it can be. But, don’t you think tagging a class makes it more readable than having a flag indicating the same. You kind of make it an implementation-independent stuff for the consumers of your classes. If your class implements an interface, it becomes part of the class signature of the published API. Otherwise, you would probably handle the situation by having a public final field having the flag set up at the time of instantiation – final because you would not like others to change it. I guess going the marker interface way would probably make more sense in many such situations.

Another advantage of going via marker interface way is that at any point of time you can easily cast the objects of the implementing classes. Again it’s not that if you go via public final approach, you can’t do that. You can very well do, but casting might look a cleaner approach in many situations.

The bottom-line is there will hardly be any enforced need for a designer/developer to go via that way as there can be possible alternatives, but marker interfaces can surely be a preferred choice for some in some cases.