Run Java Programs in Eclipse IDE

Before Creating and Running Java Programs in Eclipse IDE, I would like to explain the default items that are displayed under the Created Java Project.


Default Items under a Java Project -

1. View the Package Explorer tab in 'Eclipse IDE' and ensure that 'First Project' java project created in Post#64 is available as shown below:



2. Expand the 'First Project' java project as shown below and observe that 'src' folder & JRE System Library are displayed.



3. 'src' folder is called a source folder as it contains the projects source code. Hence all the java programs we are going to write will be created as Java Class files under this source folder 'src'

4. Expand the 'JRE System Library' as shown below and observe that it contains all the predefined libraries required to create and run the Java programs - (Predefined libraries contains set of predefined Java System Classes containing predefined methods which are categorized by Packages) - JRE System Library (Java Run Time Environment Library) - This JRE System Library got installed when we have installed Java  in our system (JDK or JRE).



Create a Package -

1. Right click on the 'First Project' folder in the 'Package Explorer' and select 'New' -> 'package' as shown below  (What is the purpose of  'packages' will be explained in future posts, for now blindly create a new 'package')



2. Ensure that the 'New Java Package' dialog is displayed, type package name as 'first_package' into the 'Name' field and click on 'Finish' button



3. Right click on the newly created  package and select  'New' -> 'class' as shown below


4. Ensure that 'New Java Class' dialog is displayed, ensure that 'first_package' name is displayed by default in the 'package' field, type 'Sum' into the 'Name' field , select 'public static void main(String args[])' check box  option, deselect 'inherited abstract methods' and click on 'Finish' button


5. Ensure that 'Sum.java' file is displayed in the Eclipse IDE as shown below



6. Write the Java code for calculating the sum of two numbers in the 'main' method as shown below



7. Save the 'Sum.java' file by clicking Eclipse IDE -> 'File' -> 'save' as shown below:


8. Right click on the 'Sum.java' class in the 'Package Explorer' pane and select 'Run As' -> 'Java Application'

9. Ensure that the output of this program is displayed in the Eclipse IDE -> 'Console' as shown below


How to create projects in Eclipse IDE?

1. Close the 'Welcome' screen if you are launching the application for the first time as shown below:



2. Ensure the panes shown in the below image are displayed:


3. Click on 'File' Menu and select New -> Project option as shown below


4. Ensure that 'New Project' dialog with 'Select a wizard' text is displayed as shown below:



5. Scroll down in the 'Select a wizard' dialog and double click on  'Java Project' under the 'Java' folder as shown below:


6. Ensure that 'New Java Project' dialog is displayed as shown below:



7. In 'New Java Project' dialog, provide a Project Name (for example say 'First Project') as shown below:


8. In 'New Java Project' dialog -> under 'JRE' column, select 'Use a project specific jre' radio option and select any version (in this example say jre7) in the corresponding dropdown field as shown below: (So every time you create a project you have the select the java version that you want to use with the project)


9. Click on 'Finish' button on the 'New Java Project' dialog
10. Ensure that 'Open Associated Perspective?' dialog with text 'This kind of project is associated with Java perspective' is displayed as shown below ( Click on 'Yes' button this dialog)


11. Ensure that a 'New Project' is created under the Package explorer pane as shown below: (In this example it is named as 'First Project' )


How to Launch Eclipse IDE

1. Extract the downloaded Eclipse software zip file as shown below (I used Winrar software to extract the zip file in the below screenshot)



2.  Open the extracted folder as shown below:

3. Select the Eclipse Application file from the extracted folder and open it as shown below:


4. Eclipse will take lot of time to launch. Wait for the eclipse to launch
5. Eclipse will ask you to provide the path to save the Workspace as shown below:  (Provide the path where you want to save your projects and click 'OK' )


6.  After loading few files the Eclipse will launch as shown below:

Install Eclipse IDE

We can use Eclipse IDE to develop Java Programs and Run them. So how to install Eclipse IDE will be explained below:


