Slide 1

Slide 1 text

Java (SE) Programming Course

Slide 2

Slide 2 text

Java arrays are objects , are dynamically created, and may be assigned to variables of type Object . All methods of class Object may be invoked on an array. Here are some examples of declarations of array variables that create array objects: Exception ae[] = new Exception[3]; Object aao[][] = new Exception[2][3]; int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 }; char ac[] = { 'n', 'o', 't', ' ', 'a', ' ','S', 't', 'r', 'i', 'n', 'g' }; String[] aas = { "array", "of", "String", }; int[] anArray; // declare an array of integers anArray = new int[10]; // create an array of integers

Slide 3

Slide 3 text

Arrays: A Simple Example The example: public class ArrayDemo2 { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create an array of integers // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); } System.out.println(); } } The output from this program is: 0 1 2 3 4 5 6 7 8 9

Slide 4

Slide 4 text

Arrays: A Simple Example The example: class Gauss { public static void main(String[] args) { int[] ia = new int[101]; for (int i = 0; i < ia.length; i++) ia[i] = i; int sum = 0; for (int i = 0; i < ia.length; i++) sum += ia[i]; System.out.println(sum); } } that produces output: 5050

Slide 5

Slide 5 text

Exercises Create module dayOfweek.java. Module Processing This module would print the array days[] collection of values. input String days[] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"}; output sun,mon,tue,wed,thu,fri,sat There are noOfdays.value days in a week Create module philHero.java Module Processing This module would print the array hero[] collection of values. input String hero[] = {“Rizal", “Bonifacio", “Aguinaldo", “Mabini", “Ninoy"}; output Rizal is our national Hero. Bonifacio started the Phil revolution. Aguinaldo was the 1st president of the Phil. Mabini was the brain behind the revolution. Ninoy started the struggle against a dictator?

Slide 6

Slide 6 text

Exercises Create module arrayVowel.java Module Processing This module would print the number of vowel found in variable copyFromMe . input char[] vowelStr = {'a','A','e','E','i','I','o','O','u','U'} String copyFromMe = "The quick brown fox jumps over the lazy dog"; output Number of Vowel found: 11 Hint: To navigate 1 char at a time in a given variable copyFromMe use string manipulation function charAt(). Ex. c = variable.charAt(i2)

Slide 7

Slide 7 text

Exercises Create module monthDays.java Module Processing This module would print the month and day from January 1 up to December 31 input: String[] x_month = {"January","February","March","April","May", "June","July","August","September","October", "November","December"}; String[] x_days = {"1","2","3","4","5","6","7","8","9", “10","11","12","13","14","15","16","17","18","19“, "20","21","22","23","24","25","26","27", "28","29","30","31"}; output January 1 January 2 . . December 31

Slide 8

Slide 8 text

Exercises Create module ArrayOfArraysDemo.java Module Processing This module would print the fallowing output. output Flintstones: Fred Wilma Pebbles Dino Rubbles: Barney Betty Bam Bam Jetsons: George Jane Elroy Judy Rosie Astro Scooby Doo Gang: Scooby Doo Shaggy Velma Fred Daphne Create module ArrayOfArraysDemo2.java Module Processing This module would print the fallowing matrix. output 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

Creating Strings and String Buffers A string is often created from a string literal—a series of characters enclosed in double quotes. For example, when it encounters the following string literal, the Java platform creates a String object whose value is Gobbledygook. "Gobbledygook" Here's an example of creating a string from a character array: char[] helloArray = { 'h', 'e', 'l', 'l', 'o' }; String helloString = new String(helloArray); System.out.println(helloString);

Slide 17

Slide 17 text

Character and Substring Methods substring() Used to extract a portion of a string object. Example String country = “Singapore”; System.out.println(country.substring(3)); Output: gapore System.out.println(country.substring(0,3)); Output: Sin length() Provides the number of characters in the string String country = “Singapore”; System.out.println(country.length()); Output: 9 System.out.println(country.substring(country.length()-1)); Output: e

Slide 18

Slide 18 text

