Loading

Pages

Thursday, February 21, 2013

How To Create An Executable Jar File With Eclipse

Here is how to create an executable jar with eclipse.

1) Create a Java project and create a main class.

2) Select the project and click on Run->Run Configurations... menu. From the left
   panel of the Run Configurations dialog, double click on Java Application.
   Specify the main class for the configuration, click  Apply  followed by Close.



3) Select File->Export... menu. In the Export dialog, select Java->Runnable Jar File. Click Next.


4) From Launch Configuration drop-down, select the Launch Configuration
    created in step 2.In Export Destination box, specify the file name for the
    exported jar file.


5) To test the exported jar file run the following command from the folder where the
   jar file is saved:
   java -jar filename.jar
  Replace filename.jar with the same file name specified in step 4. 

  








How To Write A Simple Command Line Program In Java

Here is a simple program to process command line arguments in Java.

 public class CommandLine {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           if(args.length>0&&args.length%2==0){  
             for(int i=0;i<args.length;i+=2){  
                  if(args[i].equals("-f")){  
                      System.out.println("Input File Name is : "+args[i+1]);  
                  }else if(args[i].equals("-o")){  
                       System.out.println("Output File Name is : "+args[i+1]);  
                  }  
             }  
           }else{  
                if(args.length>0){  
                 System.out.println("Mismatched arguments");  
                }else{  
                 System.out.println("No arguments specified. Exiting...");       
                }  
           }  
      }  
 }  
Execute as :

java CommandLine  -f C://abc/input.txt -o C://abc/output.txt

Output:

Input File Name is : C://abc/input.txt
Output File Name is : C://abc/output.txt





Wednesday, February 20, 2013

How To Print Contents Of A File In Java

The following program shows how to use FileInputStream and BufferedReader to print contents of a file in Java.

 import java.io.BufferedReader;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 public class PrintContents {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           BufferedReader br = null;  
           String str = null;  
           try {  
                br = new BufferedReader(new InputStreamReader(new FileInputStream(  
                          "C://abc/cde.txt")));  
                while ((str = br.readLine()) != null) {  
                     System.out.println(str);  
                }  
           } catch (FileNotFoundException e) {  
                e.printStackTrace();  
           } catch (IOException e) {  
                e.printStackTrace();  
           } finally {  
                try {  
                     if (br != null) {  
                          br.close();  
                     }  
                } catch (Exception e) {  
                     e.printStackTrace();  
                }  
           }  
      }  
 }  

How To Keep The Order Of Elements In A Java Map

The normal HashMap does not guarantee the insertion order of entries. If maintaining the insertion order is important, use the LinkedHashMap instead.

Sample:
import java.util.HashMap;  
 import java.util.LinkedHashMap;  
 import java.util.Map;  
 public class LinkedHashMapTest {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Mapmap=new HashMap();  
           map.put("ONE","1");  
           map.put("three","3");  
           map.put("FIVE","5");  
           map.put("seven","7");  
           System.out.println("Output from HashMap:");  
           for(Map.Entryentry:map.entrySet()){  
                System.out.println(entry.getKey()+":"+entry.getValue());  
           }  
           System.out.println("\nOutput from LinkedHashMap:");  
           MaporderedMap=new LinkedHashMap();  
           orderedMap.put("ONE","1");  
           orderedMap.put("three","3");  
           orderedMap.put("FIVE","5");  
           orderedMap.put("seven","7");  
           for(Map.Entryentry:orderedMap.entrySet()){  
                System.out.println(entry.getKey()+":"+entry.getValue());  
           }  
      }  
 } 
 
Output from HashMap:
seven:7
ONE:1
three:3
FIVE:5

Output from LinkedHashMap:
ONE:1
three:3
FIVE:5
seven:7 

Tuesday, February 19, 2013

Keeping Or Removing All Elements Of Another Collection From An ArrayList

All elements of a collection can be removed from a list using the list.removeAll(Collection<c>another) method. Similarly, to retain all elements of another collection in a list use list.retainAll(Collection<c>another).

