Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java How to Program, 11/e Questions?

Similar presentations


Presentation on theme: "Java How to Program, 11/e Questions?"— Presentation transcript:

1 Java How to Program, 11/e Questions? E-mail paul.deitel@deitel.com
Chapter 2 Introduction to Java Applications; Input/Output and Operators Java How to Program, 11/e Questions? © Copyright by Pearson Education, Inc. All Rights Reserved.

2 Java version of Welcome1 (aka HelloWorld)
What do we notice about this program? © Copyright by Pearson Education, Inc. All Rights Reserved.

3 Java Class Declaration
Every Java program consists of at least one user defined class. Declaring a class in Java public class Welcome1 class keyword is immediately followed by the name. Java keywords (Appendix C) are reserved for use by Java and are always spelled with all lowercase letters. Keywords are also referred to as reserved words. Notice the public keyword. What do you think it means? Are Java class public or private by default? © Copyright by Pearson Education, Inc. All Rights Reserved.

4 Java public class files
Filename for a public Class must match the class name EXACTLY! A public class must be placed in a file that has a filename of the form ClassName.java, so class Welcome1 is stored in the file Welcome1.java. If the filename is not the same as the class name, javac will produce a compilation error. This implies only one public Class per file. © Copyright by Pearson Education, Inc. All Rights Reserved.

5 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

6 Java Naming Rules and Conventions
Class Names and Identifiers A class name is an identifier. CAN contain letters, digits, underscores (_) and dollar signs ($); CAN NOT BEGIN with a digit and CAN NOT contain spaces. Java is case sensitive—uppercase and lowercase letters are distinct—so a1 and A1 are different (but both valid) identifiers. By convention, begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). This is called CamelCase. How does this differ from C++? As of Java 9, you can no longer use an underscore (_) by itself as an identifier. Why would you? © Copyright by Pearson Education, Inc. All Rights Reserved.

7 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

8 Java Class Body Class Body
A left brace, {, begins the body of every class declaration. A corresponding right brace, }, must end each class declaration. Always indent code between braces 2, 3 or 4 spaces. Be CONSISTENT! Fortunately, most IDEs handle indentation. What’s the answer to the age old question: tabs or spaces? Tabs are more uniform. Some people prefer spaces because the developer controls what is seen. Some prefer tabs because the reader controls what is seen. © Copyright by Pearson Education, Inc. All Rights Reserved.

9 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

10 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

11 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

12 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