charAt() Used to find the character at any string position. Example String country = “Singapore”; System.out.println(country.charAt(1)); Output: i Concatenation of Strings the + operators can be used to concatenate strings. String a = "abc"; String b = "def"; String c = a + b; System.out.println(c); System.out.println(c+"ghi"); Output: abcdef abcdefghi

Slide 19

Slide 19 text

concat() is also used to concatenate strings. String a = "abc"; String b = "def"; String c = a.concat(b); System.out.println(c); System.out.println(c.concat(“ghi”)); Output: abcdef abcdefghi replace() replaces characters in a String Example String a = “Juan”; String b = a.replace(‘u’,’e’); System.out.println(a); //output Juan System.out.println(b);//out Jean

Slide 20

Slide 20 text

concat() is also used to concatenate strings. String a = "abc"; String b = "def"; String c = a.concat(b); System.out.println(c); System.out.println(c.concat(“ghi”)); Output: abcdef abcdefghi replace() replaces characters in a String Example String a = “Juan”; String b = a.replace(‘u’,’e’); System.out.println(a); //output Juan System.out.println(b);//out Jean

Slide 21

Slide 21 text

equalsignoreCase() Compares without case sensitivity (returns true or false) String a = “Juan"; String b = “Peter"; String c = “Juan”; String d = “peTer”; System.out.println(a.equalsignoreCase(b)); // Output: false System.out.println(a.equalsignoreCase(c)); // Output: true System.out.println(b.equalsignoreCase(d)); //Output: true

Slide 22

Slide 22 text

equals() Compares with case sensitivity (returns true or false) String a = “Juan"; String b = “Peter"; String c = “Juan”; String d = “peTer”; System.out.println(a.equals(b)); Output: false System.out.println(a.equals(c)); Output: true System.out.println(b.equals(d)); Output: false

Slide 23

Slide 23 text

toLowerCase() and toUpperCase() Converts the string to upper or lower cases. String a = “juan"; String b = “PETER"; System.out.println(a.toUpperCase()); Output: JUAN System.out.println(b.toLowerCase()); Output: peter

Slide 24

Slide 24 text

compareTo() Similar to equals/equalsIgnoreCase except the return value (integer). String a = “JUAN"; String b = “JUAN”; String c = “XUAN”; System.out.println(a.compareTo(b));//Output: 0 System.out.println(a.compareTo(c));//Output: -14 System.out.println(c.compareTo(a));//Output: 14 Note: If string 1 and string2 are equal return is 0 if string1 is less than string2 return a negative number (difference between two string) if string1 is greater than string2 return a negative number (difference between two string)

Slide 25

Slide 25 text

Exercises Create module substrWord.java. Module Processing This module would print a list of value using substring() . input String str = “Yellow Fever” ; output Y Ye Yel Yell Yello Yellow Yellow Yellow F Yellow Fe Yellow Fev Yellow Feve Yellow Fever

Slide 26

Slide 26 text

Exercises Revise module charAtWord.java. Module Processing This module primary function is to count the number of vowel found on any given word or phrase. Your assign task is to include functionality to count consonant as well as number to charAtWord.java. Input “The quick brown fox jumps over the lazy dog 123” Expected Output. There are 11 vowel/s found There are 24 consonant/s found There are 3 numbers/s found

Slide 27

Slide 27 text

public class charAtword { public static void main(String[] args) { int i2=0,i4=0,vCtr=0; String xVowel = "AaEeIiOoUu"; try{ String strLine = "The quick brown fox jumps over the lazy dog123"; if (strLine.compareTo("")==0) { System.out.println("Enter Character/s to be check"); return; }

Slide 28

Slide 28 text

while(i4!=strLine.length()){ String x = String.valueOf(strLine.charAt(i4)); while(i2!=xVowel.length()){ String x2 = String.valueOf(xVowel.charAt(i2)); if(x.compareTo(x2)==0){ vCtr++; break; } i2++; } i2=0; i4++; }

Slide 29

Slide 29 text

i4=0; System.out.println("There are "+String.valueOf(vCtr)+ " vowel/s found"); } catch (Exception e2){ System.out.println("Error:"+e2.getMessage()); } } }

