0% found this document useful (0 votes)
45 views

Basic Elements of Java

Basic Elements of Java, Programming, CIT-U
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Basic Elements of Java

Basic Elements of Java, Programming, CIT-U
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 111

Unit 2: Basic Elements of Java

• Variables and Expressions


• The Class String
• Keyboard and Screen I/O
• Documentation and Style
• Graphics Supplement

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Variables and Expressions
UNIT 2: BASIC ELEMENTS OF JAVA
Variables
• Variables store data such as numbers and letters.
• Think of them as places to store data.
• They are implemented as memory locations.
• The data stored by a variable is called its value.
• The value is stored in the memory location.
• Its value can be changed.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Variables
• Sample program
• Class EggBasket

Sample
Sample
Screen
Screen
Output
Output

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Variables and Values
• Variables
numberOfBaskets
eggsPerBasket
totalEggs
• Assigning values
eggsPerBasket = 6;
eggsPerBasket = eggsPerBasket - 2;

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Naming and Declaring Variables
• Choose names that are helpful such as count or
speed, but not c or s.
• When you declare a variable, you provide its name and
type.
int numberOfBaskets,eggsPerBasket;
• A variable's type determines what kinds of values it
can hold (int, double, char, etc.).
• A variable must be declared before it is used.
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Syntax and Examples
• Syntax
type variable_1, variable_2, …;
(variable_1 is a generic variable called a syntactic
variable)
• Examples
int styleChoice, numberOfChecks;
double balance, interestRate;
char jointOrIndividual;

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Data Types
• A class type is used for a class of objects and has
both data and methods.
• "Java is fun" is a value of class type String
• A primitive type is used for simple,
nondecomposable values such as an individual
number or individual character.
• int, double, and char are primitive types.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Primitive Types

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Java Identifiers
• An identifier is a name, such as the name of a
variable.
• Identifiers may contain only
• Letters
• Digits (0 through 9)
• The underscore character (_)
• And the dollar sign symbol ($) which has a special
meaning
• The first character cannot be a digit.
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Java Identifiers
• Identifiers may not contain any spaces, dots (.),
asterisks (*), or other characters:
7-11 netscape.com util.* (not allowed)
• Identifiers can be arbitrarily long.
• Since Java is case sensitive, stuff, Stuff, and
STUFF are different identifiers.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Keywords or Reserved Words
• Words such as if are called keywords or reserved
words and have special, predefined meanings.
• Cannot be used as identifiers.
• See Appendix 1 for a complete list of Java keywords.

• Example keywords: int, public, class

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Naming Conventions
• Class types begin with an uppercase letter
(e.g. String).
• Primitive types begin with a lowercase letter (e.g.
int).
• Variables of both class and primitive types begin
with a lowercase letters
(e.g. myName, myBalance).
• Multiword names are "punctuated" using uppercase
letters.
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Where to Declare Variables

• Declare a variable
• Just before it is used or
• At the beginning of the section of your program that is
enclosed in {}.
public static void main(String[] args)
{ /* declare variables here */
. . .
}

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Primitive Types
• Four integer types (byte, short, int, and
long)
• int is most common
• Two floating-point types (float and double)
• double is more common
• One character type (char)
• One boolean type (boolean)

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Examples of Primitive Values
• Integer types
0 -1 365 12000
• Floating-point types
0.99 -22.8 3.14159 5.0
• Character type
'a' 'A' '#' ' '
• Boolean type
true false
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Assignment Statements
• An assignment statement is used to assign a value to
a variable.
answer = 42;
• The "equal sign" is called the assignment operator.
• We say, "The variable named answer is assigned a
value of 42," or more simply, "answer is assigned
42."

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Assignment Statements
• Syntax
variable = expression
where expression can be another variable, a
literal or constant (such as a number), or something
more complicated which combines variables and
literals using operators
(such as + and -)

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Assignment Examples
amount = 3.99;
firstInitial = 'W';
score = numberOfCards + handicap;
eggsPerBasket = eggsPerBasket - 2;

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Initializing Variables
• A variable that has been declared, but no yet given a
value is said to be uninitialized.
• Uninitialized class variables have the value null.
• Uninitialized primitive variables may have a default
value.
• It's good practice not to rely on a default value.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Initializing Variables
• To protect against an uninitialized variable (and to
keep the compiler happy), assign a value at the time
the variable is declared.
• Examples:
int count = 0;
char grade = 'A';

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Initializing Variables
• syntax
type variable_1 = expression_1,
variable_2 = expression_2, …;

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Assignment Evaluation
• The expression on the right-hand side of the assignment
operator (=) is evaluated first.
• The result is used to set the value of the variable on the
left-hand side of the assignment operator.
score = numberOfCards + handicap;
eggsPerBasket = eggsPerBasket - 2;

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Simple Input

