Pages

Friday, January 6, 2012

Java Data Types



Java Data Types

  1. Integer
Name                    Width(in bits)                                              Range
long                      64                           –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int                         32                           –2,147,483,648 to 2,147,483,647
short                     16                           –32,768 to 32,767
byte                      8                              –128 to 127


  • Long : long is a signed 64-bit type and is useful storing a value that is beyond the range of integer. The range of a long is quite large which makes it an ideal choice for handling big values.

  • Int : The int is the most widely used numerical data types. The main reason behind it is that it very efficient in handling most of the values that a programmer needs. For example for using loops, if statements and other such tasks int is the first choice because of its range(–2,147,483,648 to 2,147,483,647) and memory occupancy. If there is an integer expression involving bytes, shorts, ints, and literal numbers, the entire expression is promoted to int before the calculation is done.

  • Short : Short is used for handling small numerical values. You can use it for storing any value that is between–32,768 to 32,767. This is the same range that int of C supports.

  • Byte :The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are especially useful when you’re working with a stream of data from a network or file. Java’s file handling mechanism uses this datatype extensively.


2. Floating-Point Types

Name                            Width(in Bits)                                        Approximate Range
double                                   64                                                 4.9e–324 to 1.8e+308
float                                      32                                               1.4e-045 to 3.4e+038

  • Float :Variables of type float are useful when you need a fractional component (decimal value), but don’t require a large degree of precision. For example, float can be useful in handling weight,price,temperature etc where accuracy to the last digit of decimal is not compulsory.

  • Double :  In complex mathematical calculations where the decimal value of even the last place is very important the double data type is used. Although it requires more memory than float its capability to handle large decimal value is very effective.
3. Characters : 
As we all know, everything is not numerical, there are many things that are alphabetical or symbolic in nature. The “char” datatype is used for store characters in Java. There is a difference between the char of C/C++ and of Java. In C/C++, char is an integer that occupies 1 bytes but Java uses Unicode to represent characters. Unicode is a international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits or 2 bytes. The range of a char is 0 to 65,536. Any value to be stored in a character must be enclosed within a pair of single quotations (‘ ‘). We can store capital or small alphabets, digits or any symbol in a char variable as long as its length is 1.

4. Boolean : 
Remember the “flag” variable that we use in C/C++ to mark the status of any event. It works as a true/false indicator for different conditions. You can use the same logic in Java also but apart from that Java has a different datatype known as “Boolean” that is used to store the values “true” or “false”. Since all the relational operators, such
as x>y return either true or false, we can use this datatype for handling such results.. boolean is also the type required by the conditional expressions that govern the control statements such as if and for.

Monday, January 2, 2012

Command Line Arguments

Command Line Arguments
There are certain conditions where the user is required to pass arguments while running a program at the command line. For example, in DOS to delete a file we use the command “del filename” at the “C:” prompt and the specified file is deleted. In this case “del” is the command or the action that we want to perform and “filename” is known as the “Command Line Argument”. It is a value that is passed as input to a program during its call.
          In Java, all the command line arguments are stored automatically in an array named “args[]” declared in the main(). When we pass a value at the command prompt it automatically get stored in the “args” array. Let’s see how arguments aare passed and processed in a Java program.

  • Create the following program
class prog3
{       
          public static void main(String args[])
          {
                   System.out.println(“Hello “ + args[0]);
          }
}
  • Save and compile the program as
     
    javac prog3.java
  • Run the program using the “java” interpreter and pass the command line arguments
     
    java prog3 Steve
  • The output of the program will be
     
    Hello Steve.
How does it work ?
This is quite simple, the value passed at the command prompt (Steve) is the command line argument. Java stores the value in a predefined array named “args”. Since only one value has been passed by the user, it is stored in the index no “0” of the array. The “System.out.println()” statement prints the value of the 0 index along with the “Hello” message. As I told earlier, you can change the name “args” to any other valid name.

Passing more the one arguments 
Let’s make another program that takes multiple values as command line arguments
  •  Create the following program
     
    class prog4
     
    {
     
            public static void main(String args[])
    {
     
                   String str1,str2;
                   Str1=args[0];
                   Str2=args[1];
                   System.out.println(“Hello ” + str1+ “ “ + str2);
          }
}
 
  • Save and compile the program as
     
    javac prog4.java
  • Run the program using the “java” interpreter and pass the command line arguments
     
    java prog4 Steve Jobs
The output this time will be
Hello Steve Jobs
 The Java compiler will store the first argument in the index 0 of the args array and the second argument in the index no 1. The “println()” statement is simply printing it along with the message “Hello”
Passing integer values as command line arguments
Now the question is, Since “args” is a String array will it be able to handle integer values? Or  Can I pass numerical values as command line arguments also? The answer to both the questions is YES.  As you know strings are capable of storing any type of value and numericals are no exception, it can also store the numerical values but before performing any arithmetical calculation to these values we will have to convert them to integer or double.
Take a look
class prog4
{
          public static void main(String args[])
          {
                   int a,b,c;
                   a=args[0];
                   b=args[1];
                   c=a+b;
                   System.out.println(“Sum is “ + c);
          }
}
  • javac prog4.java
  • java prog4 10 20
In the line “a=args[0]”, we are copying a string value (args[0]) to an integer variable (a), since this is not allowed, the program will return an error. To copy the value of a string to an integer, it must be first converted to integer using the function “parseInt”. Following is the corrected version of the same program where the values have been converted to integers before assigning their values to the integer variables.
 class prog4
{
          public static void main(String args[])
          {
                   int a,b,c;
                   a=Integer.parseInt(args[0]);
                   b= Integer.parseInt(args[1]);
                   c=a+b;
                   System.out.println(“Sum is “ + c);
          }
}
  • javac prog4.java
  •  
  • Java prog4 10 20
When this program is compiled you will the result 30 will be printed. The function “parseInt” is used to convert a string value to its integer equilvalent. The string values are converted into integer and copied to integer values. To convert a string to a double value use “Double.parseDouble” instead.