Java 2: Intro to Java Applications; Input/Output Operators

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Java application

A Java application is a computer program that executes when you use the java command to launch the Java Virtual Machine (JVM).

Class Names and Identifiers

A compilation error occurs if a public class's filename is not exactly same name as the class (in terms of both spelling and capitalization) followed by the .java extension.

import Declarations

A great strength of Java is its rich set of predefined classes that you can reuse rather than "reinventing the wheel." These 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). import java.util.Scanner; // program uses class Scanner is an import declaration that helps the compiler locate a class that's used in this program. It indicates that the program uses the predefined Scanner class (discussed shortly) from the package named java.util. The compiler then ensures that you use the class correctly.

Class Body

A left brace, {, begins the body of every class declaration. A corresponding right brace }, must end each class declaration.

Filename for a public Class

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.

Error-Prevention Tip 2.1

As you write new programs or modify existing ones, keep your comments up-to-date with the code. Programmers will often need to make changes to existing code to fix errors or to enhance capabilities. Updating your comments helps ensure that they accurately reflect what the code does. This will make your programs easier to understand and modify in the future. Programmers using or updating code with out-of-date comments might make incorrect assumptions about the code that could lead to errors or even security breaches.

\\

Backslash. Used to print a backslash character.

System.out object

The System.out object—which is predefined for you—is known as the standard output object. It allows a Java application to display information in the command window (command line) from which it executes.

Common Programming Error 2.5

The compiler error message "class Welcome1 is public, should be declared in a file named Welcome1.java" indicates that the filename does not match the name of the public class in the file or that you typed the class name incorrectly when compiling the class.

System.in

The standard input object, System.in, enables applications to read bytes of data typed by the user. The Scanner translates these bytes into types (like ints) that can be used in a program.

Memory Concepts

Variable names such as number1, number2 and sum actually correspond to locations in the computer's memory. Every variable has a name, a type, a size (in bytes) and a value.

Obtaining an int as Input from the User

number1 = input.nextInt(); // read first number from user uses Scanner object input's nextInt method to obtain an integer from the user at the keyboard. At this point the program waits for the user to type the number and press the Enter key to submit the number to the program. Our program assumes that the user enters a valid integer value. If not, a runtime logic error will occur and the program will terminate.

End-Of-Line Comment

//, indicating that it's an end-of-line comment—it terminates at the end of the line on which the // appears. An end-of-line comment need not begin a line; it also can begin in the middle of a line and continue until the end

Java Variables

A variable is a location in the computer's memory where a value can be stored for use later in a program. All Java 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. A variable's name can be any valid identifier—again, a series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin with a digit and does not contain spaces. A variable's type specifies what kind of information is stored at that location in memory. Like other statements, declaration statements end with a semicolon (;).

Using Blank Lines

Blank lines, space characters and tabs make programs easier to read. Together, they're known as white space (or whitespace). The compiler ignores white space.

Class Names and Identifiers

By convention, class names begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). A class name is an identifier—a series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin with a digit and does not contain spaces. Some valid identifiers are Welcome1, $value, _value, m_inputField1 and button7. The name 7button is not a valid identifier because it begins with a digit, and the name input field is not a valid identifier because it contains a space. Normally, an identifier that does not begin with a capital letter is not a class name. Java is case sensitive—uppercase and lowercase letters are distinct—so value and Value are different (but both valid) identifiers.

\r

Carriage return. Position the screen cursor at the beginning of the current line—do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line.

\"

Double quote. Used to print a double-quote character. For example, System.out.println("\"in quotes\""); displays "in quotes".

Declaring a Class

Every Java program consists of at least one class that you (the programmer) define. The class keyword introduces a class declaration and is immediately followed by the class name (Welcome1). Keywords (sometimes called reserved words) are reserved for use by Java and are always spelled with all lowercase letters.

Common Programming Error 2.1

Forgetting one of the delimiters of a traditional or Javadoc comment is a syntax error. A syntax error occurs when the compiler encounters code that violates Java's language rules (i.e., its syntax). These rules are similar to a natural language's grammar rules specifying sentence structure. Syntax errors are also called compiler errors, compile-time errors or compilation errors, because the compiler detects them when compiling the program. When a syntax error is encountered, the compiler issues an error message. You must eliminate all compilation errors before your program will compile properly.

\t

Horizontal tab. Move the screen cursor to the next tab stop.

Integer Division

Integer division yields an integer quotient. For example, the expression 7 / 4 evaluates to 1, and the expression 17 / 5 evaluates to 3. Any fractional part in integer division is simply truncated (i.e., discarded)—no rounding occurs.

Common Programming Error 2.3

It's a syntax error if braces do not occur in matching pairs

Traditional Comments

Java also has traditional comments, which can be spread over several lines. These begin and end with delimiters, /* and */. The compiler ignores all text between the delimiters. Java incorporated traditional comments and end-of-line comments from the C and C++ programming languages, respectively.

Method System.out.println

Method System.out.println displays (or prints) a line of text in the command window. The string in the parentheses in line 9 is the argument to the method. When System.out.println completes its task, it positions the output cursor (the location where the next character will be displayed) at the beginning of the next line in the command window. This is similar to what happens when you press the Enter key while typing in a text editor—the cursor appears at the beginning of the next line in the document.

\n

Newline. Position the screen cursor at the beginning of the next line.

Scanner