13 Java Method Declaration
Declaring a Method public static void main(String[] args) { main must be defined as shown; otherwise, the JVM will not execute the application. Starting point of every Java application. What does public static mean? Every Java Program must have one public static void main method. A class can have more than one main method, but only one public static void main(String[] args). Equivalent to public static void main(String args[]) A program can have multiple classes with a public static void main method. To run a Java program, the JVM is pointed to the class with the entry point. © Copyright by Pearson Education, Inc. All Rights Reserved.

14 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

15 Java Method Body Body of the method declaration
Enclosed in curly braces { } whether it’s a single statement or multiple statements. Statement is a line of code that stands alone (ends in a semi-colon). System.out.println("Welcome to Java Programming!"); Instructs the computer to perform an action Display the characters contained between the double quotation marks. Together, the quotation marks and the characters between them are a string— also known as a character string or a string literal. Strings cannot span multiple lines of code. © Copyright by Pearson Education, Inc. All Rights Reserved.

16 Java System Object System.out object
Standard output object. Allows a Java application to display information in the command window from which it executes. System.out.print and System.out.println methods Prints text and in the latter case, followed by a newline, in the command window. The string in the parentheses the argument to the method. Positions the output cursor at the beginning of the next line in the command window. Most statements end with a semicolon. © Copyright by Pearson Education, Inc. All Rights Reserved.

17 Java Comments Commenting Your Programs – two different kinds of comments like C++ Inline Comments // Fig. 2.1: Welcome1.java // indicates that the line is a comment. Used to document programs and improve their readability. Compiler ignores comments. A comment that begins with // is an end-of-line comment—it terminates at the end of the line on which it appears. Traditional block comment, can be spread over several lines as in /* This is a traditional comment. It can be split over multiple lines */ This type of comment begins with /* and ends with */. © Copyright by Pearson Education, Inc. All Rights Reserved.

18 Java Comments (cont) Javadoc comments
Delimited by /** and */. All text between the Javadoc comment delimiters is ignored by the compiler. Enable you to embed program documentation directly in your programs. The javadoc utility program (online Appendix G) reads Javadoc comments and uses them to prepare program documentation in HTML5 format. Forgetting a comment delimiter /* or */ Block (Traditional) Comments not delimited by will usually result in a syntax error. Syntax errors are also called compile-time errors or compiler errors. © Copyright by Pearson Education, Inc. All Rights Reserved.

19 Javadoc comments Javadoc comments look very similar to a regular multi-line comment, but the key difference is the extra asterisk at the beginning: /** * This is a Javadoc Julie Harazduk */ Javadoc style comments may contain HTML tags as well. Usually, <strong>bold emphasis</strong> and <code>String code;</code> Javadoc comments should be placed above any class, method, or field which we want to document. © Copyright by Pearson Education, Inc. All Rights Reserved.

20 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

21 Use Whitespace – especially blank lines
Using Blank Lines Blank lines, space characters and tabs Make programs easier to read. Together, they’re known as white space (or whitespace). White space is ignored by the compiler. Whitespace should be used to make code more readable. Use comments above blocks of code or lines of code that perform a function. Use whitespace (blank lines) between these blocks or lines of code. Notice how most of my slides use whitespace (particularly this one) to separate content. © Copyright by Pearson Education, Inc. All Rights Reserved.

22 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

23 Java Program Compilation with javac
Compiling Your First Java Application Open a command window and change to the directory where the program is stored. Many operating systems use the command cd to change directories. To compile the program, type javac Welcome1.java If the program contains no compilation errors, preceding command creates a.class file (known as the class file) containing the platform-independent Java bytecodes that represent the application. When we use the java command to execute the application on a given platform, these bytecodes will be translated by the JVM into instructions that are understood by the underlying operating system. © Copyright by Pearson Education, Inc. All Rights Reserved.

24 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

25 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

26 Java Programs run in the JVM
Executing the Welcome1 Application Change to the directory containing Welcome1.class and run java on the class file as shown cd C:\examples\ch02\fig02_01 on Microsoft Windows or cd ~/Documents/examples/ch02/fig02_01 on Linux/macOS. java Welcome1 This launches the JVM, which loads the Welcome1.class file. The command omits the .class file-name extension; otherwise, the JVM will not execute the program. The JVM calls class Welcome1’s main method. © Copyright by Pearson Education, Inc. All Rights Reserved.

27 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

28 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

29 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

30 Escape Sequences in Java
The Newline character represents a linefeed and carriage return ↲ Newline characters are whitespace characters. The backslash (\) is called an escape character. Escape characters use multiple characters to represent a single character. When a backslash is encountered, the next character is read to interpret the sequence. Backslash is combined with the next character to form an escape sequence— \n represents the newline character. Complete list of escape sequences © Copyright by Pearson Education, Inc. All Rights Reserved.

31 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

32 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

33 Formatted Text in Java Escape sequences are used to format text.
Escape character is \. Java provides System.out.printf and System.out.format to format text. Format character is %. System.out.printf(“format_string”, arg1, arg2, arg3, …); Be careful that the number and type of arguments match what’s needed by the format_string.

34 Java format specifiers
Printf usefulness printf formatting is almost Identical for many languages: Java, C, C++, C#, perl, PHP, Ruby and Scala. Java’s new format method on System.out and String uses the printf formatting rules.

35 Java format specifiers
System.out.printf or String.format method

36 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

37 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

38 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

39 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

40 Java Console Input Scanner
A Scanner is a simple text scanner which is used to parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace much like cin in C++. Before using a Scanner, you must create it and specify the source of the data. Scanner input = new Scanner(System.in); The new keyword creates an object. Standard input object, System.in, enables applications to read bytes of data typed by the user. Scanner object translates these bytes into types that can be used in a program. © Copyright by Pearson Education, Inc. All Rights Reserved.

41 Java Console Input (cont)
All Java objects are created on the heap. Variable declaration statement Scanner input = new Scanner(System.in); Specifies the name (input) and type (Scanner) of a variable that is used in this program. Variable can have a primitive type or be an object reference. A location in the computer’s memory where a value can be stored. Variables must be declared with a name and a type before they can be used. A variable’s name enables the program to access the value of the variable in memory. The name can be any valid identifier. A variable’s type specifies what kind of information is stored at that location in memory. © Copyright by Pearson Education, Inc. All Rights Reserved.

42 Java Primitive Types There are 8 primitive types. boolean – 1 bit
Unlike C++, primitive types have a defined size as specified by the Java JVM. boolean – 1 bit byte – 1 byte short - 2 bytes int - 4 bytes long - 8 bytes char - 2 bytes float - 4 bytes double - 8 bytes © Copyright by Pearson Education, Inc. All Rights Reserved.

43 Adding Integers (cont.)
Variable declaration statement int number1 = input.nextInt(); // read first number from user declares that variables number1 holds data of type int Range of values for an int is –2,147,483,648 to +2,147,483,647. The int values you use in a program may not contain commas. For readability, you can place underscores in numbers 60_000_000 represents the int value 60,000,000 © Copyright by Pearson Education, Inc. All Rights Reserved.

44 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

45 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

46 Adding Integers (cont.)
Scanner method nextInt Obtains an integer from the user at the keyboard. Program waits for the user to type the number and press the Enter key to submit the number to the program. The result of the call to method nextInt is placed in variable number1 The = indicates that int variable number1 should be initialized in its declaration with the result of input.nextInt() © Copyright by Pearson Education, Inc. All Rights Reserved.

47 Java packages and imports
Java provides a rich set of predefined classes that you can reuse rather than “reinventing the wheel.” import is the directive that helps the compiler locate a class. You use import declarations to identify the predefined classes used in a Java program. Much like C++ include directive, though it doesn’t actually pull in source code. Classes are grouped into packages—named groups of related classes— and are collectively referred to as the Java class library, or the Java Application Programming Interface (Java API). © Copyright by Pearson Education, Inc. All Rights Reserved.

48 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

49 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

50 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

51 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

52 Arithmetic is like C++ Arithmetic operators are summarized in Fig. 2.12. Integer division yields an integer quotient. Any fractional part in integer division is simply truncated (i.e., discarded)—no rounding occurs. Precedence rules for operators are like C++ What are the precedence rules again? Associativity rules for operators are like C++ What are the associativity rules again? © Copyright by Pearson Education, Inc. All Rights Reserved.

53 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

54 Arithmetic (Cont.) As in algebra, it’s acceptable, even advisable at times, to place redundant parentheses (unnecessary parentheses) in an expression to make the expression clearer. © Copyright by Pearson Education, Inc. All Rights Reserved.

55 Equality and Relational Operators
Condition An expression that can be true or false. if selection statement Allows a program to make a decision based on a condition’s value. Equality operators (== and !=) Relational operators (>, <, >= and <=) Both equality operators have the same level of precedence, which is lower than that of the relational operators. The equality operators associate from left to right. The relational operators all have the same level of precedence and also associate from left to right. © Copyright by Pearson Education, Inc. All Rights Reserved.

56 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

57 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

58 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

59 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

60 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

61 Equality and Relational Operators (Cont.)
An if statement always begins with keyword if, followed by a condition in parentheses. Unlike C++, conditionals must result in true or false, not 0 or non-0. Remember that C++ evaluates 0 as false and everything else as true. E.g. while (1) works in C++ but not in java. We’ve enclosed each body statement in a pair of braces, { }, creating what’s called a compound statement or a block The indentation of the body statement is not required, but it improves the program’s readability by emphasizing that statements are part of the body © Copyright by Pearson Education, Inc. All Rights Reserved.

62 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

63 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

64 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

65 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.

66 © Copyright 1992-2018 by Pearson Education, Inc. All Rights Reserved.


Download ppt "Java How to Program, 11/e Questions?"

Similar presentations


Ads by Google