Prerequisites: Install Java prior to Eclipse IDE installation (See Post# 7 for Java Installation ). Eclipse IDE wont launch if Java is not installed prior to its installation.

Eclipse IDE is a multi-language software development platform. IDE means Integrated Development Environment. Integrated Development Environment is is a software application that provides comprehensive facilities to programmers to develop software applications . It is written primarily in Java and is used to develop applications in this language and, by means of the various plug-ins, in other languages as well as C/C++, Cobol, Python, Perl, PHP and more. So in order to develop Selenium Automation Scripts in Java, we need any IDE that supports Java to develop them . Since Eclipse IDE supports Java, we are going to use it for developing our Selenium Automation Scripts in Java programming language.

Follow the below steps to download it.

1. Launch any browser and visit http://www.eclipse.org/downloads/
2. In downloads page, select 'Eclipse IDE for Java EE Developers' and click on 'Windows 32 Bit' download link if you have 32 bit machine as shown below (Select Windows 64 bit' option if want to install eclipse on 64 bit machine)



3.  In the displayed 'Eclipse Downloads - Mirror Selection' page, select any mirror that is near to our place (I am from India, hence I am selecting mirror image to be downloaded from Asia category as  shown below) -



4. 'Thank You for Downloading Eclipse' page will be displayed and the current latest version of Eclipse IDE will be downloaded as shown below -



5. Installation of the Eclipse is not required after downloading it, we can directly launch it to use it.

'class' concept

The class is the logical construct upon which the entire Java language is built because it defines the shape and nature of the object. Any concept you wish to implement in a Java program must be encapsulated within a class.


Perhaps the most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus the class is a template for an object, and an object is an instance of a class.

On a high level, a Class consists of Variables and Methods. Variables store data and Methods will contian the code to use the data.

'class' syntax                                                                                                                                                                                                                                                          

  class classname
  {
     
      type instance-variable1;
      type instance-variable2;
      -
      -
      type instance-variableN;


      type methodname1(parameter-list)
      {
         //body of the method
       }

       type methodname2(parameter-list)
      {
         //body of the method
       }


       -
       -

       type methodnameN(parameter-list)

      {
         //body of the method
       }

}

Instance Variables -  The data or variables defined in the class are called Instance variables

Example  

int i;   (Here we've defined the instance variable 'i' as int)

Methods - The code is contained inside the methods.

Example 

public static void main(String args[])
{
     i=0;
    
     if(i==1)
       System.out.println("The value of i is 1");
     else 
       System.out.println("The value of i is "+i);
 }

i.e. The statements inside the method 'main( )' is nothing but code

Collectively, the variables and methods defined within a class are called members of the class.
Simple example to demonstrate the 'class'

   class Box
   {
        double width;
        double height;
        double  depth;
 
        public static void main(String args[])
        {
             double volume;
              volume = width*height*depth;
              System.out.println("The volume of the Box is "+volume);
         }  
   
    }

'continue' jump statements

Unlike 'break' jump statement which completely terminates the loop, 'continue' jump statement only skips the current iternation and continues with the next iteration.


Program to demonstrate the 'continue' jump statement  ( 'for' loop)                                                                      

class ContinueDemo
{
   public static void main(String args[])
   {
 
      for(int i=0;i<=10;i++)
      {
           if(i%2==0)
              continue;
     
           System.out.print(i+" ");
      }
 
   }
}

Output of this program:

1 3 5 7 9

Observe that the if 'continue' statement is not provided, the program would have printed 0 1 2 3 4 5 6 7 8 9 10 values, but why did it print only 1 3 5 7 9. Because when the program comes across 'continue' statement in the loop, it will just stop current iteration and go to the next iteration. i.e. The statement before the continue statement will be executed, but statements after the 'continue' statement wont be executed as the continue statement takes the control to the next iteration. Since the above program evaluates the condition if(i%2==0) i.e. If the value of i when divided by 2 results in 0, then the condition gets passed and the continue statement gets executed. Hence the values 0,2,4,6,8 and 10 are not printed by the above program.
Program to demonstrate the 'continue' jump statement  ( 'while' loop)       

class ContinueWhileLoop
{
   public static void main(String args[])
   {
      int i=0;

      while(i<=10)
      {
 if(i%2==0)
 {
                  i++;              // We've to mention it here, otherwise the while loop  iteration will stop
                    continue;
         }

          System.out.print(i+" ");
           i++;
      }

   }
}

Output of this program:

1 3 5 7 9

Unlike 'for' loop, which has incremental operation in the 'for' statement itself, the 'while' loop variable incremental should be specified in the loop itself. But when the continue statement gets executed the program execution wont execute the print and i++ statements. If it happens, this program wont print anything. Hence we've to increment the variable when the if(i%2==0) is true. i.e. before the program executing the 'continue' statement as shown in this example.

Program to demonstrate the 'continue' jump statement  ( 'do-while' loop)    

class ContinueDoWhileLoop
{
   public static void main(String args[])
   {
      int i=0;

      do{

             if(i%2==0)
             {
                 i++;
                  continue;
              }

               System.out.print(i+" ");
               i++;

      }while(i<=10);

   }
}

Output of this program:

1 3 5 7 9

Unlike 'for' loop, which has incremental operation in the 'for' statement itself, the 'do-while' loop variable incremental should be specified in the loop itself. But when the continue statement gets executed the program execution wont execute the print and i++ statements. If it happens, this program wont print anything. Hence we've to increment the variable when the if(i%2==0) is true. i.e. before the program executing the 'continue' statement as shown in this example.

Using continue to transfer the control to the outer loop

class ContinueOuterLoop
{
   public static void main(String args[])
   {
      outer: for(int i=0;i<=5;i++)   //This loop is labelled as 'outer'
             {
             System.out.println();

       inner: for(int j=0;j<=5;j++)  //This loop is labelled as 'inner'
              {
                   if(j>i)
                     continue outer;   //If this statement gets executed, the program execution control will be transferred to the loop labelled as 'outer'

                   System.out.print(j+" ");
            }

         }
   }
}

Output of this program:

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5

Observe that when ever the condition in the inner loop results true, the continue outer; loop statement gets executed and the program execution control will be transferred to the outer loop.

'for' iterative statements

For all the iterative statement types, 'for' loop is the most versatile (i.e. capable of doing many things).


'for' loop syntax                                                                                                                              
Lets first understand the 'for' loop syntax and then go to the example programs.
Syntax:
for(initialization;condition;iteration)
{
   Statement 1;
   Statement 2;
   .
   .
   Statement n;
 }
Initialization portion of the loop sets a loop control variable to an initial value.
for(i=0;condition;iteration)
{
     Statement 1;
     Statement 2;
   .
   .
     Statement n;
 }
Condition is a Boolean expression that tests the loop control variable. If the outcome of this Boolean expression is true, then the for loop continues to iterates else it gets terminated.
for(initialization;i<10;iteration)
{
    Statement 1;
    Statement 2;
    .
    .
    Statement n;
 }
Iteration expression determines how the loop control variable is changed each time the loop iterates.
for(initialization;condition;i++)
{
    Statement 1;
    Statement 2;
    .
    .
    Statement n;
 }

The flow of execution of for loop will be as shown below -

First, the intialization will be done
Second. the condition will be verified
Third, the statements inside the for loop will be executed if the above condition is true
Fourth, the value of variable will be incremented.
Fifth, the conditon will be verified
Sixth, the statements inside the for loop will be executed if the above condition is true
and so on ....

Program to demonstrate the 'for' loop                                                                                                                 

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

      int i;    //declaring the variable 'i'
 
      for(i=1;i<6;i++)
      {
         System.out.println("The value of i is "+i);
      }
   }
}

Output of this program:

The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5

The for loop operates as follows. First the variable 'i' is initialized by a value '1'. Then the condition i<6 is evaluated i.e. 1<6 is pass, hence the program enters the loop and executes the statements inside the for loop block, i.e. It prints 'The value of i is 1'. After this the control goes to iteration expression i.e i++ i.e. The value of i got incremented by 1 i.e. i is 2 now. Now the condition expression i<6 i.e. 2<6 is evaluated and result is pass, hence the program enters the for loop block and prints 'The value of i is 2'. In this way the loop repeats until the condition express i<6 results true. Finally when the i is incremented from 5 to 6 and when i<6 is evaluated i.e. 6<6 fails. Then the for loop terminates.
Program to demonstrate that the variable can be declared during its initialization in for loop

class ForLoopDemo2
{
   public static void main(String args[])
   {
      for(int i=1;i<6;i++)  //Observe that the variable 'i' got declared during initialization itself i.e. int i=1
      {
         System.out.println("The value of i is "+i);
      }
   }
}

Output of this program:

The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5
Program to demonstrate the flower braces can be ignored if the 'for' loop has only one statement

class ForLoopDemo3
{
   public static void main(String args[])
   {
      for(int i=1;i<6;i++)
        System.out.print(i+" ");   //As this is the only statement under the 'for' loop, we've ignored the flower braces i.e. { }
   }
}

Output of this program:

1 2 3 4 5

Observer the we've not used flower braces for the 'for' loop as we have only one statement
Program to demonstrate the scope of the variable that is declared during 'for' loop's variable initialization

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

      for(int i=1;i<6;i++)
       i++;

      System.out.println("The value of i is "+i);

   }
}

