1 / 55

Chapter 2 The Elements of Java

Chapter 2 The Elements of Java. Knowledge Goals. Understand the difference between syntax and semantics Understand the distinction between built-in types and objects Recognize how the char type and String class are related and differ

Download Presentation

Chapter 2 The Elements of Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2 • The Elements of Java

  2. Knowledge Goals • Understand the difference between syntax and semantics • Understand the distinction between built-intypesand objects • Recognize how the char type and String class are related and differ • See the difference between objects in general and their use in Java

  3. Knowledge Goals • Understand the difference between a named constant and a variable • See why it is important to use meaningful identifiers in Java • Understand what happens in an assignment operation • Recognize how voidand value-returning methods differ in their use

  4. Skill Goals • Read and understand the formal syntax governing Java programs • Distinguish between reserved words and identifiers • Create and recognize legal Java identifiers • Write simple output statements using the System.out class • Construct a Java application

  5. Skill Goals • Declare fields of type charand String • Assign values to variables • Construct string expressions • Use commentsto clarify programs • Instantiate a Scannerobject • Write Stringinput operations using the Scanner class • Design and interactive user interface

  6. Grammar and Words • 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 • Metalanguage • A language that is used to write the syntax rules Syntax says how to write an instruction Semantics says how to interpret an instruction

  7. Grammar and Words Syntax Template shading: optional ellipsis (…): repetition colored word: use as is black word: another template

  8. Grammar and Words • Reserved Word • A word that has a specific predefined meaning public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Underlined are reserved

  9. Grammar and Words • Identifiers • A word that we define to name something in an application; should be meaningful public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Bold are identifiers

  10. Grammar and Words Identifiers

  11. Grammar and Words • 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 TaxRaeY2K • HourlyEmployee ageOfDog • Not valid (Why?) • age# 2000TaxRate Age-Of-Dog • class char Beware: Java is case sensitive!

  12. Grammar and Words • Identifier (revised) • A name associated with a package, class, method, or field and used to refer to that element • Method • A subprogram in Java; an operation that carries out a responsibility • Field • A named place in memory that holds data

  13. 51 Java Reserved Words • abstract assert boolean break byte case catch char class const continue default do double else enum extends false* final finally float for goto if implements import instanceof int interface long native new null* package private protected public return short static strictfp super switch synchronized this throw throws transient true* try void volatile while • *false, null, and true are technically not reserved words. They are predefined literals that cannot be used as identifiers Reserved words cannot be used as identifiers

  14. Building Blocks • Data Type • Each piece of data has a specific type that determines how the data is represented in a computer • Standard (built-in) types • A data type that is automatically available for use in every Java application • Primitive type • Any of the built-in types that represent integral, real, characters, or Boolean values

  15. Java Primitive Data Types primitive integral boolean floating point byte char short int long float double We cover char here, the rest of the integral types and floating-point types in Chapter 4, and Boolean in Chapter 5

  16. Building Blocks • Character Set • A list of letters, digits, and symbols with corresponding binary representations in the computer • ASCII (pronounced ask-key) • A character set made up of English letters plus numbers and symbols; each character was 16 bits • Unicode • A superset of ASCII in which each character is represented by 32 bits Why do we need 32-bits for a character?

  17. Building Blocks • char data type • A built-in type consisting of one alphanumeric character • Examples: 'A' 'a' '1' '?' 'x' • Collating sequence • The ordering of characters, with respect to one another, within a character set • Uppercase letters are ordered • Lowercase letters are ordered • Numbers are ordered Why do we put quotes around a character?

  18. Building Blocks • Classes and Objects • Review of vocabulary • Object (general sense) An entity or thing that is relevant in the context of a problem • Object (Java) An entity containing data in fields with associated operations • Class (general sense) A description of the attributes and behavior of a group of objects with similar properties and behaviors • class (Java construct) A pattern for an object containing fields and methods

  19. Building Blocks • Responsibility An operation associated with a class • Method A subprogram that defines one aspect of the behavior of a class (a responsibility) • Instance A way of referring to an object as being an example of its class • Instantiation Creating an object, which is an instance of a class

  20. Building Blocks • String (general sense) • A sequence of characters, such as a word, name, or sentence, enclosed in double quotes • String (Java sense) • An object; an instance of the String class • Actually, Java strings are written in a program like general strings: within double quotes • Can you explain why char is lowercase • and String is uppercase?

  21. Building Blocks public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Method call

  22. Building Blocks • Call • A statement that causes a method to be executed; in Java we call a method by writing its name, followed by a list of arguments enclosed in parentheses • Argument • An expression used to communicate values to a method

  23. Building Blocks

  24. Building Blocks • System: class name (uppercase) • out: object name (lowercase) • println: method, print and go to new line • print: method, print and remain on same • line • What is printed by • System.out.print("Hi"); • System.out.println("neighbor"); • System.out.println():

  25. Building Blocks • Call (another view) • Sends a message to an object to execute a responsibility • System.out.println("neighbor"); • sends a message to System.out to execute its println responsibility; "neighbor" is the information that println needs to carry out its responsibility

  26. Putting the Pieces Together class DoNothing { } Simplest class Does it match the diagram?

  27. Putting Pieces Together • Where's the action? • To be a program (application) there must be a method main with this exact heading • public static void main(String[] args) • { • // Code for doing something • } What do you think String[] args is?

  28. Putting the Pieces Together Access modifiers Reserved words in Java that specify where a class, method, or field may be accessed; private and public are access modifiers

  29. Putting the Pieces Together Needed for input import java.util.Scanner; import java.io.*; Needed for more output

  30. Putting the Pieces Together • public class MessageOut • { • public static void main(String[] args) • { • System.out.println("Good morning neighbor!"); • System.out.println("What a beautiful day!"); • System.out.print("What is on your agenda?"); • System.out.println(); • } • } How do we know this is an application?

  31. Putting the Pieces Together Compiling and running cycle

  32. Extending the Java Dictionary • How do we define problem-related words? • Declaration • A statement that associates an identifier with field, a method, a class, or a package so that the programmer can refer to it by name myChar, myFirstName, myLastName, myName are all variables char myChar; String myFirstName; String myLastName; String myName;

  33. Extending the Java Dictionary • Variable • A location in memory, referenced by an identifier, that contains a data value that can be changed Type specifies what can be stored in the variable

  34. Extending the Java Dictionary State after declaration

  35. Extending the Java Dictionary What does this declaration actually do? char myInitial; The compiler allocates enough memory to hold a value of the char data type (2 bytes) and associates the identifier myInitial with this location myInitial

  36. Extending the Java Dictionary • But how do we get a value into a variable? Yes, but what is an expression?

  37. Extending the Java Dictionary • Assignment statement • A statement that stores the value of an expression into a variable • Expression • An arrangement of identifiers, values, and operators that can be evaluated to compute a value of a given type • Evaluate • To compute a new value by performing a specified set of operations on given values

  38. Extending the Java Dictionary • myChar = 'B';

  39. Extending the Java Dictionary • myChar = 'B'; • myFirstName = "Susy"; • myLastName = "Sunshine"; • myName = myFirstName + ' ' + myChar + • myLastName; • System.out.println(myName); Characters are in single quotes Strings are in double quotes + is the concatenation operator

  40. Extending the Java Dictionary • Initializer expressions char myChar = 'B'; String myFirstName = "Susy"; String myLastName = "Sunshine"; String myName = myFirstName + " " + myChar + ' ' + myLastName; What is the difference between ' ' and " "?

  41. Extending the Java Dictionary • What do these declarations actually do? char myChar = 'B'; String myFirstName = "Susy"; • The compiler creates the following in memory myChar myFirstname S u s y B Assignment of primitive types vs. objects

  42. Extending the Java Dictionary • Literal constant • Any value written directly in Java • Named (symbolic) constant • A location in memory, referenced by an identifier, that contains a data value that cannot be changed final is the keyword final String BORDER = "*********"; final char BLANK = ' ';

  43. Extending the Java Dictionary • No, we haven't forgotten to define static ; we have just ignored it • Class fields • Fields that belong to the class as a whole; there is one copy for the class • Instance fields • Fields that belong to an instance of a class; each instance has its own field • static fields are class fields

  44. Extending Java Dictionary • Local declarations • Declarations that are defined within a method • Thus there are three kinds of declarations • class (marked static) • instance (marked private or public) • local (carry not modifiers) (Why?)

  45. Extending Java Dictionary • Documentation • The written text and comments that make an application easier for others to understand, use, and modify • Implicit documentation • Use of coding conventions to give meaning to identifiers • constants: all uppercase • classes: begin with uppercase • variables and methods: begin with lowercase

  46. User Input

  47. User Input Access Scanner class • import java.util.Scanner; • Scanner in; • in = new Scanner(System.in); Declare Scanner variable Instantiate Scanner object The name of a class used on the right of an equal sign following word new is a call to the class's constructor, which creates and returns an instance of the class, which is then stored in the variable on the left of the equal sign

  48. User Input • String firstName; • System.out.println("Enter first name"); • firstName = in.nextLine(); • System.out.println("Welcome " + firstName); If the user types in "Sarah", what is printed?

  49. User Input Place to store input • String firstName; • System.out.println("Enter first name"); • firstName = in.nextLine(); Prompt for input Method call to in object Line of typing is stored in firstName

  50. User Input • firstName = in.nextLine(); • nextLine is a value-returning method; it returns the next line of input, which is then stored into firstName Why is there no expression between the parentheses?

More Related