Monday, January 12, 2009

How to accept inputs from user while running java program

There are different waysm through which we can pass input value while java program is running.In the below example, i have used java.util.Scanner class for the same.

One of the main reason for using Scanner class is, it actually allows user to pass primitive data types such as integers etc.

Here you dont have to pass the argument while call the java class file, here user will be asked to enter input when actually inputs are required.

I am explaining  in terms of layman point of view so that it will be easier to understand.

Here is the code:
JavaScanner.java
--------------------
import java.util.Scanner;

/*
Author: Anaparthi Subrahmanyam
Published: 01-13-2009
*/
public class  JavaScanner
{
  public static void main(String[] args) 
  {
    Scanner scanner = new Scanner(System.in);
    try
    {
      System.out.println("Value 1");
      int int1 = scanner.nextInt();
      System.out.println("Value 2");
      int int2 = scanner.nextInt();
      System.out.println("Sum");
      System.out.println("---------- Sum-------------");
      System.out.println(int1+int2);
      System.out.println("---------------------------"); 
    }
    catch (Exception e)
    {
      System.out.println("Error in input");
      e.printStackTrace();
    }
  }
}
--------------------



Sunday, January 4, 2009

Tips for String comparison in Java

Whenever we compare two strings objects in java, we normally consider both string arguments with qual importance and ignorance.I like to suggest one tip here which may be helpful for you in avoiding to generate a silly error, which looks terrible :)

I have two String objects as Str1 and Str2

Now i will compare two strings mentioned above for comparison, both may contain same value or may be having different values.

I have two options to write a conditional statement using equals opertator :

Type 1:
 if(Str1.equals(Str2))
  ...............
  ...............

Type 2:
 if(Str2.equals(Str1)) 
  ...............
  ...............

Which one you prefer.. i came across so many people explaining that its not that important to prefer which one i will opt for , as both produces same result.
Here i want to suggest you to analyze your code little bit, and reach a point where you can say, which String object cannot be null.If you found Str1 cannot be null , then use Str1.equals(Str2) , i.e. compare Str2 with Str1 , keeping Str1 at first place.
Reason for saying this is , if you are calling the equals method of the String object containing null value then it will through java.lang.NullPointerException.

So just by following a simple approache, you can avoid an exception.

There is another place where you can use this:
Whenever you are comparing a Constant String Object with a Dynamic String Object i.e. a string object which can contain different value while in the process of any kind. Please see the example mentioned below:-

String constant = "ENTRY_X";
Now i have a dynamic string object as dynamicStr, about whihc i am not sure, what type of value it can contain, then i will use:
if(constant.equals(dynamicStr))
........
.......

or 

if("ENTRY_X".equals(dynamicStr))
........
.......


This way i am avoiding the NullPointerException.
Its a very small tip, but i found this usefull information for all.
Please provide your comments if any.

If you liked my post, linking to this post will be highly appreciated.

Saturday, December 27, 2008

how to create user defined Objects in Javascript

I am really a fan of javascript as it is quite easy as well as complex. 
Here is the example of how to create objects in javascript i.e. User defined objects which is very usefull in handling large amount of data from the inout forms controls quite nicely.






How to retrieve System Properties in Java

Here is the example of retrieving the System Properties through Java Code. In this program I have retrieved and displayed few System Properties.

The primary method which actually retrieves the property is System.getProperty(), and it takes key info as a parameter.

For details of all the System Properties and how it can be retrieved, you can visit my earlier post about
How to retrieve System Properties through Java. You can generate the XML file of all the key-value pair of the properties and then you can use any if the key's from the XML file, in the below program to get the info in Java Code.

RetrieveSystemProperties.java
----------------------------