Output of this program:

Error "cannot find symbol 'i' in System.out.println("The value of is i is "+i) "

This error is displayed because the 'i' is declared inside the 'for' loop block. Hence it wont be accessible outside the 'for' loop block.
Program to demonstrate that more than one variable can used in the for loop initialization  condition and iteration expressions

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

      for(int i=1,j=3;i<j;i++,j--)            //Initialized more than one variablie i.e initialized i and j variables, iterated them and used in conditional expression
      {
        System.out.println("i = "+i);
        System.out.println("j = "+j);
      }
  }
}

Output of this program:

i=1
j=3
Program to demonstrate that initialization and iteration parts of the for loop can be empty

class ForLoopDemo6
{
   public static void main(String args[])
   {
  int i=0;

      for(;i<2;)            //Initialization part and Iterative expression parts are left blank in the 'for' statement
      {
        System.out.println("i = "+i);
        i++;
      }
  }
}

Output of the program:

i=0
i=1

Observe that the program still works even though we've left the initialization part and iterative expression parts of the 'for' statement blank.
Program to demonstrate the nested 'for' loops

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

      for(int i=0;i<5;i++)
      {
           for(int j=0;j<5;j++)
             System.out.print(".");
          System.out.println();
       }

   }
}

Output of this program:
.....
.....
.....
.....
.....
Another program to demonstrate the nested for loop

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

      for(int i=0;i<5;i++)
     {
         for(int j=i;j<5;j++)
           System.out.print(".");
         System.out.println();
       }

   }
}

