Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.

Similar presentations

Presentation on theme: "COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014."— Presentation transcript:

1 COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014

2 COMP 110: Spring Announcements Midterm on Wed Handed back on Friday Key to practice midterm has been posted Program 3 due today by 5pm Ill be out of town March 16 & 18 John Hansen will be lecturing

3 COMP 110: Spring Midterm No computers, notes, calculators etc. You will be allowed a 1-page cheat- sheet

4 COMP 110: Spring Questions?

5 COMP 110: Spring Today in COMP 110 Review for Midterm

6 COMP 110: Spring Hardware vs. Software Hardware Physical machine CPU, Memory Software Set of instructions for the machine to execute

7 COMP 110: Spring Memory Holds data for the computer to process Main Memory (RAM – Random Access Memory) Used for intermediate calculations Used to store the current program itself! Expensive Auxiliary Memory (Secondary Memory) Disk drives, CDs, Flash drives Cheap

8 COMP 110: Spring What is a Byte? Data, such as numbers and keyboard characters are stored as series of bits A bit is a digit with value 1 or 0 Examples is a byte with value is a byte with value is a byte with value 97 A byte is composed of 8 bits Just large enough to store a keyboard character

9 COMP 110: Spring Compiling & Running Java Programs Java program Java compiler Bytecode program Bytecode interpreter (Java JVM) Machine code Compiling a Java program Running a Java program Human- readable Machine- readable Java JVM- readable

10 COMP 110: Spring Comments in Java Two Types Single-line comment Begins with // int i; //this is a single-line comment, write whatever you want Multi-line comment Everything within /* */ public class Program { /* This is a multi-line comment. The compiler will completely ignore this text */ public static void main(String[] args) {

11 COMP 110: Spring Algorithms and Pseudocode Algorithm – a set of instructions for solving a problem Pseudocode – combination of code and English used to express an algorithm before writing algorithm into code

12 COMP 110: Spring Variables Used to store data in a program The data currently in a variable is its value Value can change throughout a program Name of variable is an identifier Choose variable names that are meaningful!

13 COMP 110: Spring How to Use Variables Declare a variable int number; Assign a value to the variable number = 37; Change the value of the variable number = 513;

14 COMP 110: Spring Keywords Reserved words with predefined meanings You cannot name your variables keywords if, else, return, new

15 COMP 110: Spring Type What kind of value the variable can hold Two kinds of types Primitive type - indecomposable values (single number or letter) int, double, char, boolean Class type - objects with both data and methods Scanner, System

16 COMP 110: Spring Four Kinds of Primitive Types Integer types byte, short, int, long Represent whole numbers such as 0, 5, Floating-point types float, double Represent numbers with some fractional component such as 1.01, , 0.0 Character char Represents a single character such as A, ;, 8 Boolean boolean Represents a single bit (on or off, true or false, 1 or 0)

17 COMP 110: Spring Java Primitive Types Type Name Kind of Value Memory Used Range of Values byteInteger1 byte-128 to 127 shortInteger2 bytes-32,768 to 32,768 intInteger4 bytes-2,147,483,648 to 2,147,483,647 longInteger8 bytes-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 floatFloating-point4 bytes± x to ± x doubleFloating-point8 bytes± x to ± x charCharacter2 bytes0 to 65,535 boolean 1 bitTrue or False (0 to 1)

18 COMP 110: Spring How to Name Variables Use a combination of Letters, digits (0-9), underscore (_) First character cannot be a digit Java is case sensitive myVariable & myvariable are considered different identifiers

19 COMP 110: Spring Assignment Statements Change a variables value Syntax: variable = expression; Example: sleepNeeded = 8; sleepDesired = sleepNeeded * 2; = sign is called the assignment operator

20 COMP 110: Spring Assignment Compatibilities byte » short » int » long » float » double A value of any type in the list can be assigned to a type further down the list Example int iVar = 7; double dVar = iVar; //this is legal

21 COMP 110: Spring Type Casting Type casting allows you to override assignment compatibilities Example double distance = 9.0; int points = (int)distance; //cast distance to an int //distance is not changed in any way //the value of points will be 9 int x = (int)( )

22 COMP 110: Spring Type Casting Type casting is not rounding! The effect of a type cast is truncation Any fractional portion is discarded Just like when you divide two integers Example double bill = 25.75; int dollars = (int)bill ; //cast bill to an int //bill is not changed in any way //the value of dollars will be 25

