ENGR24524D ALGORITHMS AND DATA
STRUCTURES
,
Nazrul Khan PhD, PEng.
1
Java Fundamentals
Learning outcomes:
- Refreshing your programming skill
- Java fundamentals
- Dissect Java programs
Java Fundamentals
Programming:
- Data structures and algorithms need to be implemented in a
computer program
- For that, we will be using java programming language
- Your previous programming concept will be utilized too
- Java programming language will not be taught
- The following slides are to refresh your programming concepts in
terms of java.
Java Fundamentals
Programming in java:
**Let us First dissect the example program myJavaProgram**
Things to remember:
- A java program is made of class and object
- Class (a template/recipe) is made of fields(properties) and methods
- Object (cake) is created from class
- Java is object oriented programming language
Java Fundamentals
- A java program (class) is either a library of static methods(functions)
or a data type definition.
Components of a java program:
- Primitive data types: int, double, boolean, char, byte, long, short
- Statements: declaration, assignments, conditionals, loops, calls, and
returns
- Arrays: allow us to work with multiple values of same type
- Static methods: allow us to encapsulate and reuse code and to
develop programs
- Strings: are sequence of character
- Input/output: sets up communication between programs and outside
world
- Data abstraction: extends encapsulation and reuse to allow us to
define non-primitive data types, thus supporting OOP.
Java Fundamentals
Variable: int myData;
Operator: + - * /
Literal: int 1; double 2.0; boolean true false; char ‘a’
Expression: int lo + (hi-lo)/2; boolean lo <= hi
Comparisons: compares two values and produce a boolean value:
equal (==), not equal (!=), less than (<), greater than or
equal (>=) etc.,
Conditional:
if(<boolean expression>) {block statements}
else {block statements}
if(<boolean expression>) {block statements}
if(<boolean expression>){block statements}
else if(<boolean expression>) {block statements}…
Java Fundamentals
Loops: Many computations are inherently repetitive. The basic java
construct to do repetition is:
while (<boolean expression>) {<block statements>}
The break and Continue:
- The break statement, which immediately exits the loop
- The continue statement, which immediately begins the next iteration
of the loop.
For loop:
for (<initialize>; <boolean expression>; <increment/decrement>)
{
<block statements>
}
Java Fundamentals
Initializing declaration:
- int i = 5; declaring a variable with initial value
Implicit assignments:
- Increment operator: ++i is same as i = i + 1;
- decrement operator: --i is same as i = i – 1;
Compound Operator:
- i /= 2 is same as i = i/2;
- i += 1 is same as i = i + 1;
Single-statement blocks:
- For a single statement block, the curly braces may be omitted.
Java Fundamentals
Arrays:
- An array stores a sequence of values (elements) that are all of the
same type
- We want not only to store values but also to access each individual
value
- To refer to individual values in an array is numbering and then
indexing them
- If we have N values, they are numbered from 0 to N – 1
- We then specify one of them by using a notation a[ i ] to refer to the
ith value for any value of i from 0 to N – 1
- Being an object, we can use inbuilt fields and methods( ) associated
with this object
Java Fundamentals
Arrays (Creating and initializing):
Making an array in a java program involves three steps:
- Declare the array name and type
- Create the array
- Initialize the array values
Examples:
double[ ] myArray; //declaration
myArray[N-1]
myArray = new double [N]; //creation
= ??
for(int i = 0; i < N; i++)
myArray[ i ] = 0.5; //initialization
Java Fundamentals
Arrays (Creating and initializing):
double[ ] myArray = new double[N]; // declare & creation
int[ ] myArray = {8,7,13,56,98}; // declaration and initialization
Default array initialization:
- The default initial value is zero for numeric types and false for
boolean type.
- Once we create an array, its size is fixed
- A program can refer to the length of an array myArray with the code
[Link] (Array is an object in java!)
Java Fundamentals
Aliasing:
- A array name refers to the whole array: If we assign one array name
to another, then both refer to the same array.
- Example:
int[ ] myArray = new int[N];
…
int[ ] yourArray = myArray;
yourArray [ i ] = 789; //myArray [ i ] is now 789
This phenomena is called aliasing! Can lead to errors.
Java Fundamentals
Two-dimensional array:
- A two dimensional array is an array of one dimensional array
- A M-by-N two dimensional arrays that are arrays of M rows, each an
array of length N (having N columns)
- The notation to refer a two-dimensional array is myArray[ i ][ j ]
Declaration and creation:
double [ ][ ] myArray = new double[M][N]
double [ ][ ] myArray;
myArray = new double[M][N];
for(int i = 0; i < M; i++)// Rows
for(int j = 0; j < N; j++)//Cols
myArray[ i ][ j ] = 0.0;
Java Fundamentals
Array manipulations:
Finding the maximum:
double max = myArray[0];
for(int i = 1; i < [Link]; i++){
if(myArray[ i ] > max)
max = myArray[ i ];}
Dot
Computing the average: operator
int N = [Link];
double sum = 0.0;
for(int i = 0; i < N; i++)
sum += myArray[ i ];
double average = sum/ N;
Java Fundamentals
Array manipulations:
Copying:
int N = [Link];
double[ ] yourArray = new double[N];
for(int i = 0; i < N; i++)
yourArray[ i ] = myArray[ i ];
Reversing:
int N = [Link];
for(int i = 0; i < N/2; i++)
{
double temp = myArray[ i ];
myArray[ i ] = myArray[N – i -1];
myArray[N – i -1] = temp; }
Java Fundamentals
Array manipulations:
Matrix-matrix multiplication (a[ ]*b[ ] = c[ ][ ]):
int N = [Link];
double[ ][ ] c = new double[N];
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
{//compute dot product of row i and column j
for(int k = 0; k < N; k++)
c[ i ][ j ] += a[ i ][ k ] * b[ k ] [ j ];
}
Java Fundamentals
Array manipulations:
The Enhanced for Loop:
Often, you need to visit all elements of an array. The enhanced for loop
makes this process easy
double[ ] myArray = ….
double sum = 0.0;
for (double x : myArray)// x represent each element in the array
{
sum += x;
}
Java Fundamentals
Practice Lab:
- Install Netbeans
- Create a project named myArrayProgram
- Write a java program to do the following:
Create an array(myArray) with the following values
3 6 9 12 15 18 21 24 27 30
- Process the array so that each element value will be changed to
myArray[ i ] x 2 + 3
- Display the content of this changed array
- Compile and run your program
- Upload the source file([Link]) in the assignments
folder(Practice lab).
Java Fundamentals
Strings:
- A string is a sequence of characters
- A literal string is a sequence of characters within double quotes,
such as, “Hello Students”
- It is non-primitive type and considered as an object
- Being an object, we can use inbuilt fields and methods( ) associated
with this object.
Concatenation:
- Java has a built-in concatenation operator(+) for String
- -Concatenating two String values is a String value, the first string
followed by the second
“Hello” + “Students” = “HelloStudents” How to “Hello Students”
“1” + “+” + “2” = “1+2”
Java Fundamentals
Conversion:
- Two primary uses of strings:
- Convert values that we enter on a keyboard into data-type values
- Convert data-type values to values that we can read on a display
static int parseInt (String s) //convert s to an int value
static double parseDouble (String s) //convert s to double value
static String toString(int i) // convert i to a String value
static String toString(double y) // convert y to a String value
Java Fundamentals
Input and Output:
- A java program takes input values from command-line arguments or
- From an abstract stream of characters known as the standard input
streams and
- Writes to another abstract stream of characters known as the
standard output stream
- We need to consider the interface between java and the operating
system
- By convention, both java and the operating system process the
arguments as Strings.
Commands and arguments:
In the terminal window:
Java –jar [Link] 15 100.0 500 ENTER
Java Fundamentals
Standard Input and Output:
- In java, the most convenient way for reading text is to use the
scanner class
Reading (inputting) values from the console:
Scanner in = new Scanner();//creating a scanner object for inputting
int x = [Link](); // inputing an integer
double y = [Link](); // inputing a double value
char z = [Link]().charAt(0); //inputting a char
String p = [Link]();//inputting a String(word)
String p = [Link](); // inputting a String(whole line)
Other useful static input methods:
static boolean isEmpty(); //true if no more values, false otherwise
static boolean hasNextLine(); //is there another line in the input stream?
Java Fundamentals
Standard Input and Output:
- In java, the most convenient way for outputting text is to use the
[Link] object
Writing values to the screen:
[Link] (“Hello, Class”);//outputting the string Hello, Class
[Link](“Sum: %8.2f\n”, sumTotal);//say, 1024.45
[Link] (sumTotal);// outputting the value in sumTotal variable
[Link](); // inserting a new line
Java Fundamentals
Input/output from/to a disk file:
- The scanner class relies on another class, File
How to do:
File inputFile = new File(“[Link]”); // creating a File object
Scanner in = new Scanner(inputFile); //creating a Scanner object
- This Scanner object reads text from the file [Link]
-You can use the following loop to process numbers in the input file
while([Link]())
{
double value = [Link]();// Reading from “[Link]”
Process value;
}
Java Fundamentals
Input/output from/to a disk file:
- To write output to a file, construct a PrintWriter object
How to do:
PrintWriter out = new PrintWriter(“[Link]”); // An empty file is created if not
exist, otherwise it gets emptied, if already exists
[Link](“Hello Students”);
[Link](“Sum = %8.2f/n”, sumTotal);
- PrintWriter class is an enhancement of the PrintStream class
- [Link] is a PrintStream object.
- When you are done processing a file, be sure to close the Scanner or
PrintWriter:
[Link]();
[Link]();
Java Fundamentals
Methods:
- A method (function in C!) is a sequence of instructions with a name
- Every java program has a method called main( ), the entry point
- Methods are called to execute its instructions
Example:
public static void main(String[ ] args)
{
double myResult = [Link](3,4);
……
}
- main calls the [Link]( )
- The [Link] method returns its results (34 = 81) back to main
- The main method resumes execution
Java Fundamentals
Methods:
- Static methods are distinct from instance methods
- Static methods are property of class. As such they can be called by
their name or through their class name
- Instance methods must be called through their object
- A static method can call another static method
- A static method can’t access field variables
- Instance methods can access field variables
- Arguments are passed by values
- Methods name can be overloaded
- A method has a single return value but may have multiple return
statements
- A method can have side effects
Java Fundamentals
Anatomy of a static Method:
public static double cubeVolume (double side) // signature, return type,
//argument type & value
{// body starts
double volTotal = side * side * side; // executable statement
return volTotal; // exits method and return result
}//body ends
Java Fundamentals
Anatomy of a Java Program:
Let us dissect yet another example program myArrayProgram
Java Fundamentals
Suggestive Reading list:
1. Java Concepts Late Objects, 3/e, Cay Horstmann
Acknowledgements
The above slides are adopted from:
1. JavaCocepts@CayHorstmann