Funadamental Programming structures in Java
Funadamental Programming structures in Java
Programming
Fundamental Programming
Structures in Java
Dr. Kulwadee Somboonviwat
International College, KMITL
[email protected]
Fundamental Programming Structures
• A Simple Java Program
• Comments
• Data Types
• Variables
• Operators
• Strings
• Input and Output
• Control Flow
• Arrays
• Methods
A Simple Java Program
/**
* File: FirstSample.java
* This is our first sample program in Java
* @version 1.0
* @author Kulwadee class keyword : everything in java
*/ program must be inside a class!
class name: starts with a letter,
public class FirstSample followed by any number of letters or digits
{
public static void main(String[] args)
{
System.out.println(“Welcome to Java!”);
}
}
The main method:
Access modifier the method that every java
program MUST have!
A Simple Java Program :
output a line of message to console
System.out.println(“Welcome to Java!”);
Object.method(parameters)
Now.. Let’s compile and run our first program!
FirstSample.java FirstSample.class
Welcome to Java!
Fundamental Programming Structures
• A Simple Java Program
• Comments
• Data Types
• Variables
• Operators
• Strings
• Input and Output
• Control Flow
• Arrays
• Methods
Comments
• Comments do not show up in the executable program
(typeName) expression
Example:
(int) (balance * 100)
Purpose:
To convert an expression to a different type
Constants: final
• A final variable is a constant
• Once its value has been set, it cannot be changed
• Named constants make programs easier to read and maintain
• Convention: use all-uppercase names for constants
In a method:
final typeName variableName = expression ;
In a class:
accessSpecifier static final typeName variableName = expression;
Example:
final double NICKEL_VALUE = 0.05;
public static final double LITERS_PER_GALLON = 3.785;
Purpose:
To define a constant in a method or a class
Fundamental Programming Structures
• A Simple Java Program
• Comments
• Data Types
• Variables
• Operators
• Strings
• Input and Output
• Control Flow
• Arrays
• Methods
Operators
• Assignment (=), Increment (++), Decrement (--)
• Arithmetic Operators
+ - * / %
• Relational Operators
< <= > >= == !=
• Logical Operators
! && || ^
Assignment, Increment, Decrement
• Assignment is not the same as mathematical equality:
items = items + 1;
• Increment
items++ is the same as items = items + 1
• Decrement
items-- subtracts 1 from items
Arithmetic Operations
• / is the division operator
If both arguments are integers, the result is an integer.
The remainder is discarded
7.0 / 4 yields 1.75
7 / 4 yields 1
7 % 4 is 3
The Math class
• Math class: contains methods like sqrt and pow
• To compute xn, you write Math.pow(x, n)
• To take the square root of a number, use the Math.sqrt;
for example, Math.sqrt(x)
• In Java,
can be represented as
(-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a)
The Math class
Mathematical Methods in Java
Math.sqrt(x) square root
Math.pow(x, y) power xy
Math.exp(x) ex
System.out.println(data)
println method
Print an object (i.e. data) to the standard output stream
Reading Input
• System.in has minimal set of features–it can only read
one byte at a time
• In Java 5.0, Scanner class was added to read keyboard
input in a convenient manner
import java.util.Scanner;
Scanner in = new Scanner(System.in);
System.out.print("Enter quantity: ");
int quantity = in.nextInt();
Note:
nextDouble reads a double
nextLine reads a line (until user hits Enter)
nextWord reads a word (until any white space)
Fundamental Programming Structures
• A Simple Java Program
• Comments
• Data Types
• Variables
• Operators
• Strings
• Input and Output
• Control Flow
• Arrays
• Methods
Control Structures
• Java supports both conditional statements and loops to
determine the control flow of a program
Conditional statements
If-statement
Switch-statement
Loops
While-statement
Do-While-statement
For-statement
Decisions
• if statement
Decisions
• if/else statement
if statement
Syntax 2.4: if statement
if (condition) if (condition)
{ {
statement statement1
} }
else
{
statement2
}
Example:
if (amount <= balance) balance = balance - amount;
if (amount <= balance)
balance = balance - amount;
else
balance = balance - OVERDRAFT_PENALTY;
Purpose:
To execute a statement when a condition is true or false
Exercise: implement this loop in Java
while loop
• Executes a block of code repeatedly
• A condition controls how often the loop is executed
while (condition)
statement;
Year Balance
When has the bank account
reached a target balance of
0 $10,000
$500,000 ?
1 $10,500
2 $11,025
3 $11,576.25
4 $12,155.06
5 $12,762.82
while loop
Calculating the Growth of an Investment
Invest $10,000, 5% interest, compounded
annually
while (condition)
statement
Example:
Purpose:
To repeatedly execute a statement as long as a condition is true
for loop
for (initialization; condition; update)
statement
Example:
for (int i = 1; i <= n; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
for loop
characters ‘1’ ‘3’ ‘9’ ‘8’ ’7’ ‘2’ char[] characters = new char[6];
Java Array Data Type
• Declare Array variables
• Create Arrays
• Array Initializers
• Iterate Arrays
• Copying Arrays
• Multidimensional Arrays
Declaring Array [Reference] variables
Employee[] empList =
{new Employee(“emp1”), new Employee(“emp2”) };
Array Size and Index
syntax: arrayRefVar.length // get the number of elements
arrayRefVar[index] // access the element at index
import java.util.Scanner;
public class AnalyzeNumbers {
public static void main(String[] args) {
final int NUMBER_ELEMENTS = 5;
double[] numbers = new double[NUMBER_ELEMENTS];
double sum = 0;
Scanner in = new Scanner(System.in);
for ( int i = 0; i < numbers.length; i++) {
System.out.print("Enter a new number: ");
numbers[i] = in.nextDouble();
sum += numbers[i];
}
double average = sum / NUMBER_ELEMENTS;
int count = 0;
for ( double elem : numbers )
if (elem > average) count++;
System.out.println("Average is " + average);
System.out.println("# of elements above average : " + count);
}
}
Out-of-Bounds
• Legal array indexes: [0 …. Array.length – 1]
– Accessing any index outside this range will
throw an ArrayIndexOutOfBoundsException
System.out.println(myArray[0]); // OK
System.out.println(myArray[7]); // OK
System.out.println(myArray[-1]); // exception
System.out.println(myArray[8]); // exception
Copying Arrays
int[] list2;
list2 = list1
Copying Arrays
Is this the correct way to copy arrays?
list2 = list1
list2
null
.
Copying Arrays : correct ways (1/3)
• Use a for-loop
• Use System.arraycopy()
• Use java.util.Arrays.copyOf()
list 1 2 3 4 5 6
j
result 3 2 1
Variable-Length Argument Lists
syntax: typeName… parameterName
m
m[0][0] m[0][1] m[0][2] m[0][3] m[0].length = 4
m[0]
m[1] m[1][0] m[1][1] m[1][2] m[1][3] m[1].length = 4
m[2]
m.length = 3
Multidimensional Arrays
syntax: elementType[][] arrayRefVar = { {}, {}, {} };
3 4
3 4
4
Processing Multidimensional Arrays
ArrayList
+ArrayList() Study the ArrayList class by reading the
+add(o: Object): void Java API documentation. For each
+clear(): void
+contains(o: Object): boolean method listed here, please find:
+get(index: int): int - Description
+indexOf(o: Object): int
+isEmpty(): boolean - Usage example
+lastIndexOf(o: Object): boolean
+remove(o: Object): boolean
+size(): int
+remove(index: int): boolean
+set(index: int, o: Object): Object
// CD.java
class CD {
private String artist;
private String album;
CD(String artist, String album) { this.artist = artist; this.album = album;}
public String getArtist() { return artist; }
public String getAlbum() { return album; }
@Override
public String toString() { return album + “ by “ + artist; }
}
index 0 1 2 3 4 5 6 7 8 9
inputNumber= 26206676
value 1 0 2 0 0 0 4 1 0 0
Fundamental Programming Structures
• A Simple Java Program
• Comments
• Data Types
• Variables
• Operators
• Strings
• Input and Output
• Control Flow
• Arrays
• Methods
Why use methods?
Suppose that you need to find the area of three circles,
you may come up with this code