University of Aden
Faculty of Computer &
Information Technology
Computer Programming I
Java Programming Language
Lecture 2: Basic Elements of Java
Basic Elements of Java
Java Programming Language Slide 2
Outline
Java Identifiers
Keywords ( reserved words)
Variables
Named Constants
Java Data Types
Arithmetic Operators
Precedence
Class String
String concatenation
Input stream object
Class Scanner
Java Application: Adding Integers
Java Programming Language Slide 3
Java Identifiers
Identifiers
Identifiers are the names that identify the elements such as classes,
methods, and variables in a program.
An identifier is a sequence of characters that consist of:
Letters
Digits
The underscore character (_)
The dollar sign ($)
Must begin with a letter, underscore, or the dollar sign.
An identifier cannot be a reserved word.
An identifier cannot be true, false, or null.
Java Programming Language Slide 4
Java Identifiers (continued)
Example Java identifiers:
illegal legal
me+u _myName
49ers TheCure
side-swipe ANSWER_IS_42
employee salary $bling$
Java Programming Language Slide 5
Keywords
Keywords (Reserved Words):
An identifier that you cannot use because it already has
a reserved meaning in Java.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
Java Programming Language Slide 6
Variables
Variables
A piece of the computer's memory that is given a name
and type, and can store a value that may be changed in
the program.
Steps for using a variable:
Declare it - state its name and type
Initialize it - store a value into it
Use it - print it or use it as part of an expression
The syntax for declaring a variable is:
datatype variableName;
Java Programming Language Slide 7
Variables (continued)
Variable declaration: sets aside memory for storing a value (Variables
must be declared before they can be used).
Assignment: Stores a value into a variable (The value can be an
expression; the variable stores its result).
Syntax:
datatype variableName; (declaration).
variableName = expression; (assignment).
int x; x 3
x = 3;
double yourGPA;
yourGPA 3.25
yourGPA = 1.0 + 2.25;
Java Programming Language Slide 8
Variables (continued)
Using variables: Once given a value, a variable can be used in
expressions:
int x;
x = 3;
System.out.println("x is " + x); x is 3
System.out.println(5 * x - 1); 14
You can assign a value more than once:
int x;
x = 3;
System.out.println(x + " here"); 3 here
x = 4 + 7;
System.out.println("now x is " + x); now x is 11
Java Programming Language Slide 9
Variables (continued)
A variable can be declared/initialized in one
statement:
double myGPA = 3.95; myGPA 3.95
int x = (11 % 3) + 12; x 14
Java Programming Language Slide 10
Variables (continued)
A variable can't be used until it is assigned/initialized
a value.
int x;
System.out.println(x);
ERROR: x has no value
Java Programming Language Slide 11
Named constants
A named constant is an identifier that represents a permanent
value.
Named constant
Cannot be changed during program execution
Declared by using the reserved word final
Initialized when it is declared
Example
final double CENTIMETERS_PER_INCH = 2.54;
final int NO_OF_STUDENTS = 20;
final char BLANK = ' ';
final double PAY_RATE = 15.75;
Java Programming Language Slide 12
Java Data Types
Data types specify the different sizes and values that can
be stored in the variable.
There are two types of data types in Java:
Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include
Classes, Interfaces, and Arrays.
Java is a statically-typed programming language. It means, all
variables must be declared before its use. That is why we need
to declare variable's type and name.
Java Programming Language Slide 13
Java Data Types (continued)
Java Programming Language Slide 14
Java Data Types (continued)
double vs float
The double type values are more accurate than the float
type values. For example:
System.out.println("1.0 / 3.0 is " + 1.0 / 3.0);
1.0 / 3.0 is 0.3333333333333333
16 digits
System.out.println("1.0f / 3.0f is " + 1.0f / 3.0f);
1.0f / 3.0f is 0.3333333
7 digits
Java Programming Language Slide 15
Arithmetic operators
Operator: Combines multiple values or expressions.
– + addition 2+2=4
– - subtraction 53 – 18 = 35
– * multiplication 300 * 30 = 9000
– / division 4.8 / 2.0 = 2.4
– % remainder or mod 20 % 3 = 2
6
باقي
القسمة
3 ) 20
Java Programming Language Slide 16
Precedence
Precedence: Order in which operators are evaluated.
Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4
But * / % have a higher level of precedence than + -
1 + 3 * 4 is 13
6 + 8 / 2 * 3
6 + 4 * 3
6 + 12 is 18
Parentheses can force a certain order of evaluation:
(1 + 3) * 4 is 16
Java Programming Language Slide 17
Increment and Decrement Operators
Increment operator: increase variable by 1.
Pre-increment: ++variable
Post-increment: variable++
Decrement operator: decrease variable by 1.
Pre-decrement: --variable
Post-decrement: variable--
What is the difference between the following?
x = 5; x = 5; y = 6; x = 5; x = 5; y = 5;
y = ++x; X = x +1; y = x++; y = x;
y = x; X = x +1;
Java Programming Language Slide 18
The Class String
String
Sequence of zero or more characters.
Enclosed in double quotation marks. "hello"
Null or empty strings have no characters. “” , “ “
Length is the number of characters in a string.
The length of the string "Sunny Day" is 9
May not span multiple lines.
"This is not
a legal String."
May not contain a " character.
"This is not a "legal" String either."
Java Programming Language Slide 19
String concatenation
String concatenation: Using + between a string and another
value to make a longer string.
"hello" + 42 is "hello42"
1 + "abc" + 2 is "1abc2"
"abc" + 1 + 2 is "abc12"
1 + 2 + "abc" is "3abc"
"abc" + 9 * 3 is "abc27"
"1" + 1 is "11"
4 - 1 + "abc" is "3abc"
Java Programming Language Slide 20
Implicit Import and Explicit Import
java.util.*; // Implicit import
java.util.Scanner; // Explicit Import
Java Programming Language Slide 21
Input stream object
System.in is called a standard input stream object and is
designed to input data from the standard input device
(keyboard).
However, the object System.in extracts data in the form of
bytes from the input stream. Therefore, we first create a
Scanner object, to translates these bytes into a desired form
(like ints) that can be used in a program, as follows:
Scanner input = new Scanner(System.in);
object Stream input object
Java Programming Language Slide 22
Scanner methods
Method Description
nextInt() reads an int from the user and
returns it
nextDouble() reads a double from the user
next() reads a one-word String from the
user
EachnextLine()
method waits reads a one-line
until the user presses from the
StringEnter.
The value typed by user
the user is returned.
System.out.print("How old are you? ");
int age = input.nextInt();
System.out.println("You typed " +
age);
Java Programming Language Slide 23
Scanner syntax
1. The Scanner class is found in the java.util
package.
import java.util.*;
import java.util.Scanner;
2. Constructing a Scanner object to read console
input:
Scanner input = new Scanner(System.in);
Java Programming Language Slide 24
Scanner example
import java.util.*;
public class UserInputExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
age 29
System.out.print("How old are you? ");
int age = input.nextInt(); years 36
int years = 65 - age;
System.out.println(years + " years to retirement!");
}
}
• Console (user input underlined):
How old are you?
29
36 years until retirement!
Java Programming Language Slide 25
Java Application: Adding Integers
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
// Create Scanner to read the user input
Scanner input = new Scanner (System.in);
int x, y, sum; // declare three variables of type
integers
// Prompt the user to enter the two integers number
System.out.println("Enter two integers separated by
spaces: ");
x = input.nextInt();
y = input.nextInt();
// the sum of two integers
sum = x + y;
System.out.println("The Sum of the two numbers is: "+sum);
Java Programming Language Slide 26
Exercise
1. Write a program that prompts the user to
enter five test scores and then print the
average test score.
2. Write a program that does the following:
Prompt the user to input five decimal numbers
Prints the five decimal numbers
Adds the five decimal numbers
Prints the sum and average of the five decimal
numbers
Java Programming Language Slide 27