• Sometimes the data needed for a computation are


obtained from the user at run time.
• Keyboard input requires
import java.util.Scanner
at the beginning of the file.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Simple Input
• Data can be entered from the keyboard using
Scanner keyboard =
new Scanner(System.in);
followed, for example, by
eggsPerBasket =
keyboard.nextInt();
which reads one int value from the keyboard and
assigns it to eggsPerBasket.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Simple Input
• Sample program
class EggBasket2

Sample
Sample
screen
screen
output
output

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Simple Screen Output
System.out.println("The count is " + count);

• Outputs the sting literal "the count is "


• Followed by the current value of the variable count.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Constants
• Literal expressions such as 2, 3.7, or 'y' are
called constants.
• Integer constants can be preceded by a + or - sign,
but cannot contain commas.
• Floating-point constants can be written
• With digits after a decimal point or
• Using e notation.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
e Notation
• e notation is also called scientific notation or
floating-point notation.
• Examples
• 865000000.0 can be written as 8.65e8
• 0.000483 can be written as 4.83e-4
• The number in front of the e does not need to
contain a decimal point.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Imprecision in Floating-Point Numbers
• Floating-point numbers often are only approximations
since they are stored with a finite number of bits.
• Hence 1.0/3.0 is slightly less than 1/3.
• 1.0/3.0 + 1.0/3.0 + 1.0/3.0
is less than 1.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Named Constants
• Java provides mechanism to …
• Define a variable
• Initialize it
• Fix the value so it cannot be changed
public static final Type Variable = Constant;

• Example
public static final double PI = 3.14159;

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Assignment Compatibilities
• Java is said to be strongly typed.
• You can't, for example, assign a floating point value to a
variable declared to store an integer.
• Sometimes conversions between numbers are
possible.
doubleVariable = 7;
is possible even if doubleVariable is of type
double, for example.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Assignment Compatibilities

• A value of one type can be assigned to a variable of


any type further to the right
byte --> short --> int --> long
--> float --> double
• But not to a variable of any type further to the left.
• You can assign a value of type char to a variable of type
int.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Type Casting
• A type cast temporarily changes the value of a
variable from the declared type to some other type.
• For example,
double distance;
distance = 9.0;
int points;
points = (int)distance;
• Illegal without (int)
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Type Casting
• The value of (int)distance is 9,
• The value of distance, both before and after the
cast, is 9.0.
• Any nonzero value to the right of the decimal point
is truncated rather than rounded.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Arithmetic Operators
• Arithmetic expressions can be formed using the +,
-, *, and / operators together with variables or
numbers referred to as operands.
• When both operands are of the same type, the result is of
that type.
• When one of the operands is a floating-point type and the
other is an integer, the result is a floating point type.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Arithmetic Operations
• Example
If hoursWorked is an int to which the value 40 has
been assigned, and payRate is a double to which
8.25 has been assigned

hoursWorked * payRate

