CPSC150 Spring 2006 Dr. L Lambert. Week 1/2 intro (and Chapter 1)

Slides:



Advertisements
Similar presentations
Java Basics M Taimoor Khan
Advertisements

Object Interaction and Source Code Week 2. OBJECT ORIENTATION BASICS REVIEW.
CPSC150 Fall 2008 Dr. L. Lambert. CPSC150 Overview Syllabus Use Textbook, ask questions, extra thorough, I will post sections covered All information.
Defining classes and methods Recitation – 09/(25,26)/2008 CS 180 Department of Computer Science, Purdue University.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
1 Java Basics. 2 Compiling A “compiler” is a program that translates from one language to another Typically from easy-to-read to fast-to-run e.g. from.
CPSC150 JavaDr. L. Lambert CPSC150 Fall 2005 Dr. L Lambert.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CPSC150 JavaLynn Lambert CPSC150 Spring 2005 Dr. Lambert.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables.
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
Objects Interaction and Source Code Week 2. OBJECT ORIENTATION BASICS REVIEW.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb
Introduction to C Programming
Understanding class definitions Looking inside classes.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
If statements Chapter 3. Selection Want to be able to do a statement sometimes, but not others if it is raining, wear a raincoat. Start first with how.
Hello, world! Dissect HelloWorld.java Compile it Run it.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CPSC150 Spring 2007 Dr. L. Lambert. CPSC150 Overview Syllabus Use Textbook, ask questions, extra thorough, I will post sections covered All information.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
Introduction to Java. 2 Textbook David J. Barnes & Michael Kölling Objects First with Java A Practical Introduction using BlueJ Fourth edition, Pearson.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
CSE 131 Computer Science 1 Module 1: (basics of Java)
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Classes CS 21a: Introduction to Computing I First Semester,
CPS120: Introduction to Computer Science
Flow of Control Part 1: Selection
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Objects and Classes Start on Slide 30 for day 2 Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Much of.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
CSH Intro. to Java. The Big Ideas in Computer Science Beyond programming Solving tough problems Creating extensible solutions Teams of “Computational.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
Understanding class definitions Exploring source code 6.0.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
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.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
Basic concepts of C++ Presented by Prof. Satyajit De
Functions + Overloading + Scope
Chapter 2 Basic Computation
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Data types and variables
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Understanding class definitions
Java Programming with BlueJ
IFS410 Advanced Analysis and Design
CS139 October 11, 2004.
Recap Week 2 and 3.
Chapter 2 Programming Basics.
Just Enough Java 17-May-19.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Corresponds with Chapter 5
Presentation transcript:

CPSC150 Spring 2006 Dr. L Lambert

Week 1/2 intro (and Chapter 1)

Syllabus Java CPSC150Lab Attendance, but does not count weekly quiz. Due the next week. Graded. Collaborative. Come prepared to work on it in class. Come see me/Java expert early and often Ask questions Consult with (possibly non-expert) peers, but be careful. >50% of your grade is exams.

Virtual Machine Review: –Computers understand machine language only –Each computer has its own language –No computer understands English, Powerpoint, or Java Java developed to be platform independent –Virtual machine built on top of each actual machine to make all machines (windows, mac, UNIX) look alike –Java compiles to byte-code – not machine code, but “virtual machine code”

Why Java? Java is a large, complete language Works well with web applications GUIs “part” of the language Extensive libraries (Other CS courses will cover C++)

Why BlueJ Easy to use Object-oriented Start programming immediately GUI, not console-based Object visualization using UML Debugger, Editor, other standard stuff Simple, not for advanced applications

Using Java and BlueJ We will use BlueJ for program development BlueJ runs on the Java virtual machine BlueJ is IDE – lots of others (e.g., Eclipse) BlueJ is free and available for Mac, Windows, UNIX You will test and submit program using UNIX Use your Hunter Creech Account Download BlueJ for your home machines for development: (download Java 1.5 first): (Download SDK, NOT JRE)

Reading and Writing Java Code Weeks 1 and 2 Chapters 1 and 2

By the end of this week, you should know how to: Write a Java program Use BlueJ to write and run a Java program Call methods from inside a program and from the object bench Use parameters in method definitions and method calls Use instance variables/fields Create constructors Write assignment statements Write mathematical expressions

