You are on page 1of 43

ADVANCED PROGRAMMING WITH JAVA

AND UML
CSC 417

By
Dr. Salamudeen Alhassan

March 9, 2022
Introduction to Java

Content Overview
Java Strings
Java Arrays
Files and I/O
Exceptions

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 2 / 27
The String class

Strings are sequence of characters.


They are treated as objects in Java.
The String class in java creates and manipulates strings.
The String class has 11 constructors that allow you to provide
the initial value of the string using different sources.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 3 / 27
The String class cont.

Constructing a String
String message = "Welcome to Java!"
String message = new String("Welcome to Java!“);
char[] sMessage = { ’W’, ’e’, ’l’, ’c’, ’o’, ’m’, ’e’, ’ ’, ’t’, ’o’, ’ ’,
’J’, ’a’, ’v’, ’a’, ’!’ };
String s = new String(sMessage);

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 4 / 27
The String class cont.

Some String class accessor methods


length(). Returns the number of characters contained in a
string object.
concat(String str) or the + operator. Concatenates strings.
charAt(int index). Returns the character at the specified index.
compareTo(String anotherString). Compares two strings
lexicographically.
compareToIgnoreCase(String str). Compares two strings
lexicographically, ignoring case differences.
indexOf(int ch[, int fromIndex]). Returns the index within
this string of the first occurrence of the specified character.
lastIndexOf(int ch[,int fromIndex]).Returns the index within
this string of the last occurrence of the specified character,
searching backward starting at the specified index.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 5 / 27
The String class cont.

Some String class accessor methods


replace(char oldChar, char newChar). Returns a new string
resulting from replacing all occurrences of oldChar in this string
with newChar.
toLowerCase(). Converts all of the characters in this String to
lower case using the rules of the default locale.
toUpperCase(). Converts all of the characters in this String
to upper case using the rules of the default locale.
trim(). Returns a copy of the string, with leading and trailing
whitespace omitted.
substring(int beginIndex[,int endIndex]). Returns a new
string that is a substring of this string.
intern(). Returns a canonical representation for the string
object.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 6 / 27
The StringBuffer Class

StringBuffer class is an alternative to the String class.


StringBuffer is more flexible than String.
The value of a string is fixed once the string is created.
One can add, insert or append new contents into a string buffer.
StringBuffer Constructors
public StringBuffer(). No characters, initial capacity 16
characters.
public StringBuffer(int length). No characters, initial
capacity specified by the length argument.
public StringBuffer(String str). Represents the same
sequence of characters as the string argument. Initial capacity
16 plus the length of the string argument.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 7 / 27
The StringBuffer Class

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 8 / 27
Listing: StringBuffer Example
StringBuffer strBuf = new StringBuffer () ;
strBuf . append (" Welcome ") ;
strBuf . append ( ’ ’) ;
strBuf . append (" to ") ;
strBuf . append ( ’ ’) ;
strBuf . append (" Java ") ;

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 9 / 27
Java Arrays

An array is a data structure that represents a collection of the


same types of data.
Declaring Array Variables
datatype[] arrayname;
e.g. double[] myList;
datatype arrayname[];
e.g. double myList[];

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 9 / 27
Java Arrays Cont.

Creating Arrays
You can create an array by using the new keyword.
arrayName = new datatype[arraySize];
e.g. myList = new double[10];
Or in on step
datatype[] arrayname = new datatype[arraySize];
e.g. double[] myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
The Length of Arrays
arrayname.length;
NB: Once an array is created, its size is fixed. It cannot be
changed.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 10 / 27
Java Arrays Cont.

Figure: Java Arrays


ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 11 / 27
Java Arrays Cont.

Initializing Arrays
Using a loop
for (int i = 0; i < myList.length; i++)
myList[i] = i;
Declaring, creating, initializing in one step
double[] myList = 1.9, 2.9, 3.4, 3.5;
NB: This syntax must be in one statement.
Or
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 12 / 27
Listing: Array Example 1
public class months {
public static void main ( String [] args ) {
String [] months = {" Jan " , " Feb " , " Mar " , " Apr " , " May " , " Jun " , "
July " , " Aug " , " Sep " , " Oct " , " Nov " , " Dec "};
int [] monthsDay = {31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 ,
31};
System . out . println ("\ nNo . of months in a year is " + months .
length ) ;
for ( int i = 0; i < months . length ; i ++) {
System . out . println ( months [ i ] + " has " + monthsDay [ i ] + " days
") ;
}
}
}

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 13 / 27
Listing: Array Example 2
public class months {
public static void main ( String [] args ) {
String [] weekdays = {" Sunday " , " Monday " , " Tuesday " , " Wednesday " ,
" Thursday " , " Friday " , " Saturday "};
System . out . println (" No . of days in a week is " + weekdays . length
);
System . out . println (" The days of the week are :") ;
for ( String day : weekdays ) {
System . out . println ( day ) ;
}
}
}

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 13 / 27
Java Arrays Cont.

Passing Arrays to Methods


Java uses pass by value to pass parameters to a method
There are important differences between passing a value of
variables of primitive data types and passing arrays.
For a parameter of a primitive type value, the actual value is
passed. Changing the value of the local parameter inside the
method does not affect the value of the variable outside the
method.
For a parameter of an array type, the value of the parameter
contains a reference to an array; this reference is passed to the
method. Any changes to the array that occur inside the method
body will affect the original array that was passed as the
argument.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 13 / 27
ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 13 / 27
Passing Arrays to Methods

Listing: Array Example 3


public class months {
public static void main ( String [] args ) {
String [] weekdays = {" Sunday " , " Monday " , " Tuesday " , " Wednesday " ,
" Thursday " , " Friday " , " Saturday "};
System . out . println (" No . of days in a week is " + weekdays . length
);
swap ( weekdays ) ;
System . out . println (" The days of the week are :") ;
for ( String day : weekdays ) {
System . out . println ( day ) ;
}
String day1 = " Monday " , day2 = " Tuesday ";
swap ( day1 , day2 ) ;
System . out . println (" day1 : " + day1 + " day2 : " + day2 ) ;
}
public static void swap ( String [] days ) {
String temp = days [0];
days [0] = days [1]; days [1] = temp ;}
public static void swap ( String day1 , String day2 ) {
String temp = day1 ;
day1 = day2 ; day2 = temp ;}
}
ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 13 / 27
Multidimensional Arrays

Listing: Declaration and Creation


int [][] matrix = new int [10][10];
or
int matrix [][] = new int [10][10];
matrix [0][0] = 3;

for ( int i =0; i < matrix . length ; i ++)


for ( int j =0; j < matrix [ i ]. length ; j ++)
{
matrix [ i ][ j ] = ( int ) ( Math . random () *1000) ;
}

double [][] x ;

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 13 / 27
Multidimensional Arrays

Listing: Declaration Creation and Initialization


int [][] array = {
{1 , 2 , 3} ,
{4 , 5 , 6} ,
{7 , 8 , 9} ,
{10 , 11 , 12}
};

Is equivalent to :

int [][] array = new int [4][3];


array [0][0] = 1; array [0][1] = 2; array [0][2] = 3;
array [1][0] = 4; array [1][1] = 5; array [1][2] = 6;
array [2][0] = 7; array [2][1] = 8; array [2][2] = 9;
array [3][0] = 10; array [3][1] = 11; array [3][2] = 12;

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 13 / 27
Returning an Arrays from a Methods

Listing: Array Example 4


public class sortArray {
public static void main ( String [] args ) {
int [] myList = {2 , 9 , 5 , 4 , 8 , 1 , 6};
int [] myListSorted = sort ( myList ) ;
System . out . println (" myList in sorted order is :") ;
for ( int val : myListSorted ) {
System . out . println ( val ) ;}
}
public static int [] sort ( int [] array ) {
int last , temp , larger , index =0;
last = array . length -1; larger = array [0];
while ( last >0) {
for ( int i =0; i <= last ; i ++) {
if ( array [ i ] >= larger ) {
larger = array [ i ];
index = i ;}
}
temp = array [ last ]; array [ last ] = array [ index ];
array [ index ] = temp ; larger = array [0];
last - -;}
return array ;}
}
ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 13 / 27
Files and I/O

java.io package contains all the classes needed for all input and
output.
A stream is a sequence of data.
Kinds of streams
InPutStream for reading data from a source.
OutPutStream for writing data to a destination.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 14 / 27
Files and I/O Cont.

Byte Streams are used to perform input and output of 8-bit


bytes.
Common byte stream classes
FileInputStream. Handles source file input operations.
FileOutputStream. Handles destination file operations.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 15 / 27
ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 15 / 27
Listing: Byte Streams
import java . io .*;
public class CopyFile {// this program copies the content of a
input file to an output file .
public static void main ( String args []) throws IOException {
F il eI np u tS tr ea m fin = null ; // input file
F i l e O u t p u t S t re a m fout = null ; // output file
try {
fin = new Fi l eI np ut S tr ea m (" sampleinput . txt ") ;
fout = new F i l e O u t p u t S t r e am (" output . txt ") ;
int c ;
while (( c = fin . read () ) != -1) {
fout . write ( c ) ;
}
}
finally {
if ( fin != null ) {
fin . close () ;
}
if ( fout != null ) {
fout . close () ;
}
}
}
} ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 15 / 27
Files and I/O Cont.

Character Streams are used to perform input and output for


16-bit unicode.
Common classes
FileReader. Handles source file input operations and reads
2-bytes at a time
FileWriter. Handles destination file operations and writes
2-bytes at a time.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 16 / 27
Files and I/O Cont.

Standard Streams provides facilities to take user input from


the keyboard and display result to the computer screen
The 3 standard streams
Standard Input. Handles user’s input data from the keyboard
by means of System.in
Standard Output. Handles output data produced the program
by means of System.out.
Standard Error. Handles output error data produced by the
program

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 17 / 27
Listing: Standard Streams
import java . io .*;
public class ReadConsole {

public static void main ( String args []) throws IOException {


I n p u t S t r e a m R e a d e r cin = null ;

try {
cin = new I n p u t S t r e a m R e a d e r ( System . in ) ;
System . out . println (" Enter characters , ’q ’ to quit .") ;
char c ;
do {
c = ( char ) cin . read () ;
System . out . print ( c ) ;
} while ( c != ’q ’) ;
} finally {
if ( cin != null ) {
cin . close () ;
}
}
}
}

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 18 / 27
Files and I/O Cont.

Reading and Writing Files


FileInputStream is used for reading data from the files.
Objects are created by using the new keyword.
Object - Objects have states(properties) and behaviors.
Example: A car has states - color, name, brand as well as
behavior such as engine start, engine off, moving, etc.
An object is created from a class.
Syntax for creating an object:
ClassName ObjectName = new ClassNew();

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 18 / 27
Exceptions

Java Exceptions
An Exception is a problem that arises during the execution of a
program.
Java throws an exception in such cases.
A program will terminate abnormally when an exception occurs
and not handled appropriately.
Some scenarios which can lead to exceptions.
Coding errors made by the programmer
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of
communications or the JVM has run out of memory.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 19 / 27
Exceptions

Categories of Java Exceptions


Checked exceptions / compile time exception.
It is an exception that is checked by the compiler at
compilation-time.
It cannot simply be ignored, the programmer should take care of
it.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 20 / 27
Listing: Checked exception
import java . io . File ;
import java . io . FileReader ;
public class Ch e ck ed _E xa m pl e {
// F i l e N o t F o u n d E x c e p t i o n will occur
public static void main ( String args []) {
File file = new File (" D :// myfile . txt ") ;
FileReader fr = new FileReader ( file ) ;
}
}

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 21 / 27
Exceptions

Categories of Java Exceptions


Unchecked exceptions / Runtime exceptions.
It is an exception that occurs at the time of execution..
These include programming bugs, such as logic errors or
improper use of an API.
At the time of compilation, Runtime exceptions are ignored.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 21 / 27
Listing: UnChecked exception
public class U n c h e c k e d _ E x a m p l e {
// A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e x c e p t i o n
public static void main ( String args []) {
String [] weekdays = {" Sunday " , " Monday " , " Tuesday " , " Wednesday " ,
" Thursday " , " Friday " , " Saturday "};
System . out . println ( weekdays [7]) ;
}
}

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 22 / 27
Exceptions

Categories of Java Exceptions


Errors
They are not exceptions, but problems that arise beyond the
control of the user or the programmer.
Errors are typically ignored in your code because you can rarely
do anything about an error.
They are also ignored at the time of compilation.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 22 / 27
Exceptions

Exceptions Methods in Throwable class


public String getMessage() Returns a detailed message about
the exception that has occurred. This message is initialized in
the Throwable constructor.
public Throwable getCause() Returns the cause of the
exception as represented by a Throwable object.
public String toString() Returns the name of the class
concatenated with the result of getMessage().
public void printStackTrace() Prints the result of toString()
along with the stack trace to System.err, the error output
stream.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 23 / 27
Exceptions

Catching Exceptions
Catch exceptions by using the try / catch block.
Code within a try/catch block is referred to as protected code

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 24 / 27
Try / catch syntax
try {
// Protected code
}
catch ( ExceptionName e1 ) {
// Catch block
}

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 25 / 27
Try / catch Example
public class Unchecked_Example {
// A r r a y I n d e x O u tOf Bou nds Exc ept ion exc ept ion
public static void main ( String args []) {
String [] weekdays = {" Sunday " , " Monday " , "
Tuesday " , " Wednesday " , " Thursday " , "
Friday " , " Saturday "};
try {
System . out . println ( weekdays [7]) ;
}
catch { A rr a yI ndexOutOfBoundsException e }{
System . out . println (" Exception thrown
:" + e ) ;
}
}
}

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 25 / 27
Exceptions

Finally
The finally statement lets you execute code, after try...catch,
regardless of the result
A finally block appears at the end of the catch blocks.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 25 / 27
Try / catch finally syntax
try {
// Protected code
} catch ( ExceptionType1 e1 ) {
// Catch block
} catch ( ExceptionType2 e2 ) {
// Catch block
} catch ( ExceptionType3 e3 ) {
// Catch block
} finally {
// The finally block always executes .
}

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 26 / 27
Try Question

Try Question 1
Write a program in Java that reads student scores (int) from the
keyboard, get the best score, and then assign grades based on the
following scheme:
Grade is A if score is >= best–10;
Grade is B if score is >= best–20;
Grade is C if score is >= best–30;
Grade is D if score is >= best–40;
Grade is F otherwise.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 26 / 27
Try Question

Try Question 2
Write a program in Java that reads in two square matrices A and B.
Your program should be able to add these matrices in to a matrix C
and display the results.

ByDr. Salamudeen Alhassan ADVANCED PROGRAMMING WITH JAVA AND UML March 9, 2022 27 / 27

You might also like