is a double with a value of 500.0.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Arithmetic Operations
• Expressions with two or more operators can be
viewed as a series of steps, each involving only two
operands.
• The result of one step produces one of the operands to be
used in the next step.
• example
balance + (balance * rate)

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Arithmetic Operations
• If at least one of the operands is a floating-point type
and the rest are integers, the result will be a floating
point type.
• The result is the rightmost type from the following
list that occurs in the expression.
byte --> short --> int --> long
--> float --> double

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
The Division Operator
• The division operator (/) behaves as expected if
one of the operands is a floating-point type.
• When both operands are integer types, the result is
truncated, not rounded.
• Hence, 99/100 has a value of 0.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
The mod Operator
• The mod (%) operator is used with operators of
integer type to obtain the remainder after integer
division.
• 14 divided by 4 is 3 with a remainder of 2.
• Hence, 14 % 4 is equal to 2.
• The mod operator has many uses, including
• determining if an integer is odd or even
• determining if one integer is evenly divisible by another
integer.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Parentheses and Precedence
• Parentheses can communicate the order in which
arithmetic operations are performed
• examples:
(cost + tax) * discount
(cost + (tax * discount)
• Without parentheses, an expressions is evaluated
according to the rules of precedence.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Precedence Rules
• Figure 2.2 Precedence Rules

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Precedence Rules
• The binary arithmetic operators *, /, and %, have
lower precedence than the unary operators +, -,
++, --, and !, but have higher precedence than
the binary arithmetic operators + and -.
• When binary operators have equal precedence, the
operator on the left acts before the operator(s) on the
right.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Precedence Rules
• When unary operators have equal precedence, the
operator on the right acts before the operation(s) on
the left.
• Even when parentheses are not needed, they can be
used to make the code clearer.
balance + (interestRate * balance)
• Spaces also make code clearer
balance + interestRate*balance
but spaces do not dictate precedence.
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Sample Expressions
• Some Arithmetic Expressions in Java

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Specialized Assignment Operators

• Assignment operators can be combined with arithmetic


operators (including -, *, /, and %, discussed
later).
amount = amount + 5;
can be written as
amount += 5;
yielding the same results.
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Case Study:Vending Machine Change
• Requirements
• The user enters an amount between 1 cent and 99 cents.
• The program determines a combination of coins equal to
that amount.
• For example, 55 cents can be two quarters and one nickel.
• Denominations: quarter, dime, nickel, penny

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Increment and Decrement Operators

• Used to increase (or decrease) the value of a


variable by 1
• Easy to use, important to recognize
• The increment operator
count++ or ++count
• The decrement operator
count-- or --count

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Increment and Decrement Operators

• equivalent operations
count++;
++count;
count = count + 1;

count--;
--count;
count = count - 1;
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Increment and Decrement Operators in
Expressions
• after executing
int m = 4;
int result = 3 * (++m)
result has a value of 15 and m has a value of 5
• after executing
int m = 4;
int result = 3 * (m++)
result has a value of 12 and m has a value of 5

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Class String
UNIT 2: BASIC ELEMENTS OF JAVA
The Class String
• We've used constants of type String already.
"Enter a whole number from 1 to 99."
• A value of type String is a
• Sequence of characters
• Treated as a single item.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
String Constants and Variables
• Declaring
String greeting;
greeting = "Hello!";
or
String greeting = "Hello!";
or
String greeting = new String("Hello!");
• Printing
System.out.println(greeting);

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Concatenation of Strings
• Two strings are concatenated using the + operator.
String greeting = "Hello";
String sentence;
sentence = greeting + " officer";
System.out.println(sentence);
• Any number of strings can be concatenated using
the + operator.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Concatenating Strings and Integers
String solution;
solution = "The answer is " + 42;
System.out.println (solution);

The temperature is 72
The answer is 42

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
String Methods
• An object of the String class stores data
consisting of a sequence of characters.
• Objects have methods as well as data
• The length() method returns the number of
characters in a particular String object.
String greeting = "Hello";
int n = greeting.length();

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
The Method length()

• The method length() returns an int.


• You can use a call to method length() anywhere an int
can be used.
int count = command.length();
System.out.println("Length is " +
command.length());
count = command.length() + 3;

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
String Indices

• Positions start with 0, not 1.


• The 'J' in "Java is fun." is in position 0
• A position is referred to an an index.
• The 'f' in "Java is fun." is at index 8.
String Methods

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
String Methods

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
String Methods

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
String Methods

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
String Processing
• No methods allow you to change the value of a
String object.
• But you can change the value of a String variable.
• Sample program StringDemo

Sample
Sample
Screen
Screen
Output
Output
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Escape Characters
• How would you print
"Java" refers to a language. ?
• The compiler needs to be told that the quotation
marks (") do not signal the start or end of a string,
but instead are to be printed.
System.out.println(
"\"Java\" refers to a language.");

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Escape Characters

• Figure 2.6
• Each escape sequence is a single character even
though it is written with two symbols.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Examples
System.out.println("abc\\def");

abc\def

System.out.println("new\nline");
new
line

char singleQuote = '\'';


System.out.println '
(singleQuote);
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
The Unicode Character Set
• Most programming languages use the ASCII
character set.
• Java uses the Unicode character set which includes
the ASCII character set.
• The Unicode character set includes characters from
many different alphabets (but you probably won't
use them).

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Basic I/O
UNIT 2: BASIC ELEMENTS OF JAVA
Screen Output
• We've seen several examples of screen output
already.
• System.out is an object that is part of Java.
• println() is one of the methods available to the
System.out object.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Screen Output
• The concatenation operator (+) is useful when
everything does not fit on one line.
System.out.println("Lucky number = " + 13 +
"Secret number = " + number);
• Do not break the line except immediately before or after
the concatenation operator (+).

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Screen Output
• Alternatively, use print()
System.out.print("One, two,");
System.out.print(" buckle my shoe.");
System.out.println(" Three, four,");
System.out.println(" shut the door.");

ending with a println().

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Keyboard Input
• Java has reasonable facilities for handling keyboard
input.
• These facilities are provided by the Scanner class
in the java.util package.
• A package is a library of classes.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Using the Scanner Class
• Near the beginning of your program, insert
import java.util.Scanner;
• Create an object of the Scanner class
Scanner keyboard =
new Scanner (System.in)
• Read data (an int or a double, for example)
int n1 = keyboard.nextInt();
double d1 = keyboard,nextDouble();

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Keyboard Input Demonstration
• Sample program
class ScannerDemo

Sample
Sample
Screen
Screen
Output
Output

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Some Scanner Class Methods

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Some Scanner Class Methods

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
nextLine()Method Caution

• The nextLine() method reads


• The remainder of the current line,
• Even if it is empty.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
nextLine()Method Caution
• Example – given following declaration.
int n;
String s1, s2;
n = keyboard.nextInt();
s1 = keyboard.nextLine();
s2 = keyboard.nextLine();
• Assume input shown
42
and don't you
forget it.
n is set to 42
but s1 is set to the empty string.
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
The Empty String
• A string can have any number of characters,
including zero.
• The string with zero characters is called the empty
string.
• The empty string is useful and can be created in
many ways including
String s3 = "";

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Other Input Delimiters (optional)

• Almost any combination of characters and strings can


be used to separate keyboard input.
• to change the delimiter to "##"
keyboard2.useDelimiter("##");
• whitespace will no longer be a delimiter for keyboard2
input

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Other Input Delimiters
• Sample program
class DelimitersDemo

Sample
Sample
Screen
Screen
Output
Output

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Documentation and Style
UNIT 2: BASIC ELEMENTS OF JAVA
Documentation and Style
• Most programs are modified over time to respond to
new requirements.
• Programs which are easy to read and understand are
easy to modify.
• Even if it will be used only once, you have to read it
in order to debug it .

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Meaningful Variable Names
• A variable's name should suggest its use.
• Observe conventions in choosing names for
variables.
• Use only letters and digits.
• "Punctuate" using uppercase letters at word boundaries
(e.g. taxRate).
• Start variables with lowercase letters.
• Start class names with uppercase letters.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Comments
• The best programs are self-documenting.
• Clean style
• Well-chosen names
• Comments are written into a program as needed
explain the program.
• They are useful to the programmer, but they are ignored
by the compiler.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Comments
• A comment can begin with //.
• Everything after these symbols and to the end of the
line is treated as a comment and is ignored by the
compiler.
double radius; //in centimeters

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Comments
• A comment can begin with /* and end with */
• Everything between these symbols is treated as a
comment and is ignored by the compiler.
/**
This program should only
be used on alternate Thursdays,
except during leap years, when it should
only be used on alternate Tuesdays.
*/
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Comments
• A javadoc comment, begins with /** and ends with
*/.
• It can be extracted automatically from Java
software.
/** method change requires the number of
coins to be nonnegative */

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
When to Use Comments
• Begin each program file with an explanatory
comment
• What the program does
• The name of the author
• Contact information for the author
• Date of the last modification.
• Provide only those comments which the expected
reader of the program file will need in order to
understand it.
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Comments Example
• View sample program
class CircleCalculation, listing 2.7

Sample
Sample
Screen
Screen
Output
Output

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Indentation
• Indentation should communicate nesting clearly.
• A good choice is four spaces for each level of
indentation.
• Indentation should be consistent.
• Indentation should be used for second and
subsequent lines of statements which do not fit on a
single line.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Indentation
• Indentation does not change the behavior of the
program.
• Proper indentation helps communicate to the human
reader the nested structures of the program

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Using Named Constants
• To avoid confusion, always name constants
(and variables).
area = PI * radius * radius;
is clearer than
area = 3.14159 * radius * radius;
• Place constants near the beginning of the program.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Named Constants
• Once the value of a constant is set (or changed by an
editor), it can be used (or reflected) throughout the
program.
public static final double INTEREST_RATE = 6.65;

• If a literal (such as 6.65) is used instead, every


occurrence must be changed, with the risk than
another literal with the same value might be changed
unintentionally.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Declaring Constants
• Syntax
public static final
Variable_Type = Constant;
• Examples
public static final double
PI = 3.14159;
public static final String MOTTO = "The
customer is always right.";
• By convention, uppercase letters are used for constants.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Named Constants
• Sample program
class CircleCalculation2

Sample
Sample
Screen
Screen
Output
Output

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Graphics Supplement
UNIT 2: BASIC ELEMENTS OF JAVA
Style Rules Applied to a Graphics Applet
• Named constants makes it easier to find values.
• Comments and named constants make changing the
code much easier.
• Named constants protect against changing the wrong
value.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
JFrame
• Sample program
class HappyFaceJFrame

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
JOptionPane
• Sample program
class JOptionPaneDemo

Sample
Sample
Screen
Screen
Output
Output

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
JOptionPane
• JOptionPane can be used to construct windows
that interact with the user.
• The JOptionPane class is imported by
import javax.swing.JApplet;
• The JOptionPane class produces windows for
obtaining input or displaying output.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
JOptionPane
• Use showInputDialog() for input .
• Only string values can be input.
• To convert an input value from a string to an integer
use the parseInt() method from the Integer
class, use
appleCount =
Integer.parseInt(appleString);

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
JOptionPane
• Output is displayed using the
showMessageDialog method.
JOptionPane.showMessageDialog(null, "The
total number of fruits = " +
totalFruitCount);

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
JOptionPane
• Syntax
• Input
String_Variable =
JOptionPane.showInputDialogue
(String_Expression);
• Output
JOptionPane.showMessageDialog
(null, String_Expression);
• System.exit(0) ends the program.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
JOptionPane Cautions

• If the input is not in the correct format, the program


will crash.
• If you omit the last line (System.exit(0)), the
program will not end, even when the OK button in
the output window is clicked.
• Always label any output.

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Inputting Numeric Types
• JOptionPane.showInputDialog can be used
to input any of the numeric types.
• Methods for converting strings to numbers

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Multi-Line Output Windows
• To output multiple lines using the method
JOptionPane.showMessageDialog, insert
the new line character '\n' into the string used as
the second argument.
OptionPane.showMessageDialog(null,
"The number of apples\n" +
"plus the number of oranges\n" +
"is equal to " + totalFruit);

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Multi-Line Output Windows
• A dialog window containing multiline output

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
Programming Example
• Sample program
class ChangeMakerWindow

Sample
Sample
Screen
Screen
Output
Output
Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015
References
• Walter Savitch
• Java : An Introduction to Problem Solving and
Programming 6th ed. Boston, Pearson Education © 2015

Walter Savitch, Java : An Introduction to Problem Solving and Programming 6th ed.
Boston, Pearson Education © 2015

You might also like