Writing Your First Java Program



Here is the simple program in java and this can be written in any available text pads like notepad, wordpad, etc.
1.      public class Welcome 
2.      { 
3.                           public static void main( String[] args ) 
4.      { 
5.      System.out.println( " Welcome Home" ); 
6.      } 
7.      } 

Compiling Your First Java Program

Write the above code and save it as a filename Welcome.java (remember Capital ‘W’). Open a command prompt and navigate to the folder where you saved your Welcome.java file. You are ready to compile here. To compile the java file use the tool ‘javac’ that comes along with Java 2 SDK as shown below:
javac Welcome.java 
When this is done there are two possibilities: either there is no message and the prompt appears or there are messages that show the errors. There may be an error regarding the environment variable that Java depends upon called CLASSPATH which is a list of folders that contain Java classes that you might want to include in your program, these define where your dependencies are located. The CLASSPATH is simply a list of folders delimited by semicolons (;) on Windows. The current folder is specified by a period (.), which must appear in the CLASSPATH. If you have other errors, consider the following:
·         Ensure that your Java code is correct. The case of all words must match identically, for e.g., class must be lowercase and "Welcome" must have a capital "W" and all remaining characters must be lowercase. Note that the formatting of the document does not affect the compilation, for e.g., if you want to write the entire program on one line or add as much spaces between each line.
·         Ensure that the name of your file is Welcome.java, again check the case of each letter, and if in Windows make sure Notepad did not add a .txt to the end of the filename. That can be accomplished by getting a directory of the folder your file is in by issuing a dir command.

Running Your First Java Program

After the successful compilation of Welcome.java, Welcome.class file is created. This is the file that contains the byte-code. To run Welcome, type the following from a command prompt in the folder that holds Welcome. class.
java Welcome 
The result should be displayed to the screen as Welcome Home.

Understanding Your First Java Program

Lets take a look at the above program.
Line 1:  public class Welcome
A new class called Welcome is being defined. You can create new classes by using the keyword class followed by a name for the class. Remember every java program contains class definition.
Lines 2, 7 and 4, 6: the brace pair {and}
Define the body of the Welcome class by pair 2 and 7 i.e. everything that is included between lines 2 and 7 is part of the Welcome class. Similarly body of the main method is defined by lines 4 and 6.
Line 3: public static void main( String[] args ) 
It defines a method, or function, that is a member of the Welcome class called main. main is the entry point for java applications that is run using a tool java. Let's closely look at the sub parts in the method:
public
The keyword public is known as an access modifier; an access modifier defines who can and cannot see this function (or variable.) There are three possible values for access modifiers: public, protected, and private, each having their own restrictions, which we will cover later. In this case, it is saying that this function, main, is publicly available to anyone who wants to call it. This is essential for the main function; otherwise the Java Runtime Engine would not be able to access the function, and hence could not launch our application.
static
The static keyword tells the compiler that there is one and only one method (or variable) to be used for all instances of the class. This functionality will be explained more later, but for now remember that main functions have to be static in a class.
void
The term void refers to the return type. Functions can return values; for example, integers, floating-point values, characters, strings, and more. If a function does not return any value, it is said to return void. In this declaration it is saying that the main function does not return a value.
main
The word main is the name of the function. As previously mentioned, main is a special function that must be defined when writing a Java application. It is the entry-point into your class that the Java Runtime Engine processes when it starts; it will control the flow of your program.
( String[] args ) 
The portion enclosed in parentheses next to the function name is the parameter list passed to the function. You can pass any type of data for that function to work with. In this case, the main function accepts an array (a collection or set of items) of String objects that represent the command-line arguments the user entered when he launched the application. See below for explanation:
java Welcome one two three four 
The command line then would have four items sent to it: one, two, three, and four. The variable arguments would contain an array of these four strings as:
args[0] = "one" 
args[1] = "two" 
args[2] = "three" 
args[3] = "four" 
Line 5: System.out.println( "Welcome Home" ); 
Let's break apart this statement:
System
System is actually a class that the Java language provides for you. This class is used to access the standard input (keyboard), standard output (monitor), and standard error (usually a monitor unless you have a separate error output defined).
out
The System class's out property (represents output device) is defined as follows:
               public static final PrintStream out 
All the keywords used have usual meaning. The final keyword says that this variable cannot change in value. The PrintSteam class contains a collection of print, println, and write functions that know how to print different types of variables This is how println can print out so many different types of values.
println
This is the method of PrintStream class that prints the content passed as a parameter adding new line in it.
Writing a Simple Java Applet
1.      import java.awt.*;
2.      import java.applet.*;
3.      public class SimpleAppletDemo extends Applet
4.      {
5.      public void paint(Graphics g)
6.      {
7.      g.drawString(“First Applet”, 20, 30);
8.      }
9.      }
Save above code as the file SimpleAppletDemo.java. The above applet is compiled as of application using javac tool. This creates the .class file named SimpleAppletDemo.class.
Running an Applet
There are two ways of running the applet. The first one is execute the applet within the java compatible web browsers. The second way is using the tool appletviewer. Regardless of the above method you must write a short HTML file as follows:
<applet code = “SimpleAppletDemo” width = 200 height = 100>
</applet>
You can save the HTML file as name of your choice (say fisrtapplet.html).
Now give the command appletviewer firstapplet.html and see the result.
Understanding the Code
Lines 1 and 2: import statements
Let’s break the segments:
import
the import keyword is used for importing the classes in the application. Here in our applet we are importing classes from packages java.applet and java.awt.
java.applet.*; and  java.awt.*;
The above two parts describe the packages as named.and will be described later in detail. It is important here to understand is that we have importing all the classes from packages java.applet (contains the class required for applet called Applet) and java.awt (contains the classes required for GUI, and other windowing functions, here the class Graphics is from awt).
Line 3: public class SimpleAppletDemo extends Applet
Remember this class is accessed by code out side the program so public must be there. All the parts in this section is same as of the application shown previously except a part
extends Applet
The extends keyword is used for deriving the class from the Applet class to use the functionalities provided by Applet class in our class (more on this later).
Lines 4, 9 and 6, 8: the brace pair {and}
See discussions in understanding your first java program

Line 5: public void paint(Graphics g)
Unlike the java application, applet does not require main method. However in applet there are various methods that are called and one of them is paint method. The method paint is overridden by the applet. This method is called by the applet each time when the picture in the applet is to be displayed. The parameter in this method is of the type Graphics which is the class defined in awt package. (More on applet later)
Line 7: g.drawString(“First Applet”, 20, 30);
The Graphics class has the method named drawString with the parameters as string to be displayed, and coordinate position of the string. (More on this later)



Exercises
   1.Describe the figure in how java works and building java applications and applets.
  1. Write a java programs to find
    1. Area of circle      [import java.lang.Math (actually this is not needed, why?) directly use Math.PI]
    2. Square root of a number provided [Math.sqrt(double value)]


0 comments:

Post a Comment