Sample:
import java.util.ArrayList;  
 import java.util.List;  
 public class ArrayListTest {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Listlist1=new ArrayList();  
           Listlist2=new ArrayList();  
           list1.add("ONE");  
           list1.add("TWO");  
           list1.add("THREE");  
           list1.add("FOUR");  
           list2.add("TWO");  
           list2.add("FOUR");  
           list1.removeAll(list2);  
           System.out.println("Items in list1 after removing list2 items: "+list1);  
           list1.add("TWO");  
           list1.add("FOUR");  
           list1.retainAll(list2);  
           System.out.println("Items in list1 after retaining all list2 items: "+list1);  
      }  
 }  

Output:

Items in list1 after removing list2 items: [ONE, THREE]
Items in list1 after retaining all list2 items: [TWO, FOUR]


Friday, February 15, 2013

Why Programming Requires Patience and Perseverence

If there is anything that distinguishes programming from many other careers, it is innovation and continuous learning.

You are always trying to solve something, most of the time using methods you have never used before.And that is what makes it interesting . The sense of achievement when you finally arrive at a solution for something that has been engaging your mind for days or weeks has to be experienced.

It is not joy and achievement all the time. Programming has its fair share of disappointments, failures and uncertainties. When the project is running out of schedule, and you are stuck at something and don't even know there exists a solution, it is not going to make anyone happy.

The problem with many programmers is that they stop learning once they become settled in an area of comfort. Of course, with so many technologies and frameworks around, it has become difficult to keep pace with all developments. But if you spend some time regularly to learn new things,it can go a long way in making you a better programmer. Nobody becomes a master in a day or two. You might say "What is so great about language X or framework Y, I can learn them in 2 days". Learning the syntax and printing "Hello world " is one thing, and using the language or framework to solve real world problems is another thing. You may be able to learn all the syntax and some API of a new technology, but to use it properly for solving real world problems requires time and patience.

Learning a computer language is much like learning any other language. You can't master any language in a day. You can learn the meaning of words by looking up in a dictionary, and for styles, idioms and grammar you can pick up some good books on the topic.,But that does not make you a writer overnight. It requires several years of effort to master a language.Same with computer languages. Picking up a "Dummies" book and spending a few hours is not going to make you an expert, but don't be disappointed, that is surely the first step.

Thursday, February 14, 2013

Find An IDE And Enjoy Programming

You can do quite a lot of programming with just an editor (Some programmers prefer editors to IDEs). A number of editors come with syntax highlighting for multiple languages, tabbed editing and a host of other features. Textpad, Notepad++ etc. are quite useful for small programs.

So far I have used Visual Cafe, Netbeans, JCreator, IntellijIDEA and Eclipse .I instantly fell in love with eclipse and have been using it for the last 8 years. For java development it is one of the best IDEs in the market and has many useful plugins.

What makes a good IDE?.

Here are some features I find important:
1) A good help system
2) Context sensitive help
3) CVS/SVN integration.
4) Debug support.
5) Wizards for creating projects and resources.
6) Refactoring support.

Extensibility is something desirable and most of the IDEs have support for plugins.

Most people choose an IDE and stick with it. So find an IDE for your language and enjoy programming.

An Excellent IDE for PHP

Netbeans provides excellent support for PHP development. Download the latest version from http://netbeans.org/.

Here is the IDE in Action:


Wednesday, September 19, 2012

Java Tutorial Part2 - Hello World

In comparison with some of the languages you may be familiar with, Java hello world needs more lines of code and would seem verbose.

Here is how we can print the customary "Hello World" in some scripting languages:

Ruby:
puts "Hello World";

PHP:
<?php 
 Print "Hello World";
?> 

Perl:
print "Hello World"; 

Python:
print "Hello World" 

Now, let us see the Java version.

public class HelloWorld{
  public static void main(String []args){
     System.out.println("Hello World");
  }

}

Do the following steps to compile and run the Java version.

1)Type the above Java code in your favourite editor and save it as HelloWorld.java. This is our source file.

2)From command line/shell go to the folder where you saved the file and type
   javac HelloWorld.java.  A new file  HelloWorld.class is generated in the
  same folder as the source file.

3)Execute the program by entering  java HelloWorld at the command prompt.

You should be able to see the output now.

Java Tutorial Part1-Setting Up The Java Development Environment