Output of this program:

.....
....
...
..
.

'do-while' iteration statements

As we have seen, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a loop at least once, even if the conditional expression controlling the loop is  initially false.


do-while loop in Java always executes its body at least once, because it's conditional expression is at the bottom of the loop. Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If the condition is false, the loop terminates.

Program to demonstrate that the do-while loop executes at least once even if the conditional expression controlling the do-while loop fails initially                                                                      

class DoWhile
{
  public static void main(String args[])
  {
     int i=6;

      do
      {
            System.out.println("The value of i is "+i);

      } while(i<6);  //Condition is at the bottom of the loop, hence the loop is executed at least once even if the condition initially fails

   }
 }

Output of this program:

The value of i is 6

do-while loop started without checking any condition and hence printed "The value of i is 6". After this it evaluated while(i<6) i.e. while(6<6) i.e. false, hence terminated the loop. This means even though the condition controlling the do-while loop initially fails, the statements inside the do-while loop will be executed one time.
Another program to demonstrate the do-while loop 

class DoWhile2
{
  public static void main(String args[])
  {
     int i=1;

      do
      {
            System.out.println("The value of i is "+i);
            i++;

      } while(i<6);

   }
 }

Output of this program:

The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5

Program to demonstrate the infinite times executed  do-while loop 

class InfiniteDoWhile
{
  public static void main(String args[])
  {
     int i=1;

      do
      {
            System.out.println("The value of i is "+i);

      } while(i<6);

   }
 }

Output of this program:

'The value of i is 1' will be printed infinite times

In this program, we've not incremented the value of 'i' as we did in the previous program. Hence the do-while conditional expression always results in pass (i.e. 1<6) is always pass, hence it executes the statements inside the do-while block infinite times i.e. prints 'The value of i is 1' infinite times

'while' iteration statements

Iteration statement creates loops. A loop repeatedly executes the same set of instructions until a termination condition is met. Iteration statements are another type of 'Control Flow' statements.


 Program to demonstrate the 'while' loop                                                                                                                                

'while' loop executes the statements in its block repetitively as long as the condition expression is true.

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

      int i=1;

      while(i<6)    //This loop will be executed repeatedly until the value of i is less than 6
      {
         System.out.println("The value of i is "+i);
         i++;
      }

    }

 }

Output of this program:

The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5

'while' loop executes the statements inside its block repeatedly until the value of i is less than 6 in this example. So to start with 'while(i<6) i.e. while(1<6) which is true, hence it enters into the while block and prints "The value of i is 1" and then executes i++; i.e. it increments the value of i by 1. So the value of i now is 2. The loop then gets repeated with while(i<6) i.e. while(2<6) which is true -> hence prints "The value of i is 2", while(3<6) which is true -> hence prints "The value of i is 3", while(4<6) which is true -> hence prints "The value of i is 4", while(5<6) which is true -> hence prints "The value of i is 5" and while(6<6) which is false hence wont enter into the while block as the condition is false.
Program to demonstrate the infinite times executed while loop

