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.

Thursday, December 29, 2011

Basic Addition Program

Another Basic Example
1. Open the editor, and type the following code


class prog2
{                 
                  public
static void main(String args[])
                       {

              int a,b,c;
              a=10;
              b=20;
              c=a+b;       
              System.out.println(“Sum is “ + c);
     }
}

2. Compile the program using the command “javac prog2.java
3. Once it is compiled use the “java prog2” statement to run it.
4. The output “Sum is 30” is displayed on the screen.

How does it work ?
The program declares 3 integer variables namely a,b and c. The values of a and b are initialized to 10 and 20 respectively. The value of “c” is calculated as “a+b” and the result is printed using the statement “System.out.println()”. In the statement – “Sum is + c”, the “+” is working as a concatenation operator not as an arithmetic addition operator.

Don't forget
  1. To open the command prompt to compile and run the program.
  2. To name the program file as " prog2.java"(just in this example), because the name of the program and class should be the same.

Tuesday, December 27, 2011

How does it work ?


How does it work ?
  • Compiling the program : To compile a program we have to use the statement javac prog1.java (where “prog1.java” is the name of the Java program)

Java Program Compilation Process
This statement invokes the Java compiler, javac and compiles the program. As a result of this compilation a new file having the name “prog1.class” is created. This “.class” file has something known as the “Java Bytecode”. Byte codes are a set of instructions that looks a lot like some machine codes, but that is not specific to any one processor. There is huge difference in the way programs are compiled in Java or other languages like C or C++. In other languages when you compile a program it is translated by the compiler into the machine code or what we called machine language. This machine language contains the processor specific instructions on how to run the program on a specific computer. For example, if you compile your program on a Pentium system, the resulting program will run only on other Pentium systems. If you want to use the same program on another system, you have to go back to your original source, get a compiler for that system, and recompile your code. But this is not the case with Java.
In Java, the compilation phase is divided into two stages. First the program is compiled using the “javac” command and then the program is executed using the “java” command that invokes the Java interpreter.
The Java development environment has two parts: a Java compiler and a Java interpreter. The Java compiler converts the source code into the Byte code.
Having your Java programs in byte code form means that instead of being specific to any one system, your programs can be run on any platform and any operating or window system as long as the Java interpreter is available. This capability of a single binary file to be executable across platforms is crucial to what enables applets to work, because the World Wide Web itself is also platform independent.

 A closer look at the program
  •     class prog1 {

The keyword “class” denotes that a new class is being defined whose name is “prog1”. The body of the class is enclosed within the pair of curly braces – { }.
  •     public static void main(String args[]) {The above line starts the definition of the main(). As you are aware that the main() marks the beginning of the program. All java applications (except Applets) must have a main() which make them executable.

  •   The public keyword is an access specifier, which allows the programmer to control the visibility of class members. There are three access specifiers - private, public and protected. When a class member (variable or method) is preceded by public, it denotes that member can be accessed from outside the class in which it is declared. Since main() is required to be called from outside of its class it must be declared as public.

  •  As you know, a class must instantiated in order to use it members but you can see that there is no object of the class “prog1” declared. The keyword static allows main() to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made.
  • The keyword void simply tells the compiler that main() does not return a value. If a function returns a value the “void” keyword is replaced by the type of value that it will return.
  • The “String args[]” is an array of type String that is used to store command line arguments. Command line arguments are the values that are passed to a Java program while running it. Java automatically stores the arguments in the array “arr”. Of course you can change the name of the array from “arr” to any other name but it has become a standard practice for Java programmers the world over to use this name. When the user passes some values, args stores the first value in index no 0, second value to index no 1 and so on.
  •  The last character on the line is the {. This signals the start of main( )’s body.
  • Inside main(), there is a statement

System.out.println("This is a simple Java program.");

This line prints the string “This is a simple Java program.” followed by a new line on the screen. You can also use the command “System.out.print()” instead of “System.out.println()” , if you want the output to appear on the same line. You can also say that “println()” is somewhat similar to “\n” of C or “endl” of C++.

Saturday, December 24, 2011

Your First Java Program

First Java Program - Using an Editor 

So you are ready to start with your first Java program. Here is a step by step procedure to create your first Java program in an editor.
1.    Verify the correct path of Java installation to see whether it is in C:, D: or any other drive. If you didn't play with the installation then by default Java will be installed at "C:\Program Files\Java"
2.   Once you are done with the location of Java, open - Command Prompt by clicking "Start-> Command Prompt" or by typing “CMD” at the “Run” option.
3.    You will see a black window known as the "Command Prompt" or DOS window with something like "C:\Users\Username" written and a blinking cursor. The “Username” will be replaced by the name of the current logged in user. This is where you will write commands to create and compile your Java applications.
4.     At the cursor type the command,"CD\". The command CD (Change Directory) will take you out of the current directory or folder to the "C:\" prompt.
5.    When you see the "C:\" prompt type - "CD Program Files\Java\JDK1.6.0\Bin". This command will take you to the "Bin" (Binary) folder inside the "JDK1.6.0" folder. If your Java installation is any other folder or drive replace the path with the original location.
6.    Don't worry about the case in which you are typing your commands. All the DOS commands can be written in capital or small letters. DOS commands are case insensitive but pay extra care to the spaces. There is a space between "Program" and "Files".
7.  The command prompt should now read something like this -- "C:\Program Files\Java\JDK1.6.0\Bin"
8.    At the command prompt, type "Notepad prog1.java" and hit the enter key. You can change the name of the program from "prog1" to any other valid name but don't forget to add the ".java" extension.
9.     The "Notepad" command will start the "Notepad" editor. You will see a message "Cannot find the prog1.java file. Do you want to create a new file" and three command buttons. Select "Yes" to create a program. Don't close the Command Prompt.
10. Inside the notepad window type the following code
public class prog1
{
          public static void main(String args[])
          {
                   System.out.println(“Hello World”);
          }
}
11. Save the file by either pressing "Ctrl+S" or by selecting "File->Save" and return to the "Command Prompt". On the prompt - "C:\Program Files\Java\JDK1.6.0\Bin", type
          javac prog1.java 
This command will compile the java program. If there are some compilation errors, they will be flashed here.
12. If there are no errors, the command prompt will return. Now type the following command
      java prog1
          this command will run the program and the output
Hello World 
will be shown.
Things to remember
·       If you are a Windows 7 user, don’t install the JDK inside the “Program Files” folder. A user does not have the permission to write (create/edit files) in the “Program Files” folder. Therefore you won’t be able to save your programs inside the “Bin” folder. If you try to save the file in the “Bin” folder, Windows will ask you to save the file in the “Documents” folder instead. To install JDK in any other folder just change the install location to any other drive or folder while installing java using the “Browse” button.
·      It is not compulsory that you invoke “Notepad” from the command prompt only. You can open “Notepad” directly from the “Start Menu” also. Just make sure that the program is saved in the “Bin” folder.
·       If you have installed JDK in any drive other than “C:”, switch to that drive by just typing the drive letter followed by colon (“:”). For example “D:” (without the quotes of course!)
;·     Make sure that the program name and the name of the class is exactly be the same. For example, in the above code the name of the program and the class is “prog1”.
·        The “S” in both “System.out.println” and “String args[]” should be in caps.

Wednesday, December 21, 2011

What is Path ?

Path
In DOS and Windows systems, a path is a list of directories where theoperating system looks for executable files if it is unable to find the file in the working directory. You can specify the list of directories with the PATH commandA path points to a file system location by following the directory tree hierarchy expressed in a string of characters in which path components, separated by a delimiting character, represent each directory. The delimiting character is most commonly the slash ("/"), the backslash character ("\"), or colon (":"), though some operating systems may use a different delimiter. Paths are used extensively in computer science to represent the directory/file relationships common in modern operating systems, and are essential in the construction of Uniform Resource Locators (URLs).


Setting The Path

First thing first - You can run Java applications just fine without setting the PATH environment variable. Or, you can optionally set it as a convenience. The only advantage that you will get by setting the path is that you will be able to run the Java programs from not only the "Bin" folder but any folder in your system.

Set the PATH environment variable if you want to be able to conveniently run the executables (javac.exejava.exejavadoc.exe, and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:
C:\Java\jdk1.7.0\bin\javac MyClass.java
The PATH environment variable is a series of directories separated by semicolons (;). Microsoft Windows looks for programs in the PATH directories in order, from left to right. You should have only one bin directory for the JDK in the path at a time (those following the first are ignored), so if one is already present, you can update that particular entry.
The following is an example of a PATH environment variable:
C:\Java\jdk1.7.0\bin;C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem
It is useful to set the PATH environment variable permanently so it will persist after rebooting. To make a permanent change to the PATH variable, use the Systemicon in the Control Panel. The precise procedure varies depending on the version of Windows:
Windows XP
  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Windows Vista:
  1. From the desktop, right click the My Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced tab (Advanced system settings link in Vista).
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Windows 7:
  1. From the desktop, right click the Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced system settings link.
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.

Tuesday, December 20, 2011

How to create a Java Program


How to create a Java Program :

There are two ways to create a Java program

1. Using a text editor : To create a Java application we can use any editor and start typing the code. Since JDK does not contain an editor, the Windows users can use Notepad whereas the user of Linux can user Vi or any other editor. You can even download any third party editor from the internet. Some people may ask if they can use Ms-Word for developing Java programs, the answer is yes, but you should not do it. Since the source code of a program is not expected to look attractive, the use of word processors like Ms-Word, WordPad or Write(OpenOffice) is not recommended. also these application will require more memory when compared to Notepad and some of them like Ms-Word are to be purchased and installed separately also.

2. Using an IDE (Integrated Development Environment) : IDE stands for integrated development Environment. It is a collection of facilities provided to the users. Database designer and application programmers use it.  An IDE simplifies the tasks of creating and using an IDE for application development offer a much advanced environment for 
creating,testing and debugging programs. An IDE is a software that offers many tools and options for a programmer to create a program easily. There are many IDE's available for Java some of them are - 
NetBeans, Eclipse, JDeveloper etc. Most of the IDE's are a free download from the internet. It is not that IDE's are availble for Java only. Almost all the languages have their IDEs'. For example, for creating applications using Visual Basic and Visual C#, we can use Visual Studio.Net IDE similarly applications like DreamWeaver, ExpressionWeb are IDE's for HTML.

What should you use an editor or an IDE ?

If you are just starting with Java it is always better to start with an editor. Why ? because an editor will NOT help you in creating programs. Yes, you read it right - it will NOT help you in developing programs since it is not designed to so. When there is no help from the system you will have to write the code, test the program and debug it all by yourself. This will make you understand how a java program is created, how errors occur, the different type of errors and how to correct them. Writing the statments again and again will also make you more familar with the Java environment.  Of course you will have to work hard but that will make you a much efficient programmer. Once you are familiar with the Java environment it is adivsable that you leave the editor and start using an IDE. An IDE will make the whole programming experience very smooth as compared to an editor.One disadvantage with an IDE is that if you are new to the technology it will hinder your absolute learning of the given technology as it may resolve to hand holding in certain scenarios. On the flip side if you are familiar with the technology it has the potential to greatly reduce the manual effort across the board that can come with software development.

An IDE will offer you the following advantages

1. Readymade code : In an editor the user is required to type the whole code manually. Initially this effort helps you by making you memorise the code but later on rewriting the same code makes you feel bored. An IDE helps you by giving you readymade code.
2. Design time compiling : An IDE displays the errors at design time by underlining it. You can easily correct the error there itself.
3. Inbuilt Components : Advanced components like Buttons, TextFields, Label come ready made in an IDE whereas using an editor you have write the code to create them.
4. Auto completion of code : All IDEs support auto completion of code where you write the initial part of a statement and the rest is completed by the IDE itself. 
5. Packaging : Once a project is complete an IDE has inbuilt tools to convert it to a ready to install application.

Disadvantages of an IDE:
1. IDE uses graphical interface. It requires more memory and processing power.
2. IDE are not suitable in case you want to learn the core of a language or you are fresher.