CS 200 Methods, Using Objects

Slides:



Advertisements
Similar presentations
Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Advertisements

Declaring Variables You must first declare a variable before you can use it! Declaring involves: – Establishing the variable’s spot in memory – Specifying.
Hello, world! Dissect HelloWorld.java Compile it Run it.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Lecture 2: Classes and Objects, using Scanner and String.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Math class services (functions) Primitive vs reference data types Scanner class Math class services (functions) Primitive vs reference data types Scanner.
Chapter 2: Java Fundamentals
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
Fall 2015CISC124 - Prof. McLeod1 CISC124 Have you filled out the lab section survey? (As of last night 54 left to fill out the survey.) TA names have been.
1 CS 007: Introduction to Computer Programming Ihsan Ayyub Qazi.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
By Mr. Muhammad Pervez Akhtar
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.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
Exam Review 10/01/2014 Happy October. The Exam  Will be in Canvas  Two parts  Part A is recall – closed book, closed notes ◦Quizzes, in class activity.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Object Oriented Programming Lecture 2: BallWorld.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Chapter 2 Basic Computation
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Lecture Notes – Basics (Ch1-6)
Lecture Note Set 1 Thursday 12-May-05
First Programs CSE 1310 – Introduction to Computers and Programming
CS Week 2 Jim Williams, PhD.
CS 200 Branches Jim Williams, PhD.
CS Week 4 Jim Williams, PhD.
Comp Sci 302 Introduction to Programming
CS139 – Fall 2010 How far we have come
CS 200 Using Objects Jim Williams, PhD.
CS Week 6 Jim Williams, PhD.
CS Week 7 Jim Williams, PhD.
Chapter 4: Mathematical Functions, Characters, and Strings
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
CS Week 3 Jim Williams, PhD.
CS 302 Week 8 Jim Williams, PhD.
Week 6 CS 302 Jim Williams, PhD.
Fundamentals 2.
CS 200 More Primitives, Objects, Branches and Methods
CS 200 Loops Jim Williams, PhD.
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
CS 200 Primitives and Expressions
CS 200 Primitives and Expressions
CS2011 Introduction to Programming I Elementary Programming
Unit 3: Variables in Java
CS Week 2 Jim Williams, PhD.
Happy October Exam Review 10/01/2014.
Math class services (functions)
CS Week 3 Jim Williams, PhD.
Week 7 CS 302 Jim Williams.
Ben Stanley for gAlpha gALPHA free, four-week venture-creation workshop designed to help entrepreneurially-minded students and technologists create high-growth.
CS 200 Objects and ArrayList
CS302 Week 6 Jim Williams.
Presentation transcript:

CS 200 Methods, Using Objects Jim Williams, PhD

This Week Notes Lecture: Misc, Methods, Using Objects By Friday Exam Conflict and Accommodations Install Eclipse Team Lab 2 Chap 2 Programs (P2): Due Thursday Lecture: Misc, Methods, Using Objects

