Compilation Errors

Download Report

Transcript Compilation Errors

Debugging
Polymorphism and Interface
Applet
Hands on Computing with Java
Topics
• Debugging techniques
• Advanced OO: Polymorphism
• Abstraction through Interface
• Java Applet
Debugging – a process of finding and
reducing/fixing bugs (errors or mistakes) in a
computer program.
Types of errors
• Compilation Errors
– Program cannot be compiled successfully
• Runtime or Logical Errors
– Program is compiled successfully but runs incorrectly
or crashes
Outline
• Compilation Errors
– Typical Causes of Compilation Errors
– Strategy for locating and fixing compilation errors
• Runtime/Logical Errors
– Typical Causes of Runtime or Logical Errors
– Strategy for locating and fixing logical errors
• Debugging programs with IDE (NetBeans)
• Interpreting Stack Trace of an Exception
• Adding codes to help detecting bugs
Typical Causes of Compilation Errors
• Misspelled names
– e.g.: Mixed up lowercase/uppercase letters
• Mismatched parentheses or double quotes
– i.e.:
{
}
[
]
(
)
"
• Omitting punctuation symbols
– e.g:
;
:
,
• Not closing a multi-line comment /* ... */
• Improper use of APIs
– e.g.: int x = Math.sqrt("1.23");
1
2
3
4
5
6
7
8
9
10
11
12
/********************************************
/ A program that yields compilation errors.
/*********************************************/
class DebugDemo1 {
public static void main(String args[]) {
if (args.length > 0) {
System.out.println("Hello, ");
System.out.println(args[0] + "!");}
} else
System.out.println("Hello, you!");
}
}
Where's the bug?
Hello.java:9: illegal start of type
} else
^
Hello.java:10: <identifier> expected
System.out.println("Hello, you!");
^
Hello.java:12: 'class' or 'interface' expected
}
^
Hello.java:13: 'class' or 'interface' expected
^
4 errors
There are so many compilation errors!
Which error should I fix first?
• Fact: Many of the errors listed by the compilers
are caused by the errors that appear before them.
• What should you do?
– Locate and fix the first error listed by the compiler and
recompile your program (and repeat the process as long
as you need to).
I can't find the error at line xxx!
• Fact: The bug that corresponds to the compilation
error message could appear anywhere before or
at the line indicated by the compiler.
• What should you do?
– Inspect the code backward starting at the line indicated
by the compiler (usually just within few lines)
– Divide and conquer: Use /* … */ to comment out the
block of codes that may contain the bug, then gradually
reduce the search range.
I don't know what these compilation
errors mean!
•
•
•
•
illegal start of type
'class' or 'interface' expected
cyclic inheritance involving Main
blank final
Don't panic!
• Ignore the error message and just inspect the code around
the line indicated by the compiler
Don't give up easily!
• Try harder for a little longer (After all, it is your code.)
• "Google" the error message for possible solutions
• Last resort: Ask TAs or teachers
Outline
• Compilation Errors
– Typical Causes of Compilation Errors
– Strategy for locating and fixing compilation errors
• Runtime/Logical Errors
– Typical Causes of Runtime or Logical Errors
– Strategy for locating and fixing logical errors
• Debugging programs with IDE (NetBeans)
• Interpreting Stack Trace of an Exception
• Adding codes to help detecting bugs
Typical Causes of Runtime Errors
• Uninitialized Variables
• Forget to create an object using the "new" operator
before using the object
e.g.:
String s;
int len = s.length();
• Miscalculated index range
e.g.:
String s = "abc";
char lastLetter = s.charAt(3);
• Implemented a "wrong" solution
Interest R ate Months
Interest  Principal * (1 
)
 Principal