Scanner input = new Scanner(System.in); is a variable declaration statement that specifies the name (input) and type (Scanner) of a variable that's used in this program. A Scanner enables a program to read data (e.g., numbers and strings) for use in a program. The data can come from many sources, such as the user at the keyboard or a file on disk. Before using a Scanner, you must create it and specify the source of the data.

Good Programming Practice 2.1

Some organizations require that every program begin with a comment that states the purpose of the program and the author, date and time when the program was last modified.

Prompting the User for Input

System.out.print("Enter first integer: "); // prompt uses System.out.print to display the message "Enter first integer: ". This message is called a prompt because it directs the user to take a specific action. We use method print here rather than println so that the user's input appears on the same line as the prompt.

Displaying a Single Line of Text with Multiple Statements

System.out.print("Welcome to "); System.out.println("Java Programming!"); The first statement uses System.out's method print to display a string. Each print or println statement resumes displaying characters from where the last print or println statement stopped displaying characters. Unlike println, after displaying its argument, print does not position the output cursor at the beginning of the next line in the command window—the next character the program displays will appear immediately after the last character that print displays.

Displaying Multiple Lines of Text with a Single Statement

System.out.println("Welcome to Java Programming!"); A single statement can display multiple lines by using newline characters, which indicate to System.out's print and println methods when to position the output cursor at the beginning of the next line in the command window. Like blank lines, space characters and tab characters, newline characters are whitespace characters.

Performing Output with System.out.println

System.out.println(); instructs the computer to perform an action—namely, to display the characters contained between the double quotation marks (the quotation marks themselves are not displayed). Together, the quotation marks and the characters between them are a string—also known as a character string or a string literal. White-space characters in strings are not ignored by the compiler. Strings cannot span multiple lines of code.

Displaying Text with printf

The System.out.printf method (f means "formatted") displays formatted data. System.out.printf("%s%n%s%n", "Welcome to", "Java Programming!"); The method call specifies three arguments. When a method requires multiple arguments, they're placed in a comma-separated list. Calling a method is also referred to as invoking a method. Method printf's first argument is a format string that may consist of fixed text and format specifiers. Fixed text is output by printf just as it would be by print or println. Each format specifier is a placeholder for a value and specifies the type of data to output. Format specifiers also may include optional formatting information. Format specifiers begin with a percent sign (%) followed by a character that represents the data type. For example, the format specifier %s is a placeholder for a string. The format string in line 9 specifies that printf should output two strings, each followed by a newline character. At the first format specifier's position, printf substitutes the value of the first argument after the format string. At each subsequent format specifier's position, printf substitutes the value of the next argument. So this example substitutes "Welcome to" for the first %s and "Java Programming!" for the second %s. The output shows that two lines of text are displayed on two lines. Notice that instead of using the escape sequence \n, we used the %n format specifier, which is a line separator that's portable across operating systems. You cannot use %n in the argument to System.out.print or System.out.println; however, the line separator output by System.out.println after it displays its argument is portable across operating systems.

Escape Character + Escape Sequence

The backslash (\) is an escape character, which has special meaning to System.out's print and println methods. When a backslash appears in a string, Java combines it with the next character to form an escape sequence—\n represents the newline character. When a newline character appears in a string being output with System.out, the newline character causes the screen's output cursor to move to the beginning of the next line in the command window.

Primitive Types

The types int, float, double and char are called primitive types. Primitive-type names are keywords and must appear in all lowercase letters. (boolean, byte, char, short, int, long, float and double).

Javadoc Comments

These are delimited by /** and */. The compiler ignores all text between the delimiters. Javadoc comments enable you to embed program documentation directly in your programs. Such comments are the preferred Java documenting format in industry. The javadoc utility program (part of the JDK) reads Javadoc comments and uses them to prepare program documentation in HTML format.

Commenting Programs

We insert comments to document programs and improve their readability. The Java compiler ignores comments, so they do not cause the computer to perform any action when the program is run.

Common Programming Error 2.4

When using javac, if you receive a message such as "bad command or filename," "javac: command not found" or "'javac' is not recognized as an internal or external command, operable program or batch file," then your Java software installation was not completed properly. This indicates that the system's PATH environment variable was not set properly. Carefully review the installation instructions in the Before You Begin section of this book. On some systems, after correcting the PATH, you may need to reboot your computer or open a new command window for these settings to take effect.

Java Inputs

import java.util.Scanner; // program uses class Scanner // create a Scanner to obtain input from the command window Scanner input = new Scanner(System.in); number1 = input.nextInt(); // read first number from user

Declaring a Method

public static void main(String[] args) is the starting point of every Java application. The parentheses after the identifier main indicate that it's a program building block called a method. Java class declarations normally contain one or more methods. For a Java application, one of the methods must be called main and must be defined; otherwise, the Java Virtual Machine (JVM) will not execute the application. Methods perform tasks and can return information when they complete their tasks. Keyword void indicates that this method will not return any information. The String[] args in parentheses is a required part of the method main's declaration The left brace begins the body of the method declaration. A corresponding right brace must end it.


Kaugnay na mga set ng pag-aaral

Finance Final Exam: Cost of Capital(14)/ Financial Leverage and Capital Structure Policy(16)

View Set

Final (new material) Panopto Question

View Set

Chapter 24: Management of Patients with COPD

View Set

Scrum Master Certification Practice

View Set

AP Computer Science Principles - Fall Semester Exam

View Set