Download presentation
Presentation is loading. Please wait.
1
1 Chapter 2 Java Syntax and Semantics, Classes, and Objects
2
2 Chapter 2 Topics l Elements of Java Programs l Application Construction l Application Entry, correction, and Execution l Classes and methods
3
3 What is syntax? l Syntax is a formal set of rules that defines exactly what combinations of letters, numbers, and symbols can be used in a programming language l Syntax rules are written in a simple, precise formal language called a metalanguage l Examples are Backus-Naur-Form, syntax diagrams, and syntax templates
4
4 l Blue shading indicates an optional part of the definition. Three dots... mean the preceding symbol or shaded block can be repeated. A word not in color can be replaced with another template. Identifier Letter Letter... _ _ Digit $ $ Identifier Syntax Template
5
5 A a B b C c D d E e F f G g H h I J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z Letter 01234567890123456789 Digit
6
6 Java Identifiers l A Java identifier must start with a letter or underscore or dollar sign, and be followed by zero or more letters (A-Z, a-z), digits (0-9), underscores, or dollar signs. VALID age_of_dog taxRateY2K HourlyEmployee ageOfDog NOT VALID (Why?) age# 2000TaxRate Age-Of-Dog
7
7 What is an Identifier? l An identifier names a class, a method (subprogram), a field (a variable or a named constant), or a package in a Java application l Java is a case-sensitive language; uppercase and lowercase letters are different l Using meaningful identifiers is a good programming practice
8
51 Java Reserved Words abstractbooleanbreakbytecase catchcharclassconst continue default dodoubleelseextends false finalfinallyfloatfor gotoifimplementsimportinstanceof int interfacelongnativenew nullpackageprivateprotectedpublic returnshortstatic strictfpsuper switch synchronizedthisthrowthrows transienttruetryvoidvolatile while Reserved words cannot be used as identifiers.
9
9 Samples of Java Data Values int sample values 4578 -4578 0 double sample values 95.274 95..265 char sample values ‘ B ’ ‘ d ’ ‘ 4 ’ ‘ ? ’‘ * ’
10
10 ASCII and Unicode l ASCII (pronounced ask-key) is an older character set used to represent characters internally as integers l ASCII is a subset of the newer Unicode character set l The character ‘A’ is internally stored as integer 65, and successive alphabet letters are stored as successive integers. l This enables character comparisons with ‘A’ less than ‘B’, etc.
11
11 Primitive Data Types in Java l Integral Types ncan represent whole numbers and their negatives when declared as byte, int, short, or long ncan represent single characters when declared as char l Floating Point Types nrepresent real numbers with a decimal point ndeclared as float, or double
12
12 Java Primitive Data Types primitive integralfloating point byte char short int long float double boolean We cover boolean in Chapter 4.
13
13 Vocabulary Review l class (general sense: A description of a group of objects with similar properties and behaviors class (Java construct) A pattern for an object l Object (general sense) An entity or thing that is relevant in the context of a problem l Object (Java) An instance of a class l Instantiation Creating an object, which is an instance of a class l Method A subprogram that defines one aspect of the behavior of a class
14
14 Simplest Java class class DoNothing { } HEADING BODY
15
What’s in a class heading? public class PrintName ACCESS MODIFIER class IDENTIFIER
16
16 l A block is a sequence of zero or more statements enclosed by a pair of curly braces { }. Block { Statement... } Block (Compound Statement)
17
17 What is a Variable? l A variable is a location in memory to which we can refer by an identifier, and in which a data value that can be changed is stored l Declaring a variable means specifying both its name and its data type or class
18
18 What Does a Variable Declaration Do? A declaration tells the compiler toallocate enough memory to hold a value of this data type, and to associate the identifier with this location. int ageOfDog; 4 bytes for ageOfDog
19
19 Variable Declaration Modifiers TypeName Identifier, Identifier... ; Constant Declaration Modifiers final TypeName Identifier = LiteralValue; Syntax for Declarations
20
20 Java String Class l A string is a sequence of characters enclosed in double quotes. l string sample values “Today and tomorrow” “His age is 23.” “A” (a one character string) The empty string contains no characters and is written as “”
21
21 Actions of Java’s String class l String operations include njoining one string to another (concatenation) nconverting number values to strings nconverting strings to number values ncomparing 2 strings
22
22 What is a Named Constant? l A named constant is a location in memory to which we can refer by an identifier, and in which a data value that cannot be changed is stored. VALID NAMED CONSTANT DECLARATIONS final String STARS = “****”; final float NORMAL_TEMP = 98.6; final char BLANK = ‘ ’; final int VOTING_AGE = 18; final double MAX_HOURS = 40.0;
23
23 Giving a value to a variable You can assign (give) a value to a variable by using the assignment operator = VARIABLE DECLARATIONS String firstName; char middleInitial; char letter; int ageOfDog; VALID ASSIGNMENT STATEMENTS firstName = “Fido”; middleInitial = ‘X’; letter = middleInitial; ageOfDog = 12;
24
24 Why is String uppercase and char lower case? char is a built in type String is a class that is provided nClass names begin with uppercase by convention
25
Variable = Expression; First, Expression on right is evaluated. Then the resulting value is stored in the memory location of Variable on left. NOTE: The value assigned to Variable must be of the same type as Variable. Assignment Statement Syntax
26
26 String concatenation (+) l Concatenation uses the + operator. l A built-in type value can be concatenated with a string because Java automatically converts the built-in type value for you to a string first.
27
27 Concatenation Example final int DATE = 2003; final String phrase1 = “Programming and Problem “; final String phrase2 = “Solving in Java “; String bookTitle; bookTitle = phrase1 + phrase2; System.out.println(bookTitle + “ has copyright “ + DATE);
28
28 System.out.print (StringValue); System.out.println (StringValue); Using Java output device METHOD CALL SYNTAX These examples yield the same output. System.out.print(“The answer is, ”); System.out.println(“Yes and No.”); System.out.println(“The answer is, Yes and No.”);
29
29 Java Input Devices l More complex than Output Devices l Must set one up from a more primitive device InputStreamReader inStream; inStream = new InputStreamReader(System.in); // declare device inData BufferedReader inData; inData = new BufferedReader(inStream)
30
30 Using a Java Input Device // Get device in one statement inData = new BuffredReader(new InputStreamReader(System.in)); String oneLine; // Store one line of text into oneLine oneLine = inData.readLine(); Where does the text come from?
31
31 Interactive Input readLine is a value-returning method in class BufferedReader readLine goes to the System.in window and inputs what the user types l How does the user know what to type? The program (you) tell the user using System.out
32
32 Interactive Output continued BufferedReader inData; inData = new BufferedReader(new InputStreamReader(System.in)); String name; System.out.print(“Enter name: ”); name = inData.readLine(); Name contains what the user typed in response to the prompt
33
33 A Java Application Must contain a method called main() Execution always begins with the first statement in method main() l Any other methods in your program are subprograms and are not executed until they are sent a message
34
34 // ****************************************************** // PrintName prints a name in two different formats // ****************************************************** public class PrintName { public static void main (String[ ] args) { BufferedReader inData; String first; // Person’s first name String last; // Person’s last name String firstLast; // Name in first-last format String lastFirst; // Name in last-first format inData = new BufferedReader(new InputStreamReader(System.in)); Java Program
35
35 Java program continued System.out.print(“Enter first name: “); first = inData.readLine(); System.out.print(“Enter last name: “); last = inData.readLine(); firstLast = first + “ “ + last; System.out.println(“Name in first-last format is ” + firstLast); lastFirst = last + “, “ + first; System.out.println(“Name in last-first format is ” + lastFirst); }
36
36 Method Declaration Modifiers void Identifier (ParameterList) { Statement... } Method Declaration Syntax
37
37 Statement Syntax Template Statement NullStatement LocalConstantDeclaration LocalVariableDeclaration AssignmentStatement MethodCall Block NOTE: This is a partial list.
38
38 /* This is a Java comment. It can extend over more than one line. */ /* In this second Java comment the asterisk on the next line * is part of the comment itself. */ One Form of Java Comments l Comments between /* and */ can extend over several lines.
39
39 Another Form of Java Comment l Using two slashes // makes the rest of the line become a comment. // ****************************************************** // PrintName prints a name in two different formats // ****************************************************** String first; // Person’s first name String last; // Person’s middle initial
40
40 Debugging Process Enter program Compile program Compile-time errors? Run program Logic errors? Success! Figure out errors, get back into editor, and fix errors in program. Go back to algorithm and fix design. Get back into editor and fix errors in program. No Yes
41
41 ClassesRevisited class Name { String first; String second; } Classes are active; actions, called methods, are bound (encapsulated) with the class variables
42
42 Methods l Method heading and block void setName(String arg1, String arg2) { first = arg1; second = arg2; } l Method call (invocation) Name myName; myName.setName(“Nell”, “Dale”);
43
43 Some Definitions l Instance field A field that exists in ever instance of a class String first; String second; l Instances method A method that exists in every instance of a class void setName(String arg1, String arg2); myName.setName(“Chip”, “Weems”); String yourName; yourName.setName(“Mark”, “Headington”);
44
44 More Definitions l Class method A method that belongs to a class rather than it object instances; has modifier static Date.setDefaultFormat(Date.MONTH_DAY_YEAR); l Class field A field that belongs to a class rather than its object instances; has modifier static Will cover class fields in later chapters
45
45 More Definitions Constructor method Special method with the same name as the class that is used with new when a class is instantiated public Name(String frst, String lst) { first = frst; last = lst; } Name name; name = new Name(“John”, “Dewey”); Note: argument cannot be the same as field
46
46 Void Methods l Void method Does not return a value System.out.print(“Hello”); System.out.println(“Good bye”); name.setName(“Porky”, “Pig”); object method arguments
47
47 Value-Returning Methods l Value-returning method Returns a value to the calling program String first; String last; Name name; System.out.print(“Enter first name: “); first = inData.readLine(); System.out.print(“Enter last name: “); last = inData.readLine(); name.setName(first, last);
48
48 Value-returning example public String firstLastFormat() { return first + “ “ + last; } System.out.print(name.firstLastFormat()); object method Argument to print method is string returned from firstLastFormat method
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.