Home > Developing & Testing a Java Technology program > Developing & Testing a program in Java

Developing & Testing a program in Java

 

 

Module 3: Developing & Testing a Java Technology program.

 

Objectives:

1. Identify  4 components of class.
2. Use main method in a test class to run a java program from command line.
3. Compile & execute a java program.

 

1. Identify  4 components of class:

Going back to what we discussed before about classes, to construct a house you will first need a blueprint. Same thing applies for classes & objects. Similarly once you have a class blueprint, you  can have as many objects of that class as u like. These objects are called instances of a class. i.e., a shirt object is an instance of a shirt class.

 

27. class and its objs

 

Lets take a look at our first class:

Class is a blueprint that tells the computer how to make objects. This class blueprint – Shirt, tells the computer how to make Shirt objects.

 

28. 1st class

 

 

Structuring classes:

There are 4 major components of class that you will find more often:

  • class declaration – required
  • attribute variable declaration & initialization – optional
  • methods – optional
  • comments – optional

1. Class declaration is required, and this is all that you need to make a class valid. If all you had was this, then the class and its objects would be uninteresting serving no purpose. You will be needing some attributes and operations to jazz up the object.

2. Variables are characterstics of your objects. As we discussed in previous posts, these are characterstics /  properties and they are also data holders. They hold the data for the object.

3. In this Shirt class, only one method is defined. Methods are operations. They tell the class what to do.  Its what the class can do.  This method is printing all its information to the command window.

4. Comments are for developers to understand what the code is doing, they dont influence the execution in anyway.

 

Class declaration:

For a class, following should be noted:

  • Each class should be declared in its own file.
  • The name of the file should be the same as the name of the class with a .java extension.  ex: class Shirt should be saved in a file called Shirt.java

Syntax:

[modifiers] Class class_indentifier{
 class_body
}

ex:
public class MyShirt
{
 class_body
}

  • [modifiers] -> optional – as indicated by square brackets. ex: such as public, abstract or final.
  • class -> required – class indicates that the code block is class declaration. class is a Java keyword.
  • class_indentifier -> required –  Its a name you give to the class. It should be nouns in  mixed case with the 1st letter of each word captalized. ex: Shirt. It should contain whole words, avoid acronyms and abbreviations. It cant contain space, period, dash or begin with digit. Its case sensitive.
  • class_body -> optional –  it can contain variables, methods and/or comments.

Include left and right curly brackets. In between this is the class body where atributes & methods go. If you dont follow these conventions, you will get problems while compiling your source code.

 

Variable declaration & assignments:

Syntax:

[modifiers] type indentifier [=value];
ex: public int shirtId = 0;

  • modifiers -> optional – These are special Java keywords that modify the way the associated entity functions.
  • type -> required – indicates the type of data the variable is going to hold. ex: int will hold integer data.
  • indentifier -> required – this is the name we give to a variable, make sure to start with letter or certain special characters usually lower case to start with.
  • [=value] -> optional – initialize a variable to this value.

Make sure to end the variable declaration / intialization with “;” which is a must and by doing so this becomes a statement or a single line of java code.

 

Comments:

Another part of a program which dont interfere with code execution, or matter for its behavior. It is just some information to the developer regarding the following piece of code. There are 3 types of comments:

  • Single line comments – These comments starts with ‘//’.  It covers one line. ex: // this is a comment for my information.
  • Traditional comments – These are comments that span multiple lines or large block. They start with ‘/*’ and end with ‘*/’ unlike single line which auto termintates at the end of line. ex: /* this is going to span lot of lines */
  • Java doc – We will discuss about these type of comments in the coming posts.

 

Methods:

Methods are operations of an object. Its what an object can do i.e., its functionality. There can be zero or more methods and is completely upto you.

Syntax:

[modifiers] return_type method_indentifier([arguments])
{
 method_code_block
}
ex: public void dispalyShirtInfo(){
//..some java code performing some opern.
}

  • [modifiers] -> optional – Just like attribute modifiers, these ate special Java keywords that modifies the way the method will behave.
  • return_type -> required – Always have to specify what a method returns at the end of its execution, it can return utmost one value. If it doesnt return anything, then it shud still return void, which is an indication to the compiler that this method doesnt return anything. If it did return something, then you should specify the return  type. ex : int if it return type is integer value.
  • method_indentifier -> required – This is what gives a method its name. Its always better to provide descriptive names, can start with lowercase letter or other special characters.
  • ([arguments]) -> optional –  These are entities that can be specified inside the method paranthaseis. Its an input to the method. If we want to provide some external information to a method, we can pass that information through these arguments. If you dont need any arguments, you can just leave it blank, but the method should have paranthesis.

Make sure to begin and end the method body with left & right curly brackets. The method body will most likely contain java statements which perform certain set of operations.

 

 

2. Use main method in a test class to run a java program from command line.

Now that we have a class called Shirt. Can we just run it? Not yet. We are still missing something. We need something that creates a Shirt object. To do that a java program will need a main method. This main method is an entry point into your program. Its a starting point. It can be placed in any class. Usually it should be put in a class of its own, i.e., a class other than the one which contained the above code.

