Writing our first JAVA program…

Now that JDK is installed and Environment Variables are set up in our machine, lets try to create and execute a simple “HelloWorld” program using Command Prompt or Terminal.

  • Using a text editor like Notepad or TextEdit write a simple program and then save the file as “HelloWorld” with .java extension. You can save it in any location.
screen-shot-2017-02-13-at-10-40-51-pm
HelloWorld in text editor
  • Open your Command Prompt or Terminal and go to the location where your .java file is saved.
  • Type in “javac -d . HelloWorld.java” in the Command Prompt or Terminal. Here “javac” refers to JAVA Compile command. As you remember in our previous post, we set our PATH to JDK Bin in our machine. Bin folder contains the executable files for “javac” and “java” commands. “-d” refers to Directory where “.class” files will be stored. When we run “javac” command, the javac compiler compiles your .java source files into .class files, and so that JavaVM can execute (interpret) those files. “.” refers to current working directory and “HelloWorld.java” is the file that we just created.
  • As you see we created a package “com.selenium.test” in our first JAVA program. What is a package? I know many will have this question. A package in JAVA can be defined as a grouping of related types like classes, interfaces, enumerations and annotations and providing them access protection and namespace management. In simple terms, it will store the source file inside a folder structure. Here in this case, folder structure will be created in the form of com -> selenium -> test. When we run this command, system will automatically create a folder structure com -> selenium -> test and store the “.class” file inside the “test” folder.
screen-shot-2017-02-14-at-12-03-16-pm
com folder is created inside HelloWorld folder
  • Once the compilation is complete, next step is to execute the “.class” file. Type in “java com.selenium.test.HelloWorld” in the Command Prompt or Terminal and hit Enter. This time we don’t have to use the file extension. And as you see below, the execution is success.
screen-shot-2017-02-14-at-12-08-42-pm
Hello World!
  • If we are not using any package is our program, then we can simply go to our source folder and run the below commands.

Screen Shot 2017-02-14 at 12.14.23 PM.png

Additional Notes:

Command Prompt is Windows based DOS application and Terminal is Mac Os based Linux application. The purpose is same but the commands are bit different. You can get a complete list of required commands for both Windows and Mac machine from below URL:

DOS Linux Commands