Today… Style hints for Assignment 1. (Nothing else you need from lecture for assn 1.) Designing and writing methods. Some useful classes from the java.lang.

Slides:



Advertisements
Similar presentations
Today Quiz in the lab, this week. Assignment 1 due Friday, this week. Continue useful classes from the java.lang package. (We did Math and wrapper classes,
Advertisements

Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
The Class String. String Constants and Variables  There is no primitive type for strings in Java.  There is a class called String that can be used to.
Static Class Members Wrapper Classes Autoboxing Unboxing.
Characters and Strings. Characters In Java, a char is a primitive type that can hold one single character A character can be: –A letter or digit –A punctuation.
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Primitive Data Types. Identifiers What word does it sound like?
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
17-Mar-16 Characters and Strings. 2 Characters In Java, a char is a primitive type that can hold one single character A character can be: A letter or.
Today… Style, Cont. – Naming Things! Methods and Functions Aside - Python Help System Punctuation Winter 2016CISC101 - Prof. McLeod1.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
Today… Quiz 1 Topics and “Rules”. Some useful classes from the java.lang package. Includes: –static methods discussion. –The concept of mutability. Winter.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Today Javadoc. Packages and static import. Viewing API source code. Upcoming Topics: –protected access modifier –Using the debugger in Eclipse –JUnit testing.
Today Review passing by reference and pointers. null pointers. What is an Object? Winter 2016CMPE212 - Prof. McLeod1.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 3 Last time: –Lots of fundamental Java: Console I/O Conditionals Loops For reading: –File I/O –Exceptions.
Today… Continue Building Expressions: –Literals –Constants –Casting –Array Declaration –Operators and Operator Precedence –Keywords Winter 2016CMPE212.
Next Week… Quiz 2 next week: –All Python –Up to this Friday’s lecture: Expressions Console I/O Conditionals while Loops Assignment 2 (due Feb. 12) topics:
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter 2 Variables.
4. Java language basics: Function
Last Time (Midterm Exam!) Before that – methods. Spring 2006
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Variables and Primative Types
CISC124 Labs start this week in JEFF 155: Meet your TA.
CMPE212 – Stuff… Assn 2 due next Friday. Winter 2018
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Winter 2018 CISC101 11/27/2018 CISC101 Reminders
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CISC101 Reminders Assn 3 due Friday, this week. Quiz 3 next week.
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
Fall 2018 CISC124 12/1/2018 CISC124 Note that the next assignment, on encapsulation, is due next Wednesday at 7pm – not Friday. The next Quiz is not until.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Java Classes and Objects 3rd Lecture
Fall 2018 CISC124 2/15/2019 CISC124 TA names and s will be added to the course web site by the end of the week. Labs start next week in JEFF 155:
CISC124 Labs start this week in JEFF 155.
Fall 2018 CISC124 2/17/2019 CISC124 Quiz 1 This Week. Topics and format of quiz in last Tuesday’s notes. You are ready for exercises 4 and 5, and assignment.
CISC124 Labs start this week in JEFF 155. Fall 2018
CISC124 Assignment 1 due this Friday, 7pm.
Fall 2018 CISC124 2/22/2019 CISC124 Quiz 1 This Week. Topics and format of quiz in last Tuesday’s notes. The prof. (me!) will start grading the quiz.
CMPE212 – Reminders The other four assignments are now posted.
CISC101 Reminders All assignments are now posted.
Winter 2019 CMPE212 4/5/2019 CMPE212 – Reminders
Winter 2019 CMPE212 4/7/2019 CMPE212 – Reminders
CMPE212 – Reminders The other four assignments are now posted.
CMPE212 – Reminders Course Web Site:
CISC101 Reminders All assignments are now posted.
Winter 2019 CISC101 4/28/2019 CISC101 Reminders
Winter 2019 CMPE212 5/4/2019 CMPE212 – Reminders
Outline Creating Objects The String Class The Random and Math Classes
Unit 3: Variables in Java
Chap 2. Identifiers, Keywords, and Types
Winter 2019 CMPE212 5/10/2019 CMPE212 – Reminders
Chapter 2 Variables.
Chapter 2 Primitive Data Types and Operations
Variables in C Topics Naming Variables Declaring Variables
CISC101 Reminders Assignment 3 due today.
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

Today… Style hints for Assignment 1. (Nothing else you need from lecture for assn 1.) Designing and writing methods. Some useful classes from the java.lang package. Winter 2016CMPE212 - Prof. McLeod1

Assignment 1 Style Hints Let Eclipse help you with style! It will “suggest” indentation and spacing – let it! Separate methods with one blank line to make them stand out. Minimize the use of blank lines inside methods. Follow the { } alignment conventions discussed in the last lecture. Put spaces on both sides of binary operators. Do not put spaces before, or ; Put a single space after, in a parameter list and after ; in a for loop. Winter 2016CMPE212 - Prof. McLeod2

Assignment 1 Style Hints, Cont. There is never any need for more than one empty line at a time. Once a line or comment is indented you don’t have any need for multiple consecutive spaces in the rest of the line. If your code lines are shorter, you can choose to use in-line comments lined up at the RHS of your code, but: If your lines of code are longer, then use comments above and lined up with the code they are commenting. Winter 2016CMPE212 - Prof. McLeod3

Assignment 1 Style Hints, Cont. Use descriptive method, attribute and variable names. Usually a name can have one or two nouns or a verb/noun combination, for a method. Don’t get carried away! Be concise, yet descriptive. Use camelCase or the underscore, _, but not both. Remember to capitalize constant attribute names (the only kinds of attributes allowed in assignment 1). You can use _ in these names… Winter 2016CMPE212 - Prof. McLeod4

Assignment 1 Commenting Place a block comment at the top of your program with your name and SN. Also, in general terms describe what your program does (a few sentences only). Use one or two sentences before each method to describe what it does and any assumptions made. Indicate what the parameters are. Use in-line comments to specify units, where needed. A few comments inside methods might help to describe what is going on – don’t get carried away! Winter 2016CMPE212 - Prof. McLeod5

More Style Hints Leaving commented out code in your program is really irritating to someone trying to read your program – it makes it look unfinished. If your program is not finished – go ahead and admit this in a comment above the method or class. Note what you think the problem is. Your TA is going to find out anyways if the code is broken – so you might as well just come clean and save her some effort! Winter 2016CMPE212 - Prof. McLeod6

Building Modular Code You should already know the advantages to modularity: –Easier to build. –Easier to test. –Easier to debug. –Easier to modify. –Easier to share. Building objects just takes modular design to the next level. But for now, let’s focus on methods. Winter 2016CMPE212 - Prof. McLeod7

Winter 2016CMPE212 - Prof. McLeod8 Designing Methods Methods (or “Methods”) are written to avoid repeating code. So, make sure you only have one methods to do the “one thing”. Methods should be short: –How short is “short”? One to ten lines? –If you can satisfy all the other rules and the code still explains itself, then the method is short enough.

Winter 2016CMPE212 - Prof. McLeod9 Designing Methods, Cont. Methods should only do one thing and do it well. –Yah, but how can we define “one thing”? –Write the most abstract description of what the method does – does it still have the word “and” in it? –Look for loosely coupled sections within a method if it seems too large – these are natural dividing points. Sometimes the coder puts an empty line between sections as an unconscious admission of loose coupling.

Winter 2016CMPE212 - Prof. McLeod10 Designing Methods, Cont. Keep all code within the method at the same level of abstraction. If you find yourself writing detailed code right beside high level code, you are not following this rule. Your program should be readable as a top-down narrative. The most abstract methods will be at the top of the program, leading to the least abstract methods further down.

Winter 2016CMPE212 - Prof. McLeod11 Designing Methods, Cont. Use less than three parameters wherever possible – the best number is zero! Try to use parameters for input only. Flag parameters are ugly – they are saying that the method does at least two things. If needed, multiple parameters can be grouped into an object or list, provided they share a theme. For example: drawCircle(Point centrePoint, int radius) is better than drawCircle(int centreX, int centreY, int radius)

Winter 2016CMPE212 - Prof. McLeod12 Designing Methods, Cont. Check to see how readable the method name is when it has its parameter list – does it read like a sentence? (verb then noun?).

Winter 2016CMPE212 - Prof. McLeod13 Designing Methods, Cont. The method should not spawn any side effects. –Such as changing the contents of variables passed by reference. –Or spawning off another process that is at the same level of abstraction as the method itself. The method should only invoke methods that are at a lower level of abstraction than itself. A method should either do something or answer something, not both.

Winter 2016CMPE212 - Prof. McLeod14 How to Write Good Methods It is not easy to do, especially if you are used to writing much larger methods. Be prepared to write and then re-write your code several times. Each time, you will probably be breaking larger methods into smaller ones. Each time you re-write (or refactor!) the code it gets better (tidier, easier to read, and often shorter!). Will a multiple method program be faster than a single method version that does the same thing?

Some Useful Java Classes The classes defined in the java.lang package are automatically imported for you, since they are used quite often. They include: –The Wrapper classes –Math –Object –String –System –Thread (How do I know all this?...) Winter 2016CMPE212 - Prof. McLeod15

Aside - static Methods static attributes and methods are loaded once into memory and not garbage collected until main is finished. These methods will run faster the second time (and later) they are invoked. Generally, they are utility methods that do not depend on the values of a class’ attributes. static methods can be invoked without instantiation of the Object that owns them. Math.random(), for example. Winter 2016CMPE212 - Prof. McLeod16

static Methods, Cont. static methods and attributes are shared by all instances of a class – there is only one copy of these methods in memory. A static method can only invoke other static methods in its own class – you can’t have pieces of code disappearing from a static method in memory... This is all done for reasons of ease of use and efficiency. Winter 2016CMPE212 - Prof. McLeod17

Math Class As you would expect: A collection of static constants and static, mathematical methods. You cannot instantiate the Math class, BTW… Let’s just look over the API Docs. Winter 2016CMPE212 - Prof. McLeod18

Winter 2016CMPE212 - Prof. McLeod19 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.

Winter 2016CMPE212 - Prof. McLeod20 Wrapper Classes - Cont. Each primitive type has an associated wrapper class: 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. charCharacter intInteger longLong floatFloat doubleDouble

Winter 2016CMPE212 - Prof. McLeod21 Wrapper Classes - Cont. 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

Winter 2016CMPE212 - Prof. McLeod22 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 See the API for other methods and constants dealing with NaN and -Infinity and Infinity

Winter 2016CMPE212 - Prof. McLeod23 Wrapper Classes – Cont. The Character wrapper class: –has methods to convert between ASCII and Unicode numeric values and characters. –isDigit(character) returns true if character is a digit. –isLetter(character) –isLetterOrDigit(character) –isUpperCase(character) –isLowerCase(character) –isWhitespace(character) –toLowerCase() –toUpperCase() –… static non-static

System Class We have used: –System.out.println() –System.out.print() –System.out.printf() Also: –System.err.println() Winter 2016CMPE212 - Prof. McLeod24

Winter 2016CMPE212 - Prof. McLeod25 Other Useful System Class Methods System.currentTimeMillis() –Returns, as a long, the number of milliseconds elapsed since midnight Jan. 1, System.exit(0) –Immediate termination of your program. System.getProperties() –All kinds of system specific info - see the API. System.getProperty(string) –Displays single system property. System.nanoTime() –Time in nanoseconds

Winter 2016CMPE212 - Prof. McLeod26 String literals: “Press 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 s, so Far

Winter 2016CMPE212 - Prof. McLeod27 String s - 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

Winter 2016CMPE212 - Prof. McLeod28 String s, so Far - Cont. For example, the code: System.out.println(“Hello\nclass!”); prints the following to the screen: Hello class!

Winter 2016CMPE212 - Prof. McLeod29 String Class - Cont. Since String’ s are Objects they can have methods. String methods (67 of them!) include: length() equals(OtherString) equalsIgnoreCase(OtherString) toLowerCase() toUpperCase() trim() charAt(Position) substring(Start) substring(Start, End)

Winter 2016CMPE212 - Prof. McLeod30 String Class - 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.

Winter 2016CMPE212 - Prof. McLeod31 A few examples: int i; boolean aBool; String testStuff = “A testing string.”; i = testStuff.length(); // i is 17 aBool = testStuff.equals(“a testing string.”); // aBool is false aBool = testStuff.equalsIgnoreCase(“A TESTING STRING.”); // aBool is true String Class - Cont.

Winter 2016CMPE212 - Prof. McLeod32 String Class - Cont. char aChar; aChar = testStuff.charAt(2); // aChar is ‘t’ i = testStuff.indexOf(“test”); // i is 2

Winter 2016CMPE212 - Prof. McLeod33 Aside - More about String ’s Is “Hello class” (a String literal) an Object? Yup, “Hello class!”.length() would return 12. Also, String’s are immutable – meaning that they cannot be altered, only re-assigned. There are no methods that can alter characters inside a string while leaving the rest alone. Arrays are mutable, in contrast – any element can be changed