object (on object bench and in source code) class, instance default constructor, overloading method (definition) method call return value parameter source code signature (in source code and external view) formal parameter actual parameter type Terms on test 1

Writing a Java program // import statements if any public class Name { // instance variables or fields // visible to all methods in class // constructors. with no parameters is Default // methods }

/** starts javadoc. TimesTable performs multiplication/times table */ public class TimesTable // NO ( ) s in class { private int factor; // field /** have javadoc for every class, constructor and method * Constructor. without parameter, called default constructor. no return type */ // return type void because nothing is returned public void TimesTable(int nbr) // actual parameter has type AND name { factor = nbr; // assignment statement } public int times(int nbr) // return type int { return nbr * factor; // math } // other methods go in here. printTimes(int nbr) and printTable( ) }

Do your own On the board, with 1 or 2 others, write: printTimes(int nbr) printTable( )

// insert these methods into class on previous slide public void printTimes(int nbr) { // System.out.println changes System.out.println(factor + " times " + nbr + " is " + times(nbr)); } public void printTable( ) // methods start with lowercase { printTimes(0); printTimes(1); printTimes(2); printTimes(3); printTimes(4); printTimes(5); printTimes(6); printTimes(7); printTimes(8); printTimes(9); }

Class Details Using bluej Using methods Fields/instance variables constructors methods

Class details: fields/instance variables Lifetime/scope of class –field vs local variable private int myfield; // primitive –char, boolean, double, a few others private String mystring; // class private Circle sun; // from Shapes –user and library defined BlueJ: primitive has data; object has pointer

Source Code (Internal View) import Comments // single line /* */ multiline /** */ Javadoc Class definitions public class Picture { // fields // constructors // methods }

Class details: constructors Initialize objects. Called when object is created no return type can be overloaded public void TimesTable (int nbr) { factor = nbr; factor = nbr;} public void TimesTable ( ) { factor = 1; factor = 1;}

Source Code (Internal View) import Comments // single line /* */ multiline /** */ Javadoc Class definitions public class Picture { // fields // constructors // methods } writing a method methods vs fields vs local variables Java statements accessor/mutator methods

Class Details: Methods General Structure: public/private return-type name (param1name param1type, param2name param2type) times method from TimesTable: public int times(int nbr) { int answer; answer = nbr * factor; return answer; } return type int first line signature or header (visible in external view also) Java statements inside body, e.g., single = assignment curly braces, stuff inside is method body return statement formal parameter list: type AND name Local variabl e

Method vs. Field Both have private or public Both have types Both have names fields have ‘;’ at end of line/methods do not methods have ( ) (even without parameters); fields do not methods have a body; fields do not fields have memory to hold information; methods do not

Field vs. Local variable local variables declare in a method; fields outside of all methods local variables have the lifetime of the method call local variables and fields have type and ‘;’ when possible, use local variables local variables do NOT have private/public designation

Writing methods: More Java statements Arithmetic Expressions Compound Assignment System.out.println this new dot notation: external method calls return

Arithmetic +, /, *, -, % Be careful about integer division 4/3  r 3 Use codepad (Choose view, then codepad) – int answer=30; answer %= 4; System.out.println("Answer is " + answer);

Compound Assignment assignment: –answer = factor1 * factor2; –answer = answer + newsum; compound assignment –answer += newsum; –answer -= diff; –answer *= product; // e.g., factorial –answer /= digit; // getting rid of digits –answer %= digit;

Math Problems Do on board int x=3; double y=4.0; x + y x / 2 y / 3 x % 2 x % 3

System.out.println( ) To print out messages to a terminal Can print strings or integers Use + to concatenate/append. Be careful with numbers e.g., –System.out.println("Answer is " + answer); –System.out.println(answer + answer); –System.out.println(“answer is” + answer + answer);

this public void changeColor(String newColor) { color = newColor; draw( ); } public void changeColor(String color) { this.color = color; draw( ); } this specifies the current object

