Chapter 2 Basic Elements of Java
Chapter 2 Basic Elements of Java
Java Programming:
From Problem Analysis to Program Design,
Second Edition
Chapter Objectives
Become familiar with the basic components of a Java
program, including methods, special symbols, and
identifiers.
Explore primitive data types.
Discover how to use arithmetic operators.
Examine how a program evaluates arithmetic
expressions.
Explore how mixed expressions are evaluated.
Float: Precision = 6 or 7
Double: Precision = 15
Boolean:
True
False
Mixed expressions
Example 2-11
final double CENTIMETERS_PER_INCH = 2.54;
final int NO_OF_STUDENTS = 20;
final char BLANK = ' ';
final double PAY_RATE = 15.75;
Example 2-12
double amountDue;
int counter;
char ch;
int x, y;
Java Programming: From Problem Analysis to Program Design, Second Edition 25
Input
The Assignment Statement
variable = expression;
Example 2-13
int i, j;
double sale;
char first;
String str;
i = 4;
j = 4 * 5 - 11;
sale = 0.02 * 1000;
first = 'D';
str = "It is a sunny day.";
Java Programming: From Problem Analysis to Program Design, Second Edition 26
Input
Standard input stream object is System.in.
Input numeric data to program.
Separate by blanks, lines, or tabs.
To read data:
1. Create an input stream object of the class
Scanner.
2. Use the methods such as next, nextLine,
nextInt, and nextDouble.
Example 2-16
static Scanner console = new Scanner(System.in);
int feet;
int inches;
23 7
Example 2-20
String str;
int num1, num2;
num1 = 12;
num2 = 26;
str = "The sum = " + num1 + num2;
Methods:
print
println
Syntax:
System.out.print(stringExp);
System.out.println(stringExp);
System.out.println();
variable += expression;