Chapter 2
Chapter 2
Programming
Basics
1
Comments
Explanation to improve readability of program
// comments -- one line
int nquest; // number of questions.
/* ... */ comments -- multiple lines
javadoc comments
Comments that in form of /** …*/ are used by the javadoc
program to produce HTML documentation for the program
Example:
/** This is an example of special java doc comments used for \n
generating an html documentation. It uses tags like:
@author Florence Balagtas
@version 1.2
*/
2
Javadoc
Tool that pulls out the class and the method etc.,
defined in the source file, and creates the reference
manual of the program
Main tag of ‘javadoc’
@see Reference destination name : Make the reference
link of other classes and related packages from the class
of the object .
@exception Explanation of exception class name:
Describe the explanation of the exception that the
method of object has possibility to throw.
@param Explanation of argument name
@return The explanation of the return value of the
method of the object is described.
3
Hand on Lab: Javadoc
Use your text editor or Eclipse to create a
java program named: Circle.java
The content of this file will be shown in next
slides
4
Circle.java
import java.awt.*; /**
import java.applet.*; * Create a new circle with specified
diameter and color.
/** */
* A simple circle class.
public Circle(int diameter, Color color) {
*
* @author Samuel A. Rebelsky this.diameter = diameter;
* @version 1.1 of February 1999 this.setColor(color);
*/ } // Circle(int, Color)
public class Circle {
/**
/** The current color of the circle. */ * Create a new circle with specified
protected Color color; diameter and default color.
*/
/** The current diameter of the circle. */ public Circle(int diameter) {
protected int diameter; this.diameter = diameter;
this.setColor(Color.blue); // Blue is as
good a default as any.
} // Circle(int)
5
Circle.java
/**
/**
* Set the color of this circle.
* Draw this circle centered at a particular
position in a */
* graphics thingy. To make it look more public void setColor(Color newColor) {
interesting, I outline
this.color = newColor;
* the circle in some color.
*/ } // setColor(Color)
public void draw(int x, int y, Graphics g) {
g.setColor(this.color); /**
g.fillOval( * Set the diameter of this circle.
x-this.diameter/2, // Left margin
*/
y-this.diameter/2, // Top margin
this.diameter, // Width public void setSize(int newDiameter) {
this.diameter); // Height this.diameter = newDiameter;
} // draw(int,int,Graphics) } // setSize(int)
/**
} // class Circle
* Get the diameter of this circle.
*/
public int getSize() {
return this.diameter;
} // getSize() 6
Result
7
Identifier
Tokens that represent names of variables,
methods, classes
Java identifiers are case-sensitive.
This means that the identifier Hello is not the
same as hello.
Identifiers must begin with either a letter, an
underscore “_”, or a dollar sign “$”. Letters
may be lower or upper case. Subsequent
characters may use numbers 0 to 9.
8
Identifier
Nolimit of length
Identifiers cannot use Java keywords like
class, public, void, etc.
9
Coding guidelines – Naming Rule
For names of classes, capitalize the first letter of
the class name. For example,
ThisIsAnExampleOfClassName, Circle, Account, ..
10
Java keywords
Keywords are predefined identifiers reserved
by Java for a specific purpose. You cannot
use keywords as names for your variables,
classes, methods ... etc.
11
Java keywords
The Java reserved words:
abstract else interface switch
assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
12
Primitive Data
There are eight primitive data types in Java
Four of them represent integers:
byte, short, int, long
13
Numeric Primitive Data
The difference between the various numeric
primitive types is their size, and therefore the
values they can store:
Type Storage Min Value Max Value
14
Unicode
Two byte code system that can correspond
to a lot of natural languages.
Unicode
ASCII Code
Vietnamese Korean
Japanese
15
Variables
A variable is a name for a location in memory
int total;
int count, temp, result;
Examples:
"This is a string literal."
Every character string is an object in Java, defined by the
String class. Every string literal represents a String
object
Character strings can be connected by using + operator
Examples
String message = “Hello” + “ World.”;
17
Variable Initialization
A variable can be given an initial value in the
declaration
int sum = 0;
int base = 32, max = 149;
18
Basic data type and reference type
Reference Variables
Primitive Variables 150
copy
150
19
Basic data type and reference type
Reference Variables
variables that stores the address in the
memory location
points to another memory location where
the actual data is
When you declare a variable of a certain
class, you are actually declaring a
reference variable to the object with that
certain class.
20
Reference type
int num = 10; // primitive type
String name = "Hello"; // reference type
21
Java Literal
Literals are tokens that do not change - they
are constant.
The different types of literals in Java are:
Integer Literals
Floating-Point Literals
Boolean Literals
Character Literals
String Literals
22
Java Literal
Integer
Decimal: 100 or 100L
Octal: 013 or 013L
Hexadecimal: 0x52 or 0xFFL
Floating Point (default is double type)
Decimal Expression: 0.23445 or 0.23445F (float
type)
Exponent (Scientific) Expression: 6.02E13
23
Java Literal
Boolean literals have only two values, true or false.
24
Operators
Different types of operators:
arithmetic operators
substitution operators
relational operators
logical operators
conditional operators
ternary operators
instanceof operator
25
Operators
Arithmetic operators:
Addition (+), Substraction (-), multiplication (*), division
(/), modulo (%)
System.out.println(" i % j = " + (i % j));
Substitution operators:
Stores the value of right side to left side
=, +=, -=, *=, /=
26
Increment and Decrement
The increment and decrement operators use only one
operand
The increment operator (++) adds one to its operand
The decrement operator (--) subtracts one from its operand
The statement
count++;
is functionally equivalent to
count = count + 1;
27
Relational & Logic Operators
Relational operators: judges the equivalence or bigness and
smallness of two expression and variables.
== (equal) , <= (less than) , >= (more than) , != (not equal), >
(bigger), < (smaller)
Logic operators
&& (logical AND)
|| (logical OR)
! (logical NOT)
28
Hand on
public class TestAND {
public static void main( String[] args
Compile and Run ){
program TestAND int i = 0;
int j = 10;
to understand the boolean test= false;
difference between //demonstrate &&
test = (i > 10) && (j++ > 9);
two AND operators System.out.println(i);
System.out.println(j);
System.out.println(test);
//demonstrate &
test = (i > 10) & (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}
29
Logical Operators: &&(logical)
and &(boolean logical) AND
The basic difference between && and & operators :
&& supports short-circuit evaluations (or partial
evaluations), while & doesn't.
Given an expression:
exp1 && exp2
&& will evaluate the expression exp1, and immediately
return a false value is exp1 is false.
If exp1 is false, the operator never evaluates exp2
because the result of the operator will be false regardless
of the value of exp2.
In contrast, the & operator always evaluates both
exp1 and exp2 before returning an answer.
30
Ternary – instanceof operator
Ternary operator: returns a value that is different according
to the truth of conditional expression.
Format: Conditional expression ? value A:value B
boolean b = (i%10 ==0)? true: false;
31
Shift operator
Right shift: shifts the value's bit row to the right by a
specified bit.
Format: n >> p Shifts the bits of n right p positions
Example:
int x = -4;
System.out.println(x>>1); // -2
Left shift:
Format: n << p Shifts the bits of n left p positions.
Example: 3 << 2 12
32
Type casting
Implicit type casting: When operating on values of different
data types, the lower one is promoted to the type of the
higher one.
int intVal = 123;
long longVal = 213000L;
longVal = intVal;
33
Arrays
An array is an ordered list of values
The entire array Each value has a numeric index
has a single name
0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91
34
Definition of array
Declaration:
int[] scores = new int[10]; or
boolean[] flags;
flags = new boolean[20];
Initialization of array:
scores[0] = 23;
int array[] = {2, 3, 5, 7,11, 13,
17, 19, 23, 29};
35
Example
36
Operation of array
In order to get the number of // Calculate the array’s sum total
elements in an array, you can use the int sum=0;
length field of an array. for(int i=0; i< a.length; i++)
arrayName.length sum+=a[i];
Copy of array:
System.arraycopy(Object org,
int org_index, Object dest,
int dest_index, int num);
37
Array of reference type
Be aware that the array of the reference type
is "array of the variable that refers to the
object", and that it is not "array of the
object".
String array[] = new String[5];
array[0] = “Chao”;
38
Multidimensional Array
Multidimensional arrays are implemented as arrays of
arrays.
Example
// integer array 512 x 128 elements
int[][] twoD = new int[512][128];
// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];
// String array 4 rows x 2 columns
String[][] dogs = {{ "terry", "brown" },
{ "Kristin", "white" }
{ "toby", "gray"},
{ "fido", "black"}
};
39
Caution with System.copyarray
40
Command line arguments
The argument can be passed from the command line at the Java
application‘s starting
Format:
public static void main(String args[]){…}
Use: java classname args[0] args[1] args[2]
prompt>java Introduce HuuBinh 21; args[1]
args[0]
true false
public static int max(int n1, int n2) {
if (n1 >= n2) {
return(n1); statement1 statement2
} else {
return(n2);
}
}
42
Example: Calculate wages
import java.text.NumberFormat;
import java.util.Scanner;
44
The switch Statement
Often a break statement is used as the last statement in
each case's statement list
45
Question: What is the result of this code?
int month = 1;
switch(month){
case 1:
System.out.println("A Happy New Year!");
case 12:
System.out.println("Merry Christmas !");
break;
}
46
The for Statement
A for statement has the following syntax:
The initialization The statement is
is executed once executed until the
before the loop begins condition becomes false
48
Hand on Lab
Write a program named Arithmetic that calculates the sum total (int)
and the mean value (float) when an int type 1-dimension array is given
Array int data[] = {78,65,78,21,93,45,33,55,22,81} ;
The output expected and source code given
prompt>java Arithmetic
sum: 571
avg: 57.1
class Arithmetic {
public static void main(String args[]) { public static void main(String args[])
{
int data[] = {78, 65, 78, 21, 93, 45, 33, 55, 22, 81};
// Describe a necessary variable and a processing, and complete the
programming.
}
}
49
Hand on Lab
Continue the previous exercise so that the
program display the Min, Max value of the
array.
51
while and do while statement
while statement The while Loop The do Loop
while (continueTest) {
body; condition
statement
evaluated
} true
body; false
} while (continueTest);
52
break and continue
break: exit from the iteration
continue: Returns to the head of repetition.
question: What is the output of the following code?
public class BreakContinue{
public static void main(String argv[]){
System.out.println("Break");
for(int i=1; i < 4; i++){
System.out.println(i);
if(i > 1) break;
}
System.out.println("Continue");
for(int i=1; i < 4; i++){
System.out.println(i);
if(i > 1) continue;
}
}
} 53
Enumerated type
enum OperatingSystems {
windows, unix, linux, macintosh
Type to define related two or }
more strings collectively
public class TestEnum {
Definition public static void main(String args[])
{
[Modifier] enum Enumeration type- OperatingSystems os;
identifier { Element1, Element2, Element os = OperatingSystems.windows;
3,… Element n} switch(os) {
case windows:
Use System.out.println("You chose Windows!");
[Modifier] enum Enumeration type- break;
case unix:
identifier Variable name; System.out.println("You chose Unix!");
Variable name = Enumeration type- break;
identifier.Element name; default:
System.out.println("I don't know your OS.");
break;
}
}
}
54
Reading Simple Input
For simple testing, use standard input
Note that you need import statement. See next slide!
Scanner inputScanner = new Scanner(System.in);
int i = inputScanner.nextInt();
double d = inputScanner.nextDouble();
55
Example
import java.util.*;
public class RandomNums {
public static void main(String[] args) {
System.out.print("How many random nums? ");
Scanner inputScanner = new Scanner(System.in);
int n = inputScanner.nextInt();
for(int i=0; i<n; i++) {
System.out.println("Random num " + i +
" is " + Math.random());
}
}
}
56
Hands on Lab
Input two integers (a, b) from the command line, and make the program
that calculates ‘b’ multiplication of ‘a’. However, assume that ‘a’ is a
discretionary integer and ‘b’ is an integers of 0 or more. If the number of
parameters from the command line is insufficient or too much, or if a
negative value is input to ‘b’, output the error message to terminate the
program.
57
Hint
Method to convert the character string into
the value
int Integer.parseInt(String str)
long Long.parseLong(String str)
float Float.parseFloat(String str)
double Double. parseDouble(String str)
58
Setting the value for arguments in Eclipse
Run\Run Configurations
60
Hand on Lab
The mock exam of the Information Technology Engineer Test was done
three times in a certain company. Examinees were five people (Okada,
Tamura, Matsuda, Asai,and Natsuki), and the score was Okada {79, 65,
78} , Tamura {21, 93, 45}, Matsuda {31, 55, 22}, Asai {81, 66, 81}, and
Natsuki {76, 90, 86}. The test results and the examinees' names are
stored in the array as follows.
Calculate the average score of each examinee from this array, and make
a bar chart that shows the degrees of their achievement. The bar chart
shows the degree of chievement by the number of '*', and records one
'*' for 10 points of the average score.
61