Pages

Showing posts with label simple java. Show all posts
Showing posts with label simple java. Show all posts

Monday, February 10, 2014

java version configuration in ubuntu

to set default java version in your machine type in the terminal,

sudo update-alternatives --config java

there you will get a prompt and then you can set it.

to set java home globally follow the instructions add the following lines in the .barshrc file which is located in the /home/yourusername/ directory

export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
PATH=$PATH:JAVA_HOME


Sunday, November 3, 2013

Java lambdas

Java lambdas is a powerful feature that comes with java 8. The idea is, this is an anonymous function( has no identifier) that can be passed as method parameters  (Bit like javascript functions that can be passed as arguments to a function).  These are also called first class functions. An article on explaining this concept can be found here.

http://java.dzone.com/articles/java-lambda-expressions-basics

Tuesday, October 29, 2013

Handling collections in java

Recently I was wondering about how java handles collections and the existing opensource java libraries to handle this scenario. Common alternatives to java collections framework are
  1. Apache commons
  2. Guava
  3. PCJ
  4. Trove
Number 1 and 2 alternatives are more popular among developers while 3 and 4 are not mentioned frequently (They are for primitives).  3 and 4 provide more performance compared to Java collections framework. Guava can be used in most cases while it seems like using this library is bit complex but at the same time it reduces many bottlenecks present in the collections operations.

Having mentioned all these libraries, one should also note that if your app does not demand handling complex collection operation, lots of data to be stored in a collection, java collections framework itself is more than adequate.

Below is a nice article that analyze the above topic in detail

http://stackoverflow.com/questions/629804/what-is-the-most-efficient-java-collections-library


Monday, October 21, 2013

java thread pool example

Do you have multiple jobs to execute using a pool of threads and need to know how to do it gracefully? See the link below to know how it can be done using executors and thread pool executors.

http://www.javacodegeeks.com//2013/01/java-thread-pool-example-using-executors-and-threadpoolexecutor.html

Wednesday, October 3, 2012

Using third party library and how to handle exceptions?

I think most of you must have come across situations where you need to use third party classes and you need to do some changes. Sometimes you can do this by decompiling the .class file then modifying it. The point is it works some times. But not always. Specially when the code is  obfuscated, chances are very low of decompilling correctly. So how can you overcome this? Well the most suitable method to do this is to use a wrapper class that extends the third party class.

Eg;
///this is the third party class
public class SomeLibrary{
     public void readBook(){

     }
}


Now you can write the wrapper class like this.

Sunday, September 23, 2012

what's the difference between forward and sendRedirect?

forward happens in server and does not make the browser to redirect.
sendRedirect actually redirects the browser and makes another httpRequest.

Saturday, September 8, 2012

what is java internationalization

In general internationalization in making the software usable by multiple languages. By using this we can make application to support languages like english, french, latin etc...

The way to tackle this problem is to use  .properties file.

The link below provides a nice simple tutorial on how to do this.

http://www.roseindia.net/java/example/java/swing/internationalization.shtml

Sunday, August 26, 2012

Java Persistence API

What is persistence?

The general objective of persistence is to increase the life span of an object. This could be done by storing it in a disk, file etc... One simple method is to store the object in xml format. Another way of implementing the persistence is to use the databases.

Why do we need JPA?

If you consider about databases, usually it is used in the form of tables that are related in the traditional relational methods. How ever on the other hand objects are entities that has states and can invoke methods that makes it unique. So there is some conflict in objects way of keeping data and keeping data in databases.  JPA is introduced to fulfill this inadequacy.

Java Persistence

The Java Persistence Architecture API is a java specification for accessing, persisting, managing data between java objects, classes and databases. It is considered as the industry approach for object relational mapping (an ORM). That is it helps to retrieve data from the data in the form of java objects. This simplifies the life of a java developer significantly. 

However JPA  is a standard for the java persistence. Probably most of you must have heard about hibernate. Hibernate is a vendor implementation of the JPA and addition to that it provides some additional non JPA facilities as well.

Friday, August 24, 2012

proxy design pattern using java

what is proxy design pattern?
It is a design pattern that uses a proxy to control access to another object. What is the meaning of proxy? It means acting something on behalf of something. In this case, the client access an object through proxy.
So to what kind of objects do we need to provide a proxy?
Usually for objects that takes a lot of memory, files, resources that are expensive or hard to duplicate.

Below a simple implementation of the proxy design pattern.

Interface Game{
   void playGame();
}

public RealGame implements Game{

    private String game;

    public RealGame(String game){
         this.game = game;
         loadGame(game);
    }

    private loadGame(String game){
           System.out.println("loading game : "+game);
    }

    public void playGame(){
         System.out.println("playing game: "+ game);
    }
}

public ProxyGame implements Game{

     private RealGame game;
     private String gameName;
     public ProxyGame(String game){
         this.game = game;
   }
 
   public void playGame(){
      if(game==null)
           game=new RealGame(gameName);
      }
      game.playGame();
}



public DemoProxy{

   public static void main(String[] args){
       Game proxyGame = new ProxyGame("modern warfare");
        proxyGame.playGame();
   }
}

Thursday, August 23, 2012

Facade Design pattern in java

Facade design pattern is a pattern that is used to provide a simple interface to a large amount of code. This makes it very easy to use libraries in programming language. The following example is taken from http://en.wikipedia.org/wiki/Facade_pattern.


/* Complex parts */
class CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}

class Memory {
public void load(long position, byte[] data) { ... }
}

class HardDrive {
public byte[] read(long lba, int size) { ... }
}

/* Facade */

class Computer {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public Computer() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}

public void startComputer() {
cpu.freeze();
memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
cpu.jump(BOOT_ADDRESS);
cpu.execute();
}
}

/* Client */

class You {
public static void main(String[] args) {
Computer facade = new Computer();
facade.startComputer();
}
}

Tuesday, August 21, 2012

serialize and deserialize an object with java

We usually use serialization, when we need to store an object with the state to a storage medium so that we can use it later or when we need to transfer an object through the network.
Now lets see how to serialize an object to a file.


ObjectOutputStream o = new ObjectOutputStream(new             FileOutputStream("file.ser"));//saving to a file named file.ser
o.writeObject(ObjectToSerialize);//writing the object
o.close();

Now lets see how to deserialize the saved object.


        FileInputStream fileIn =
                          new FileInputStream("file.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
        try {
            dictionaryMap = (ObjectType) in.readObject();//add cast
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Dictionary.class.getName()).log(Level.SEVERE, null, ex);
        }
            in.close();
            fileIn.close();

Saturday, August 18, 2012

How to install tom cat on ubuntu

You can do this in two ways.

  1. Install using : sudo apt-get install tomcat7
  2. You can Install manually which is straight forward. download tomcat 7 binaries from http://tomcat.apache.org/ and extract it to a location you want and go to the bin folder in your extraction using the terminal.  Then type
                                                                             sh startup.sh : to start the server 
                                                                             sh shutdown.sh : to down the server

after you start up the server, you can access the server at the port 8080 (which is the default port for tomcat).

How ever the tomcat server is some what considered light weight compared to servers like glassfish, jboss etc... Therefore if you consider having a server with all the capabilities and features of java, it is better to use a server like glassfish.

Unit testing with java.

First question is what is unit testing?
Well unit testing is a code written by a programmer to test a specific functionality of a program.

Now the question is how can we do this in java? 
There are some libraries in java that helps unit testing. How ever the most popular and the common library used is the JUnit. Actually it is a framework that uses annotations to identify the test methods. Also one thing to remember is JUnit assumes that the tests can be conducted in an arbitrary order. That is the tests we write should not depend on each other.

Setting up JUnit.
You can download JUnit from http://www.junit.org/ and add the junit.jar to your project and classpath.

Using Junit
Create a java project using eclipse. Then right click on the project and create new->source folder and name it as test.
Now create a package inside the src folder and create a class named MyClass inside the package.

Enter the following code inside the MyClass.

public int divide(int x, int y) {
   return x * y;
 }

Now right on the MyClass file and create new->JUnit Test. change the path from src to test in the screen you get after choosing JUnit Test in the menu. Name the file to MyClassTest. Now click next and choose the methods to be tested. click finish.

Now you will see a class called MyClassTest inside test folder. You will see something like below in the class.


@Test
public void testDivide() {

}

Now put the following code inside your testDivide method.


 MyClass tester = new MyClass();
assertEquals("Result", 2, tester.divide(10, 5));

Now right click on the MyClassTest file and run as junit test. You will see a red bar as the result. This is because the result should be 2 but it returns 50. Now correct the code in divide method inside MyClass and rerun the unit test. You will see a green bar. That means the test is ok.

You can create a test suit also. That is you can select several tests and run all the selected methods.


 Now select the Test classes and right click on it. Then new->other and then use Junit ->test suit. Fill the parameters according. After finishing, you will see the Test suit class is created. If you run the file, all the mentioned tests will be run.

Now lets see how you can run tests using your code.
create a class called MyTestRunner inside the test source folder. Then put the following code inside it.

public static void main(String[] args) {
   Result result = JUnitCore.runClasses(MyClassTest.class);
   for (Failure failure : result.getFailures()) {
     System.out.println(failure.toString());
   }
}

Now you will see if there are any errors in the test.

There are some annotations like @Test , @Before, @After, @AfterClass , @BeforeClass, @Ignore, @Test(timeout=100) , @Test(expected=Exception.class). Google and find what these annotations are used for.



Sunday, August 12, 2012

What is a java factory method ?


Java Factory Method is a creational design pattern used by java developers. what it basically does is it instantiates objects from a set of classes by considering a certain logic. That is creating an object without specifying the exact class of object that will be created. This is quite simple. Let's see how we can do this.

Say for an example we have a shape interface

public interface Shape{
      void drawShape();
}

Now lets say we have two classes that implement the interface called Triangle and Square.


public class Triangle implements Shape{

      public void drawShape(){
         System.out.println("drawing three points and joining them");
     }
}



public class Square implements Shape{

      public void drawShape(){
         System.out.println("drawing four points and joining them");
     }
}

Now lets create the ShapeFactory class that is used to instantiate a shape.

public class ShapeFactory{

    public Shape getShape(int numberOfEdges){

               if(numberOfEdges==3)
                     return new Triangle();
               if(numberOfEdges==4)
                     return new Square();
          return null;//just to make the compiler happy ;)
    }
}


Now let's see how to create a new square or a triangle. create a new class ShapeManager.

public class ShapeManager{

    public static void main(String[] args){
           ShapeFactory factory = new ShapeFactory();
           Shape triangle = factory.getShape(3);//note that the object will be a triangle since the //parameter is 3
    }
}


This is simply what happens in a factory method. You do not directly call "new"
 key word to create an instance of shape. Instead you use a factory method to get an instance.

Java UnsupportedClassVersionError

This exception is most likely to be thrown when you compile the program from one version of java and running it on another version of java.
Eg : You compile the code using jdk 7, 6 etc... and run on version 4.

Wednesday, August 8, 2012

How to operate with big integer, big decimal

Sometimes the range of long, double  etc... becomes inadequate for certain mathematical operations. So  java provides a way to handle this problem by introducing BigInteger and Bigdecimal. These are very useful when the programmer needs to calculate big values.  Below examples shows how to work with big integer and big decimal.

First lets see an example of big integer.

BigInteger b1  = new BigInteger("293847293847938798");

BigInteger b2  = BigInteger.valueOf(1298L);
b1 = b1.add(b2);
b1 = b1.subtract(b2);
b1 = b1.multiply(b2);
b1 = b1.divide(b2);
b1 = b1.negete();

int exponent = 3;
b1=b1.pow(exponent);

Now lets see an example of big decimal.

Bigdecimal b1  = new Bigdecimal("348950394.943859438");

Bigdecimal b2  = Bigdecimal.valueOf(1298L);

b1 = b1.add(b2);
b1 = b1.subtract(b2);
b1 = b1.multiply(b2);
b1 = b1.divide(b2);
b1 = b1.negete();

Saturday, July 28, 2012

java apache commons logging

apache commons logging focuses on all aspects of reusable Java components.
It contains 3 main parts




  • The Commons Proper - A repository of reusable Java components.
  • The Commons Sandbox - A workspace for Java component development.
  • The Commons Dormant - A repository of components that are currently inactive.
  • Friday, July 27, 2012

    computational reflection

    Java is a programming language that has the computational reflection. That is it has the ability to examine and modify the structure of the program at run time. The package java.lang.reflect has the above mentioned facility.

    Tuesday, July 24, 2012

    Java How to change jvm memory settings.


    If you a using ecplise then you can set memory settings for a particular applicartion by simply setting VM arguments in it's run configuration as
    -Xms128m -Xmx512m. 
     In this particular  instance -Xms means the minimum memory and it is 128mb. -Xmx is maximum memory and it is 512mb.

    If you want to change the memory in system jvm then simply run java command in a terminal with -Xms281m -Xmx512m parameters given that the class path variable is set.