23 COMP 110: Spring Arithmetic Operators Unary operators +, -, ++, --, ! Binary arithmetic operators *, /, %, +, -

24 COMP 110: Spring Division Operator The division operator (/) behaves differently depending on the data types used! Example 9 / 2 = 4 Truncation when used with integers 9.0 / 2 = 4.5 Maintains fractions when used with real numbers

25 COMP 110: Spring Remainder Operator The remainder or modulo operator (%) gives the remainder when one whole number is divided by another Example i = 10%4; //the value of i will be 2 j = 6%3; //the value of j will be 0 k = 17%6; //the value of k will be 5

26 COMP 110: Spring Specialized Assignment Operators += a += 3; //same as a = a + 3; -= a -= 4; //same as a = a – 4; *= a *= 2; //same as a = a * 2; /= a /= 3; //same as a = a / 3;

27 COMP 110: Spring Parentheses and Precedence Expressions inside parentheses evaluated first (cost + tax) * discount cost + (tax * discount) Highest Precedence First: the unary operators +, -, ++, --, ! Second: the binary operators *, /, % Third: the binary operators +, - Lowest Precedence

28 COMP 110: Spring Programming Errors Syntax Error – Failure to follow the rules of the language E.g. missing semi-colon Run-time Error – An error that causes the program to halt and produce an error message E.g. Program crashes Logic Error – When a program fails to produce the correct result E.g accidentally using addition when you meant to use subtraction Hardest to locate!

29 COMP 110: Spring Strings A string is a sequence of characters Hello world! Enter a whole number from 1 to 99. String (capital S) is a class in Java, not a primitive type

30 COMP 110: Spring String Indices Strings consist of a sequence of characters Each character has a position in the String UNCisGreat Positions Characters

31 COMP 110: Spring String Concatenation We can concatenate two Strings together using the (+) operator Example String name = Bob; String greeting = Hi + name; System.out.println(greeting); //prints Hi Bob to the screen

32 COMP 110: Spring String Methods string.length() string.equals(A_String) string.toLowerCase(); And others

33 COMP 110: Spring Escape Characters \"\" Double quote \'\' Single quote \\Backslash \nNew line \rCarriage return \tTab

