5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!
|
|
- Mariah Cox
- 5 years ago
- Views:
Transcription
1 Last Time Announcements (Midterm Exam!) Assn 2 due tonight. Before that methods. Spring 2006 CISC101 - Prof. McLeod 1 Spring 2006 CISC101 - Prof. McLeod 2 Today Look at midterm solution. Review method overloading. A few useful Java classes: Other handy System class methods Wrapper classes String class StringTokenizer class Classes for File I/O Method Overloading A method can have the same name in many different classes ( println, for example). Overloading is when a method name is used more than once within the same class. The rule is that no two methods with the same name within a class can have the same number and/or types of parameters in the method declarations. (The NOT rule.) Spring 2006 CISC101 - Prof. McLeod 3 Spring 2006 CISC101 - Prof. McLeod 4 Method Overloading - Cont. Why bother? Convenience! Allows the user to call a method without requiring him to supply values for all the parameters. One method name can be used with many different types and combinations of parameters. Allows the programmer to keep an old method definition in the class for backwards compatibility. Method Overloading - Cont. How does it work? Java looks through all methods until the parameter types match with the list of arguments supplied by the user. If none match, Java tries to cast types in order to get a match. (Only widening casting like int to double, however.) Spring 2006 CISC101 - Prof. McLeod 5 Spring 2006 CISC101 - Prof. McLeod 6 1
2 Method Overloading - Cont. Final notes on overloading: You can have as many overloaded method definitions as you want, as long as they are differentiated by the type and/or number of the parameters listed in the definition. Note that you cannot use the return type to differentiate overloaded methods. Method Exercise 2 1. Add a method (called average) to the class containing your main method that returns, as a double, the average of an array of ints supplied as a parameter. This method should also take two more parameters: the starting and finishing positions in the array, over which to carry out the calculation. 2. Write an overloaded version of this same method that only has one parameter just the array. Note that this method only needs one line of code Spring 2006 CISC101 - Prof. McLeod 7 Spring 2006 CISC101 - Prof. McLeod 8 Method Exercise 2, Cont. 3. Test the operation of both methods using an array literal. Other Classes in Java Classes we have used so far: System Math Scanner JOptionPane Java has hundreds of other classes scattered over many different libraries (or packages ) We don t have time to visit them all, but Spring 2006 CISC101 - Prof. McLeod 9 Spring 2006 CISC101 - Prof. McLeod 10 System Class We have used:.out object (with print, println and printf methods).in object (as a parameter to the Scanner class instantiation).exit(0) (to halt a program) Other Useful System Class Methods System.currentTimeMillis() Returns, as a long, the number of milliseconds elapsed since midnight Jan. 1, System.getProperties() All kinds of system specific info - see the API. System.getProperty(string) Displays single system property. System.nanoTime() Time in nanoseconds (? Does this work?) Spring 2006 CISC101 - Prof. McLeod 11 Spring 2006 CISC101 - Prof. McLeod 12 2
3 Wrapper Classes Sometimes it is necessary for a primitive type value to be an Object, rather than just a primitive type. Some data structures only store Objects. Some Java methods only work on Objects. Wrapper classes also contain some useful constants and a few handy methods. Wrapper Classes - Cont. Each primitive type has an associated wrapper class: char int long float double Character Integer Long Float Double Each wrapper class Object can hold the value that would normally be contained in the primitive type variable, but now has a number of useful static methods. Spring 2006 CISC101 - Prof. McLeod 13 Spring 2006 CISC101 - Prof. McLeod 14 Integer Wrapper Class - Example Integer number = new Integer(46);// Wrapping Integer num = new Integer( 908 ); Integer.MAX_VALUE // gives maximum integer Integer.MIN_VALUE // gives minimum integer Integer.parseInt( 453 ) // returns 453 Integer.toString(653) // returns 653 number.equals(num) // returns false int anumber = number.intvalue(); // anumber is 46 Unwrapping Aside - Why an equals Method for Objects? The String class also has equals and equalsignorecase. These wrapper classes also have an equals method. Why not use the simple boolean comparators (==,!=, etc.) with Objects? These comparators just compare memory addresses. How are you going to sort Objects? Spring 2006 CISC101 - Prof. McLeod 15 Spring 2006 CISC101 - Prof. McLeod 16 Aside - Why an equals Method for Objects?, Cont. == can only compare memory addresses when Objects are compared. Most Data Container Objects will have both an equals method and a compareto method. The equals method tests for equality using whatever you define as equal. The compareto method returns a postive or negative int value (or zero to indicate equal ), again depending on how you define one Object to be greater or less than another. Wrapper Classes Cont. The Double wrapper class has equivalent methods: Double.MAX_VALUE // gives maximum double value Double.MIN_VALUE // gives minimum double value Double.parseDouble( 0.45E-3 ) // returns 0.45E-3 parsedouble is only available in Java 2 and newer versions. Spring 2006 CISC101 - Prof. McLeod 17 Spring 2006 CISC101 - Prof. McLeod 18 3
4 Character Wrapper Class Many useful methods to work on characters: character is a char getnumericvalue(character) isdigit(character) isletter(character) islowercase(character) isuppercase(character) tolowercase(character) touppercase(character) Wrapper Classes Summary Wrapper classes serve a dual purpose: They can wrap primitive types to make objects out of them. The have useful static methods. See the API documentation for more detail on wrapper classes. Spring 2006 CISC101 - Prof. McLeod 19 Spring 2006 CISC101 - Prof. McLeod 20 String Class, So Far String literals: Press <enter> to continue. String variable declaration: String teststuff; or: String teststuff = A testing string. ; String concatenation ( addition ): String teststuff = Hello ; System.out.println(testStuff + to me! ); Would print the following to the console window: Hello to me! String Class, So Far - Cont. Note that including another type in a String concatenation calls an implicit tostring method. So, in: System.out.println( I am + 2); the number 2 is converted to a String before being concatenated. Spring 2006 CISC101 - Prof. McLeod 21 Spring 2006 CISC101 - Prof. McLeod 22 String Class, So Far Cont. Escape sequences in Strings: These sequences can be used to put special characters into a String: \ a double quote \ a single quote \\ a backslash \n a linefeed \r a carriage return \t a tab character String Class, So Far Cont. For example, the code: System.out.println( Hello\nclass! ); prints the following to the screen: Hello class! Spring 2006 CISC101 - Prof. McLeod 23 Spring 2006 CISC101 - Prof. McLeod 24 4
5 String Class, Methods Since String s are Objects they can have methods. String methods include: length() equals(otherstring) equalsignorecase(otherstring) tolowercase() touppercase() trim() charat(position) substring(start) substring(start, End) Spring 2006 CISC101 - Prof. McLeod 25 String Class, Methods Cont. indexof(searchstring) replace(oldchar, newchar) startswith(prefixstring) endswith(suffixstring) valueof(integer) String s do not have any attributes. See the API Docs for details on all the String class methods. String class methods are not static, so you must invoke them from a String object. Spring 2006 CISC101 - Prof. McLeod 26 Examples: int i; boolean abool; String Class - Cont. String teststuff = A testing string. ; i = teststuff.length(); // i is 17 char achar; String Class - Cont. achar = teststuff.charat(2); // achar is t i = teststuff.indexof( test ); // i is 2 abool = teststuff.equals( a testing string. ); // abool is false abool = teststuff.equalsignorecase( A TESTING STRING. ); // abool is true Spring 2006 CISC101 - Prof. McLeod 27 Spring 2006 CISC101 - Prof. McLeod 28 Aside - More about String s Is Hello class (a String literal) an Object? Yup, Hello class!.length() would return 12. String s are actually stored as arrays of char s. So, a String variable is actually just a pointer to an array in memory. StringTokenizer class This useful class is in the java.util package, so you need to have an import java.util.*; or import.java.util.stringtokenizer; statement at the top of your program. This class provides an easy way of parsing strings up into pieces, called tokens. Tokens are separated by delimiters, that you can specify, or you can accept a list of default delimiters. Spring 2006 CISC101 - Prof. McLeod 29 Spring 2006 CISC101 - Prof. McLeod 30 5
6 The constructor method for this class is overloaded. So, when you create an Object of type StringTokenizer, you have three options: new StringTokenizer(String s) new StringTokenizer(String s, String delim) new StringTokenizer(String s, String delim, boolean returntokens) s is the String you want to tokenize. delim is a list of delimiters, by default it is: \t\n\r or space, tab, line feed, carriage return. You can specify your own list of delimiters if you provide a different String for the second parameter. Spring 2006 CISC101 - Prof. McLeod 31 Spring 2006 CISC101 - Prof. McLeod 32 If you supply a true for the final parameter, then delimiters will also be provided as tokens. The default is false - delimiters are not provided as tokens. Creating a StringTokenizer Object, for example: String astring = "This is a String - Wow!"; StringTokenizer st = new StringTokenizer(aString); Now the Object st has inherited a bunch of useful methods from the StringTokenizer class. Spring 2006 CISC101 - Prof. McLeod 33 Spring 2006 CISC101 - Prof. McLeod 34 Here is example code using the methods: String astring = "This is a String - Wow!"; StringTokenizer st = new StringTokenizer(aString); System.out.println("The String has " + st.counttokens() + " tokens."); System.out.println("\nThe tokens are:"); while (st.hasmoretokens()) { System.out.println(st.nextToken()); } // end while Screen output: The String has 6 tokens. The tokens are: This is a String - Wow! Spring 2006 CISC101 - Prof. McLeod 35 Spring 2006 CISC101 - Prof. McLeod 36 6
7 Aside - Scanner Class Also has a built-in tokenizer. We ll use this tokenizer when reading text files. StringTokenizer Example See SystemPropertiesDemo.java. String allproperties = System.getProperties().toString(); System.out.println("\nTokenized string:"); StringTokenizer st = new StringTokenizer(allProperties, ","); while (st.hasmoretokens()) System.out.println(st.nextToken()); Spring 2006 CISC101 - Prof. McLeod 37 Spring 2006 CISC101 - Prof. McLeod 38 File I/O Files provide a convenient way to store and restore to memory larger amounts of data. We will use arrays to store the data in memory, and we ll talk about these things later. Three kinds of file I/O to discuss: Text Binary Random access For now, we ll stick with text I/O. Spring 2006 CISC101 - Prof. McLeod 39 Text File Output in Java 5.0 Use the PrintWriter class. (As usual), you must import the class: import java.io.printwriter; In your program: PrintWriter fileout = new PrintWriter(outFilename); (outfilename is a String filename we obtained somewhere else ) Spring 2006 CISC101 - Prof. McLeod 40 Text File Output in Java 5.0, Cont. Unfortunately the instantiation of the PrintWriter object can cause a FileNotFoundException to be thrown and you must be ready to catch it: try { writefile = new PrintWriter(outputFile); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(0); } // end try catch Spring 2006 CISC101 - Prof. McLeod 41 Aside Try/Catch Blocks I ve been avoiding them An Exception is another way for a method to provide output in particular an error condition. Exceptions are not returned by a method, instead you have to write code to catch them. You only catch an exception when there is some kind of error condition. To catch an exception you must use a Try/Catch block: Spring 2006 CISC101 - Prof. McLeod 42 7
8 Aside Try/Catch Blocks, Cont. Syntax of a try-catch block : try { // block of statements that might // generate an exception } catch (exception_type identifer) { // block of statements }[ catch (exception_type identifer) { // block of statements }][ finally { // block of statements }] Spring 2006 CISC101 - Prof. McLeod 43 Aside Try/Catch Blocks, Cont. You must have at least one catch block after the try block (otherwise the try block would be useless!) You can have many catch blocks, one for each exception you are trying to catch. The code in the finally block is always executed, whether an exception is thrown, caught, or not. Spring 2006 CISC101 - Prof. McLeod 44 Aside Try/Catch Blocks, Cont. A method can throw more than one kind of exception. Why would you want to do this? You can also include more than one line of code that can throw an exception inside a try block. Why would you not want to do this? Aside Try/Catch Blocks, Cont. There are two kinds of exceptions: checked and un-checked Checked exceptions must be caught so you must enclose the method that throws a checked exception in a try/catch block the compiler will force you to do so. The PrintWriter() constructor throws this kind of exception, so we have to use a try/catch block. The Scanner class nextint() method throws an InputMismatchException that you don t have to catch. Spring 2006 CISC101 - Prof. McLeod 45 Spring 2006 CISC101 - Prof. McLeod 46 How to Avoid the Pain!! The java compiler will tell you if you are attempting to execute code that must be in a try/catch block. In Eclipse select the line of code that must be put in a try/catch block, then: Choose Source from the main menu, then Choose Surround with try/catch Block Aside Try/Catch Blocks, Cont. What to do inside the catch block? Message to the user describing error. If you cannot easily fix the problem, then exit the program. Exceptions and try/catch blocks are not part of the CISC101 syllabus, so they will never be on an exam! However, for file I/O many problems with files can be encountered! Spring 2006 CISC101 - Prof. McLeod 47 Spring 2006 CISC101 - Prof. McLeod 48 8
9 Back to Text File Output in Java 5.0 Unfortunately the instantiation of the PrintWriter object can cause a FileNotFoundException to be thrown and you must be ready to catch it: try { writefile = new PrintWriter(outputFile); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(0); } // end try catch Spring 2006 CISC101 - Prof. McLeod 49 Aside - File Paths in Strings Sometimes you might have to include a path in the filename, such as C:\Alan\CIS101\Demo.txt Don t forget that if you have to include a \ in a String, use \\, as in: C:\\Alan\\CISC101\\Demo.txt Spring 2006 CISC101 - Prof. McLeod 50 Text File Output in Java 5.0, Cont. The Object writefile, owns a couple of familiar methods: print() and println(). When you are done writing, don t forget to close the file with: writefile.close(); Way easy!! Text File Input in Java 5.0 Use the FileReader and Scanner classes. Our usual import statements: import java.util.scanner; import java.io.filereader; import java.io.filenotfoundexception; We ll get to that last one in a minute. Spring 2006 CISC101 - Prof. McLeod 51 Spring 2006 CISC101 - Prof. McLeod 52 Text File Input in Java 5.0, Cont. In a program: filein = new FileReader("Test.txt"); Scanner fileinput = new Scanner(fileIn); Unfortunately the FileReader constructor (what s a constructor anyways?) throws a kind of exception that cannot be ignored - so the code above cannot be used exactly in this way. Text File Input in Java 5.0, Cont. This works: FileReader filein = null; try{ filein = new FileReader("Test.txt"); } catch (FileNotFoundException e) { // Do something useful here? } Scanner fileinput = new Scanner(fileIn); Spring 2006 CISC101 - Prof. McLeod 53 Spring 2006 CISC101 - Prof. McLeod 54 9
10 Text File Input in Java 5.0, Cont. To get the file contents, and print them to the console, for example: while (fileinput.hasnextline()) { System.out.println(fileInput.nextLine()); } Aside - Scanner Class Tokenizer The Scanner class has a built in String Tokenizer. Set the delimiters using the usedelimiter(delimiter_string) method. Obtain the tokens by calling the next() method. The hasnext() method will return false when there are no more tokens. Spring 2006 CISC101 - Prof. McLeod 55 Spring 2006 CISC101 - Prof. McLeod 56 Text File I/O Sample Programs TextFileIODemo.java Saves a file with text provided by the user and then opens the file again and displays the contents to the screen. TextFileIODemoWithChooser.java Same program as above except the use of the JFileChooser class is demonstrated as an alternate means of getting a filename from the user. Without using FileReader You can also send a File object to the Scanner class when you instantiate it instead of a FileReader object. You will still need to do this in a try catch block as shown in the previous slide. See the second demo program. Spring 2006 CISC101 - Prof. McLeod 57 Spring 2006 CISC101 - Prof. McLeod 58 The File Class File is a class in the java.io.* package. It contains useful utility methods that will help prevent programs crashing from file errors. For example: File myfile = new File( test.dat ); myfile.exists(); // returns true if file exists myfile.canread(); // returns true if can read from file myfile.canwrite(); // returns true if can write to file Spring 2006 CISC101 - Prof. McLeod 59 The File Class, Cont. myfile.delete(); // deletes file and returns true if successful myfile.length(); // returns length of file in bytes myfile.getname(); // returns the name of file (like test.dat ) myfile.getpath(); // returns path of file (like C:\AlanStuff\JavaSource ) Spring 2006 CISC101 - Prof. McLeod 60 10
11 The File Class, Cont. All of these methods can be used without having to worry about try/catch blocks, which is nice! See the second demo program for a few examples of File class method use. Binary and Random Access Binary files contain data exactly as it is stored in memory you can t read these files in Notepad! Text file is sequential access only. What does that mean? Random access can access any byte in the file at any time, in any order. More about Binary and Random File Access later! Spring 2006 CISC101 - Prof. McLeod 61 Spring 2006 CISC101 - Prof. McLeod 62 11
Fall 2017 CISC124 10/1/2017
CISC124 Today First onq quiz this week write in lab. More details in last Wednesday s lecture. Repeated: The quiz availability times will change to match each lab as the week progresses. Useful Java classes:
More informationFall 2017 CISC124 9/27/2017
CISC124 Assignment 1 due this Friday at 7pm by submission to an onq dropbox. First onq quiz next week write in lab. More details in yesterday s lecture. Today Intro. to 2D Arrays (and iteration examples).
More information5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.
Last Time Reviewed method overloading. A few useful Java classes: Other handy System class methods Wrapper classes String class StringTokenizer class Assn 3 posted. Announcements Final on June 14 or 15?
More informationVariables of class Type. Week 8. Variables of class Type, Cont. A simple class:
Week 8 Variables of class Type - Correction! Libraries/Packages String Class, reviewed Screen Input/Output, reviewed File Input/Output Coding Style Guidelines A simple class: Variables of class Type public
More informationWeek 6: Review. Java is Case Sensitive
Week 6: Review Java Language Elements: special characters, reserved keywords, variables, operators & expressions, syntax, objects, scoping, Robot world 7 will be used on the midterm. Java is Case Sensitive
More informationFundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!
Fundamental Java Syntax Summary Sheet for CISC101, Spring 2006 Notes: Items in italics are things that you must supply, either a variable name, literal value, or expression. Variable Naming Rules Java
More informationFundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!
Fundamental Java Syntax Summary Sheet for CISC124, Fall 2015 Notes: Items in italics are things that you must supply, either a variable name, literal value, or expression. Java is Case - Sensitive! Variable
More information5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.
Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you
More informationCISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.
CISC-124 20180129 20180130 20180201 This week we continued to look at some aspects of Java and how they relate to building reliable software. Multi-Dimensional Arrays Like most languages, Java permits
More informationwhen you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally
I. Methods week 4 a method consists of a sequence of instructions that can access the internal data of an object (strict method) or to perform a task with input from arguments (static method) when you
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationFall 2017 CISC124 9/16/2017
CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems
More informationA variable is a name for a location in memory A variable must be declared
Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;
More informationChapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.
Chapter 10 File I/O Copyright 2016 Pearson Inc. All rights reserved. Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program,
More informationAny serious Java programmers should use the APIs to develop Java programs Best practices of using APIs
Ananda Gunawardena Java APIs Think Java API (Application Programming Interface) as a super dictionary of the Java language. It has a list of all Java packages, classes, and interfaces; along with all of
More informationCSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI
CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are
More informationWe now start exploring some key elements of the Java programming language and ways of performing I/O
We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects
More informationExam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming
Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose
More informationToday s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board
Ananda Gunawardena Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO Lab 1 Objectives Learn how to structure TicTacToeprogram as
More informationCSC Java Programming, Fall Java Data Types and Control Constructs
CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference
More informationThis Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.
CS121: Computer Programming I A) Collections B) File I/O & Error Handling Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use
More informationJ.43 The length field of an array object makes the length of the array available. J.44 ARRAYS
ARRAYS A Java array is an Object that holds an ordered collection of elements. Components of an array can be primitive types or may reference objects, including other arrays. Arrays can be declared, allocated,
More informationWhen we reach the line "z = x / y" the program crashes with the message:
CSCE A201 Introduction to Exceptions and File I/O An exception is an abnormal condition that occurs during the execution of a program. For example, divisions by zero, accessing an invalid array index,
More informationToday s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO
Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO Ananda Gunawardena Objects and Methods working together to solve a problem Object Oriented Programming Paradigm
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions
More informationSimple Java Input/Output
Simple Java Input/Output Prologue They say you can hold seven plus or minus two pieces of information in your mind. I can t remember how to open files in Java. I ve written chapters on it. I ve done it
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationProctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.
QUEEN'S UNIVERSITY SCHOOL OF COMPUTING HAND IN Answers Are Recorded on Question Paper CISC124, WINTER TERM, 2011 FINAL EXAMINATION 7pm to 10pm, 26 APRIL 2011, Ross Gym Instructor: Alan McLeod If the instructor
More informationboolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while
CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and
More informationUsing Java Classes Fall 2018 Margaret Reid-Miller
Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationFirst Java Program - Output to the Screen
First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the
More informationc) And last but not least, there are javadoc comments. See Weiss.
CSCI 151 Spring 2010 Java Bootcamp The following notes are meant to be a quick refresher on Java. It is not meant to be a means on its own to learn Java. For that you would need a lot more detail (for
More information1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8
Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(
More informationCISC 323 (Week 9) Design of a Weather Program & Java File I/O
CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming
More informationGetting started with Java
Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving
More informationStarting Out with Java: From Control Structures Through Objects Sixth Edition
Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 11 I/O File Input and Output Reentering data all the time could get tedious for the user. The data can be saved to
More informationFull file at
Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as
More informationData and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:
Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions
More informationF1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept
F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming
More information1.00 Lecture 30. Sending information to a Java program
1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes
More informationHST 952. Computing for Biomedical Scientists Lecture 8
Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8 Outline Vectors Streams, Input, and Output in Java
More informationClasses Basic Overview
Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Classes Basic Overview A class is a container
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All This chapter discusses class String, from the java.lang package. These classes provide the foundation for string and character manipulation
More informationCS 251 Intermediate Programming Java Basics
CS 251 Intermediate Programming Java Basics Brooke Chenoweth University of New Mexico Spring 2018 Prerequisites These are the topics that I assume that you have already seen: Variables Boolean expressions
More informationFile I/O Introduction to File I/O Text Files The File Class Binary Files 614
10.1 Introduction to File I/O 574 Streams 575 Text Files and Binary Files 575 10.2 Text Files 576 Writing to a Text File 576 Appending to a Text File 583 Reading from a Text File 586 Reading a Text File
More informationStreams and File I/O
Chapter 9 Streams and File I/O Overview of Streams and File I/O Text File I/O Binary File I/O File Objects and File Names Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch
More informationExceptions. Examples of code which shows the syntax and all that
Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces
More informationFull file at
Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional
More informationWeek 7 - More Java! this stands for the calling object:
Week 7 - More Java! Variable Scoping, Revisited this Parameter Encapsulation & Principles of Information Hiding: Use of public and private within class API, ADT javadoc Variables of class Type Wrapper
More informationIntroduction Unit 4: Input, output and exceptions
Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.
More informationChapter 2: Data and Expressions
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data
More informationWentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output
WIT COMP1000 File Input and Output I/O I/O stands for Input/Output So far, we've used a Scanner object based on System.in for all input (from the user's keyboard) and System.out for all output (to the
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Advanced Java This chapter discusses class String, class StringBuilder and class Character from the java.lang package. These classes provide
More informationFall 2017 CISC/CMPE320 9/27/2017
Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader
More informationStrings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics
Strings Strings and their methods Produced by: Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list Primitive Types: char Object Types: String Primitive vs Object Types
More informationWhat did we talk about last time? Examples switch statements
Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation
More informationCS Programming I: File Input / Output
CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624
More informationLecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4
Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.
More informationCS 106 Introduction to Computer Science I
CS 106 Introduction to Computer Science I 06 / 03 / 2015 Instructor: Michael Eckmann Today s Topics Finish up discussion of projected homeruns 162 as a constant (final) double vs. int in calculation Scanner
More informationSTUDENT LESSON A7 Simple I/O
STUDENT LESSON A7 Simple I/O Java Curriculum for AP Computer Science, Student Lesson A7 1 STUDENT LESSON A7 Simple I/O INTRODUCTION: The input and output of a program s data is usually referred to as I/O.
More informationCS Programming I: File Input / Output
CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455
More informationPIC 20A The Basics of Java
PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and
More informationChapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics
Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional
More informationAP Computer Science Unit 1. Programs
AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated
More informationUSING LIBRARY CLASSES
USING LIBRARY CLASSES Simple input, output. String, static variables and static methods, packages and import statements. Q. What is the difference between byte oriented IO and character oriented IO? How
More informationText User Interfaces. Keyboard IO plus
Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on
More informationExceptions. When do we need exception mechanism? When and why use exceptions? The purpose of exceptions
Exceptions When do we need exception mechanism? When and why use exceptions? The purpose of exceptions Exceptions An exception is thrown when there is no reasonable way for the code that discovered the
More informationProgram Fundamentals
Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java
More informationMore About Objects and Methods
More About Objects and Methods Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch/info1 Objectives! learn more techniques for programming with classes and objects!
More informationMore About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.
More About Objects and Methods Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch/info1 Objectives! learn more techniques for programming with classes and objects!
More informationLanguage Features. 1. The primitive types int, double, and boolean are part of the AP
Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are
More informationFile I/O Array Basics For-each loop
File I/O Array Basics For-each loop 178 Recap Use the Java API to look-up classes/method details: Math, Character, String, StringBuffer, Random, etc. The Random class gives us several ways to generate
More informationChapter 4 Introduction to Control Statements
Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?
More informationChapter 2: Data and Expressions
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types
More informationChapter 2: Using Data
Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that
More informationString related classes
Java Strings String related classes Java provides three String related classes java.lang package String class: Storing and processing Strings but Strings created using the String class cannot be modified
More informationOperators and Expressions
Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationComputational Expression
Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name
More informationLab 5: Java IO 12:00 PM, Feb 21, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, 2018 1 The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers 2 3.1 Buffering
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationJAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015
JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015 1 administrivia 2 -Lab 0 posted -getting started with Eclipse -Java refresher -this will not count towards your grade -TA office
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data
More informationI/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O
I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)
More informationLecture Set 2: Starting Java
Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationReview of Java. or maybe not
Review of Java or maybe not Complete this class public Foo Bar Comparable { /** name of this Foo */ private String name; /** initialize a new Foo */ public Foo(String name) { = } public String tostring()
More informationCOMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015
COMP-202: Foundations of Programming Lecture 22: File I/O Jackie Cheung, Winter 2015 Announcements Assignment 5 due Tue Mar 31 at 11:59pm Quiz 6 due Tue Apr 7 at 11:59pm 2 Review 1. What is a graph? How
More informationChapter 2 ELEMENTARY PROGRAMMING
Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple
More informationException Handling. Sometimes when the computer tries to execute a statement something goes wrong:
Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer
More informationChapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited
Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error,
More informationCOMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string
COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an
More informationException Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:
Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes
More informationMidterm Review 01. SP17 ICS 111 Ed Meyer
Midterm Review 01 SP17 ICS 111 Ed Meyer Exam Details On Laulima > Quizzes, Tests and Surveys Due Thursday 2/23 by 11:55pm Password: toast 1 attempt; 1 hr 15 minutes Reserve uninterrupted time for yourself
More informationWeek 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O
Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file
More informationChapter 2 Elementary Programming
Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical
More informationClasses and Objects Part 1
COMP-202 Classes and Objects Part 1 Lecture Outline Object Identity, State, Behaviour Class Libraries Import Statement, Packages Object Interface and Implementation Object Life Cycle Creation, Destruction
More information