8/8/2019 Developing and Testing a Java Program
1/27
DEVELOPING AND TESTINGA
JAVA PROGRAM
8/8/2019 Developing and Testing a Java Program
2/27
OBJECTIVES
After completing this chapter, you will be able to:
Id entify the components of a class in the Java
Programming Language
Learn the compilation techniques for creation of
.class files
Learn d ebugging techniques
Write a simple Java program
Dissect the first Java program
Compile an d execute a Java program
8/8/2019 Developing and Testing a Java Program
3/27
COMPONENTS OF ACLASS
Class is a collection of homogeneous real world objects.
A single class can be divided into four separate sections,namely:
Declaration of a classVariable declaration and initialization (optional)
Methods (optional)y O rdinary Methodsy Constructorsy m ain method
Comments (optional)
8/8/2019 Developing and Testing a Java Program
4/27
EXAMPLEF ilename: Book.javapublic class Book //Declaration of the class{
public int Book Id = 0;public String BookName = I ntro to Java ;public String Author = Sara d a Satapathy ;public Double Price = 100.00 ;
public int Quantityinstock = 0; //This metho d d isplays the information about theBook.public voi d Book I nfo() //Metho d
{System.out.println(Book Id : +Book Id );System.out.println(Book Name : +BookName);
System.out.println(Author : +Author);System.out.println(Price of the Book : +Price);System.out.println(Quantity in Han d :
+Quantityinstock);}
}
class CallBook //Declaration of the class
{
public static voi d main (Stringargs[]) //Main Metho d
{
Book ob1 = new Book(); //Object Creation
ob1.Book I nfo();
//Calling Metho d}}
In order to execute thisprogram, you need amain method, withinwhich you have to createan object for the Bookclass and call theBookInfo() method.
Main Method
8/8/2019 Developing and Testing a Java Program
5/27
CLASS DECLARATION
J ava is purely object oriented - anything we write to solve aproble m has to be written within a class .
Before you use, a class must be declared, for each class youdesigned for the problem domain.
Syntax for declaring the class is:
[access modifier] class class_identifier
T he class definition is followed by an open curly brace ( {),indicating the beginning of the class_body, the attribute variablesand the methods that compose the class.
T he braces { } around the class_body define where the classstarts and ends .
8/8/2019 Developing and Testing a Java Program
6/27
CLASS NAMINGGUIDELINES
Class names must be meaningful, in mixed case with the firstletter of each word capitalized.
For example, MyClass.
T hey must contain whole words.Acronyms and abbreviations are avoided (unless theabbreviation is much more widely used than the long form,such as J VM or UML).
It is not advisable to use any reserve word for declaration of class name.
8/8/2019 Developing and Testing a Java Program
7/27
VARIABLEDECLARATIONS AND
ASSIGNMENTST he declaration of the attributes and its assignment of values isdone just after the first curly brace ( {).
T he code for Book class example contains five attribute variabledeclarations, and is also assigned some values:
public int Book Id = 0; //Attributes
public String BookName = Intro to J ava; //Attributes
public String Author = Sarada Satapathy; //Attributes
public Double Price = 100.00; //Attributes
public int Quantityinstock = 0; //Attributes
8/8/2019 Developing and Testing a Java Program
8/27
COMMENTS
Inserting comments is nothing but documentation within
programs .
It is advisable to put comments in every class that you create
to make it easier to determine the objective and behavior ofthe program.
Commenting is very much useful in longer programs
developed by large teams, where several programmers need
to work on the same code by reading it.
It helps with the maintenance of a program when new
programmers need to determine what the code is doing.
8/8/2019 Developing and Testing a Java Program
9/27
Single-line co mm entsy A // marker tells the compiler to ignore everything to the end of
the current line.y Example:
public intB
ookId = 0; //Attributes// T his method displays the information about the Book.
Multi Line Co mm entsy A /* character combination tells the compiler to ignore everything
on all lines up to, and including, a comment terminating marker( */).
y Example:public int Book Id = 0;/* T his method ..
.. */
Comm ents continued
8/8/2019 Developing and Testing a Java Program
10/27
Docu m entation Co mm enty T his type of comment must begin with a forward slash
and two asterisks ( /**), and end with an asterisk and a
forward slash ( */).y A J ava Technology Tool, the J avadoc software , can be
used to create documentation of your class.
Comm ents continued
8/8/2019 Developing and Testing a Java Program
11/27
METHODS
Syntax:[access modifiers] return_type method_name
([arguments],[arguments],[...]){ method_code_block............. }
[access modifiers] specifies the accessibility of the current methoddepending on which the other classes/methods/package can have theaccessibility.T he return_type indicates the type of value that the method returns.T
he method_name is the name of the method.T he ( [argu m ents] ) represents a list of variables whose values arepassed to the method for use by the method.T he method_code_block is a sequence of statements that the methodperforms.
8/8/2019 Developing and Testing a Java Program
12/27
EXAMPLE
public void Book Info() //Method{
System.out.println( Book Id : + Book Id);System.out.println( Book Name : + BookName);System.out.println(Author : +Author);System.out.println(Price of the Book : +Price);System.out.println(Quantity in Hand : +Quantityinstock);
}
8/8/2019 Developing and Testing a Java Program
13/27
COMPILINGTECHNIQUES
All high level languages need to be translated to machinelanguage before the machine can execute it.Typically, a programmer writes language statements in alanguage, such as J ava or 'C', one line at a time using an 'editor'
(like notepad/textpad).T he file that is created contains what are called the sourcestatements . T he programmer then runs the appropriatelanguage translator, specifying the name of the file thatcontains the source statements .T here are three methods of translation available:
y Compilationy Pure interpretationy Hybrid interpretation
8/8/2019 Developing and Testing a Java Program
14/27
COMPILATION
T he programs are translated into machine level language andstored in the machine language or object code form.
The co m piler first parses (or analyzes) all the state m ents -
one after the other - and the output code, m aking sure thatstate m ents that refer to other state m ents are referred tocorrectly in the final code.Traditionally, the output of the compilation has been called
'object code ' or sometimes an ' object m odule '.The object code is the m achine code that the processor canprocess or execute - one instruction at a ti m e.
8/8/2019 Developing and Testing a Java Program
15/27
PURE INTERPRETATION
T he source code is translated into machine code andsimultaneously executed, one line at a time, by thesoftware called interpreter .T he program can be executed only if the interpreteris present on the machine .
Execution is much slower than in compiled systems.
8/8/2019 Developing and Testing a Java Program
16/27
HYBRIDINTERPRETATION
T he J ava compiler converts the source code program into
a generalized m achine instruction (the intermediatecode) called byte code , which is then translated by the
J ava virtual machine (interpreter) present on themachine.
T he VM converts each generalized machine instruction
into a specific machine instruction or instructions that
the computer's processor understands.T his enables J ava to be platfor m independent .
8/8/2019 Developing and Testing a Java Program
17/27
DEBUGGINGTECHNIQUES
Debugging is a method used by software developers to figureout where the problems ( bugs ) lie in their code.
Some common bugs are:
Typographical errors - instead of
Om issions Forgetting to close off a section with a slash,such as followed by a
Syntax errors Not using the correct syntax for a method
or propertyLogical errors Can be as simple as forgetting to take intoaccount what happens to your script when cookies areturned off, or using the wrong method or property.
8/8/2019 Developing and Testing a Java Program
18/27
Detecting BugsDetecting bugs is a fairly simple task during the early stages ofsoftware development.
However, the more time you spend looking for bugs, the harder it
becomes to find them.J ava 2 SDK contains a debugger called jdb , which can be used forthis purpose.
Repairing Bugs
T he task of repairing bugs, also known as implementing a bug-fix, can be a tiresome and frustrating process.O nce repaired, however, you need to distribute the changed codeto all of your users.
Debugging techniques continued
8/8/2019 Developing and Testing a Java Program
19/27
YOUR FIRST J AVAPROGRAM
/* T his is a simple J ava program. Call this file Hello.java */
class Hello{
//your program starts executing from main()public static void main(String args[])
{System.out.println(Hello World);
}}
Program name: Hello.java
8/8/2019 Developing and Testing a Java Program
20/27
ENTERING THECODE
In J ava, a unit of code or a program must reside in aclass.By convention, the na me of that class should match
the na me of the file that holds the progra m .You should also make sure that the capitalization of thefilename matches the class name.T
he reason for this is that Java is case-sensitive .
8/8/2019 Developing and Testing a Java Program
21/27
DISSECTING THEJ AVAPROGRAM
a) T he program begins with the following:/* This is a si m ple Java progra m . Call this file Hello.java */T his is a comment. Like most programming languages, J ava letsyou enter a remark into a program's source file. T he contents of acomment are ignored by the compiler.
b) T he next line of code in the program is shown below:
class Hello {T his line uses the keyword class to declare that a new class isbeing defined. Hello is an identifier that is the name of theclass. T he entire class declaration, including all of its members(data and methods), will be between the opening curly brace ( {)and the closing curly brace ( }).
8/8/2019 Developing and Testing a Java Program
22/27
c) T he next line in the program is the single-line comment, shownbelow:
// Your progra m starts executing at m ain:T his is the second style of comment supported by J ava. A single-
line comment begins with a // and concludes at the end of theline.
d) T he next line of code is shown below:
public static void m ain(String args [])T his line begins the m ain() method. As the comment preceding itindicates, this is the line at which the program will beginexecuting. All J ava applications begin execution by calling m ain() .
Dissecting continued
8/8/2019 Developing and Testing a Java Program
23/27
e) T he next line of code is the one which occurs withinm ain() :
Syste m .out.println(Hello World);
T his line outputs the string Hello World followed by a newline character to screen.
O utput is accomplished by the built-in println() method .T he first closing brace ( }) after the println() statement ends
m ain() , and the last closing brace ( }) ends the Hello classdefinition.
Dissecting continued
8/8/2019 Developing and Testing a Java Program
24/27
COMPILING AJ AVAPROGRAM
To compile the Hello program, execute the compiler, javac , specifying the name of the source file.T he javac compiler creates a file called Hello.class
that contains the bytecode version of the program.To run the program, you must run the J ava interpreter,called java .To do so, pass the Hello.class file (it is enough to specify
only the primary name; the java interpreter will anywaylook for a Hello.class file) as a command line argumentto the java interpreter.
8/8/2019 Developing and Testing a Java Program
25/27
To run the program, you must run the J ava interpreter,
called java .
To do so, pass the Hello.class file (it is enough to specifyonly the primary name; the java interpreter will anyway
look for a Hello.class file) as a command line argument to
the java interpreter.
Com pilation continued
8/8/2019 Developing and Testing a Java Program
26/27
EXECUTING AJ AVAPROGRAM
To execute the program, enter the following at the
prompt:
c:\YourNa me> java classna me.class
To run your application, a user needs to install theJ ava virtual machine ( J VM), the J ava platform core
classes and various support programs and files.
T his collection of software is known as runti meenviron ment .
8/8/2019 Developing and Testing a Java Program
27/27
SUMMARY
You now shoul d be able to:
Id entify the components of a class in the Java
Programming Language
Learn the compilation techniques for creation of
.class files
Learn d ebugging techniques
Write a simple Java program
Dissect the first Java program
Compile and
execute a Java program