This is the first step we need to take before starting on our journey. Set up the
Java Development Environment. Java programs run inside the
JVM(Java Virtual Machine). Java compiler(javac) converts Java programs into an
intermediate bytecode format called class files, which is platform independent.

The latest JDK can be downloaded from the following link:

Download the 32/62 bit version of the JDK for your OS(Linux, Windows or Mac) and follow the installation instructions .

Once the installation completes successfully, we are ready for the next step.

Tuesday, September 18, 2012

Java Tutorial -Introduction

You may be new to programming or you may already have some experience in scripting languages like Perl or PHP and want to learn an object oriented programming or you may be already familiar with C, C++ etc, and  now want to try  Java also- whatever be your background, we can help you. We will take you through a series of lessons on Java to give you a good understanding of the language. Let's get started with Part 1 .


Tuesday, January 31, 2012

How To Concatenate Strings In Java

StringBuilder and StringBuffer classes can be used to concatenate strings. The difference between the two is that StringBuffer is thread-safe while
StringBuilder is not. In practice you will be using StringBuilder most of the
time.

public static void main(String[] args) {

StringBuilder builder=new StringBuilder();
builder.append("ONE");
builder.append(" TWO");
builder.append(" THREE");

System.out.println("Concated :"+builder.toString());

StringBuffer buffer=new StringBuffer();
buffer.append("FOUR");
buffer.append(" FIVE");
buffer.append(" SIX");

System.out.println("Concated2 :"+buffer.toString());

}

Saturday, October 23, 2010

Handle nulls with care

We all have ignored nulls at some point of time without considering the consequences. Most often newbie programmers are more prone to making this
mistake since they assume the value will be there or they don't bother to
check if null can be one of the possible return values of a method.This
often results in disaster at the most unexpected time.

Here are some typical scenarios when one could miss the null checking.

1)Null checking on collections returned by method calls.

 List<String>getCustomers(Long acId){
   ...
   ...
   if(noCustomers){
      return null;
   }
 }



If code uses the the above method as follows.

List<String>customers=getCustomers(10);
if(!customers.isEmpty()){//throws NPE when getCustomers()returns null.

}


2)Wrong order of null checking.

if(!customers.isEmpty()&&customers!=null){

}


3)null Strings
String value=getFromSomeMethod();
if(value.equals("TEST")){ 
  
}


A quick way to fix the above is to rewrite it as follows:

if("TEST".equals(value)){
  
}

4)Forgetting to assign a default value.

String value=null;
  
if(condition1){
   value=getSomething1();
}else if(condition2){
 value=getSomething2();
}

value can still be null.Assign a default to avoid further null checks and
exceptions.

 if(value==null){
   value="";//default.
 }

Find Duplicates Using Java.util.HashSet

Here is an example to find duplicates in strings using Java.


import java.util.HashSet;
import java.util.Set;


public class Duplicates {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
        Set<String> set=new HashSet<String>();
        Set<String>duplicates=new HashSet<String>();
        String inputs[]={"ONE","one","TWO","ONE","ONE","THree","two","TWO"};
        for(String input:inputs){
           if(!set.add(input)){
              duplicates.add(input);
           }
        }
        for(String item:duplicates){
            System.out.println(item);
        }
    }

}

Friday, July 11, 2008

Debugging applets from eclipse

Here is how to debug the applet from eclipse.
First configure the jdk plugin for debugging
1)From settings/Control Panel select Java-Plugin(Java-plugin control panel)
2)In the advanced tab under java Runtime Parameters
paste the following line Djava.compiler=NONE -Xnoagent -Xdebug - Xrunjdwp:transport=dt_socket,address=9999,server=y,suspend=n address can be any valid port .
Now in eclipse select debug from the run menu.
1)Create a debug configuration for applet under Remote Java Application
2)Specify host and port(port is same as the value of address in the java-plugin configuration.
3)To allow termination of debug session from eclipse,check the allow termination of remote vm.
Now load the applet in the browser first.Then from eclipse start the debug session.

Tuesday, July 1, 2008

Furure plans for this site

Technical articles, tutorials, book reviews, code samples
and useful links for programmers.