ex: public void ShirtTest{
public void main (String args[]){
Shirt myShirt; – declare myshirt variable, holds one shirt object
myShirt = new Shirt(); – creating shirt object, new keyword is used for creating that.
myShirt.dispalyShirtInformation(); – call the method on the shirt object, perform the operation in the method.
}
}

 

Syntax:

public static void main (String args[]){
}

Unlike any other method in a java program, the main method always has the same syntax. And all the programs which needs to create objects, need to have a main method in some class, and any main method should always have the same syntax as mentioned above.

  • modifiers ->  public & static are required.
  • return_type -> Doesnt return any value so void keyword should be specified.
  • method_identifier -> Method name must be main. This is the method identifier used always. This is how a java program will know that this is the starting point. 
  • arguments ->Main method must accept an array of String objects as arguments.

After the execution, the main method will exit and so will the main program.

 

 

3. Compile & execute a java program.

 

So our Shirt class is ready and so is a test class called ShirtTest which has a main method ready, so is it all done yet? Well, we  just have the source code, it needs to be translated into bytecode. For that we have to compile it using javac (compiler).

In command prompt, type javac ShirtTest.java – this command starts the compiler, it will take the test file, bring into the compiler, goes thro’ the code and outputs the Shirt.class file which is a bytecode file. It isnt going to print anything in the command if it compiles successfully. It will only print something when there are errors. If there are errors, they are called compiler errors or compile – time errors and they have to be fixed before proceeding any further.

 

Compiling a program – compiler errrors:

Compiler errors are many times self-explanatory of the actual errors, but sometimes the compiler can’t totally determine the exact line number where the error actually is. For ex: the compiler  has displayed a line with semi-colon as missing semi-colon, so you have to look into the source code for missing semi-colon. Look around the line displayed in the command prompt here, in the lines above or below.

For ex:

Shirt.java:12: ‘;’ expectd
System.out.println(“display shirt ID”+ shirtId);
1 error

or

Shirt.java:1: ‘class’ or ‘interface’ expectd
public Class MyShirt{
 ^
1 error

Syntax for compiler error messages usually is: file_name : line_number: error_msg possible_locn_of_error. 

 

Debugging tips:

Tracking down compiler errors if you are new to java can be pain. So 2 tips are here for offering.

  • Help with error messages –  so that you dont get overwhelmed with it.
  • Tips to minimise the error msgs.

 

 1. File Dependancy:

 

29. compiling class

 

Alwys compile the least dependant class first. If a file uses another file, this is dependant on the other, so you have to compile the other file firrst. Ex: Shirt & ShirtTest. ShirtTest is using Shirt whereas Shirt is not dependant on any other class.  So compile Shrit.java first which doesn’t rely on any other class. Once its compiled next compile the test file.

Whats the difference or how does it matter? When you compile a file, the compiler also checks if any class that this class uses is compiled. If not,  then it compiles the other class as well. So in that case, if there’s any error in either of the files, all the error messages are going to be displayed together which becomes difficult to understand. If we have already compiled the least dependant file first, and resolve any error messages for it first and then compile the other then compiler errors are going to be less confusing.

 

2. Good coding practices.

  • Make sure to match left & right brackets. If this is missed, then the compiler will show lot of eror messages.
  • Make sure that each statement ends with a semiclon.
  • Make sure to use correct spelling for all names (variables / methods) and keywords. (case-sensitive)

 

Executing a program:

So, now whats going to happen when we run our compiled program? Its now interesting to see how JVM uses the 2 class files. We have to run them thro’  JVM. Make sure that both the class files are in the same directory.

For our example, these are the steps that JVM will follow:

1. Launch application –  “java” is the commant to do that, and this is the JVM itself.  To launch the application or program, type java ShirtTest in command prompt. Here, you should type the name of the file which has been compiled and has the main method. You dont type in ShirtTest.class. jvm will knw tht its .class file. and dnt type eother .java which is the source code.

30 - a launch appln

 

2. Load .class into memory – After typing the above command, JVM loads the specified  .class file into memory.

 

30 - b load MyShirt

 

3. Invoke main method –  JVM here tries to find the main method in the .class file it has loaded in the memory. Once it finds it, it begins the execution. It now turns the control to our program. In our code, its to create a variable.

 

30 - c invike main meth

 

4. Load dependant classes Shirt.class – JVM then loads the dependant classes if any when needed. Once a class needs another class, JVM will load it at run-time. This is one of the important feature of Java called Dynamic Class Loading. Classes are not loaded all at once, they are loaded only when needed. 

 

30 - d load dep class 

 

5. Create myShirt object – Our code has used a ‘new’ keyword which creates a new object. Once this object has been created, we can access its variables & methods.

 30 - e create obj

 

6. Invoke displayShirtInfo method – As the next line in the code is invocation of a method on the object, the method displayShirtInfo is called. The control is then passed from the main method to this method to run that code.

 30 - f invoke meth

 

7. Code in invoked method is executed – This method executes whatever code is in the invoked method. This one prints output to the console.

 

30 - g meth display

 

8. Control bakc to JVM – After completing the execution of the method, the control returns back to the invoking method, which is the main method here. After the main method exits, the program also exits and the JVM shuts down.

 

 30 - h control bak to jvm

 

 

Note:

 

Source: Sun Microsystems Educational Services Course – Introduction to java programming language WJ-1101A

 

 

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: