Intermediate Java 95-713 Sakir YUCEL MISM/MSIT Carnegie Mellon University Program Control Slides adapted from Steven Roehrig.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

ISBN Chapter 7 Expressions and Assignment Statements.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
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.
Object-Oriented Programming MISM/MSIT Carnegie Mellon University Lecture 2: Program Control.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
More about Numerical Computation CS-2301, B-Term More about Numerical Computation CS-2301, System Programming for Non-Majors (Slides include materials.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion.
© 2001 by Ashby M. Woolf Revision 3 Using Java Operators The Basic Toolkit Pliers, Screwdriver, Hammer and Drill.
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
© 2005 Lawrenceville Press Slide 1 Chapter 5 Relational Operators Relational OperatorMeaning =greater than.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
S ystem P rogrammers' A ssociation for R esearching C omputer S ystems 3. Operators SPARCS JAVA Study.
BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA TYPES AND OPERATIONS.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Arithmetic Expressions
1 Operations Making Things Happen (Chap. 3) Expressions.
Controlling Program Flow. Data Types and Variable Declarations Controlling Program Flow.
ISBN Chapter 7 Expressions and Assignment Statements.
3: Controlling Program Flow Using Java operators Mathematical operators Relational operators Logical operators –Primitive type: ALL (the same with C) –String:
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Operators in JAVA. Operator An operator is a symbol that operates on one or more arguments to produce a result. Java provides a rich set of operators.
“Great leaders are never satisfied with current levels of performance. They are restlessly driven by possibilities and potential achievements.” – Donna.
CompSci Primitive Types  Primitive Types (base types)  Built-in data types; native to most hardware  Note: not objects (will use mostly first.
Software Technology - I Tools to do operations.....
Control statements Mostafa Abdallah
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
Programming Principles Operators and Expressions.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Object-Oriented Programming and Problem Solving Dr. Ramzi Saifan Introduction and basics of Java Slides adapted from Steven Roehrig.
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.
Object-Oriented Programming Ramzi Saifan Program Control Slides adapted from Steven Roehrig.
Chapter 7: Expressions and Assignment Statements
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
Primitive Data, Variables, Loops (Maybe)
Fundamental of Java Programming Basics of Java Programming
Expressions and Control Flow in JavaScript
Operators and Expressions
OPERATORS (2) CSC 111.
Java Tokens & Data types
Expressions and Assignment
Just Enough Java 17-May-19.
Chap 7. Advanced Control Statements in Java
Controlling Program Flow
Control Structure.
Problem 1 Given n, calculate 2n
Presentation transcript:

Intermediate Java Sakir YUCEL MISM/MSIT Carnegie Mellon University Program Control Slides adapted from Steven Roehrig

Today We Look At  Java operators  Control structures  Some example programs

Java Operators  An operator takes one or more “things” and produces a resultant “thing”.  “Things” are usually primitive types, but they are sometimes objects.  The “things” operated upon are called operands.  An operator is just a function, but with a different syntax.

A Familiar Example  The assignment operator and the addition operator are used (each exactly once!).  This is a more familiar syntax than, e.g., k.equals(i.add(j)); int i = 3, j = 4, k; k = i + j;

More Operator Facts  All operators produce a value.  Sometimes they produce side effects, i.e., they change the value of an operand.  Evaluation of a statement with several operators follows precedence rules. Use parentheses for readability.  (x + y) * z / 3 is different than x + y * z / 3

Assignment Is Tricky, Part I public class Number { public int i; } public class Assignment1 { public static void main(String[] args) { Number n1 = new Number(); Number n2 = new Number(); n1.i = 2; n2.i = 5; n1.i = n2.i; n2.i = 10;// what is n1.i? }

Assignment Is Tricky, Part II public class Assignment2 { public static void main(String[] args) { Number n1 = new Number(); Number n2 = new Number(); n1.i = 2; n2.i = 5; n1 = n2; n2.i = 10;// what is n1.i? n1.i = 20;// what is n2.i? }

A Picture Might Help n1n2 reference variablesNumber objects n2.in1.i Before assignment n1 = n2 n1n2 reference variablesNumber objects n2.in1.i After assignment n1 = n

“Aliasing” In Function Calls public class PassObject { static void f(Number m) { m.i = 15; } public static void main(String[] args) { Number n = new Number(); n.i = 14; f(n);// what is n.i now? }

Math Operators  +, -, *, /, %  Integer division truncates, i.e., 16/3 = 5  Modulus operator returns remainder on integer division, i.e., 16%3 = 1  Shorthand: x += 4; is the same as x = x + 4;  This works for the other arithmetic operators as well.

Auto Increment and Decrement  ++ increases by one, and -- decreases by one.  Two flavors of each: pre and post: int i = 1, j; j = i++;// j = 1, i = 2 j = ++i;// j = 3, i = 3 j = i--;// j = 3, i = 2 j = --i;// j = 1, i = 1

Booleans and Relational Operators  The boolean type has two possible values, true and false.  The relational operators >, >=, <, <=, == and != produce a boolean result.  >, >=, <, <= are legal for all built-in types except booleans, == and != are legal for all.

Testing for (Non-)Equivalence  The == and != operators need to be used with care with objects. public class Equivalence { public static void main(String[] args) { Integer n1 = new Integer(47); Integer n2 = new Integer(47); System.out.println(n1 == n2);// prints false System.put.println(n1 != n2);// prints true }

The equals( ) Operator  This exists for all objects (don’t need it for built-in types). Integer n1 = new Integer(47); Integer n2 = new Integer(47); System.out.println(n1.equals(n2);// prints true

The equals( ) Operator (cont.)  But exists doesn’t necessarily mean properly defined! class Number { int i; } : Number n1 = new Number(); Number n2 = new Number(); n1.i = 3; n2.i = 3; System.out.println(n1.equals(n2));// prints false

The equals( ) Operator (cont.)  The equals( ) operator is properly defined for most Java library classes.  The default behavior is to compare references, so…  When you define a class, if you’re planning to use equals( ), you need to define it (i.e., override the default behavior).

Logical Operators  These are AND (&&), OR (||), and NOT (!).  These work on booleans only; if you have old “C” habits, forget them!  Use parentheses freely to group logical expressions.  Logical expressions short-circuit; as soon as the result is known, evaluation stops.

Short-Circuiting Example public class ShortCircuit { static boolean test1(int val) {return val < 1;} static boolean test2(int val) {return val < 2;} static boolean test3(int val) {return val < 3;} public static void main(String[] args) { if (test1(0) && test2(2) && test3(2)) System.out.println(“Expression is true”); else System.out.println(“Expression is false”); }

Bitwise, Shift, Ternary Operators  Bitwise & shift operators manipulate individual bits in integral primitive types.  The ternary if-else operator looks like this: boolean-expression ? value0 : value1  The result is either value0 or value1, depending on the truth of the boolean.

The String + Operator  The + operator is “overloaded” for String objects; it means concatenation.  It reminds me of good old C++…  If an expression begins with a String, then all the following operands of + will be converted into Strings: int x = 0, y = 1, z = 2; String myString = “x, y, z ”; System.out.println(myString + x + y + z);

A Useful Figure byteshortintlong doublefloat char When multiple types are mixed in an expression, compiler will convert the operands into the higher type: double, float, long, int

Casting  A cast produces a temporary new value of a designated type.  Implicit and explicit casts: int i = 2; double d= i;// OK, since d can hold all of i float g = F; //! int j = g;// not OK, loses information int k = (int) g;// OK, compiler is reassured

Execution Control: if-else if (boolean_expression) statement else if(boolean_expression) statement : else if(boolean_expression) statement else statement

if-else Example public int test(int testVal, int target) { int result = 0; if (testVal > target) result = 1; else if (testVal < target) result = -1; else { System.out.println(“They are equal”); result = 0; } return result; }

Execution Control: return  Exit a method, returning an actual value or object, or not (if the return type is void). public int test(int testVal, int target) { if (testVal > target) return 1; else if (testVal < target) return -1; else { System.out.println(“They are equal”); return 0; }

Three Kinds of Iteration while (boolean_expression)// evaluate first statement_or_block do statement_or_block// evaluate last while (boolean_expression) for (initialization ; boolean_expression ; step) statement_or_block Example: for (int i = 0; i < myArray.size(); i++) { myArray[i] = 0; }

public class BreakAndContinue { public static void main(String[] args) { for (int i = 0; i < 100; i++) { if (i == 74) break;// out of for loop if (i % 9 != 0) continue;// next iteration System.out.println(i); } Break and Continue

Selection Via switch for (int i = 0; i < 100; i++) { char c = (char) (Math.random() * 26 + ‘a’); switch(c) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: System.out.println(“Vowel”); break; case ‘y’: case ‘w’: System.out.println(“Sometimes a vowel”); break; default: System.out.println(“Not a vowel”); }

Digression on Random Numbers  Despite theory, most random number generators are more like “kids playing with matches”. See “Random Number Generators: Good Ones Are Hard to Find” by S. Park and K. Miller, CACM Oct  Most random number generators use “multiplicative linear congruential” schemes: A modulus m, a large prime integer A multiplier a, an integer in the range 2,3,…m-1 These produce a sequence z 1, z 2, z 3 … using the iterative equation z i+1 = f(z i ) = a*z % m

Random Numbers (cont.)  The sequence is initiated by choosing a seed.  Example: f(z) = 6z %13. This produces the sequence...1, 6, 10, 8, 9, 2, 12, 7, 3, 5, 4, 11, 1,...  Example: f(z) = 7z % 13. This produces the sequence...1, 7, 10, 5, 9, 11, 12, 6, 3, 8, 4, 2, 1,...  Is the latter somehow "less random"?  Example: f(z) = 5z %13. This produces the sequence...1, 5, 12, 8, 1...

Using Java’s RNGs (cont.)  java.lang.Math static double random()random in [0, 1.0)  The sequence doesn’t seem to be repeatable  Bad for debugging  Good for experimental work

Using Java’s RNGs (cont.)  java.util.Random Constructors:  Random()  Random(long seed) Methods:  nextInt()random in (-2 31, )  nextInt(int n)random in [0, n)  nextFloat()random in [0, 1)  setSeed(long seed)  java.lang.Math static double random()random in [0, 1.0)