Download presentation
Presentation is loading. Please wait.
Published byShannon Dennis Modified over 9 years ago
1
Lecture 3: Branching Tami Meredith
2
Roadmap Brief Review of last class OOP and Methods: using the library procedures Strings Revisited: A useful Class/Data Type Branching: Simple non-sequential control flow
3
Assignments Assignments are intended to be done in the labs Their purpose is to provide an overview of the skills you will need to master The assignments are NOT enough for some of you Assignment 1 simply presented a few skills – LOTS more REPETITION is needed to become competent
4
Comments in Java 1. One line comments // starts a one line comment Everything from the // to the END of the line is ignored e.g., // Written by Tami clock = 2.95; // CPU speed in GHz 2. Multi-line comments /* begins a multi-line comment */ ends a multi-line comment e.g., /* Author: Tami Meredith Date: September 26, 2011 */
5
Data Types Integers: byte, short, int, long (8, 16, 32, 64 bits, or 1, 2, 4, 8 bytes each) e.g., -10, -1, 0, 1, 100, 23456789654 Floating Point: float, double e.g., 3.14, 0.19, 22.0 Characters: char (Unicode) e.g., 'a', 'b', 'A', 'B', '_', '$',... Booleans: boolean, Created by tests, used to make decisions e.g., true, false (and nothing else!)
6
Representation vs. Meaning Each type has a different representation We, as humans, may interpret the value of a type and apply meaning Applying similar meanings does not mean that the values are similar 1.0 ≠ 1 ≠ '1' ≠ "1" All mean "one" But they are not represented the same in memory
7
Operators Standard math: +, -, *, / Modulus (Remainder): % Assignment to a variable name uses = Can change the type of something using a cast int x = 1; float y = (float) x; + is also string concatenation e.g., "Hi " + "there" creates "Hi there"
8
Changing Types Computers like everything to be the same Adding 2 ints, concatenating two strings Will convert something into a different type so they are the same – this is "coercion" LOTS of rules about when coercion occurs Avoid learning them by always casting (changing types) yourself
9
Basic Data Management float avg; // Calculated mean score int cnt = 4; // Count: number of scores (a constant) int score1, score2, score3, score4; /* Record the scores obtained */ score1 = 72; score2 = 12; score3 = 66; score4 = 99; /* Calculate the average (fails because of coercion) */ avg = (score1 + score2 + score3 + score4) / cnt; /* Display the result */ System.out.println("The mean is " + (string) avg);
10
Our First Example (revisited) // First Example // By Tami Meredith /* Define "program" class called hello in the file hello.java */ public class hello { /* Define the method main for the program */ public static void main (String[] args) { /* Use the method println() */ System.out.println("Hello! Welcome to CSCI1226."); } // end main() } // end class hello
11
Exercise Write a complete and correct Java program that will convert a temperature in Celcius into a temperature in Fahrenheit The initial temperature should be stored in a variable named temp The formula is: F = (9/5 * C) + 32 The result should be printed to the screen
12
Solution // Temperature Converter // By Tami Meredith public class ctof { public static void main (String[] args) { float temp = 12.0f; float fahr = ((9.0f/5.0f) * temp) + 32.0f; System.out.println(temp + " degrees C is " + fahr + " degrees F"); } // end main() } // end class ctof
13
Constants A value in the code is called a constant or literal It is constant because it does not change when the program is executed – it must be changed by editing A named constant is a constant that is given a name and for which the value does not change when the program is executed public static final int RADIX= 8; x = 2 * RADIX; System.out.println("Hello");
14
Filling in Gaps We've been putting magic words in our program to make them work e.g., public, static, void, class, import Now we will start to learn what some of these words mean Hopefully some of the confusing parts of our programs will start to make a little more sense BUT – DON'T PANIC if you are still confused (I got confused trying to make the slides )
15
The Empty Type Sometimes we want to specify that something doesn't exist E.g., in Java all methods specify what they produce, but some methods don't produce anything and have to indicate this fact We use the void type to specify something has no value or won't exist void represents an empty set It is a type with no values
16
Object Oriented Programming Often abbreviated OOP Came into vogue in the 90s but was first presented in the language Simula 67 One way of thinking about data, but not the only way Java requires the use of OOP (we have no choice) Problem: To understand objects and classes one needs to understand simpler concepts such as procedures or subroutines, BUT, we can't learn these without using objects and classes! ( Stop the bus, I want to get off... ) This is why we ignored public, static, class etc.
17
Another Look at OOP myprogram.java class myprogram class System (contains) out class PrintWriter method main Other methods... method println Other classes
18
OOP: Summary Methods perform actions Classes group methods and data Objects are classes that have been given memory (instantiated) so they can store data Every program has one class (in program.java ) The "program" class has a method called main
19
Methods A method in OOP is (almost) the same as a procedure, routine, or function in other programming languages Every Java program has at least one method (called main ) and may have others Methods perform some set of steps on some group of data Big programs with lots of steps are broken down into smaller parts and each part is put into its own method Methods are like "Lego Blocks" of programming
20
Using Methods Methods require they be given data to use This data is referred to as the method's parameters or arguments Methods are either: 1. created (defined) by the programmer 2. imported from a library Examples of methods: println(), print(), main() Methods do work, they accomplish a task or a part of a task Methods (or functions/procedures/subroutines) are one of the KEY concepts in programming
21
Return Types Methods do things such as print characters to the screen Methods also produce things so they can be used in an assignment statement What a method produces is called its "return value" Methods can only produce (i.e., return) one thing The return value can be used in an assignment but the other things the method does cannot and thus are called "side effects"
22
Method Definition (Again) public static void main (String[] args) {... } public: there are no restrictions on who can use this method (the opposite is private ) static: this method is not related to any specific set of data, no object must be instantiated if we want to use this method void: the method returns nothing, it cannot be used in an assignment statement main: the method is named main (String[] args): the method must be given a list (array, []) of String s to work with (these are the parameters or arguments) – we named this list of String s as args {... }: the Body of the method where we put code that does work
23
public class multimethods { /* Define a method to print something */ public static void printname () { System.out.println("My name is Tami."); } /* Define a method that returns something */ public static int makezero () { return (0); } /* Define the method main for the program */ public static void main (String[] args) { int zero; /* Use the methods we defined */ printname(); zero = makezero(); System.out.println("makezero returns " + zero); } // end main() } // end class multimethods
24
Calling Methods We've seen: printname(); name.length(); where name is variable of type String System.out.println("stuff"); Why do they differ? When a method needs to access data, we have to specify what data to access. In this case we tell it to access the String stored in name We will come back to this more in another lecture I wish Java was easier and less complex Sorry!
25
Enough already... By now, your brains are full... Full brains explode (which can make zombies happy) Cleaning the classroom is expensive To save money and Lysol we will take a break now...
26
How to program with OOP 1. Figure out what the program is called, e.g., addstuff 2. Create a file called addstuff.java 3. In addstuff.java create a class called addstuff 4. In class addstuff, create a method called main 5. Make main public so everyone can use it (it is required that main is public ) 6. Make main static so that we can use main without needing to instantiate the class (this is also required) NOTE: static methods are special cases and are not the normal way we do things!
27
Instantiation A class is a grouping of data and methods When we define a class, we are simply describing what it looks like and what it does When we instantiate a class and create an object, we are giving it memory space to store its data A class is like a type, it just describes something An object is like a variable, it stores the group of data described in the class static means we can use something without instantiating the class (creating an object) because we don't need the data
28
Programming Process (Technical) Text Editor Compiler (javac) Interpreter (JVM: java) User Libraries Operating System (Windows) OutputInput JDK
29
Clicking "Run" program.java is in the editor window 1. javac is invoked to create program.class 2. the jvm is started 3. System.out, System.in, System.err are opened (the System "class" is "instantiated" as part of the jvm ), the Runtime class is instantiated 4. program.class is loaded 5. main is called and values for args are provided 6. the program executes until it ends 7. System and Runtime are deleted 8. control is given back to JCreator
30
Types vs. Values int x = 3; String s = "Hello"; 3 and "Hello" are values (and literals) int and String are types x and s are instances of the type that hold values (e.g., variables) A class is also a type The computer stores an instance of the class containing main for us! Uses the name of the file we execute to determine what to make an instance of (looks for a class with the same name)
31
Strings Strings are a special class in Java They are different to other classes because strings are such a common and important kind of data A String is an ordered (sequential) set of characters A String can have 0 to billions of characters In practice, Strings longer than a line or two are a bad idea String constants (literals) are simply defined using double quotes "Hello World!", "Resistance is fertile", "a", and "" are all strings
32
Indices Strings are indexed so we can refer to and examine each character in them The index is the offset from the beginning of the String So, the characters in a String are numbered 0, 1, 2, 3,... First index is zero Last index = length - 1 String "Hello!" Index 012345
33
String Methods See Figure 2.5 in the text (page 86) length() returns the length of a string (as an integer) indexOf( string2 ) returns the index of string2 in string or -1 if string2 is contained in string equals( string2 ) returns true if string equals string2 otherwise it returns false String sentence = "Hello programming class"; int len = sentence.length(); boolean same = sentence.equals("Good bye!");
34
Exercise The String method charAt(i) returns the character that is located at index value i Write a program that has one string called name, which stores your name and that will print out the first character of your name
35
Solution // First Initial Exercise // By Tami Meredith public class first { public static void main (String[] args) { String name = "Tami Meredith"; char init = name.charAt(0); System.out.println("The first initial of " + name + " is " + init); } // end main() } // end class first
36
Control Flow Until now all programs have been sequential We do the instructions one after another without skipping or jumping over any This is the default flow of execution This is really boring and very limiting Need a way to say, "lets only do... when... occurs", or "do this.... if.... happens and do.... otherwise" Going to explore conditional statements to achieve this (Chapter 3)!
37
Control Flow Four Basic Concepts 1. Sequential: go to the next line 2. Branch: make a choice between two branches based on some condition E.g., if raining then take umbrella else leave at home 3. Loop: Do something a set number of times 4. Call a Method: Ask a method to do something for us and go to its code. Come back to where we were when its done.
38
PseudoCode (A Helpful Tool) Something like Java, but it won’t actually execute Used to structure our thinking and solutions method go-out { isRaining = call checkWeather; if (isRaining) gear = umbrella; else gear = nothing; }
39
Tests Tests compare things and generate the boolean value of true or false You have seen tests before in mathematics 3 < 4 is a test that returns true 4 < 3 is a test that returns false There are 6 kinds of numeric comparison, =, ==, != = means assignment, == is the equality test (you will mess this up forever – we all do, its frustrating)
40
Other Tests methods that return a boolean, such as equals, can be used as a test String str1 = "one"; String str2 = "1"; // = means assignment // b can be used where a test is needed boolean b = str1.equals(str2);
41
Using a test - BRANCHING We have the "if" statement in Java to use tests if ( test ) true-actions else false-actions Example: int n1 = 3; int n2 = 4; if (n1 < n2) System.out.println("N1 is smaller"); else System.out.println("N2 is equal or smaller");
42
Alternative Format if ( test ) true-actions No "else" part in this version Example: int n1 = 3; int n2 = 4; int result = 1; if (n1 != 0) result = n2 / n1; System.out.println("Quotient is " + result);
43
Blocks We can group a set of statements that we wish to perform Such a group is called a "Block" Blocks are identified with { and } We have used blocks in methods and classes Blocks can be used other places
44
Blocks in Action int n1 = 3; n2 = 4; int result; if (n1 != 0) // Situation A result = n2 / n1; // indenting next statement does not put it inside the “if” System.out.println("Quotient is " + result); if (n1 != 0) { // Situation B – Same as Situation A result = n2 / n1; } System.out.println("Quotient is " + result); if (n1 != 0) { // Situation C result = n2 / n1; System.out.println("Quotient is " + result); }
45
Style Points Things inside a block should be indented Indenting indicates that something is in a block, it does not CAUSE it to be part of the block Blocks should be used liberally Blocks have no detrimental impacts on performance Like parentheses, blocks add clarity and make code more understandable
46
Boolean Algebra Special operators exist to connect tests That is, what if we want to test if a variable is between 10 and 20? Our test would be: " x >= 10 " and " x <= 20 " We use the boolean "and" operator, && && is a binary operator and takes two operands && returns true if both operands are true and false otherwise ((x >= 10) && (x <= 20))
47
Boolean Operators && (and) Both are true || (or) Either one or the other (or both) are true Operand 1Operand2&&|| true false true falsetruefalsetrue false
48
Negation We can negate (i.e., reverse) the results of a test Uses the ! operator !false is true, !true is false (opposites) ! is unary, requires only 1 operand e.g., !(x = y) NOTE: We use parentheses liberally in expressions for clarity. There are no penalties for using parentheses and many benefits.
49
Don't Give Up! We've moved fast and covered a lot! We need to teach you enough to do some basic programming Once we have done that we will slow down and consolidate everything with LOTS of repetition It does get easier! Sometimes you will need to read a Chapter more than once The Assignments may NOT be enough – they are just a minimum to pass, you might have to do more practice on your own!
50
To Do Go to the lab and complete Assignment 2 Read Chapter 4 (For next class), make notes, write down your questions and bring them next class If you want to work at home, install JDK 1.7 and JCreator LE Get the (any) textbook if you have not already!!! Read Chapter 1,2 (Material from previous classes) and Chapter 3 (Material from this class), if you have not already
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.