Pages

Monday 30 September 2013

Programming basics of Java

Programming basics of Java:


  •         Source File: It is a document with .java extension containing class. The class contains statements and methods.


  •        *.class file: It is the output file created after the compilation of the source file. It is the bytecode version of the program. 



How Java Works?

           Below image shows you how source file is compiled and executed to obtain desired out on JVM devices.

             


  

 First Simple Program “Hello World”:  

     
         /** simple hello world program
 *
 * @author Jaivanth
 *
 */
public class SampleHelloWorld
{
    //program will start with call to main method
           
            public static void main(String[] args)
            {
                System.out.println("Say Hi HelloWorld!!");//print instruction           
            }
}


Steps for executing java program using command window:


1.     Rename the source file as SampleHelloWorld.java (same name as the class name). 
2.     Open command prompt (shortcut key: windows + R, type cmd, press enter).
3.     To compile and execute, In command prompt type: 
                 C:\> javac SampleHelloWorld.java (compile command)
                 C:\>java SampleHelloWorld
4.      Execution successful!! Message printed HelloWorld!!. 


Note: Why its’ always good to name your source file with same name as the class name?

                    Because after the compilation of source file, a .class extension output file is created with the same as that of the class name. So programmers think it’s good to do so.  



Second Simple Program to add two integers:

/** program to add two integer
 * numbers.
 *
 * @author Jaivanth
 *
 */
public class SampleAddTwoInts
{
    //program starts with call to main method
           
            public static void main(String[] args)
            {
                        int a=10;
                        int b=20;
                        int sum;
                       
                        sum=a+b; // addition instruction.
                       
                        System.out.println("Addition of a+b= "+sum);
            }
}

Output:  Addition of a+b= 30