After completion of this chapter, you should be able to
System.outto display output to the console (screen)
Scannerclass to read keyboard input
JOptionPaneclass to display input and message dialog boxes
Here is a simple Java program that displays "Programming is great fun" on the computer screen.
Simple.java(or in more general terms ClassName.java)
javafile may contain many classes but may only have one public class.
System.out.println("Programming is great fun");"
System.out.print()statements are used to produce console output
//) at the beginning of the line indicates that this is a comment.
The steps involved in writing a Java program:
While it is possible to perform all these steps at the command prompt, most programmers prefer to use an integrated development environment (IDE) that provides a Graphical User Interface (GUI also known as WIMP) to the four steps involved in writing Java programs.
The computers in the Hebeler labs have jGRASP IDE installed and ready to use with CS 110 and CS 111 assignments. jGRASP is available online with tutorials to help first time users.
All but the simplest Java programs consist of multiple source code files (*.java) and class files (*.class). jGRASP's projects manage the multiple source code and class files that make up a Java program.
Programming style refers to the coding standards, conventions, and guidelines for writing correct, high-quality, and maintainable Java code.
If you are brand new to programming, some of the content of the Java Programming Style Guide at his point may be confusing. One student learning objective of CS 110 is to have you leave knowing how to correctly apply the style guidelines that produce readable and maintainable Java programs.
Variables are names for values in our programs that can be changed.
In Java, every variable must be declared once before it can be used.
Declaring a variable means informing the compiler of the variable's name and its type.
The two most common primitive types in Java are
double: Variables of type double store numbers (with decimal points).
int: Variables of type int also store numbers (but with no decimal points allowed).
In Java, the pattern to declare (designate) a name with a variable is
the type> <the name>;
The Java Style convention for capitalizing variable names is to use lower camel casing. Do not use spaces or underscore characters in your variable names.
If you know the variable's initial value, you can also set it to that value at the same time as the variable declaration.
The pattern to assign a name to variable along with an initial value is
the type> <the name> = <the initial value>;
Java has 8 built-in primitive data types
int(stores a whole number)
double(stores a number with a decimal point)
boolean(stores one of two values: true or false)
char(stores a single character)
Of these eight, we will primarily use four of them in CS 110:
Named Constants are names for variables whose values cannot be changed
Java uses the keyword
final to indicate constants.
In Java, the pattern to assign a name to constant value that cannot be changed is
the type> <the name> = <the constant value>;
The Java Style convention for capitalizing constant names is to use all capital letters. To improve readability, subsequent words in the name are combined with the underscore character ('_')
An assignment statement is used to change the value of a variable
The assignment operator is the equal sign:
The pattern to write an assignment statement is
%modulus (also called remainder)
The first three operators work as expected. Division and modulus need some explanation.
Integer division occurs with the
/ and two integer values (operands).
number1 is 2 after the integer division operation. (The remainder of 1 is ignored)
Integer Division ignores any fractional part of the result, no matter how large. For example, even if the result was 7.9999, integer division would report the result as 7. Computer scientists say integer division truncates rather than rounds.
If you want the remainder that results from the division, use the modulus operator:
number2 is 1 after the integer modulus operation. (The quotient of 2 is ignored)
The modulus operator % is often referred to as remainder in simple mathematics. As you may learn later in discrete math, modulus actually means something slightly different.
Why are we interested in modulus? Some things cannot be divided easily. We have a basket of 22 apples that we would like to divide evenly between 4 students. Each student gets 5.5 apples? No, half an apple will spoil too quickly. Each student gets 5 apples and the remaining two apples go to their teacher.
If you want a precise (fractional) result, you must use floating point division (the
Floating Point Division occurs when one or both of the values being divided (operands) are
// Declare a variable
doublenumber3; // Do floating point division number3
number3 is 2.25 after the floating point division operation.
( ... ) to help group values in expressions, the Java compiler uses precedence rules
to determine the order to perform operations.
Operator Precedence Rule: Without parenthesis, perform multiplication, division, and modulus operations before addition and subtraction.
With multiple operators of equal precedence, Use left-associativity. That is, perform the operations from left-to-right order.
Programming Tip: Always use parenthesis, don't rely on the precedence rule.
The Math class contains a number of methods for performing
mathematical calculations. These methods are called by writing
Math.name, where name is the name of the method.
The methods in the Math class return a value when they have completed execution.
System.out uses works with both print() and println() methods to display output on the computer screen.
Do you know why I placed an blank space character before the word World?
One way to display a blank line on the computer screen is with
I could display three blank lines by coding:
Another way to print a blank line is to use an escape sequence:
Each occurrence of
\n causes the output to begin on a new line.
There are a lot of different escape sequences built into Java.
Another common escape sequence is
\", which represents
" (a double quote):
In order to print a backslash character as part of a string, the string will need to contain two backslash characters:
The concatenation operator (
+) operator can be used to combine multiple items into a single String for printing purposes:
At least one of the two operands for the
+ operator must be a String.
Getting input from the user involves two tasks:
The prompt task is easily accomplished with the System.out.
Reading in from the keyboard is more involved. Java was designed to create GUI applications. Input and output to the console window was expected to be used primarily for debugging purposes. However, since so many beginning programmers are now learning to program with Java, the Scanner class was introduced with Java 5 to simplify reading in values from the keyboard.
To use the
Scanner in your programs, the line
java.util.Scanner; must be at the start of
your program to tell the Java compiler where to find the definition of the Scanner class.
Scanner objects work with
System.in. To create a Scanner object, use
We can now use the keyboard object with the
Scanner class methods to read in user input.
Scanner class methods are listed in Table 2-18 in the text. So far this quarter we have used
We can also use the
nextLine() method to read in a String
The Java Application Programmer Interface (API) provides a huge number of pre-written classes. Of these, the String class is one of the most used.
The String class is included in the package named java.lang. This java.lang package is automatically imported into every Java program. (No other package has this property.)
We are used to using Strings as literal constants inside our
println methods. We can also use Strings as reference variables inside our program.
The String class
length() method returns the number of characters in the String variable.
The String class
charAt() method returns the single character stored at a specified position in the String object
toUpperCase() will convert the letters in a string to lowercase or uppercase.
Any characters other than letters inside the string object are not changed by methods
Java has some combined assignment operators that allow the programmer to perform an arithmetic operation and assignment with a single operator.
Although not required, these operators are popular since they shorten simple equations.
Scope refers to the part of a program that has access to a variables contents.
Variables declared inside a method (like the main method) are called local variables. A local variables' scope begins at the declaration of the variable and ends at the end of the method in which it was declared.
Java provides three methods for commenting code.
/* ... */
/** ... */
File header comments provide readers and graders with the information they need to find your project on the network, identify the program's author, and to collect statistics on the project's difficulty based on the hours required to complete the program.
A dialog box is a small graphical window that displays a message to the user or requests input.
A variety of dialog boxes can be displayed using the
JOptionPane class. Two methods available with dialog boxes are:
showMessageDialog- a dialog box that displays a message to the user.
showInputDialog- a dialog box that prompts the user for input.
showInputDialog method always returns the user's input as a String
A String containing a number, such as "127.89", can be converted to a numeric data type using the Java methods