Upgrade to Pro — share decks privately, control downloads, hide ads and more …

java presentation part II

Avatar for jamspidy jamspidy
January 27, 2012

java presentation part II

java powerpoint presentation part2

Avatar for jamspidy

jamspidy

January 27, 2012
Tweet

More Decks by jamspidy

Other Decks in Technology

Transcript

  1. 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
  2. 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
  3. 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
  4. 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?
  5. 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)
  6. 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
  7. 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
  8. 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);
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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)
  17. 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
  18. 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
  19. 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; }
  20. 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
  21. 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.
  22. 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.
  23. 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.
  24. 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.
  25. 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.
  26. 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.
  27. 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.
  28. 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();
  29. String s = "This is a test."; for(int i=0;i<s.length();++i) outStream.write(s.charAt(i));

    System.out.println("outstream: "+outStream); System.out.println("size: "+outStream.size()); //Create a ByteArrayInputStream ByteArrayInputStream inStream; inStream = new ByteArrayInputStream(outStream.toByteArray()); //determine the number of bytes available to be read int inBytes = inStream.available(); System.out.println("inStream has "+inBytes+" available bytes"); //Create a byte array that contains available bytes available tp be read byte inBuf[] = new byte[inBytes]; int bytesRead = inStream.read(inBuf,0,inBytes); //Print number of bytes read System.out.println(bytesRead+" bytes were read"); System.out.println("They are: "+new String(inBuf,0)); } }
  30. 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();
  31. 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
  32. 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.
  33. 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<s.length();++i){ outStream.write(s.charAt(i)); }
  34. //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(); } }
  35. 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));
  36. 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.
  37. 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.
  38. 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);
  39. 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.
  40. 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(); } }
  41. 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.
  42. 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(); } }
  43. 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)
  44. 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());
  45. 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
  46. for (int i2=0;i2<vowel.length();i2++){ outStream1.write(vowel.charAt(i2)); } //Copy outStream data to inStream

    data ByteArrayInputStream inStream; inStream = new ByteArrayInputStream(outStream1.toByteArray()); int inBytes = inStream.available(); byte inBuf[] = new byte[inBytes]; int bytesRead = inStream.read(inBuf,0,inBytes); inStreamRead = new String(inBuf,0); System.out.println("inStreamRead: "+inStreamRead); System.out.println("Word to be check: "+s);
  47. try{ for(int i=0;i<s.length();++i){ outStream2.write(s.charAt(i)); for (int i3=0;i3<10;i3++) { if (s.charAt(i)

    == inStreamRead.charAt(i3)){ System.out.println("Vowel found "+s.charAt(i)); outStream3.write(s.charAt(i)); break; } } }
  48. //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); } } }
  49. 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(); } }