public class RetrieveSystemProperties
{

/*
File : RetrieveSystemProperties.java
Purpose: Retrieves and displays the System Property details
Author : Anaparthi Subrahmanyam
Published: 2008-12-27
Usage Notification: Author doesnt own responsibility of any loss of data,
responsibility for misuse or loss of any nature if this code is used. If possible,
please provide link to this webpage
*/
public static void main(String[] args)
{
try
{
/*
the below functions will retrieve the System Properties of the System
*/

// retrieving Operating System Name of the machine
System.out.println("Operating System Info: "+System.getProperty ("os.name"));

// retrieving Unicode Encoding
System.out.println("Unicode Encoding Info: "+System.getProperty ("sun.io.unicode.encoding"));

// retrieving User Language
System.out.println("Operating System Info: "+System.getProperty ("user.language"));

// retrieving Operating System Name of the machine
System.out.println("User Language Info: "+System.getProperty ("sun.management.compiler"));

// retrieving Desktop Information
System.out.println("Desktop Info: "+System.getProperty ("sun.desktop"));

// retrieving Sun Compiler name
System.out.println("Sun Compiler Info: "+System.getProperty ("sun.management.compiler"));

// retrieving Operating System patch level
System.out.println("Patch Info: "+System.getProperty ("sun.os.patch.level"));

// retrieving File encoding package
System.out.println("File encoding package Info: "+System.getProperty ("file.encoding.pkg"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
----------------------------

Please provide your comments, i will really appreciate it.

How do I retrieve the System Properties on Windows Machine using Java

There are different ways to get the System properties of a System or Machine using Java Program. 
The following code first create a file called SystemProperties.xml and then retrieves all the System Property using Java's own function called getProperties() of Properties class and finally dumps it to the the created XML File.

SystemProperties.java
--------------------------------------------
import java.util.Properties;
import java.io.PrintStream;
import java.io.File;

/*
  File   : SystemProperties.java
  Purpose: Dumps all the System Properties and values to a XML file
  Author : Anaparthi Subrahmanyam 
  Published: 2008-12-27
  Usage Notification: Author doesnt own responsibility of any loss of data, responsibility for misuse or loss of any nature if this      code is used. If possible, please provide link to this webpage
*/

public class SystemProperties 
{
  public static void main(String[] args) 
  {
    try
    {
       File f = new File("SystemProperties.xml");
       //if creating a file called SystemProperties.xml, if returns false, exception will be thrown
       if(!f.createNewFile())
       {
          throw new Exception("Exception encoutered may be due to the file already exist.");
       }
       Properties prop = System.getProperties();
       // opening file in print stream so that later this stream will be used to write 
       PrintStream pst = new PrintStream(f.getName());
       // Passing three parameters to the storeToXML.
       //1. printstream
       //2. Comment to the XML File 
       //3. encoding format
       prop.storeToXML(pst,"System Properties details", "UTF-8");
       System.out.println("Sucessfully dumped the System Details to the file: " +f.getName());
    }
    catch (Exception e)
    {
      System.out.println("Error: "+e.getMessage());
    }
   }
}
-----------------------
Please provide your comments.

If you like this content please provide a link of this page on your page.


Friday, December 26, 2008

Details about installing java on different Operating Systems

Sun Microsystems has provided a very nice page providing all the details about steps and links for How to Install Java and also provided  links of different JDK’s for various operating systems.

 Here is the Link : http://www.java.com/en/download/manual.jsp

How do i verify whether an URL is active or not through Java

There are different ways in java through which we can verify whether any specific URL is active or not.
Here is the Java Program which displays success message if the URL is active and Failed message if URL is not active/dead.

URLVerification 
----------------
import java.net.*;
import java.io.*;

public class URLVerification {
    public static void main(String[] args) throws Exception {
        URL url_to_verify = new URL("http://www.google.com");
        try
        {
          URLConnection connObj = url_to_verify.openConnection();
          connObj .connect();
          InputStream stream_to_recieve_data = connObj .getInputStream();
          stream_to_recieve_data.close();  
          System.out.println("Successful in establishing connection.");
        }
        catch (Exception e)
        {
          System.out.println("Failed in establishing connection.");
        }
    }
}
-------------------
I also want to share the few scenarios where we can use this such as:

1. You have to write a code which will call a specific URL to get data after each interval
2. Before Sending request , you can write a filter to verify whether the url is active or not.
3. Directly you want to call a servlet/jsp through a java program to get the status 

I hope my above comments will help you to come up with new ideas as well.

Please provide comments if any...