Java Concepts and Style;
|
|
- Holly Jacobs
- 5 years ago
- Views:
Transcription
1 Java Concepts and Style; By Stephan Jossie Iowa State University
2 Variable Names Consider the two following code segments. The first is an example of bad variable names, while the second example is an example of code with good variable names. double a = 1000; double b = 0.08; int c = 20; for(int d = 0; d < c - 1; d++) a = a + a * (1 + b); Do you any idea what it s doing? Not likely. double capital = 1000; double interestrate = 0.08; int numberofyears = 20; for(int year = 0; year < numberofyears - 1; year++) capital = capital + capital * (1 + interestrate); What about now? You probably don t know exactly what it s doing, but you can at least now guess that it has something to do with computing interest of some sort. (It s actually computing compound interest). This is a great example of how bad variable names make code more confusing (also known as obfuscating), and how good variable names make self documenting code. Commenting Only about half of the code in this document contains comments in any form. That s because most of the code in this document is straight-forward enough that either common knowledge or a quick gander at the Java API will answer any questions about what is happening. Comments are important, however. Let s look at this code: public long method(int n) if (n == 0) return 1; long retval = n; for (int i = n; i > 1; i--) n -= 1; retval *= n; return retval; Not clear, huh?
3 Is it clearer what it is accomplishing if I add comments? Let s take a look. public long method(int n) // empty product is 1 if (n == 0) return 1; long retval = n; // compute n * (n-1) * (n-2) *... * (1) for (int i = n; i > 1; i--) n -= 1; retval *= n; return retval; It should be clearer now that the code is computing a factorial (in math notation that s: n!). Factoring out Common Code Let s take a look at a method that computes the n th Fibonacci number using the mathematical formula (as opposed to looping or recursion). F n = φn φ n 5 ; φ = A straight translation of the formula into code might look something like this: private static long getfibonaccinumber(int n) double phi = (1 + Math.sqrt(5)) / 2; return (long)((math.pow(phi, n)-math.pow(-phi, -n)) / Math.sqrt(5)); But hopefully you noticed that φ (phi) is constant. And hopefully you noticed that 5 is constant and you hopefully also noted that we calculated 5 twice. So why recalculate these values every time that you call fib? You could save some time (division and computing the square root (more so than division) are two math operations that are somewhat time intensive). So the code might look like this after extracting the constants: private static final double SQRT5 = Math.sqrt(5); private static final double PHI = (1 + SQRT5) / 2; private static long getfibonaccinumber (int n) return (long)((math.pow(phi, n) - Math.pow(-PHI, -n)) / SQRT5);
4 Now the values of 5 and φ are calculated when the class is first instantiated instead of every time the method is called (also final because they will never change). Sure this is a very trivial example and the benefit of doing these three statements outside of the method probably will have no discernable impact on the run time, but being able to see code that is common between multiple parts of a program will make it easier to implement those common functions in a way which they can be easily reused. Suppose that we had another function that required the use of φ, having already calculated it we can just use it in whatever methods need it. And if the definition of φ were to change, we d only have to change it in one place in our code instead of every time we used it. (Trivia: φ represents the golden ratio). Let s look at some other examples of code that could be reused. Take a likely implementation of some of the java.lang.string methods. Let s look at substring and its overloaded counterpart. Assuming that a String is implemented as a char[] a possible implementation is: private char[] characters =...; public String substring(int startindex, int endindex) // The length of the substring is the difference between the start and // end indices char[] substring = new char[endindex - startindex]; // Copies substring.length characters from the characters array // to the substring array. Starts at characters[startindex] // and copies to substring starting at substring[0]. // No need to do a for loop to copy the array since the Java library // already has a method that does array copying System.arraycopy(characters, startindex, substring,0,substring.length); return new String(substring); public String substring(int startindex) return substring(startindex, characters.length); You should see code reuse in the single-parameter version. All it does it call the two-parameter version with the same startindex but substituting the length of the char array in for the end index. We also avoided implementing our own array copying routine we simply used the one that the Java library provides. Let s take a look at a real-world program. This next segment of code is from a class that reads data from a database and stores it into an XML document. Consult chapters 22 and 23 of Big Java 3 rd Edition for more information on Databases and XML document manipulation in Java. (Comments and omitted for brevity; indentation not necessarily preserved to avoid excessive line wrapping where possible).
5 public class ThespianXMLDocument private DocumentBuilder builder; private Document doc; private ThespianDataset data; public ThespianXMLDocument() throws ParserConfigurationException DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newdocumentbuilder(); data = new ThespianDataset(); public Document build(arraylist<thespian> thesp) throws SQLException doc = builder.newdocument(); doc.appendchild(createthespians(thesp)); return doc; private Element createthespians(arraylist<thespian> thesp) throws SQLException Element e = doc.createelement("thespians"); for(thespian thespian : thesp) e.appendchild(createthespian(thespian)); return e; private Element createthespian(thespian thespian) throws SQLException Element e = doc.createelement("thespian"); e.appendchild(createtextelement("firstname", thespian.getfirstname())); e.appendchild(createtextelement("lastname", thespian.getlastname())); e.appendchild(createtextelement("gradyear", ""+ thespian.getgradyear())); e.appendchild(createtextelement("initiated", ""+thespian.isinitiated())); e.appendchild(createtextelement("totalpoints", "" + thespian.gettotalpoints())); e.appendchild(populateevents(thespian)); return e;
6 private Element populateevents(thespian thespian) throws SQLException ArrayList<Event> events = data.getevents(thespian.getfirstname(), thespian.getlastname()); Element e = doc.createelement("events"); for(event eve : events) Element event = doc.createelement("event"); event.appendchild(createtextelement("name", eve.geteventname())); event.appendchild(createtextelement("location", eve.geteventlocation())); event.appendchild(createtextelement("year", "" + eve.getyear())); event.appendchild(createtextelement("points", "" + eve.getpointsawarded())); e.appendchild(event); return e; private Element createtextelement(string name, String text) Text t = doc.createtextnode(text); Element e = doc.createelement(name); e.appendchild(t); return e; // End class ThespianXMLDocument The point of this code isn t to understand what it s doing, but rather the fact that code was broken up into smaller parts that deal with logically different parts of the constructing the document. This code could be written as one large method that simply createthespians constructs the XML document; however it is more logical to break it up into these five smaller units because each unit has its own designated purpose, which overall makes it much easier to read. We can see createthespian in the method createthespian, it creates an element, fills that element with name and other information, and then it defers to a method called createevent. CreateEvent creates an element populateevents that contains data for each event for that thespian. Graphically, the document is similar to the tree to the right. Each method points to an element in the tree that it would produce. CreateTextElement would create any element that is depicted by a gray dot. CreateThespians creates the root element Thespians. createtextelement
7 Blocks and Shadowing Consider the following code: if(...) int number = 7; System.out.println(number); // Will cause a compile-time error You get a compile error on the system-out. Why? Because number was declared inside the body of the if-statement. You cannot access variables that are declared inside of a block, outside of that block. The correct version of this code is below: int number = 0; if(...) number = 7; System.out.println(number); Consider this code (assume that we intended to have nothing printed; i.e. we expected 100%7 == 0 to be false): private int number = 100; public void dosomething() int number = 7; if(number % 7 == 0) System.out.println("Number is divisible by 7 evenly!"); What does it print? If you guessed Number is divisible by 7 evenly! then you re correct. Why? Well, it s because the declaration of number inside the method dosomething shadows the member variable of the same name. How do we fix this? We have two options: 1. Change the name of either variable 2. Use the this keyword when we want to access the member variable instead of the local variable
8 Using solution 1 (renaming; change is underlined): private int number = 100; public void dosomething() int localnumber = 7; if(number % 7 == 0) System.out.println("Number is divisible by 7 evenly!"); Using solution 2 (this keyword; change is underlined): private int number = 100; public void dosomething() int number = 7; if(this.number % 7 == 0) System.out.println("Number is divisible by 7 evenly!"); Often beginner programmers make the same mistake when they shadow instance variables with parameter variables as well. They might create the following code thinking that naming the instance and parameters the same name will somehow automatically set the instance variable. public class Test private int number; public Test(int number) However, this code actually does nothing except set number to 0 (because that s what Java does to ints that are declared as member variables; initializes them to 0). Eclipse implies that the member number and the parameter number are different by the way it highlights the variables Other programmers do the following, probably thinking that the compiler will know what they intended. public class Test private int number; public Test(int number) number = number; But this code does nothing as well. Basically it says to set number to itself (which Eclipse complains is a statement that has no effect ; which is only a warning of course, so it happily lets you compile some
9 code that won t do anything). In either case, the solution is the same as above: either rename one of the variables (perhaps add a p for parameter) or use the this keyword when you need to access the member variable. Try-Catch & Exceptions Whenever you use a method that throws a checked exception Java requires you to either place a trycatch block around it or to add a throws declaration to the header of the method in which you are using the method that may throw an exception. Some students try to make the compiler happy by doing the following: Scanner filein = null; try filein = new Scanner(new File("...")); catch(exception e) // BAD!! This isn t very good for at least two reasons. 1. Your program may run fine but if you try to use any Scanner method after the catch block you ll get a NullPointerException because a Scanner object was never made, thereby meaning that filein still is null. 2. This will catch any and every exception that is thrown inside the try block, even unchecked exceptions such as IndexOutOfBounds and InputMismatchException and exceptions that you may need/want to let the calling method deal with or maybe you just need to have it propagate all the way back to the JVM and have the program terminate. a. You should always use the most specific Exception type(s) for your catch block(s). And always put the most specific Exception type first. If the current method isn t appropriate for handling the exception, then add the throws declaration to the method and let the caller handle it. You should also resist the urge to place all of your code inside of a try-catch block. It s not good style to surround code that never throws exceptions in try-catch blocks it s misleading, potentially confusing, and doesn t force you to think critically about exceptional states in your program. For example, suppose you have a main method that gets a file from the user then prints the contents of the file to standard out. Part of this code will never throw an exception, while part of it may. You shouldn t include the part that won t throw the exception in the try-catch block unless it depends on the code that might throw an exception. See the following:
10 // Bad public static void main(string[] args) try //This covers code that will never throw a FileNotFoundException Scanner stdin = new Scanner(System.in); Scanner filein = null; // Get user input (the user types a file name on each line) while (stdin.hasnextline()) // make a new file with the next file name File f = new File(stdin.nextLine()); filein = new Scanner(f); // output the contents of the file while (filein.hasnext()) System.out.println(fileIn.next()); // if the scanner was successfully created...close it when // we're done if (filein!= null) filein.close(); stdin.close(); catch (FileNotFoundException e) System.err.println("The file was not found. " + e.getmessage()); // Good public static void main(string[] args) Scanner stdin = new Scanner(System.in); Scanner filein = null; // Get user input (the user types a file name on each line) while(stdin.hasnextline()) // make a new file with the next file name File f = new File(stdin.nextLine()); try // This covers the code that will likely throw an exception filein = new Scanner(f); // output the contents of the file while(filein.hasnext()) System.out.println(fileIn.next()); catch(filenotfoundexception e) System.err.println("The file was not found. " + e.getmessage()); // if the scanner was successfully created...close it when we're // done if(filein!= null) filein.close(); stdin.close();
11 When reading from a file (or other similar tasks) where you cannot handle the exception, you should still do some cleanup after an exceptional event occurs. See the following code for an example. public void writestuff(string[] towrite) throws IOException, FileNotFoundException // Create a new PrintWriter; You may notice that PrintWriter s // constructor throws a FileNotFoundException and yet it s outside of // the try-finally...why? Because if we place it inside the try, we // cannot access it in the finally block, as we saw earlier in the // shadowing examples (and we re going to let the exception be thrown // anyway since we have no catch block) PrintWriter out = new PrintWriter("path"); try // write some stuff to file finally // happens whether or not an exception is thrown // Close the PrintWriter whether or not an exception was thrown. // We have no risk of generating a NullPointerException because // at this point we are guaranteed that a PrintWriter was created // (since if the constructor threw the FileNotFoundException // we could not have made it to this point in the code) out.close(); Any statements in the finally block execute whether or not there is an exception, which is good. If there was an exception while writing the file, then we no longer need to keep the file open as we cannot continue to write to it. Conversely, if we re done writing the file and it was successfully completed, we no longer need the file open since we don t have anything else to put in it. Absolute vs. Relative File Paths Let s say that your program needs to access files in a subdirectory and you know that your directory structure looks like the tree (gray dots are files) to the right. The current working directory is the directory from which your program is being executed, therefore you may use relative paths to access anything in the subdirectories. So if I were running this program on Windows I would be able to simply access the Text.txt file using the following line of code: File textfile = new File("Test Folder\\Text.txt"); You might be wondering if the above line of code is specific to one machine. Nope. When you create a File object in java it normalizes the path, that is (among other things) it parses the path and changes any file path separators to the correct one for the current operating system. In the above code, if running
12 on a Unix system (OS X or Linux, for instance) then all of the \\ will be replaced with / which are the correct file path separators for the system. Likewise if it contained / and was run on a Windows system then all of the / will be replaced with \\. Do note though that case is important on most (all?) Unix based systems: Text!= text. // On Windows, the following line prints the string "Test Folder\Text.txt" // On Unix systems (Mac, Linux, etc) "Text Folder/Text.txt" System.out.println(textFile.getPath()); Why should you use relative paths? Well suppose I stored my program on my Windows desktop (which has a path of C:\users\stephdogg\desktop). To access the text file from above using an absolute path I would need to say the following instead: textfile = new File("C:\\users\\stephdogg\\desktop\\Test Folder\\Text.txt"); Now, let s say that I gave the file to my friend who knows nothing about programming. Would he be able to run it from his desktop with path C:\users\friend\desktop? No, he wouldn t if I had used the absolute path. What if I gave it to someone running on a different operating system? Would Linux Friend be able to use it from his desktop (which has a path of /home/linuxfriend/desktop)? Nope, he couldn t either. This demonstrates that you can t always know the exact path to the location of files you need. However, assuming that your program was installed correctly you can know where the files you need are relative to the program. When we use the relative path above (TestFolder\Text.txt) we can access the correct file. File textfile = new File("Test Folder\\Text.txt"); System.out.println(textFile.getAbsolutePath()); // On my computer this prints C:\users\stephdogg\desktop\Test Folder\Text.txt // On my friend s computer C:\users\friend\desktop\Test Folder\Text.txt // On Linux Friend s computer /home/linuxfriend/desktop/text Folder/Text.txt Path Separator Characters Remember our little tangent earlier about the File object correctly deducing our path even when we had the wrong file path separator characters (/ instead of \\ or vice-versa)? Well in order to guarantee that we have the correct file separator we should use one of the File object s handy constants. Using our text file from above and the more appropriate way of setting its path, our code would look like this: File textfile = new File("Test Folder" + File.separatorChar + "Text.txt"); Note the File.separatorChar where the double slash was before. This File.separatorChar is replaced with the correct file path separator for the operating system that the program is being run on. // On Windows, the following line prints the string "Test Folder\Text.txt" // On Unix systems (Mac, Linux, etc) "Text Folder/Text.txt" System.out.println(textFile.getPath());
13 Special note: you may notice that there are four similar looking constants in the File object: pathseparator pathseparatorchar separator separatorchar The first two (pathseparator and pathseparatorchar) are semicolon on Windows and colon on Unix based systems. These are use in the path variable that describes the location where the operating system searches for commands (definition from IBM). While the latter two (separator and separatorchar) are the actual character that is between folder names and file names you would use separator or separatorchar when you are specifying file paths. The String versions are there simply for convenience.
Exceptions. 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 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 information4. Java Project Design, Input Methods
4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java
More informationWriting your own Exceptions. How to extend Exception
Writing your own Exceptions How to extend Exception When would you write your own exception class? When to write your own custom exception is a matter for discussion in your project design team. There
More informationLecture 4 CSE July 1992
Lecture 4 CSE 110 6 July 1992 1 More Operators C has many operators. Some of them, like +, are binary, which means that they require two operands, as in 4 + 5. Others are unary, which means they require
More informationCOMP-202 Unit 9: Exceptions
COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,
More informationCS159. Nathan Sprague
CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************
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 information16-Dec-10. Consider the following method:
Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to
More informationThe name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.
Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that
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 informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise
More informationExceptions and Libraries
Exceptions and Libraries RS 9.3, 6.4 Some slides created by Marty Stepp http://www.cs.washington.edu/143/ Edited by Sarah Heckman 1 Exceptions exception: An object representing an error or unusual condition.
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationCS 251 Intermediate Programming Methods and More
CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More information11 Coding Standards CERTIFICATION OBJECTIVES. Use Sun Java Coding Standards
11 Coding Standards CERTIFICATION OBJECTIVES Use Sun Java Coding Standards 2 Chapter 11: Coding Standards CERTIFICATION OBJECTIVE Use Sun Java Coding Standards Spacing Standards The Developer exam is challenging.
More informationBBM 102 Introduction to Programming II Spring Exceptions
BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom
More informationChapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Chapter 8 Exception Handling CS 180 Sunil Prabhakar Department of Computer Science Purdue University Clarifications Auto cast from char to String does not happen. Cast between int and char happens automatically.
More informationWhat is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1
CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Singleton Pattern Mar. 13, 2007 What is it? If you need to make sure that there can be one and only one instance of a class. For example,
More informationASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists
ASSIGNMENT 5 Data Structures, Files, Exceptions, and To-Do Lists COMP-202B, Winter 2009, All Sections Due: Tuesday, April 14, 2009 (23:55) You MUST do this assignment individually and, unless otherwise
More informationName: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.
Lab 14 Name: Checked: Objectives: Practice handling exceptions and writing text files. Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More information4. Java language basics: Function. Minhaeng Lee
4. Java language basics: Function Minhaeng Lee Review : loop Program print from 20 to 10 (reverse order) While/for Program print from 1, 3, 5, 7.. 21 (two interval) Make a condition that make true only
More informationCS 3 Introduction to Software Engineering. 3: Exceptions
CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction
More informationCS 61B Discussion 5: Inheritance II Fall 2014
CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation
More informationSome Patterns for CS1 Students
Some Patterns for CS1 Students Berna L. Massingill Abstract Students in beginning programming courses struggle with many aspects of programming. This paper outlines some patterns intended to be useful
More informationCOMP-202 Unit 9: Exceptions
COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual
More informationCS11 Java. Fall Lecture 4
CS11 Java Fall 2014-2015 Lecture 4 Java File Objects! Java represents files with java.io.file class " Can represent either absolute or relative paths! Absolute paths start at the root directory of the
More informationCSCI 261 Computer Science II
CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More informationclass objects instances Fields Constructors Methods static
Class Structure Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance variables)that hold the data for each object Constructors that
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 informationLecture 14: Exceptions 10:00 AM, Feb 26, 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 Contents 1 Exceptions and How They Work 1 1.1 Update to the Banking Example.............................
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationCSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley
CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley In Brief: What You Need to Know to Comment Methods in CSE 143 Audience o A random person you don t know who wants
More informationControl Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur
Control Structures Code can be purely arithmetic assignments At some point we will need some kind of control or decision making process to occur C uses the if keyword as part of it s control structure
More informationKey Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent
Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information
More informationCSE 142 Su 04 Computer Programming 1 - Java. Objects
Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request
More informationLesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014
Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class
More informationClasses, interfaces, & documentation. Review of basic building blocks
Classes, interfaces, & documentation Review of basic building blocks Objects Data structures literally, storage containers for data constitute object knowledge or state Operations an object can perform
More informationMP 3 A Lexer for MiniJava
MP 3 A Lexer for MiniJava CS 421 Spring 2012 Revision 1.0 Assigned Wednesday, February 1, 2012 Due Tuesday, February 7, at 09:30 Extension 48 hours (penalty 20% of total points possible) Total points 43
More informationException handling & logging Best Practices. Angelin
Exception handling & logging Best Practices Angelin AGENDA Logging using Log4j Logging Best Practices Exception Handling Best Practices CodePro Errors and Fixes Logging using Log4j Logging using Log4j
More information9. Java Errors and Exceptions
Errors and Exceptions in Java 9. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,
More informationStarting to Program in C++ (Basics & I/O)
Copyright by Bruce A. Draper. 2017, All Rights Reserved. Starting to Program in C++ (Basics & I/O) On Tuesday of this week, we started learning C++ by example. We gave you both the Complex class code and
More informationExceptions and Design
Exceptions and Exceptions and Table of contents 1 Error Handling Overview Exceptions RuntimeExceptions 2 Exceptions and Overview Exceptions RuntimeExceptions Exceptions Exceptions and Overview Exceptions
More informationErrors and Exceptions
Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying
More information- 1 - Handout #33 March 14, 2014 JAR Files. CS106A Winter
CS106A Winter 2013-2014 Handout #33 March 14, 2014 JAR Files Handout by Eric Roberts, Mehran Sahami, and Brandon Burr Now that you ve written all these wonderful programs, wouldn t it be great if you could
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG 1 Notice Reading Assignment Chapter 1: Introduction to Java Programming Homework 1 It is due this coming Sunday
More informationCSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, :30pm)
CSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, 2015 11:30pm) This program focuses on binary trees and recursion. Turn in the following files using the link on the
More informationIntroduction to Programming
CHAPTER 1 Introduction to Programming Begin at the beginning, and go on till you come to the end: then stop. This method of telling a story is as good today as it was when the King of Hearts prescribed
More information6.001 Notes: Section 6.1
6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of
More informationLab 2: File Input and Output
Lab 2: File Input and Output This lab introduces how to handle files as both input and output. We re coming back to Tracery (which you implemented in Lab 1) with this assignment but instead of always reading
More informationCS 163/164 - Exam 2 Study Guide and Practice Written Exam
CS 163/164 - Exam 2 Study Guide and Practice Written Exam October 22, 2016 Summary 1 Disclaimer 2 Methods and Data 2.1 Static vs. Non-Static........................................... 2.2 Static...................................................
More informationThe NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.
Introduction to Netbeans This document is a brief introduction to writing and compiling a program using the NetBeans Integrated Development Environment (IDE). An IDE is a program that automates and makes
More informationCS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L
CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Introduction At this point, you are ready to beginning programming at a lower level How do you actually write your
More informationMP 3 A Lexer for MiniJava
MP 3 A Lexer for MiniJava CS 421 Spring 2010 Revision 1.0 Assigned Tuesday, February 2, 2010 Due Monday, February 8, at 10:00pm Extension 48 hours (20% penalty) Total points 50 (+5 extra credit) 1 Change
More informationGetting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners
Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008
More informationDay 8. COMP1006/1406 Summer M. Jason Hinek Carleton University
Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there
More informationChapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.
Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual
More informationUNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING
UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING CMPE13/L: INTRODUCTION TO PROGRAMMING IN C SPRING 2012 Lab 3 Matrix Math Introduction Reading In this lab you will write a
More informationCONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops
COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables
More informationCS 302: Introduction to Programming in Java. Lectures 17&18. It s insanely hot. People desperately need some snowflakes
CS 302: Introduction to Programming in Java Lectures 17&18 It s insanely hot. People desperately need some snowflakes Static variables Again (class variables) Variables unique to the class (all objects
More informationENCM 339 Fall 2017: Editing and Running Programs in the Lab
page 1 of 8 ENCM 339 Fall 2017: Editing and Running Programs in the Lab Steve Norman Department of Electrical & Computer Engineering University of Calgary September 2017 Introduction This document is a
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
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 informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
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 informationSoftware Design & Programming I
Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 4 Making
More informationCOSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan
COSC 123 Computer Creativity I/O Streams and Exceptions Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Objectives Explain the purpose of exceptions. Examine the try-catch-finally
More informationTopic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations
Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write
More informationAbstract Classes, Exceptions
CISC 370: Inheritance, Abstract Classes, Exceptions June 15, 1 2006 1 Review Quizzes Grades on CPM Conventions Class names are capitalized Object names/variables are lower case String.doStuff dostuff();
More informationGood Coding Practices Spring 2018
CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Good Coding Practices Spring 2018 1 Introduction 1 2 The Don ts 1 3 The Dos 4 4 CS 18-Specific Practices 5 5 Style 6 1 Introduction
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 informationExceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology
Exceptions Algorithms Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie Exceptions ± Definition
More informationUnit 10: exception handling and file I/O
Unit 10: exception handling and file I/O Using File objects Reading from files using Scanner Writing to file using PrintStream not in notes 1 Review What is a stream? What is the difference between a text
More informationGive one example where you might wish to use a three dimensional array
CS 110: INTRODUCTION TO COMPUTER SCIENCE SAMPLE TEST 3 TIME ALLOWED: 60 MINUTES Student s Name: MAXIMUM MARK 100 NOTE: Unless otherwise stated, the questions are with reference to the Java Programming
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 informationStatistics Case Study 2000 M. J. Clancy and M. C. Linn
Statistics Case Study 2000 M. J. Clancy and M. C. Linn Problem Write and test functions to compute the following statistics for a nonempty list of numeric values: The mean, or average value, is computed
More information6. Java Errors and Exceptions
Errors and Exceptions in Java 6. Java Errors and Exceptions Errors and exceptions interrupt the normal execution of the program abruptly and represent an unplanned event. Exceptions are bad, or not? Errors,
More informationSoftware Design and Analysis for Engineers
Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:
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 informationJava Errors and Exceptions. Because Murphy s Law never fails
Java Errors and Exceptions Because Murphy s Law never fails 1 Java is the most distressing thing to hit computing since MS-DOS. Alan Kay 2 Corresponding Book Sections Pearson Custom Computer Science: Chapter
More informationMobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02
Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.
More informationRACKET BASICS, ORDER OF EVALUATION, RECURSION 1
RACKET BASICS, ORDER OF EVALUATION, RECURSION 1 COMPUTER SCIENCE 61AS 1. What is functional programming? Give an example of a function below: Functional Programming In functional programming, you do not
More informationBBM 102 Introduction to Programming II Spring 2017
BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception
More informationStage 11 Array Practice With. Zip Code Encoding
A Review of Strings You should now be proficient at using strings, but, as usual, there are a few more details you should know. First, remember these facts about strings: Array Practice With Strings are
More informationExceptions Handeling
Exceptions Handeling Dr. Ahmed ElShafee Dr. Ahmed ElShafee, Fundamentals of Programming II, ١ Agenda 1. * 2. * 3. * ٢ Dr. Ahmed ElShafee, Fundamentals of Programming II, Introduction During the execution
More informationJava Methods. Lecture 8 COP 3252 Summer May 23, 2017
Java Methods Lecture 8 COP 3252 Summer 2017 May 23, 2017 Java Methods In Java, the word method refers to the same kind of thing that the word function is used for in other languages. Specifically, a method
More informationThe return Statement
The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return
More informationName: Checked: Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab.
Lab 14 Name: Checked: Objectives: Practice handling exceptions and writing text files. Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning
More informationAssertions and Exceptions Lecture 11 Fall 2005
Assertions and Exceptions 6.170 Lecture 11 Fall 2005 10.1. Introduction In this lecture, we ll look at Java s exception mechanism. As always, we ll focus more on design issues than the details of the language,
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 informationException-Handling Overview
م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG 1 Notice Class Website http://www.cs.umb.edu/~jane/cs114/ Reading Assignment Chapter 1: Introduction to Java Programming
More informationG51PGP Programming Paradigms. Lecture OO-4 Aggregation
G51PGP Programming Paradigms Lecture OO-4 Aggregation 1 The story so far We saw that C code can be converted into Java code Note real object oriented code though Hopefully shows you how much you already
More informationChapter 12 Exception Handling
Chapter 12 Exception Handling 1 Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can
More informationCOMP 250 Winter 2011 Reading: Java background January 5, 2011
Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP
More informationFunctions. Lecture 6 COP 3014 Spring February 11, 2018
Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its
More informationCS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun
CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what
More informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More information