TOPIC 3
Basic
Java Features (Part 1)
sufian, marini,
norleyza, noor faezah
Objectives
Use constants and variables
Learn about primitive data types
Write arithmetic statements
Understand numeric type conversion
Use the JOptionPane class for GUI input and output
Constants and Variables
Constant: value stays fixed after compilation
Constants may be assigned symbolic name
Constant's literal value may be used directly
Variable: named memory location
Contents may change at run-time
Contents described by data type
Constants and Variables
Data type: specifies data in three ways
Kind of item being represented
Amount of memory item occupies
Operations that may be performed on item
Eight primitive (basic) data types:
byte, short, int, long, float, double, char, boolean
Reference types (classes) are built upon primitives
Constants and Variables
int Data Type
Variables of type int store integers (whole numbers)
int range: –2,147,483,648 to +2,147,483,647
Commas omitted in actual code
Plus (+) and minus (-) signs are optional
Integer variations: byte, short, int, long
Byte size increases from left to right
Use integer variation based on programming need
int Data Type
Real/Floating-Point Data Types
Real or floating-point numbers contain decimal positions
Real numbers of type float must end with F,
eg: 3.14F
Without the F, it is assumed as a double
The type double is the default of real numbers in Java
The ending D can also be used for type double, eg:
3.14D
Floating-point division returns floating-point value
Floating-Point Data Types
float: holds values up to 6 or 7 significant digits
double: holds values up to 14 or 15 significant digits
Significant digits indicate mathematical accuracy
Example: myFloat = .324616777F; // F/f specifies float
Displays as .324617 (precision up to sixth position)
char Data Type
The Keyword for data type characters: char
char data type holds a single character
A single quote ‘ indicates a character
Example initialization: char myMiddleInitial = ‘N';
All characters are represented by binary numbers
Two major character codes
ASCII: eight-bit code contains 256 characters
Unicode sixteen-bit code contains 65,536 characters
Java has now adopted the Unicode character set
char Data Type
char Data Type
Strings store character sequences enclosed with double quotes
Example: “Hello There”
Escape sequence: backslash and character as one unit
Example: char aNewLine = '\n';
Newline character moves cursor to next line
Plain meaning of 'n' altered by prefixed backslash
Use of escape sequences generates efficiencies
Example: System.out.println ("Hello\nthere");
One line performs work of two println ( ) statements
char Data Type
boolean Data Type
boolean data type has two values: true and false.
Logical expressions in Java are of boolean data type.
Program example:
boolean hungry;
hungry = true;
if (hungry) {
System.out.println(“Feed..");
hungry = false;
}
hungry has the value of true/false.
The if statement is executed because hungry is true.
The value of hungry becomes false after “Feed.." is
printed out.
Using data with Variables and Constants
Three steps to use/manipulate data in a program
1. Declare variables / constants to store the data value
2. Assign initial value to declared variables / constants
3. Use the variables / constants in arithmetic statements
Declaring Variables
Variables must be named
Rules: similar to those for constructing class identifiers
Convention: first letter is lowercase
Keywords in Java cannot be used as identifiers, eg:
abstract, boolean, break, byte, case, catch,
char, class, const, continue, default, do,
double, else, extends, final, finally, float,
for, goto, if, implements, import, instanceof,
int, interface, long, native, new, null, package,
private, protected, public, return, short,
static, super, switch, synchronized, this,
throws, transient, try, void, volatile, while
Declaring Variables
Variable declaration has four parts:
Data type
Name
Assigned initial value (optional)
Ending semicolon
Example declaration:
int myAge;
Example with initial value:
int myAge = 25;
Declaring Variables
Multiple declarations of same type allowed on one line
Example:
float width, height;
Different types declared in different statements
Example:
byte age;
int count;
char grade;
boolean found;
Displaying Variables using Standard
Output
Methods for console output: print() or println()
Variables displayed alone or with string
Ex1:
System.out.print (billingDate);
Ex2:
System.out.println ("Next bill:
October " +
billingDate);
Concatenation: joins arguments with (+) operator
Displaying Variables
Displaying Variables
Declaring Constants
In Java, constants are defined as the following:
public static final type var_name = value;
Eg:
public static final double PI = 3.142;
public static final int LOOP = 1000;
Writing Arithmetic Statements
Java has five binary arithmetic operators:
add (+), subtract (-), divide (/), multiply(*), mod (%)
Basic arithmetic expression
Two operands and one operator
Example: 45 + 35
Arithmetic expression with variables
Example: 1989 + yourAge
Arithmetic expression with constants
Example: 2 * PI
Writing Arithmetic Statements
Integer division does not return fractional part
Modulus arithmetic returns remainder of int division
Applies only to integers
Example: 45 % 35 = 10
Operator precedence: rules ordering operation sequence
Multiply, divide, and mod before add and subtract
Parentheses override normal precedence
Writing Arithmetic Statements
Associativity: left to right for binary operators
Nested parentheses: evaluate from inside out
Example: 65 + 35 – (45 + 9) / 9 * 7
Evaluates to 58
Without parentheses: evaluates to 62 (do not distribute -)
Writing Arithmetic Statements
Using Arithmetic Statements
Assignment statements in Java contain:
A variable : stores the evaluated value of an arithmetic
statement
Assignment symbol : =
Arithmetic statement
Semi colon – ends the assignment statement
Syntax:
var = arithmetic_statement;
Example:
area = PI * radius * radius;
Numeric Type Conversion
Unifying type: highest type among mixed operands
hierarchy: double, float, long, int, short, byte
Java allows convertion of nonconforming operands to the
higher type without using casting
Example:
int hoursWorked = 37;
double payRate = 6.73;
double grossPay = hoursWorked * payRate;
hoursWorked is temporarily promoted to double type
Numeric Type Conversion
Sometimes we want to convert (cast) a value into a certain
type
Place result type in ( ) before variable to be cast
Example
float myMoney = 47.82f;
int dollars = (int) myMoney;
Expression on right converted to int
Data is truncated (possible loss of value)
dollars value = 47
Type Conversion
If the value is not converted explicitly, Java will convert
the values implicitly based on the following order:
byte short int long float double
char int long float double
Example:
float temp = 20.23F;
40 + temp ← The summation value is 60.23
40 + (int) temp ← The summation value is 60
Comments
**As in C/C++
We can comment out a line of program as follows:
// this is a comment
We can also comment out a block of program using /* and
*/ as follows:
/* This is also a comment */
Automatically Generated Documentation
A comment which begins with /** and ends with */
has a special meaning. It is used in generating
documentation automatically.
javadoc is a tool for generating documentation
automatically, which searches all Java source files
and looks for comments beginning with /**
Documentation is generated in HTML files.
Operators
**As in C
Basic operators:
+, -, /, *, %
Combined operators are also allowed as in C.
Eg: Equivalent to
num += 5; num = num + 5;
Increment and decrement (++ and –-)
Eg:
int i = 1;
++i; // The value of i becomes 2
Relational Operators
**As in C
Basic operators:
==, !=, <, >, <=, >=
Difference between an assignment and a relational
expression
num = 0// num becomes 0
num == 0 // is num equals to 0?
Java will give a syntax error message if we mistakenly write
the following statement:
if (num = 0) // num will be assigned the value of 0
Logical Operators
Basic operators:
&& AND
|| OR
! NOT
^ EXCLUSIVE OR