34 COMP 110: Spring Keyboard Input Scanner kb = new Scanner(; int num = kb.nextInt(); double d = kb.nextDouble();

35 COMP 110: Spring Boolean Expressions (result == 0) is a boolean expression Boolean expressions evaluate to either true or false Examples 10 > 5, (true) 4 > 6, (false) Integers are whole numbers, (true)

36 COMP 110: Spring If-Else Statement An if-else statement allows us to make decisions in a program int result = n % 2; if(result == 0) System.out.println(That number is even!); else System.out.println(That number is odd!);

37 COMP 110: Spring Java Comparison Operators Math Java Name ===Equal to !=Not equal to >>Greater than >=Greater than or equal to < 5 5 == 3

38 COMP 110: Spring &&, || operators AND if ((temperature > 50) && (temperature < 75)) { // walk to school } OR if (sunny || cloudy) { // walk to school }

39 COMP 110: Spring The ! Operator (NOT) Boolean negation !false is true !true is false Example boolean cloudy; … if (!cloudy) { // walk to school if its not cloudy }

40 COMP 110: Spring Effect of Boolean Operators ABA && BA || B!A true false truefalse truefalse truefalsetrue false true

41 COMP 110: Spring The Type boolean Can be either true or false boolean sunny = true; boolean cloudy = false; if (sunny || cloudy) { // walk to school } 41

42 COMP 110: Spring Nested If Statements if(balance >= 0) { if(INTEREST_RATE >= 0) balance = balance + INTEREST_RATE*balance; else System.out.println(Negative Interest!); } else balance = balance – FEE;

43 COMP 110: Spring Multi-Branch If Statements if(score >=90) grade = A; else if(score >=80) grade = B; else if(score >=70) grade = C; else if(score >=60) grade = D; else grade = F;

44 COMP 110: Spring Switch Statement Example int year; … switch(year) { case 1: System.out.println(You are a freshman); break; case 2: System.out.println(You are a sophomore); break; case 3: System.out.println(You are a junior); break; case 4: System.out.println(You are a senior); break; default: System.out.println(This is a default case); break; }

45 COMP 110: Spring Enumerations An enumeration allows us to give unique numeric values to a list of items enum Flavor {Vanilla, Chocolate, Strawberry} This statement assigns a unique numeric value to each of {Vanilla, Chocolate, Strawberry}

46 COMP 110: Spring Floating-Point Numbers Consider the number 1/3 = Computers have finite storage and cannot store infinitely repeating decimals In a computer, the number 1/3 is stored as , with part of the fraction missing or truncated Since is < 1/3, this representation is inexact

47 COMP 110: Spring Floating-Point Comparison To compare two floating-point numbers, check if the difference is within some tolerance float a,b; final float EPSILON = 1e-6; //10^-6 … if(Math.abs(a – b) < EPSILON) //Math.abs() is absolute value System.out.println(a and b are the same!); else System.out.println(a and b are different!);

48 COMP 110: Spring Loops A portion of a program that repeats some action is called a loop Evaluate i <= n ? Execute Print i i = i + 1; Execute End Program Start i = 1 false true Loop Body Stopping Condition A loop that counts up to a certain number n

49 COMP 110: Spring Types of Loops Do-While When you want the body to be executed at least once Useful for checking user input For More convenient/readable when the number of iterations is known beforehand, e.g. stored in some counter variable While Safest choice, can be used to create any kind of loop When it might be necessary for the loop to iterate zero times

50 COMP 110: Spring While Example A program that counts up to a certain number int number; … //number is set to some value, e.g. user input int count = 1; while(count <= number) { System.out.print(count + ", "); count++; } 1, 2, 3, 4, …. Output

51 COMP 110: Spring Do-While Example Read in a positive integer, if integer is negative, try again int input; do { System.out.println("Please enter a positive integer: "); input = keyboard.nextInt(); } while (input <= 0); //note the semicolon! //input is guaranteed to be > 0 at this point

52 COMP 110: Spring For Loop Example Pseudocode for a possible for loop Do the following for each value of count from 1-3: Display count Java code int count; for(count = 1; count <= 3; count++) System.out.println(count); Output

53 COMP 110: Spring Infinite Loops A loop that never ends is called an infinite loop int count = 3; do { System.out.println(count); count++; } while(count >= 0); //execution will never reach this point System.out.println("count after loop = " + count);

54 COMP 110: Spring Ending a Loop Count-controlled loops If you know the number of loop iterations for (count = 0; count < iterations; count++) User-controlled loops Ask-before-iterating Sentinel value 54

55 COMP 110: Spring Nested Loops Example int sum = 0; int i = 0; while(i < 10) { for(int j = 0; j < 20; j++) sum = sum + j; //executes 10 * 20 times i++; //executes 10 times, i = [0, 9] }

56 COMP 110: Spring Classes, Objects, and Methods Class: a definition of a kind of object Object: an instance of a class Contains instance variables (data) and methods Methods Methods that return a value Methods that return nothing 56

57 COMP 110: Spring Classes Car - make: String - model: String - year: int - owner: String - location: String + accelerate(double pedalPressure): void + brake(double pedalPressure): void + sell(String newOwner): void + start(): void Class name Attributes Methods (actions) A class is the definition of a kind of object A UML Diagram

58 COMP 110: Spring Creating Objects Create an object called jack of class Student Student jack = new Student(); Create an object Assign memory address of object to variable

59 COMP 110: Spring Instance Variables The data members of a class are called instance variables private String name; private int year; private double gpa; private String major; private No direct access to the variables from outside the class

60 COMP 110: Spring Methods Two kinds of methods Methods that return a value Examples – string.substring() – string.charAt() Methods that return nothing Example –System.out.println()

61 COMP 110: Spring Methods public String getMajor() { return major; } public void increaseYear() { year++; } returns a String returns nothing return type

62 COMP 110: Spring Calling Methods that Return Nothing Syntax object.method(); Use them like Java statements Student jack = new Student(); jack.year = 1; jack.increaseYear(); //year = 2 jack.increaseYear(); //year = 3 System.out.println("Jacks class year is " + jack.year); Jacks class year is 3 Output

63 COMP 110: Spring Methods that Return a Value public String getClassYear() { if(year == 1) return "Freshman"; else if(year == 2) return "Sophomore"; else if... } //add two numbers and return the result public double getSum(double a, double b) { return a+b; }

64 COMP 110: Spring Calling Methods that Return a Value Syntax object.method(); Use as a variable of the methods return type Student jack = new Student(); = "Jack Smith"; jack.major = "Computer Science"; String m = jack.getMajor(); System.out.println("Jacks full name is " + jack.getName()); System.out.println("Jacks major is " + m); 64

65 COMP 110: Spring Local/Instance Variables public class Student { public String name; public int year; //... public void printInfo() { String info = name + ": " + year; System.out.println(info); } public void increaseYear() { year++; } public void decreaseYear() { year--; } year and name are instance variables can be used in any method in this class info is a local variable declared inside method printInfo() can only be used inside method printInfo()

66 COMP 110: Spring Methods with Parameters Some methods need data as input in order to perform their function Parameters can be used as (local) variables inside the method public int square(int number) { return number * number; } Parameters go inside parentheses of method header

67 COMP 110: Spring Methods with Multiple Parameters Multiple parameters separated by commas public double getTotal(double price, double tax) { return price + price * tax; }

68 COMP 110: Spring Method Parameters and Arguments Order, type, and number of arguments must match parameters specified in method heading public String getMessage(int number, char c) { return number + ":" + character; } object.getMessage(7, 'c'); //ok object.getMessage(7, 'c', 7); //error object.getMessage(7.5, 'c'); //error object.getMessage(7, 6); //error

69 COMP 110: Spring Public vs Private public void increaseYear() public int year; public: there is no restriction on how you can use the method or instance variable

70 COMP 110: Spring Public vs Private private double gpa; private int year; private: can not directly use the method or instance variables name outside the class

71 COMP 110: Spring Example public class Student { public int year; private String major; } Student jack = new Student(); jack.year = 1; jack.major = Computer Science; OK, year is public Error!!! major is private

72 COMP 110: Spring Information Hiding A programmer using a method should only need to know what the method does, not how it does it keyboard.nextInt() Information hiding means hiding the details of the code from the programmer

73 COMP 110: Spring Accessors and Mutators How do you access private instance variables? Accessor methods (a.k.a. get methods, getters) Allow you to look at data in private instance variables Mutator methods (a.k.a. set methods, setters) Allow you to change data in private instance variables

74 COMP 110: Spring Example: Student public class Student { private String name; private int age; public void setName(String studentName) { name = studentName; } public void setAge(int studentAge) { age = studentAge; } public String getName() { return name; } public int getAge() { return age; } Accessors Mutators

75 COMP 110: Spring Encapsulation Hiding details of a class that are not necessary to understand how objects of the class are used Two parts Interface Implementation

76 COMP 110: Spring Encapsulation Implementation: Private instance variables Private constants Private methods Bodies of public methods Interface: Comments Headings of public methods Public named constants Programmer Who Uses the Class: Create objects Call methods

77 COMP 110: Spring Call-by-Value Parameters in Java are passed by value The value of a variable is passed, not the variable itself Variables passed to a method can never be changed public class Example { public void setVariable(int a) { a = 7; } public static void main(String[] args) { Example example = new Example(); int a = 5; //a == 5 example.setVariable(a); //does not change the value of a //a == 5 } Different Variables!

78 COMP 110: Spring Parameters of a Primitive Type public void increaseNum(int num) { num++; } public void foo() { int x = 5; increaseNum(x); System.out.println(x); } What is the output? 5

79 COMP 110: Spring Variables of a Class Type The value of a variable of a class type is a memory address The address of the object it refers to Student jack = new Student(); //jack holds the address of the newly created //object of the Student class The address to this other location is called a reference to the object Class types are also called reference types

80 COMP 110: Spring Parameters of a Class Type public void changeBook(Book book) { book = new Book("Biology"); } public void foo() { Book jacksBook = new Book("Java"); changeBook(jacksBook); System.out.println(jacksBook.getName()); } What is the output? Java

81 COMP 110: Spring Parameters of a Class Type public void changeBook(Book book) { book.setName("Biology"); } public void foo() { Book jacksBook = new Book("Java"); changeBook(jacksBook); System.out.println(jacksBook.getName()); } What is the output? Biology 81

Download ppt "COMP 110: Introduction to Programming Tyler Johnson Mar 2, 2009 MWF 11:00AM-12:15PM Sitterson 014."

Similar presentations

Ads by Google