Slide 30

Slide 30 text

Exercises Revise module charAtWord.java. Module Processing This module primary function is to count the number of vowel, consonant and numbers found on any given word or phrase. Your assign task is to include functionality that would make all vowels appear in uppercase while consonant would appear in lowercase.The current module gets it’s input coming from a static data source. It is a must that we add the functionality that data would be coming from inputted data source. I don’t see any problem with this functionality for I am sure that I given you from past task handling such functionality. Input coming from keyboard “The quick brown fox jumps over the lazy dog 123” Expected Output. There are 11 vowel/s found There are 24 consonant/s found There are 3 numbers/s found thE qUIck brOwn fOx jUmps OvEr thE lAzy dOg 123

Slide 31

Slide 31 text

Streams Java input and output is based on the use of streams. Streams are sequences of bytes that travel from a source to a destination over a communication path. If your program is writing to a stream, it is the stream's source. If it is reading from a stream, it is the stream's destination. The communication path is dependent on the type of I/O being performed. It can consist of memory-to-memory transfers, file system, network, and other forms of I/O. Java defines two major classes of streams: InputStream OutputStream. These streams are subclassed to provide a variety of I/O capabilities.

Slide 32

Slide 32 text

The java.io Class Hierarchy

Slide 33

Slide 33 text

The InputStream Class The InputStream class is an abstract class that lays the foundation for the Java Input class hierarchy. As such, it provides methods that are inherited by all InputStream classes. The read() Method is the most important method of the InputStream class hierarchy. It reads a byte of data from an input stream and blocks if no data is available. When a method blocks, it causes the thread in which it is executing to wait until data becomes available. This is not a problem in multithreaded programs. The read() method takes on several overloaded forms. It can read a single byte or an array of bytes, depending upon what form is used. It returns the number of bytes read or -1 if an end of file is encountered with no bytes read. The close() Method Closes an input stream and releases resources associated with the stream. It is always a good idea to close a stream to ensure that the stream processing is correctly terminated.

Slide 34

Slide 34 text

The InputStream Class The InputStream class is an abstract class that lays the foundation for the Java Input class hierarchy. As such, it provides methods that are inherited by all InputStream classes. The read() Method is the most important method of the InputStream class hierarchy. It reads a byte of data from an input stream and blocks if no data is available. When a method blocks, it causes the thread in which it is executing to wait until data becomes available. This is not a problem in multithreaded programs. The read() method takes on several overloaded forms. It can read a single byte or an array of bytes, depending upon what form is used. It returns the number of bytes read or -1 if an end of file is encountered with no bytes read. The close() Method Closes an input stream and releases resources associated with the stream. It is always a good idea to close a stream to ensure that the stream processing is correctly terminated.

Slide 35

Slide 35 text

The InputStream Class The InputStream class is an abstract class that lays the foundation for the Java Input class hierarchy. As such, it provides methods that are inherited by all InputStream classes. The read() Method is the most important method of the InputStream class hierarchy. It reads a byte of data from an input stream and blocks if no data is available. When a method blocks, it causes the thread in which it is executing to wait until data becomes available. This is not a problem in multithreaded programs. The read() method takes on several overloaded forms. It can read a single byte or an array of bytes, depending upon what form is used. It returns the number of bytes read or -1 if an end of file is encountered with no bytes read. The close() Method Closes an input stream and releases resources associated with the stream. It is always a good idea to close a stream to ensure that the stream processing is correctly terminated.

Slide 36

Slide 36 text

The available() Method returns the number of bytes that are available to be read without blocking. It is used to peek into the input stream to see how much data is available. However, depending on the input stream, it might not be accurate or useful. Some input streams on some operating systems may always report 0 available bytes. In general, it is not a good idea to blindly rely on this method to perform input processing. The skip() Method Skips over a specified number of input bytes. It takes a long value as a parameter.

Slide 37

Slide 37 text