new, dot notation public void draw() { wall = new Square( ); wall.moveVertical(80); wall.changeSize(100); wall.makeVisible(); //rest of method from Picture class } To create a new object, use new. calls constructor External method call dot notation

return statement public int sum(int x, int y) { int answer; answer = x+y; return answer; } type of method is return type to return a value, use ‘return value’; can be calculation

Another Java Example: Picture.java public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; public Picture() { // nothing to do... instance variables are automatically set to null } // other methods }

Picture.java public void draw( ) { wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(20); window.moveVertical(100); window.makeVisible(); roof = new Triangle(); roof.changeSize(50, 140); roof.moveHorizontal(60); roof.moveVertical(70); roof.makeVisible(); sun = new Circle(); // set sun to be where it should be }

Picture.java Constructor: –now: blank canvas like TV show –one option: create a finished picture –another option: create shapes, then put them on Modify to do second option

Picture.java On the board, write a new constructor and a new draw( ) that creates the shapes, then puts them on

More Picture.java on the board Write a new constructor in Circle.java that allows Circles to be created in the right place with the right color. For example, instead of // old sun = new Circle( ); sun.changeColor("yellow"); sun.moveHorizontal(180); sun.moveVertical(-10); sun.changeSize(60); sun.makeVisible( ); // new // xPosition = ; // yPosition = sun = new Circle("yellow", 60, 200, 50); sun.makeVisible( );

Common Methods to Write Wizard at writing code; let’s look at common methods Mutator method: change value of a field Accessor method: get the value of a field

Common methods: Accessor Retrieve the value of a part of a class, often a field no parameter, return type is type of value being returned method body is (often) one line public class Fraction { // only a little bit defined private int numerator; private int denominator; public int getNum() { return numerator; }

Common Method: mutator Changes field value void return type, one parameter, the new value not all fields have mutator methods public class fraction {// only a portion of this class private int numerator; private int denominator; public void setNum(int newvalue) { numerator = newvalue; }

Do on board Write a setFactor and a getFactor method

Conditionals

Execute code under some conditions In Canvas public static Canvas getCanvas() { // only create Canvas if not already created if (canvasSingleton == null) { canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300, Color.white); } canvasSingleton.setVisible(true); // does this no matter what return canvasSingleton; }

if statements if (booleanexpression) java statement; any Java statement you know about we don’t know about this

Boolean Expressions Evaluate to be true or false boolean variables –boolean isVisible = false; relational expressions (compares values) logical expressions (compares expressions with and, or, not)

Relational Operators for primitives int x, y; x < y x <= y x > y x >= y x != y x == y // NOT x=y NOTE: most of these don’t work for classes (== is a problem)

Evaluating Boolean Expressions Do on board with partners int x=3; int y = 4; int z=5; x < y x < y < z x = y y == 4 z >= x x != 3 (x + 4) < (y - 1) true error: < cannot be applied to boolean,int error: incompatible types - found int; expected boolean true false false 7 < 3; false

Logical Operators and (&&, single & very different) –both values must be true for the expression to be true –if it is cold and rainy, wear your winter raincoat (both must be true) or (|| - on keyboard, called pipe symbol) –either value can be true –if it is cold or rainy, wear a coat (if either or both is true, do) not (!) –changes the truth value of the expression –if it is not cold, do not wear a winter coat

Logical Operators Do on board int x=3; int y=10; (x < y) && (y < 20) (x == 3) || (y == 3) x < y; 3 < 10; true y < 20; 10 < 20; true true && true is true x == 3 true. short circuit evaluation (y==3 false true || false is true)

More logical operators Do on board int x=3; int y=10; !(y=10) (x != 3) || (y != 3) trick question error !(y==10) y == 10 true !true false x != 3 false Keep going. y != 3 true false || true is true

Yet more logical operators Do on board int x=3; int y=10; !((x+1 < 4) || (y <= 10)) !((x+1 < 4) && (y <= 10)) x+1 = 4 4 < 4 false.keep going y <= 10 true false || true true ! true is false 4 < 4 false. DONE with &&. Do not look at y <=10. !false true

Strings and Classes == tests if objects are equal (point to the same thing), NOT if they have the same content. May return false when true should be returned use equals no corresponding <, lessthan,… use compareTo Difference between primitives (holds a value) and Classes (holds a pointer) is important. = is for comparing if values are the same

CompareTo Returns 0 if 2 Strings are equal Returns negative number if object<parameter Returns positive number if object > parameter

compareTo code write on board what will print String s1 = “Here is a string”; String s2 =“Here is another string”; String s3 = “here is another string”; if (s1.compareTo(s2) < 0) System.out.println(“s1 less than s2”); if (s2.compareTo(s1) < 0) System.out.println(“s2 less than s1”); if (s2.compareTo(s3) < 0) // case matters; uppercase < lowercase System.out.println(“s2 less than s3”); if (s3.compareTo(s2) < 0) System.out.println(“s3 less than s2”); // will print // will not print // will print // will not print

More String comparisions on board String s1 = “Here is a string”; String s2 =“Here is a string”; String s3 = “here is another string”; if (s1.compareTo(s2) == 0) System.out.println(“s1 is the same as s2”); if (s2.compareTo(s1) == 0) System.out.println(“s2 still the same as s1”); if (s2.equals(s1)) System.out.println(“s2 is STILL the same as s1”); if (s3.compareTo(s2) == 0) System.out.println(“s3 is the same as s2”); if (s1 == s2) System.out.println(“s1 and s2 point to the same object”); (done with board work) // will not print // will print; symmetric // will print // will not print // compareTo == 0 is same as equals

if statements if statement form: –if (boolean expression) java statement; if (x < y) System.out.println(“x < y”); you know both parts now

if statements cautions MUST have ( )s around boolean expression no syntax error for non-boolean like expressions only ONE statement in an if statement no ';' after if condition Make sure you account for values that are equal use relational operators only with primitives use equals, compareTo with String

Do on board Write an if statement that prints "Before Middle" if String x is alphabetically less than middle and "After Middle" otherwise What’s logically wrong with this?

if-else If you want to do one thing if a condition is true and something else if not, use if-else. –form: if (condition) Java statement else Java statement if (x < y) System.out.println(x + " is less than the other number”); else System.out.println(y + " is less than the other number”);

> one statement in an if If you want to have more than one statement inside an if or an else, use {}s: if (x < y) { System.out.println(x + " is less than the other number”); x = 0; } else { System.out.println(y + " is less than the other number”); y = 0; }

If-else cautions either if clause or else clause or both may have {}s. After statements inside if and else clause are executed, control passes back to next sequential statement no ';' after else Make sure you account for values that are equal

Class Work Write an if statement to assign x to y if x is greater than y Consider a class public class MyString { private String s; // write method here } Write the method lessThan that takes a String as a parameter and returns true if s (from MyString) is less than its String parameter

Watch Out if (3 < 4) x = 3; else System.out.println(“3 < 4 is false”); x = 0; System.out.println( "the value of x is " + x); Prints what?

Embedded ifs If statements and if-else statements may be embedded (if within if). simply evaluate them as the Java code is executed: if-else example is most common. sets up a table of conditions

Embedded if-else for table if (ave >= 90) grade = 'A'; else if ((ave = 80)) // note: need ()s around entire condition grade = 'B'; else if ((ave =70)) grade = 'C'; else if ((ave =60)) grade = 'D'; else if ((ave < 70) && (ave < 60)) grade = 'F';

Tracing through the embedded if

Fixing the embedded if if (ave >= 90) grade = 'A'; else if (ave >= 80) // We know (ave < 90) or we wouldn't be here grade = 'B'; else if (ave >=70) // we know ave < 80 grade = 'C'; else if (ave >=60) grade = 'D'; else // if ((ave < 70) && (ave < 60)) grade = 'F';

Cautions for embedded ifs Don't use redundant comparisons Make sure you check for values that are equal Account for out of range values

Program style Put {}s on a line by themselves indent {}s 2-3 spaces, statements one more than that All code outside if statements should line up All code inside of if statements should line up.

More complicated embedded ifs if (x < 3) if (y < 6) System.out.println( "x and y between 3 and 6"); else System.out.println( "x = 6"); else if (y > 6) System.out.println( "x and y not in 3-6 range"); else System.out.println( "x >= 3; y <= 6 "); Write on board output for: (1) x is 3 and y is 6; (2) x is 0 and y is 0; (3) x is 0 and y is 6; (4) x is 99 and y is 6