CS 111A Lecture Notes - Simple I/O in Java - Chapter 2 part 1
Console Output
Identifiers
- Identifier - the name of a variable (or other item), which is made up by the programmer, and
should give the reader some hint of what it is used for. (e.g. number_of_candy_bars is a very good,
clear variable name.) Java is case sensitive with all identifiers and keywords.
- Indentifier Rules - Identifiers must follow the following rules:
They must start with a letter or underscore, and contain only letters, digits, or underscore. E.g.
variables called 3X or %change are not allowed.
- Reserved Words - pre-defined names (keywords) in Java must not be used for your own identifier
names (for example you can't name a variable "int".) For a complete list of reserved words,
see this Java tutorial page
Variables
- Variable - a named location in memory that can be used to store a specified type of data, and
whose value may be changed in the course of the program. Variables must be declared before they are used
in Java.
- int - a datatype that stores an integer (no decimal value allowed). Can be positive or
negative.
- String - a datatype (class, actually) that stores any sequence of characters, such as a word,
a sentence, or a combination of numbers and symbols, etc.
- Variable declaration examples:
int x = 5;
String s1;
int age, height;
Echo.java: Here is an example demonstrating the use of variables, and of the Scanner
class for console input.
Programming Style
- Programs are written to be read by other humans as well as the computer.
- Use my sample programs and those in the book as your guide for style.
- Indentation: always indent consistently. It greatly improves readability
- Indentation reflects the level, or scope, of a line of code.
- The contents of a set of curly braces "{" and "}" are always indented
- You should always have Comments at the top of your program, stating your name, the name of
your program source file, the name of the class and assignment, and a brief description of what the
program does.
- Comments should also be used to explain hard-to-understand code, and to summarize big steps such as
functions and sometimes loops.
- Use helpful variable names (strive for self-commenting code - clear without comments to explain it.)
- Provide a good user interface, including prompting for inputs and explaining outputs.
In-class exercise: input user's first name, then last name, and store them into two separate variables. Output
them in reverse order with a comma between them.
Names.java: Solution to above exercise
Return to CS 111A page