The OutputStream Class is an abstract class that lays the foundation for the output stream hierarchy. It provides a set of methods that are the output analog to the InputStream methods. The write() Method allows bytes to be written to the output stream. It provides three overloaded forms to write a single byte, an array of bytes, or a segment of an array. The write() method, like the read() method, may block when it tries to write to a stream. The blocking causes the thread executing the write() method to wait until the write operation has been completed. The flush() Method causes any buffered data to be immediately written to the output stream. Some subclasses of OutputStream support buffering and override this method to "clean out" their buffers and write all buffered data to the output stream. They must override the OutputStream flush() method because, by default, it does not perform any operations and is used as a placeholder.

Slide 38

Slide 38 text

The close() Method It is generally more important to close output streams than input streams, so that any data written to the stream is stored before the stream is deallocated and lost. The close() method of OutputStream is used in the same manner as that of InputStream. Byte Array I/O Java supports byte array input and output via the ByteArrayInputStream and ByteArrayOutputStream classes. These classes use memory buffers as the source and destination of the input and output streams. These streams do not have to be used together. They are covered in the same section here because they provide similar and complementary methods. The StringBufferInputStream class is similar to the ByteArrayInput class and is also covered in this section. The ByteArrayInputStream Class creates an input stream from a memory buffer.

Slide 39

Slide 39 text

