2
Java Syntax and Semantics Syntax
– The formal rules governing how valid instructions are written in a programming language
Semantics– The set of rules that determines the meaning of instructions
written in a programming language
Conventions– General agreement or consent; accepted usage, esp. as a
standard of procedure.
3
Types of errors
There are three general types of errors:– Syntax (or “compile time”) errors
» Syntax errors are “grammatical” errors and are detected when you compile the program
» Syntax errors prevent your program from executing
– Runtime errors» Runtime errors occur when you tell the computer to do something
illegal
» Runtime errors may halt execution of your program
– Logic errors » Logic errors are not detected by the computer
» Logic errors cause your results to be wrong
4
Common Compile Time Errors (Syntax)
1. Mismatched curly braces ({ or } expected).
2. Mismatched quotations.
3. Misplaced semicolon.
4. Improper file name.
5. Attempting to use variable before initializing it.
6. (cannot resolve symbol or <identifier> expected)
7. Mismatched parentheses. ( ( or ) expected)
8. Missing semicolon. (; expected)
9. Misspelling printLine method.
10. Package does not exist.
5
Classes and objects
Class– A description of behavior of a group of objects with
similar properties and behaviors
– A pattern for an object
– Contains fields or data values and methods. (Method: A subprogram that defines one aspect of the behavior of the class)
Object– An entity or thing that is relevant in the context of a
problem
– An instance of a class
6
Classes and Objects
How do we create an object from a class? Instantiation– Use of an operator called new, takes the class name and
returns an object of the class type.
– Object that is returned is an instance of the class
7
Organization of a class A class may contain data declarations and methods (and
constructors, which are like methods), but not statements A method may contain (temporary) data declarations and
statements A common error:
class Example {int variable ; // simple declaration is OKint anotherVariable= 5; // declaration with initialization is OKvariable = 5; // statement! This is a syntax error
void someMethod( ) { int yetAnotherVariable; //declaration is OK yetAnotherVariable = 5; // statement inside method is OK
}}
8
Getting started
Your programs will be full of errors, of all kinds You cannot avoid this, no matter how good you get You cannot learn not to make errors--it’s impossible
– But, with practice, you will get a little bit better
You can and must learn:– How to recognize the various types of errors
– How to find and fix them
What is important is not avoiding errors, but knowing how to fix them
9
What to do about errors
Error messages are your friends--read them and try to understand them
With practice, you can fix most syntax errors almost immediately
Runtime and logic errors may take considerably longer to track down and fix
Here’s what’s important to remember:– Everyone makes lots of stupid errors (and almost all errors are
stupid ones--mine included); it’s nothing to be ashamed of
– However, it is not OK to let those errors survive
– Approximately 90% of your time will be spent debugging
10
Syntax errors A syntax error is a “grammatical” error--bad
punctuation, misuse of keywords, etc. Syntax error messages tell you two things:
– The line number at which an error was detected» Usually, this is the line containing the error» In some cases, the actual error is earlier in the program text
– What the compiler thinks the problem is» Since the compiler cannot know what you meant, the message is
only a “best guess,” and is sometimes misleading
Syntax errors can cascade: An early error can cause spurious error messages later in the program– Always fix the earliest message first– If later messages don’t make sense, try recompiling
11
Example syntax errors
System.out.println("(g1 == g2) = " + (g1 == g2);– ')' expected
System.out.println("(g1 == g2) = " + (g1 == g2)));– ’;' expected
a = g1 + g2;– cannot resolve symbol -- variable a
» a was never declared; or» a was declared, but not where it can be seen from here
a = 5;– <identifier> expected
» This is a statement, and statements can only occur inside methods
a = b;– variable b might not have been initialized
12
Runtime errors A runtime error occurs when your program does
something illegal– Runtime errors typically stop your program
– Runtime errors can be “caught” by your program, thus allowing the program to continue running
» We’ll discuss how to do this later in the course
– Runtime errors are usually caused by something the program did (or failed to do) earlier in execution
»Because the cause of the error is somewhere else in the program, runtime errors are usually harder to solve
13
A common runtime errorn
java.lang.NullPointerException at Test.run(Test.java:22) at Test.main(Test.java:6) at __SHELL1.run(__SHELL1.java:6) at bluej.runtime.ExecServer.suspendExecution(ExecServer.java:187) at bluej.runtime.ExecServer.main(ExecServer.java:69)
} What kind of error it was
Traceback: How your program got to where the error was detected (in line 22 of the file Test.java)
The part of the traceback in your code (line 22 of the file, in your run method, called from line 6 of the file, in your main method)
The part of the traceback in the Java and BlueJ system; you can pretty much ignore this part
14
Null pointer exceptions
The NullPointerException is one of the most common runtime errors– It occurs when you send a message to a null variable (a
non-primitive variable that doesn’t refer to an actual object)
– The null variable causing the problem is always just before a dot
– Example: g.drawLine(x1, y1, x2, y2);» If this caused a NullPointerException, the variable g must
have been null
» You probably never initialized g» Java tries to catch uninitialized variables, but it cannot catch
them all
15
Logic errors
A logic error is when your program compiles and runs just fine, but does the wrong thing
In very simple programs, logic errors are usually easy to find and fix, if they occur at all
In all but the simplest of programs,– 10% of your time is spent writing the program and fixing the
syntax errors (more if you are still learning the syntax)
– 90% of your time is spent finding and fixing runtime and logic errors
Logic errors can take hours, or even days, to find– Allocate your time accordingly!
16
Make better use of your time While you cannot avoid making errors, you can prepare
for them– Keep your programs as simple as possible
– Indent properly so you can see the structure of your code
– Comment your programs so you can find things again
– Write test cases and use them» “Write a little, test a little”
– Write assert statements for the things that you “know” cannot possibly happen
Programming is a creative activity, and can be very enjoyable and satisfying– For most of us, debugging is not the fun part
17
Approaches to finding errors
Try a random change and see if it helps– “An infinite number of monkeys, given an infinite number of
typewriters, will eventually produce the complete works of Shakespeare”
– No monkey has ever passed this course
– You can’t afford this approach--it’s stupid and doesn’t work
Better approach: Think about what could have caused the results you see, and then look for where that might have occurred– Advantage: Leads you directly to the error
– Disadvantage: Not always possible to figure out what could have happened
18
Good approaches, I
Put in print statements– Advantage: Helps you see what the program is doing
– Disadvantage: You have to take them out again
Use a Debugger– A debugger is a program that lets you step through your
program line by line and see exactly what it is doing
– Advantages:» Takes no prior preparation
» Lets you see exactly what the program is doing
– Disadvantages» You have to learn to use one
BlueJ has one!
19
Good approaches, II Explain your code to a friend (even if your friend
can’t program)– Advantage: Forces you to actually look at what you did– Disadvantage: Requires you to have friends
» In a pinch, even your dog will do (if you can get him to hold still long enough)
– Note: This is not a violation of academic honesty! In extremis: Throw out the offending code and
rewrite it– Advantages:
» Usually works» Usually makes your code simpler
– Disadvantage: Can be psychologically difficult
20
Why such high standards?
Large programs are the most complex entities ever devised by mankind– Large programs consist of thousands of methods and
hundreds of thousands of lines
– A single error can cause catastrophic failure
– There are a great many examples, from space vehicles crashing to deaths from badly programmed medical equipment
– We give partial credit for “mostly working” programs--and, believe it or not, I think this is generous
21
Conventions Capitalization of Identifiers
Variables and methods begin with a lowercase letter and capitalize each successive English word.– lenghtInYards middleInitial hours
Class names begin with an upper case letter but are capitalized the same as variable names thereafter.– PayRollFrame String MyDataType
Identifiers representing named constants are all upper case with underscores used to separate the English words– BOOK_TITLE OVERTIME MAX_LENGTH
22
Spaces You should put a single space around every binary
operator, including comparisons and = Example: perimeter=2*(width+height); Do not put spaces just inside parentheses:
perimeter = 2 * (width + height); //bad These are style rules, not Java rules
– If you break these rules, your program will still compile OK, but you will lose points if we notice
23
Indentation and spacing if(x<10){
___x=x+1;}else{___x=x-1;}
OR: if(x<10){
___x=x+1;}else{___x=x-1;}
while(x>0){___System.out.println(x);___x=x-1;}
Recommended indentation is from 2 to 4 spaces, but must be consistent throughout the program
Notice that there is not a space after println
Most important style rule: If you are modifying or adding to an existing program, keep to the original style (whatever it may be)
25
Data Types
Data is stored internally in memory, externally on disk or tape or input from an input device
Data type determines how the data is represented in the computer and the kinds of processing the computer can perform on it.
26
Data Types Standard or built-in data types
– Used frequently and provided by Java
– integer number, real number, characters and boolean
User-defined or Complex data types– These are referred to as classes
27
The String Class A string is a sequence of characters enclosed in double
quotes. In Java, a string is an object, an instance of the class
String. Examples
– “Introduction to” “Program” “ Design”
A string must be typed entirely on one line Quotes are not considered parts of the string
28
Declarations – defining terms
A statement that associates a name (an identifier) with a description of an element in a Java program. - elements : field, a method, a class or a package sot that the
programmer can refer to that item by name.
int minAB;
– Compiler picks a location in memory to be associated with identifier
29
Declarations In Java, the identifier must be declared before it is used. Allows compiler to verify that the use of the identifier is
consistent with what it is declared to be.– Java is strongly typed. A variable can only contain a value of the
type or class specified in its declaration Fields can be variable or constant
30
Variables
?VARIABLE
Variable Identifier
char myChar;
myChar(memory location 111001010101)
VALUE DATA TYPE
(char)
31
Variables
A variable is a location in memory, referenced by an identifier or name, that contains a data value that can be changed
Variable declarationModifiers TypeName Identifier, Identifier...;
TypeName – Name of class or type such as char or String
char letter, middleInitial, ch;OR
char letter;char middleInitial;char ch;
Top Related