12
// A program to compute interest
class CalculateInterest {
public static void main(String args[]) {
double interestRate, principal, interest;
int months;
}
}
// Input
…
Suppose this program always prints
the interest as $0.00.
// Calculation
…
What could go wrong?
// Output
…
How should you approach to locate
the bug?
Basic approaches to find bugs
• Inspect the value of variables
– The behavior or the output of your program
depend on the values of some variables.
Basic Approaches To Locate Bugs
• Inspect the value of variables
– Select some input values which you know what
the output is
– Decide which variables to inspect and where to
inspect them
– Print the value of the variables (to see if they
match your expected values)
Decide which variables to inspect
class CalculateInterest {
public static void main(String args[]) {
double interestRate, principal, interest;
int months;
}
}
// Input
…
Input: Does not depend on any variable
// Calculation
…
Calculation: Depends on interestRate,
principal, and months
// Output
…
Output: Depends on interest
Output the value of the dependent variables
class CalculateInterest {
public static void main(String args[]) {
double interestRate, principal, interest;
int months;
// Input
…
System.out.println("Before calculation: ");
System.out.println("interestRate = " + interestRate);
System.out.println("principal = " + principal);
System.out.println("months = " + months);
// Calculation
…
System.out.println("Before output: ");
System.out.println("interest = " + interest);
// Output
…
}
}
Debugging part of program
• Sometimes you may only want to debug part
of your program because …
– The rest of the code have already been fully
tested
– Execution time is long
• e.g: You only want to test the output part but the
calculation part takes several hours to complete
– That's the only part that you write/modify.
Debugging only the "Calculation" part …
class CalculateInterest {
public static void main(String args[]) {
double interestRate, principal, interest;
int months;
// Input
…
interestRate = 0.12; // 12%
Manually set the value of the
principal = 10000;
dependent variables
months = 2;
// Expected interest is 201
// Calculation
…
System.out.println("interest = " + interest);
// Output
…
}
}
Check the calculated value
against the expected value
Debugging only the "Calculation" part …
class CalculateInterest {
public static void main(String args[]) {
double interestRate, principal, interest;
int months;
/*
Optionally, comment the codes that are not
// Input
subject to testing
…
*/
interestRate = 0.12; // 12%
principal = 10000;
months = 2;
// Expected interest is 201
// Calculation
…
System.out.println("interest = " + interest);
/*
// Output
…
*/
}
}
Outline
• Compilation Errors
– Typical Causes of Compilation Errors
– Strategy for locating and fixing compilation errors
• Runtime/Logical Errors
– Typical Causes of Runtime or Logical Errors
– Strategy for locating and fixing logical errors
• Debugging programs with IDE (NetBeans)
• Interpreting Stack Trace of an Exception
• Adding codes to help detecting bugs
Introduction
How can IDE help you in debugging your
programs?
– Visual debugger (easy to use)
– Allows you to specify where to pause an
executing program
– Allows you to inspect the value of the variables
when a program is paused
– Allows you to trace your program execution
Running Program in Debugging Mode
• Run Main Project (F6)
– Execute the program in normal mode
• Debug Main Project (Ctrl+F5)
– Execute the program in debugging mode
– Debugger can pause a program ONLY WHEN
you are running the program in debugging
mode
Specifying Where To Pause A Program
A breakpoint typically represents a location (usually
a line of code) where an executing program is
paused.
To toggle (set or remove) a
breakpoint at a line of code, click at
the spot in the left grey area next to
the line in the editing window.
A small red square indicates that a
break point is set at that line.
Multiple breaks points are allowed.
Inspecting Value of Variables
When a program is paused, you can view the
value of the variables through:
• "Local Variables" window (Alt-Shift-1)
– Automatically shows all the initialized local
variables
• "Watches" window (Alt-Shift-2)
– Shows only the variables added manually by
the programmer.
In Between Breakpoints
When you want to continue running your
program, you can use
• Continue (F5)
– continue execution until next breakpoint is
encountered
• Step
– Take one "step" of execution and pause
– How big is one step?
Stepping
• Step Over (F8)
– Execute one line of code and pause
• Step Into (F7)
– If a line of code involves a method call, go into the
method if possible and pause
– Otherwise, execute one line of code and pause
• Step Out (Ctrl-F7)
– Execute the remaining lines of codes in the current
method and pause
Other Features
• Run to cursor (F4)
– Use the cursor in the editing window as a temporary
breakpoint so execution will pause at the cursor.
• Finish Debugger Session (Shift-F5)
– Stop debugging the program
Outline
• Compilation Errors
– Typical Causes of Compilation Errors
– Strategy for locating and fixing compilation errors
• Runtime/Logical Errors
– Typical Causes of Runtime or Logical Errors
– Strategy for locating and fixing logical errors
• Debugging programs with IDE (NetBeans)
• Interpreting Stack Trace of an Exception
• Adding codes to help detecting bugs
Interpreting Stack Trace of an Exception
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 3
at java.lang.String.charAt(String.java:558)
at javaapplication1.Main.someMethod(Main.java:33)
at javaapplication1.Main.main(Main.java:27)
From time to time, you may come across error
messages that look like this.
How should you interpret the message?
Try clicking on the lines with “at java….”
Adding codes to help detecting bugs
• 預防勝於治療
• You can minimize runtime errors in your
program by adding code to check variables
against invalid values.
• e.g.:
// Before calculate interest …
if (month < 0 || principal < 0.0 ||
interestRate < 0.0) {
// Print an error message and perhaps
// write code to recover from the error.
}
Summary
• Techniques for locating and fixing
compilation errors
• Techniques for locating and fixing
runtime/logical errors
• Using the debugger integrated in
NetBeans to debug programs
3-Minute Soft Break
Next…revision on OO concepts,
to introduce Polymorphism
Subclass Object Reference
• Given the following subclass relationship:
class OctopusWatch extends Octopus
Octopus
(class)
OctopusWatch
(class)
Subclass Object Reference
• Do you recall:
short s = 999;
OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);
Octopus
(class)
myWatch
OctopusWatch
(object)
OctopusWatch
(class)
Subclass Object Reference
• Super-class object reference to sub-class object:
short s = 999;
int
i = s;
// copy value of s to i
OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);
Octopus anOctopus = myWatch;
// copy object reference
myWatch
anOctopus
OctopusWatch
(object)
Octopus
(class)
OctopusWatch
(class)
General VS Special
• A super-class type is considered to be general.
• A sub-class type is said to be special.
• Why?
• Because we supplement the sub-class
– Adding fields and methods
• Thus, an object of the sub-class type is also
considered to be an object of the super-class
type.
Limit Yourself
• Super-class object reference to sub-class object:
OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);
myWatch.showTime();
// ok
Octopus anOctopus = myWatch;
anOctopus.addValue(100);
anOctopus.showTime();
// copy object reference
// ok
// invalid operation
myWatch.useValue(6.5);
// ok
• Object reference of the super-class type cannot refer to
the fields/methods newly defined by the sub-class.
Michael’s Nature Example
Inheritance is also known as specialization!
What For?
• Dynamic binding or known as
Polymorphism.
• By overriding a method declared in the
super-class, we may send the same
message to different objects of different
(class) type.
Polymorphism
• Super-class object reference to sub-class object:
OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);
Octopus
myCard = new Octopus(“Microphone”);
Octopus anOctopus;
anOctopus = myWatch;
anOctopus.useValue(10.2);
anOctopus = myCard;
anOctopus.useValue(6.5);
//
//
//
//
//
an object reference
copy object reference
ok
copy object reference
ok
• The object anOctopus via which in fact is sometimes
sending messages to an Octopus object while
sometimes to an OctopusWatch object.
Better Design Methodology
• This supports incremental development.
• We may create new classes from existing
ones and override their methods.
• In such case, messages sending to these
“new” objects may behave differently.
Backward Type Casting
• Backward type casting needs an explicit target type:
OctopusWatch myWatch = new OctopusWatch(“Michael Fung”);
Octopus anOctopus;
anOctopus = myWatch;
anOctopus.useValue(10.2);
// an object reference
// copy object reference
// ok
OctopusWatch aWatch;
aWatch = (OctopusWatch) anOctopus;
aWatch.showTime();
• Beware of the type given!!!
– It must be a correct/compatible one!
// specializing
// ok then
Abstraction Through Interface
interface InterfaceIdentifier
{
type1 method1(parameter1);
type2 method2(parameter2);
...
}
class ClassIdentifier implements Interface1, Interface2
{
type1 method1(parameter1)
{
}
type2 method2(parameter2)
{
}
...
}
Interface
•
•
•
•
An interface is a specification.
It is a standard.
It is a list of method signatures.
It is a guarantee: any class that
implements this interface is guaranteed to
provide these methods.
Example
• The AWT uses interfaces extensively.
interface MouseMotionListener
{
// simplified version
public void mouseDragged(MouseEvent e);
public void mouseMoved(MouseEvent e);
}
// in some Component class:
void addMouseMotionListener(MouseMotionListener obj);
• The method is not requesting a class type or
primitive type parameter.
• It is requesting a parameter of ANY class type
that meets the MouseMotionListener standard.
3-Minute Soft Break
Next…Java Applet
Applet
• Mini-application run by a browser
• A number of security restrictions on what
applets can do e.g. local file system
• Extends applet and overriding some
standard methods
• Browser will invoke your method when
some events happen e.g. initialization
Applet
• init()
called when applet first loaded, pefrorming initialisation
• destroy()
called when unloading, for freeing resources
• stop()
called when temporarily invisible e.g scrolling
• getAppletInfo()
get information about the applet i.e. a string
• paint()
browser invokes to ask the applet draw itself
• mouseDown()
responds to mouse click
Applet
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet {
public void paint(Graphics pen) {
pen.drawString("Hello World", 25, 50);
}
Compile the above FirstApplet.java to
}
FirstApplet.class
•
With the following HTML file applet.html
<APPLET code="FirstApplet.class" width="150" height="100">
</APPLET>