ByteArrayOutputStream class is a little more sophisticated than its input complement. It creates an output stream on a byte array, but provides additional capabilities to allow the output array to grow to accommodate new data that is written to it. Sample program demo for Byte Array I/O import java.lang.System; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ByteArrayIOApp { public static void main(String args[]) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream();

Slide 40

Slide 40 text

String s = "This is a test."; for(int i=0;i

Slide 41

Slide 41 text

Exercise Create Module ByteArrayVowel.java using the pseudo code listed below 1.Create the fallowing ByteArrayOutputStream. outStream1 outStream2 outStream3 ByteArrayInputStream inStream Variable String s = “The quick brown fox jumps over the lazy dog” String vowel = “AaEeIiOoUu” inBytes 2. Iterate using the variable vowel until int i2 < vowel.length. 2.1 outStream outStream.write(vowel. .write(vowel.charAt charAt(vowel.length() (vowel.length()- -i2)); i2)); 3. 3. Move outStream outStream content into content into inStream inStream. . 4. Initialize inBytes variable with inStream.available();

Slide 42

Slide 42 text

5. Print “Word to be check: “+ s 6. Iterate using the variable i until i < s.length. 6.1 Iterate using variable i3 until i3 < inBytes 6.1.1 Write to outStream2 containing s.charAt(i) 6.1.2 Compare s.charAt(i) to vowel.charAt(i3). If the result is true 6.1.1.1 Print “Vowel found ”+ s. s.charAt(i) 6.1.1.2 Write to outStream3 containing s.charAt(i) 6.1.1.3 Do control break 7. At end of the iteration in step 6 print the fallowing 7.1 “Value of Instream ” + inStream 7.2 “Value of outStream “ + outStream 7.3 “ Value of outStream2 “ + outStream2 7.4 “Vowel found :” + outStream3

Slide 43

Slide 43 text

The StringBufferInputStream Class is similar to ByteArrayInputStream except that it uses a StringBuffer to store input data. The input stream is constructed using a String argument. Its methods are identical to those provided by ByteArrayInputStream. The File Class is used to access file and directory objects. It uses the file-naming conventions of the host operating system. The File class encapsulates these conventions using the File class constants. The FileDescriptor Class provides access to the file descriptors maintained by operating systems when files and directories are being accessed. The FileInputStream Class allows input to be read from a file in the form of a stream. Objects of class FileInputStream are created using a filename string or a File or FileDescriptor object as an argument. The FileOutputStream Class allows output to be written to a file stream.

Slide 44

Slide 44 text

The FileIOApp Program illustrates the use of the FileInputStream, FileOutputStream, and File classes. It writes a string to an output file and then reads the file to verify that the output was written correctly. The file used for the I/O is then deleted. import java.lang.System; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; import java.io.IOException; public class FileIOApp { public static void main(String args[]) throws IOException { //Create FileOutputStream FileOutputStream outStream = new FileOutputStream("test.txt"); String s = "This is a test."; //write current position value “s” into outStream (FileOutputStream) for(int i=0;i

Slide 45

Slide 45 text

//close outStream outStream.close(); //Create FileInputStream inStream FileInputStream inStream = new FileInputStream("test.txt"); //count the number of bytes in the inStream int inBytes = inStream.available(); System.out.println("inStream has "+inBytes+" available bytes"); //move value of inBytes in byte array inBuff[] byte inBuf[] = new byte[inBytes]; //Read the inStream and move red data into bytesRead int bytesRead = inStream.read(inBuf,0,inBytes); System.out.println(bytesRead+" bytes were read"); System.out.println("They are: "+new String(inBuf,0)); //close inStream inStream.close(); File f = new File("test.txt"); //delete test.txt f.delete(); } }

Slide 46

Slide 46 text

Exercise Create Module FileIOarray.java using the pseudo code listed below 1.Create the fallowing Array String days[] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"}. FileInputStream inStream FileOutStream outStream Variable String xDays = “”, 2. Iterate using the I variable until last element of days[]. 2.1 move days[1] to xDays. 2.2 iterate using the i2 variable until i2 < xDays.length 2.2.1 outStream.write(xDays.charAt(i2));

Slide 47

Slide 47 text

3. 3. Close outSteam 4. Create FileInputStream instream 4.1 filename "C:/StreamJava/days.txt" 5. Move inBytes to byte inBuf[] 6. Read inStream and move red data to bytesRead variable. 7. Print bytesRead + “ bytes were read” 8. Print “They are” + new String(inBuf,0) 9 close inStream.

Slide 48

Slide 48 text

Data I/O implement the DataInput and DataOutput interfaces. These interfaces identify methods that provide the capability to allow arbitrary objects and primitive data types to be read and written from a stream. The DataInputStream Class provides the capability to read arbitrary objects and primitive types from an input stream. As you saw in the previous programming example, the filter provided by this class can be nested with other input filters. The DataOutputStream Class provides an output complement to DataInputStream. It allows arbitrary objects and primitive data types to be written to an output stream. It also keeps track of the number of bytes written to the output stream. It is an output filter and can be combined with any output-filtering streams.

Slide 49

Slide 49 text

import java.lang.System; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; import java.io.IOException; public class DataIOApp { public static void main(String args[]) throws IOException { //Create test.txt file File file = new File("test.txt"); //Create FileOutputStream outFile FileOutputStream outFile = new FileOutputStream(file); //Create dataOutputStream outStream DataOutputStream outStream = new DataOutputStream(outFile); //Write into outStream outStream.writeBoolean(true); outStream.writeInt(123456); outStream.writeChar('j'); outStream.writeDouble(1234.56);

Slide 50

Slide 50 text

Data I/O implement the DataInput and DataOutput interfaces. These interfaces identify methods that provide the capability to allow arbitrary objects and primitive data types to be read and written from a stream. The DataInputStream Class provides the capability to read arbitrary objects and primitive types from an input stream. As you saw in the previous programming example, the filter provided by this class can be nested with other input filters. The DataOutputStream Class provides an output complement to DataInputStream. It allows arbitrary objects and primitive data types to be written to an output stream. It also keeps track of the number of bytes written to the output stream. It is an output filter and can be combined with any output-filtering streams.

Slide 51

Slide 51 text

System.out.println(outStream.size()+" bytes were written"); //FileOutStream DataoutputStream files outStream.close(); outFile.close(); //Open a FileInputStream DataInputStream files FileInputStream inFile = new FileInputStream(file); DataInputStream inStream = new DataInputStream(inFile); //Read DataInputStream file System.out.println(inStream.readBoolean()); System.out.println(inStream.readInt()); System.out.println(inStream.readChar()); System.out.println(inStream.readDouble()); //Close FileInputStream & DataInputStream files inStream.close(); inFile.close(); //Delete test.txt file file.delete(); } }

Slide 52

Slide 52 text

The RandomAccessFile Class provides the capability to perform I/O directly to specific locations within a file. The name "random access" comes from the fact that data can be read from or written to random locations within a file rather than as a continuous stream of information. Random access is supported through the seek() method, which allows the pointer corresponding to the current file position to be set to arbitrary locations within the file. RandomAccessFile implements both the DataInput and DataOutput interfaces. This provides the capability to perform I/O using all objects and primitive data types. The RandomIOApp Program provides a simple demonstration of the capabilities of random-access I/O. It writes a boolean, int, char, and double value to a file and then uses the seek() method to seek to offset location 1 within the file. This is the position after the first byte in the file. It then reads the int, char, and double values from the file and displays them to the console window. Next, it moves the file pointer to the beginning of the file and reads the boolean value that was first written to the file. This value is also written to the console window.

Slide 53

Slide 53 text

import java.lang.System; import java.io.RandomAccessFile; import java.io.IOException; public class RandomIOApp { public static void main(String args[]) throws IOException { RandomAccessFile file = new RandomAccessFile("test.txt","rw"); file.writeBoolean(true); file.writeInt(123456); file.writeChar('j'); file.writeDouble(1234.56); file.seek(1); System.out.println(file.readInt()); System.out.println(file.readChar()); System.out.println(file.readDouble()); file.seek(0); System.out.println(file.readBoolean()); file.close(); } }

Slide 54

Slide 54 text

Exercise Revised RandomIOApp.java Program 1. Revised logic in the fallowing lines of codes file.writeBoolean(true); file.writeInt(123456); file.writeDouble(1234.56); 1.1 this module should now iterate 10 times to the above lines codes 1.2 Comment out the above lines of codes and apply necessary changes as reflected below. Create necessary variables to accomplish the task. //file.writerBoolean(bolArray[ true ]) file.writerBoolean(true) //file.writerInt(123456) file.writerInt(123456* i) //file.writerDouble(1234.56) file.writerDouble(1234.56* i)

Slide 55

Slide 55 text

1.4 this module should now iterate 10 times at lines codes written below file.seek(0); change to file.seek(i2); System.out.println(file.readBoolean()); System.out.println(file.readInt()); System.out.println(file.readChar()); System.out.println(file.readDouble());

Slide 56

Slide 56 text

import java.lang.System; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ByteArrayVowel { public static void main(String args[]) throws IOException { ByteArrayOutputStream outStream1 = new ByteArrayOutputStream(); ByteArrayOutputStream outStream2 = new ByteArrayOutputStream(); ByteArrayOutputStream outStream3 = new ByteArrayOutputStream(); String s = "This is a test."; String vowel = "AaEeIiOoUu"; // String vowel = ""; String inStreamRead = ""; //Move variable s value into outStream File

Slide 57

Slide 57 text

for (int i2=0;i2

Slide 58

Slide 58 text

try{ for(int i=0;i

Slide 59

Slide 59 text

//Print value inStream,outStream1,outStream2 and outStream3 Files System.out.println("Value of inStream: "+new String(inBuf,0)); System.out.println("Value of outStream1: "+outStream1); System.out.println("Value of outStream2: "+outStream2); System.out.println("Value of outStream3: "+outStream3); } catch (NullPointerException n) { // a subclass of RuntimeException System.out.println(n); } catch (RuntimeException r) { // a subclass of Exception System.out.println(r); } catch (Exception e) { // a subclass of Throwable System.out.println(e); } catch (Throwable t) { System.out.println(t); } } }

Slide 60

Slide 60 text

import java.lang.System; import java.io.RandomAccessFile; import java.io.IOException; public class RandomIOShop { public static void main(String args[]) throws IOException { RandomAccessFile file = new RandomAccessFile("test.txt","rw"); for(int i=1;i<10;i++){ file.writeBoolean(true); file.writeInt(123456* i); file.writeChar('j'); file.writeDouble(1234.56* i); } for(int i2=0;i2<10;i2++){ file.seek(i2); System.out.println(file.readBoolean()); System.out.println(file.readInt()); System.out.println(file.readChar()); System.out.println(file.readDouble()); } file.close(); } }