'while' block will get executed infinite times if the condition expression is always true

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

      int i=1;

      while(i<6)
      {
         System.out.println("The value of i is "+i);
      }

    }

 }

Output of this program:

"The value of i is 1" will be printed infinite times.

In this example, we've not incremented the value of i by 1 as we did in the earlier example. As a result the value of i is always 1. Since while(i<6) i.e. while(1<6) is always true, the statement "The value of i is 1" inside the while loop will be printed infinite times.
Program to demonstrate a never executed while loop

'while' block wont be executed at least single time when the condition expression is false.

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

      int i=6;

      while(i<6)
      {
         System.out.println("The value of i is "+i);
      }

    }

 }

Output of this program:

[No output] - Since while(i<6) i.e. while(6<6) is false, the statements inside the while block wont be executed at least once.
Finding the mid value of 1 and 11 using the 'while' loop

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

      int i=1,j=11;

      while(++i<--j);   //There are no statements in the while loop, hence we have not used the flower braces.

      System.out.println("The mid value of 1 and 11 is "+i);

    }

 }

The output of this program:

The mid value of 1 and 11 is 6

'switch' selection statements

switch provides a better alternative for a large series of if-else-if ladder. 'switch' is another 'Control Flow' statement.


Program to demonstrate the 'switch' selection                                                                                

class SwitchDemo
{
   public static void main(String args[])
   {
          int a=2;

         switch(a)
        {
            case 0:
                System.out.println("The value of a is zero");
                break;

            case 1:
                System.out.println("The value of a is one");
                break;

            case 2:
                System.out.println("The value of a is two");
                break;

            default:
                System.out.println("The value of a is "+a);
         }
   }
}

Output of this program:

The value of a is two

switch(a) i.e. switch(2) in this example : As we have mentioned switch(2), the program will directly go to case 2: and execute all the statements under case 2 i..e first it will print 'The value of a is two' and will execute the break; statement ( break; will make the program execution come out of the switch case without executing the next cases)
Program to demonstrate what happens when we don't write break; statement for all the cases

class SwitchWithoutBreak
{
   public static void main(String args[])
   {
      int a=0;

      switch(a)
      {

        case 0:
           System.out.println("The value of a is zero");

        case 1:
           System.out.println("The value of a is one");

        case 2:
           System.out.println("The value of a is two");

         default:
           System.out.println("The value of a is "+a);

      }
   }
}

Output of this program:

The value of a is zero
The value of a is one
The value of a is two
The value of a is 0

switch(a) i.e. switch(0) in this example: As we've mentioned switch(0), the program execution will go to case 0: and execute all the statements under case 0, i.e. it will print "The value of a is zero". Since we've not written break; statement under case 0, the program execution will go to next case i.e. case 1 and will print :The value of a is one". Since the break; statement is not written under case 1, the program execution will go to case 2 and prints "The value of a is two". Since the break; statement is not provided in the case 2, the program execution will go to case default and prints "The value of a is 0".
Program to demonstrate what happens when the expression provided don't match any case

class SwitchExpressionDontMatch
{
   public static void main(String args[])
   {
      int a=5;

      switch(a)    // switch(a) i.e switch(5), there is no case 5 below
      {

        case 0:
           System.out.println("The value of a is zero");

        case 1:
           System.out.println("The value of a is one");

        case 2:
           System.out.println("The value of a is two");

         default:
           System.out.println("The value of a is "+a);

      }
   }
}

Output of this program:

The value of a is 5

switch(a) i.e. switch(5): After executing switch(5) in this program, the program searches for case 5 for directly jumping to that case and executing the steps under case 5. But as we don't have case 5 written in this example, the program will jump to case default and execute the statements under it i.e. in this example the program prints "The value of a is 5"
Program to demonstrate the switch with a different expression

class SwitchExpression
{
   public static void main(String args[])
   {
      int a=1,b=1;

      switch(a+b)   //Used expression 'a+b' instead of simple variable 'a' here
      {

        case 0:
           System.out.println("The value of a+b is zero");
           break;
        case 1:
           System.out.println("The value of a+b is one");
           break;
        case 2:
           System.out.println("The value of a+b is two");
           break;
        default:
           System.out.println("The value of a+b is "+(a+b));

      }
   }
}

Output of this program:

The value of a+b is two

switch(a+b) -> switch(1+1) -> switch(2): Switch(2) will jump directly to case 2 and execute the statements under case 2. Hence this program printed "The value of a+b is two" and executed break; to get out of the switch.