Magic Numbers (bad practice) Numbers with unexplained meaning: public class H { public static void main(String []args) { double s = 71 / 39.3701; }

Variable Names Useful variable names can help with code readability. public class H { public static void main(String []args) { double height = 71; height = height / 39.3701; }

Constants Constants (final variables) can help with readability. public class H { public static void main(String []args) { final double INCHES_IN_METER = 39.3701; double heightInInches = 71; double heightInMeters = heightInInches / INCHES_IN_METER; }

Number Systems Decimal 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Binary 0, 1

Decimal 100 10 1 3 0 2 = 302

Binary 8 4 2 1 1 1 1 0 = 14

Binary 8 4 2 1 0 1 0 1 = 5

Hexadecimal (group bits by nibble) 0000 = 0 0001 = 1 0010 = 2 0011 = 3 0100 = 4 0101 = 5 0110 = 6 0111 = 7 1000 = 8 1001 = 9 1010 = A 1011 = B 1100 = C 1101 = D 1110 = E 1111 = F

What character is this? 0000 0000 0100 0001 A B Unicode: @ Unicode: 0x003E 62 > 0x003F 63 ? 0x0040 64 @ 0x0041 65 A 0x0042 66 B 0x0043 67 C A http://www.ssec.wisc.edu/~tomw/java/unicode.html

What character is this? char letter = '\u0043'; A B Unicode: @ Unicode: 0x003E 62 > 0x003F 63 ? 0x0040 64 @ 0x0041 65 A 0x0042 66 B 0x0043 67 C http://www.ssec.wisc.edu/~tomw/java/unicode.html

Color 183, 1, 1 B70101 Red, Green, Blue (RGB) 183, 1, 1 B70101 Red, Green, Blue (RGB) https://umark.wisc.edu/brand/web/colors.php

CS Core Principles: Algorithms: A step-by-step set of operations to be performed. Analogy: Recipe, Instructions Abstraction: a technique for managing complexity. Analogy: Automobile, CS200 Computer View

Methods A named section of code that can be "called" from other code. Lots of existing methods that you can use rather than writing yourself. To use, "call the method".

Definition vs Call Definition: What to do. Call: Do it.

main method public static void main(String []args) { System.out.println("Hello from main"); } Is this a Method Definition or Method Call?

Calling Class (static) Methods Call the method with the name of the class or, if within the defining class, just use the name of the method. double numInts = Math.pow( 2, 32); double root = Math.sqrt( 16); int num1 = 16; int num2 = 3; double result = num2 + Math.sqrt( num1);

API Application Programmer Interface Search for "Java 8 Math" Describes how to use the method.

Find Scanner Methods How can you find out what Scanner methods are available?

Calling Instance/object Methods Scanner elephant = new Scanner(System.in); int num = elephant.nextInt(); String name = elephant.next(); String line = elephant.nextLine(); elephant.close();

What kind of methods? max: class nextInt: instance Math.max( 10, 20); max: instance nextInt: class Math.max( 10, 20); Random randGen = new Random(); randGen.nextInt( 5); A is the best answer

Instance vs. Class (static) Methods method definition has “static” modifier use name of class when calling Math.max( 10, 20); Instance (non-static) Methods method definition does Not have “static” modifier use instance of class when calling Scanner in = new Scanner( System.in); int num = in.nextInt();

mPrint - which is Call, Definition? static void mPrint() { System.out.println("my print"); } public static void main(String []args) { mPrint(); mPrint definition mPrint call B is the correct answer

Defining Methods public class M { //method definition static void mPrint() { System.out.println("my print"); } public static void main(String []args) { mPrint(); // method call. B is the correct answer

Is count: Argument or Parameter? public static void main(String []args) { int num = 10; printCount( 23); printCount( num+3); } static void printCount(int count) { System.out.println("result:" + count); argument parameter count is a parameter (zyBooks) or formal parameter the number 23, for example is an argument (also called an actual parameter).

This Week Notes Lecture: Methods, Using Objects By Friday Exam Conflict and Accommodations Install Eclipse Chap 2 Programs (P2): Due Thursday Lecture: Methods, Using Objects

Thought Experiment Are you simply looking for an "A" or are you preparing yourself to teach programming to others?

Time Spent This Week

Which is called first: calc or println? error static int calc(int num) { num -= 33; //num = num - 33; return num; } public static void main(String []args) { int n = 55; System.out.println( calc( n)); put a print statement within the calc method to see if it is called before the println method.

Variables Local Parameters Variables declared within a method. Must be initialized before reading from them. Parameters Variables declared within a method parameter list. Initialized with arguments. Scope: Both are only visible within the method they are declared.

What prints out? static void calc(int num) { num = 3; } 5 35 error static void calc(int num) { num = 3; } public static void main(String []args) { int num = 5; calc( num); System.out.println( num); try it.

Returning a Value from a Method static int triple(int num) { return num * 3; } public static void main(String []args) { int value = 5; int result = triple( value); System.out.println("triple 6 = " + triple( 6));

Returning a Value from a Method Method Definition: must have return data type must have return statement with value Method Call: In an expression, the value of method call is the returned value.

Testing Methods Methods written to run test cases to help validate and debug your code. Easily run multiple tests. If changes are made, easy to retest.

Testing Method static int triple(int num) { return num * 3; } static void testTriple() { System.out.println("expect: 9, actual: " + triple(3)); System.out.println("expect: 3, actual: " + triple(1)); } public static void main(String []args) { testTriple();

Using Objects CS 200 focus on writing class methods and Use of Objects. Structured/procedural programming CS 300 creating instantiable classes and introductory data structures Object-oriented programming. Must instantiate a class to call instance methods (use an object).

Read In Values Using Scanner Whitespace: space, tab, newline Token: a sequence of non-whitespace characters. 14 23.0 hello This, is a sentence. 2nd line 3rd line 43

What are values of variables? String note = "1 2\nAlex two words"; Scanner input = new Scanner( note); int num1 = input.nextInt(); int num2 = input.nextInt(); String name = input.next(); String words = input.nextLine();

What are values of variables? name: Minsub\n age: 22\nCS major: name: Minsub\n22\CS age: name: Minsub age: 22 String note = "Minsub\n22\nCS"; Scanner input = new Scanner( note); String name = input.nextLine(); int age = input.nextInt(); String major = input.nextLine();

What are values of variables? name: Minsub\n22\CS age: major: name: Minsub age: 22 name: Minsub major: CS String note = "Minsub\n22\nCS"; Scanner input = new Scanner( note); String name = input.nextLine(); int age = input.nextInt(); String major = input.nextLine();

What are values of variables? score1: 20 score2: 25 title: scores title: score1: 20 25 score2: scores String note = "20 25\nscores"; Scanner input = new Scanner( note); int score1 = input.nextInt(); int score2 = input.nextInt(); String title = input.nextLine();

Primitive vs Reference Data Types Store value int i = 5; 5 i Reference Store a reference to another location in memory that contains value Integer num; num = new Integer(9); num 9

Wrapper Classes Wrapper classes contain helpful methods. Primitive type Wrapper class boolean Boolean byte Byte char Character float Float int Integer long Long short Short double Double

Data Type Conversions String weekNum = 3; String weekNum = "" + 3; String numStr = Integer.toString( 4); int num = Integer.parseInt( numStr);

Wrapper Classes Boxing: Putting primitive into instance of wrapper class Unboxing: retrieve primitive from instance auto-boxing/unboxing: when compiler inserts code to box/unbox. Primitive type Wrapper class boolean Boolean byte Byte char Character float Float int Integer long Long short Short double Double

Primitive vs Reference Variables int num1; num1 = 5; Integer num2; num2 = new Integer(7); Integer num3 = 9; int num4 = num3; //use Java Visualizer, options Show String/Integer objects checkbox //use Java Visualizer, options Show String/Integer objects checkbox

What will show when d3 is printed? Double d1 = new Double(10); double d2 = d1; d1 = 14.1; Double d3 = d1; d1 = d2; System.out.println( d3); 10 14.1 a reference error try it.

String class A reference (class), not a primitive data type. Frequently used final String TITLE_PREFIX = "Welcome to Week "; System.out.println( TITLE_PREFIX + 3);

String Alex Johnson alex johnson String name2 = "Alex"; error String name2 = "Alex"; name2.toLowerCase(); String name3 = name2 + " Johnson"; System.out.print( name3); instances of String are immutable (cannot change) methods in String class that appear to change strings actually return new strings.

Calling String methods aChar: 'i' aChar: 's' aChar: ' ' String strA = "This is a string"; char aChar = strA.charAt( 3);

java.util.Random Random randGen; //Declare reference variable randGen = new Random(); //create instance // randGen.setSeed( 123); //set state int valueA = randGen.nextInt( 5); //get a value int valueB = randGen.nextInt( 5); int valueC = randGen.nextInt( 5);

What is the answer? x = rand.nextInt(10)-2; What expression to get a value between 2 and 10, inclusive of both 2 and 10? Assume: Random rand = new Random(); int x; x = rand.nextInt(10)-2; x = rand.nextInt(9)+1; x = rand.nextInt(8)+2; x = rand.nextInt(9)+2; Other try it.

Debugging with Print statements See what is going on. Divide and conquer. String s1 = "An important programming tool."; String s2 = s1.substring( 9, 10); String s4 = new String( "?"); if ( s1.contains( "gram")) { s4 = s1.substring( 2, 4).trim(); } char c3 = s1.charAt( s1.indexOf('g') -3); String answer = (s2 + c3 + s4).toUpperCase();

What is the answer? AP? String s1 = "An important programming tool."; String s2 = s1.substring( 9, 10); String s4 = new String( "?"); if ( s1.contains( "gram")) { s4 = s1.substring( 2, 4).trim(); } char c3 = s1.charAt( s1.indexOf('g') -3); String answer = (s2 + c3 + s4).toUpperCase(); AP? api ANP IM API try it.