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

Chapter 2

The document discusses basic programming concepts in Java including comments, identifiers, keywords, primitive data types, variables, and strings. It explains that comments are used to improve code readability, identifiers name variables and follow specific naming conventions, keywords are reserved words that cannot be used as names, there are 8 primitive data types including integers and floating point numbers, variables declare a name and type to reference a memory location, and strings represent character data using double quotes.

Uploaded by

Anh Đức
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Chapter 2

The document discusses basic programming concepts in Java including comments, identifiers, keywords, primitive data types, variables, and strings. It explains that comments are used to improve code readability, identifiers name variables and follow specific naming conventions, keywords are reserved words that cannot be used as names, there are 8 primitive data types including integers and floating point numbers, variables declare a name and type to reference a memory location, and strings represent character data using double quotes.

Uploaded by

Anh Đức
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Chapter 2.

Programming
Basics

ITSS Java Programming

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

 javadoc –private Circle.java

 javadoc -author -version Circle.java

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, ..

 For names of methods and variables, the first letter


of the word should start with a small letter. For
example,
 thisIsAnExampleOfMethodName, setColor, isFull, ..

 The basic data type constant is all capital letters


and the object constant is all small letters,
 MAX_LENGTH, TAX_VALUE, Color.red, System.out ..

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

 Two of them represent floating point numbers:


 float, double

 One of them represents characters:


 char

 And one of them represents boolean values:


 boolean

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

byte 8 bits -128 127


short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018

float 32 bits +/- 3.4 x 1038 with 7 significant digits


double 64 bits +/- 1.7 x 10308 with 15 significant digits

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

 A variable must be declared by specifying the


variable's name and the type of information
that it will hold
data type variable name

int total;
int count, temp, result;

Multiple variables can be created in one declaration


16
Character Strings
 A string of characters can be represented as a string literal
by putting double quotes around the text:

 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;

 When a variable is referenced in a


program, its current value is used

18
Basic data type and reference type

 Two types of variables in


Java:
store
 Primitive Variables 150 150

 Reference Variables
 Primitive Variables 150
copy
150

 Variables with primitive data


types such as int or long. int x,y;
 Stores data in the actual
y=150;
memory location of where the
variable is x=y;

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.

 Character literals: ‘a’, ‘\t’, ‘\u3042’

 String literal: “Go ahead!”

 Null literal (reference type)


 Null (there no data should be referenced)

24
Operators
 Different types of operators:
 arithmetic operators
 substitution operators
 relational operators
 logical operators
 conditional operators
 ternary operators
 instanceof operator

 These operators follow a certain kind of precedence so that


the compiler will know which operator to evaluate first in
case multiple operators are used in one statement.

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)

 & (boolean logical AND)

 || (logical OR)

 | (boolean logical inclusive OR)

 ^ (boolean logical exclusive 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;

 instanceof operator: The ‘instanceof’ operator is an operator


that judges if an object is a product generated from a class
 Format: object instanceof class

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;

 Explicit type casting: the type is put in parentheses in front


of the value being converted
 For example, if total and count are integers, but we want a floating
point result when dividing them, we can cast total:
result = (float) total / count;

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

An array of size N is indexed from zero to N-1

This array holds 10 values that are indexed from 0 to 9

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

boolean results[] = { true, false, true, false };

double []grades = {100, 90, 80, 75};

String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”,


“Sat”, “Sun”};

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

 System.arraycopy() working range of method

int array1[][] = new int[3][5];


int array1[][] = new int[3][5];
int array2[][] = new int[3][5];
// Copy all elements of ‘array1’ onto ‘array2’
System.arraycopy(array1[0], 0, array2[0], 0, 5);
System.arraycopy(array1[1], 0, array2[1], 0, 5);
System.arraycopy(array1[2], 0, array2[2], 0, 5);
// improper code
// System.arraycopy(array1, 0,array2, 0, 15);

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]

public static void main(String args[]){


if (args.length ==2){
System.out.println(“My name: “ + args[0]);
System.out.println(“I am “ + args[1] + “years old.”);
}
else
System.out.println(“Please run your program with 2
arguments.”);
}
41
The if-else Statement
 An else clause can be added to an if statement to
make an if-else statement
if ( condition )
statement1;
else condition
statement2; evaluated

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;

public class Wages{


public static void main (String[] args) {
final double RATE = 8.25; // regular pay rate
final int STANDARD = 40; // standard hours in a work week
Scanner scan = new Scanner (System.in);
double pay = 0.0;
System.out.print ("Enter the number of hours worked: ");
int hours = scan.nextInt();
System.out.println ();
// Pay overtime at "time and a half"
if (hours > STANDARD)
pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5);
else
pay = hours * RATE;

NumberFormat fmt = NumberFormat.getCurrencyInstance();


System.out.println ("Gross earnings: " + fmt.format(pay));
}
} 43
The switch Statement
 The general syntax of a switch statement
is: switch switch ( expression )
and {
case case value1 :
are statement-list1
reserved case value2 :
words statement-list2
case value3 :
statement-list3 If expression
case ... matches value2,
control jumps
} to here

44
The switch Statement
 Often a break statement is used as the last statement in
each case's statement list

 A break statement causes control to transfer to the end of


the switch statement

 If a break statement is not used, the flow of control will


continue into the next case

 Sometimes this may be appropriate, but often we want to


execute only the statements associated with one case

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

for ( initialization ; condition ; increment )


statement;

The increment portion is executed at


the end of each iteration

for (int count=1; count <= 5; count++)


System.out.println (count);
47
For each statement
• Result
for (variable : arr) {
body; String[] test = {"This", "is", "a",
} "test"};
listEntries(test);
for(variable: collection) {
body; This
} is
a
public static void test
listEntries(String[]
entries) {
for(String entry: entries) {
System.out.println(entry);
}
}

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

 do while statement true false condition


evaluated
do { statement

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();

 Convert explicitly (Integer.parseInt, Double.parseDouble)


String seven = "7";
int i = Integer.parseInt(seven);

 In real applications, use a GUI


 Collect input with textfields, sliders, combo boxes, etc.
 Convert to numeric types with Integer.parseInt, Double.parseDouble, etc.

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

 Select Tab Arguments

 Tape the right value

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.

String name[] = {"Okada", "Tamura", "Matsuda", "Asai",


"Natsuki"};
int data[][] = {{79, 65, 78}, {21, 93, 45}, {31, 55, 22}, {81,
66, 81}, {76, 90, 86}};

 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

You might also like