Download presentation
Presentation is loading. Please wait.
Published byNorman Mervyn Tyler Modified over 9 years ago
1
Catie Welsh March 4, 2011
2
Midterm on Monday, March 14th ◦ Closed books, no notes, no computer No office hours during Spring Break ◦ However, I will be around, so email me if you have questions or want to meet 2
3
3
4
Go over Program 3 A whirlwind tour of almost everything we have covered so far ◦ These slides are essentially extracted from earlier lectures 4
5
5
6
Hardware - physical machine ◦ CPU, Memory Software - programs that give instructions to the computer ◦ Windows XP, Games, Eclipse 6
7
CPU – the “brain” of your computer Memory – stores data for the computer ◦ How much the “brain” can remember ◦ Main memory ◦ Auxiliary memory 7
8
Measured in bytes 1 byte = 8 bits Bit is either 0 or 1 Language of the computer is in bits 8
9
9 Your Program Compiler Machine Language (Bits) High-level language (human readable) Low-level language (computer readable)
10
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 10
11
Used to store data in a program The data currently in a variable is its value Name of variable is an identifier Can change value throughout program Choose variable names that are meaningful! 11
12
Declare a variable ◦int number; Assign a value to the variable ◦number = 37; Change the value of the variable ◦number = 513; 12
13
Reserved words with predefined meanings You cannot name your variables keywords if, else, return, new 13
14
What kind of value the variable can hold Two kinds of types. ◦ Primitive type - indecomposable values Names begin with lowercase letters int, double, char, float, byte, boolean, some others ◦ Class type - objects with both data and methods Names by convention begin with uppercase letter Scanner, String, Student 14
15
Change a variable’s value Syntax: ◦ variable = expression; Example: ◦ sleepNeeded = 8; ◦ sleepDesired = sleepNeeded * 2; 15
16
int x = 5; double y = 12.7; y = x; = x = y; = 16 OK Not OK
17
x = (int) y; = 17 (int) OK
18
Unary operators ◦ +, -, ++, --, ! Binary arithmetic operators ◦ *, /, %, +, - rate*rate + delta 1/(time + 3*mass) (a - 7)/(t + 9*v) 18
19
Remainder 7 % 3 = 1 (7 / 3 = 2, remainder 1) 8 % 3 = 2 (8 / 3 = 2, remainder 2) 9 % 3 = 0 (9 / 3 = 3, remainder 0) 19
20
Expressions inside parentheses evaluated first ◦(cost + tax) * discount ◦cost + (tax * discount) Highest precedence First: the unary operators: +, -, ++, --, ! Second: the binary arithmetic operators: *, /, % Third: the binary arithmetic operators: +, - Lowest precedence 20
21
Syntax error – grammatical mistake in your program Run-time error – an error that is detected during program execution Logic error – a mistake in a program caused by the underlying algorithm 21
22
A string (lowercase) 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 22
23
String animal = “aardvark”; System.out.println(animal); aardvark 23
24
String animal = “aardvark”; String sentence; sentence = “My favorite animal is the ” + animal; My favorite animal is the aardvark 24
25
myString.length(); myString.equals(“a string”); myString.toLowerCase(); myString.trim(); Many others 25
26
26 UNCisGreat 01234567891011 String output = myString.substring(1, 8);
27
27 UNCisGreat 01234567891011 String output = myString.substring(1, 8);
28
28 \”Double quote \’Single quote \\Backslash \nNew line \rCarriage return \tTab
29
Scanner kb = new Scanner(System.in); int num = kb.nextInt(); 29
30
// this is a comment /* This is also a comment */ 30
31
An expression that is either true or false Examples: ◦ It is sunny today (true) ◦ 10 is larger than 5 (true) ◦ Today is Saturday (false) 31
32
32 Is input greater than 10? Yes No Prompt user for integer Print: “big number ” Print: “small number ” import java.util.*; public class FlowChart { public static void main(String[] args) { System.out.println("Give me an integer:"); Scanner keyboard = new Scanner(System.in); int inputInt = keyboard.nextInt(); if (inputInt > 10) { System.out.println("big number"); } else { System.out.println("small number"); } } }
33
33 == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Example expressions: variable <= 6 myInt > 5 5 == 3
34
Can be either true or false boolean sunny = true; boolean cloudy = false; if (sunny || cloudy) { // walk to school } 34
35
AND if ((temperature > 50) && (temperature < 75)) { // walk to school } OR if (sunny || cloudy) { // walk to school } 35
36
!true is false !false is true Example: walk to school if it is NOT cloudy if (!cloudy) { // walk to school } 36
37
switch(year) { case 1: System.out.println(“freshman”); break; case 2: System.out.println(“sophomore”); break; case 3: System.out.println(“junior”); break; case 4: System.out.println(“senior”); break; default: System.out.println(“unknown”); break; } 37 Controlling expression Case labels Break statements Default case: all other values
38
Loop: part of a program that repeats Body: statements being repeated Iteration: each repetition of body Stopping condition 38 Start Enough sandwiches ? Distribute sandwiches No Yes Make sandwich
39
while ◦ Safest choice ◦ Not always most elegant do-while ◦ Loop iterates AT LEAST once for ◦ Similar to while, but often more convenient syntax ◦ Most useful when you have a known # of iterations you need to do 39
40
int n = 1; while (n <= 10) { System.out.println(n); n = n + 1; } 40
41
int n = 1; do { System.out.println(n); n = n + 1; } while (n <= 10); 41 Don’t forget the semicolon!
42
int n; for (n = 1; n <= 10; n++) { System.out.println(n); } 42
43
int n; for (n = 1; n <= 10; n = 0) { System.out.println(n); } 43
44
for (int item = 1; item <= 5; item++) { System.out.print(“Enter cost of item #” + item + “: $”); amount = keyboard.nextDouble(); total = total + amount; if (total >= 100) { System.out.println(“You spent all your money.”); break; } System.out.println(“Your total so far is $” + total); } System.out.println(“You spent $” + total); 44
45
Output instructions to the user Initialize variables Prompt user for input Read a number into variable next sum = sum + next; Prompt user for input Read a number into variable next sum = sum + next; Prompt user for input Read a number into variable next sum = sum + next;... Output the sum 45 Repeated statements become your loop body Statements that are only done once are not part of your loop body
46
Variables used in your loop need to be initialized (set to a value) before the loop next ◦Read a number into variable next ◦ We read a new value for next before using it during each iteration of the loop so we do not need to initialize it sum ◦sum = sum + next; ◦sum is on the right side of an assignment statement. sum MUST have a valid value before the loop starts. 46
47
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 47
48
for (int stdLineA = 1; stdLineA <= 3; stdLineA++) { for (int stdLineB = 4; stdLineB <= 6; stdLineB++) { System.out.println(“Student ” + stdLineA + “ shakes Student ” + stdLineB + “’s hand.”); } 48 Inner loop Outer loop
49
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 49
50
A class is the definition of a kind of object ◦ A blueprint for constructing specific objects 50 Class Name: Automobile Data: amount of fuel speed license plate Methods (actions): accelerate: How: Press on gas pedal. decelerate: How: Press on brake pedal.
51
51 Object Name: patsCar amount of fuel: 10 gallons speed: 55 miles per hour license plate: “135 XJK” Object Name: suesCar amount of fuel: 14 gallons speed: 0 miles per hour license plate: “SUES CAR” Object Name: ronsCar amount of fuel: 2 gallons speed: 75 miles per hour license plate: “351 WLF” Instantiations, or instances, of the class Automobile
52
Important: classes do not have data; individual objects have data Classes specify what kind of data objects have 52
53
Create an object jack of class Student Student jack = new Student(); Scanner keyboard = new Scanner(System.in); Create an object keyboard of class Scanner 53 Create an object by calling a constructor Return memory address of object Assign memory address of object to variable
54
Data defined in the class are called instance variables public String name; public int classYear; public double GPA; public String major; 54 public: no restrictions on how these instance variables are used (more details later – public is actually a bad idea here) type: int, double, String… variables
55
Two kinds of methods ◦ Methods that return a value Examples: String’s.substring() method, String’s.indexOf() method, etc. ◦ Methods that return nothing Example: System.out.println() 55
56
public String getMajor() { return major; } public void increaseYear() { classYear++; } 56 returns a String returns nothing return type
57
object, followed by dot, then method name, then () Use them as Java statements Student jack = new Student(); jack.classYear = 1; jack.increaseYear(); System.out.println(“Jack’s class year is ” + jack.classYear); 57
58
public String getClassYear() { if (classYear == 1) return “Freshman”; else if (classYear == 2) return “Sophomore”; else if... } 58
59
object, followed by dot, then method name, then () (same as before) Use them as a value of the type specified by the method’s return type Student jack = new Student(); jack.major = “Computer Science”; String m = jack.getMajor(); System.out.println(“Jack’s full name is ” + jack.getName()); System.out.println(“Jack’s major is ” + m); 59
60
public class Student { public String name; public int classYear; //... public void printInfo() { String info = name + “: ” + classYear; System.out.println(info); } public void increaseYear() { classYear++; } public void decreaseYear() { classYear--; } 60 classYear 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()
61
public class Student { public String name; public int classYear; //... public void printInfo() { String info = name + “: ” + classYear; System.out.println(info); } public void increaseYear() { classYear++; info = “My info string”; // ERROR!!! } public void decreaseYear() { classYear--; } 61 The compiler will not recognize the variable info inside of method increaseYear()
62
Parameters are used to hold the value that you pass to the method Parameters can be used as (local) variables inside the method public int square(int number) { return number * number; } 62 Parameters go inside parentheses of method header
63
Multiple parameters separated by commas public double getTotal(double price, double tax) { return price + price * tax; } 63
64
Order, type, and number of arguments must match parameters specified in method heading Add these two numbers 64 += ???
65
public class Student { public String name; public int classYear; //... public void setName(String studentName) { name = studentName; } public void setClassYear(int year) { classYear = year; } 65
66
public static void main(String[] args) { Student jack = new Student(); jack.setName(“Jack Smith”); jack.setClassYear(3); } 66 Arguments
67
A method body can call another method ◦ Done the same way: receiving_object.method(); If calling a method in the same class, do not need receiving_object: ◦method(); Alternatively, use the this keyword ◦this.method(); 67
68
Information hiding Encapsulation 68
69
public void setMajor() public int classYear; public: there is no restriction on how you can use the method or instance variable 69
70
private void setMajor() private int classYear; private: can not directly use the method or instance variable’s name outside the class 70
71
public class Student { public int classYear; private String major; } Student jack = new Student(); jack.classYear = 1; jack.major = “Computer Science”; 71 OK, classYear is public Error!!! major is private
72
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 72
73
73 Programmer Implementation: Private instance variables Private constants Private Methods Bodies of all methods Method definitions Interface: Comments Headings of public methods Public defined constants Interface: Comments Headings of public methods Public defined constants
74
When declaring a variable, a certain amount of memory is assigned based on the declared primitive type What goes in this memory? 74 int age ; double length ; char letter ; memory
75
A data value is stored in the location assigned to a variable of a primitive type 75
76
What goes in these variables? 76 Student jack ; String inputString ; memory
77
Contain the memory address of the object named by the variable ◦ NOT the object itself What is an address? Object is stored in some other location in memory The address to this other location is called a reference to the object Class types are also called reference types 77
78
String is a class type What happens when you have String s1 = new String(“Hello”); String s2 = new String(“Hello”); boolean strEqual = (s1 == s2); strEqual is false! Why? s1 and s2 store different addresses! 78
79
What happens when you have String s1 = new String(“Hello”); String s2 = new String(“Hello”); boolean strEqual = (s1.equals(s2)); strEqual is true! Why? String’s.equals() method checks if all the characters in the two Strings are the same 79
80
public class Book { private String name; private int page; public boolean equals(Book book) { return (this.name.equals(book.name) && this.page == book.page); } 80
81
public void increaseNum(int num) { num++; } public void doStuff() { int x = 5; increaseNum(x); System.out.println(x); } Prints 5. Why? num is local to increaseNum method; does not change x 81
82
public void changeBook(Book book) { book = new Book(“Biology”); } public void doStuff() { Book jacksBook = new Book(“Java”); changeBook(jacksBook); System.out.println(jacksBook.getName()); } Prints Java. Why? book is local to changeBook, does not change jacksBook 82
83
public void changeBook(Book book) { book.setName(“Biology”); } public void doStuff() { Book jacksBook = new Book(“Java”); changeBook(jacksBook); System.out.println(jacksBook.getName()); } Prints Biology. Why? book contains the same address as jacksBook! 83
84
Solution will be posted later or tomorrow, depending on when everyone gets it turned in 84
85
Midterm exam 85
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.