Expressions & Flow Control

Similar documents
Introduction to Programming Using Java (98-388)

PROGRAMMING FUNDAMENTALS

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

SECTION II: LANGUAGE BASICS

Exercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014

Operators and Expressions

Java Basic Programming Constructs

The Java language has a wide variety of modifiers, including the following:

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Chapter 3: Operators, Expressions and Type Conversion

Values and Variables 1 / 30

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

CSC 1214: Object-Oriented Programming

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Zheng-Liang Lu Java Programming 45 / 79

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Object Oriented Software Design

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

JAVA OPERATORS GENERAL

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Continued from previous lecture

Lecture Set 4: More About Methods and More About Operators

Fundamental of Programming (C)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture Set 4: More About Methods and More About Operators

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Introduction to Programming (Java) 2/12

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Programming for Engineers Iteration

CS 112 Introduction to Programming

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

C - Basics, Bitwise Operator. Zhaoguo Wang

Java Notes. 10th ICSE. Saravanan Ganesh

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Programming refresher and intro to C programming

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Program Fundamentals

CS 231 Data Structures and Algorithms, Fall 2016

JAVA Programming Fundamentals

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Getting started with Java

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

LAB A Translating Data to Binary

Fundamentals of Programming

Programming with Java

VARIABLES AND TYPES CITS1001

Array. Prepared By - Rifat Shahriyar

Full file at

The Design of C: A Rational Reconstruction: Part 2

Software Practice 1 Basic Grammar

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Operators in java Operator operands.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

About this exam review

ESc101 : Fundamental of Computing

Review for Test 1 (Chapter 1-5)

Prof. Navrati Saxena TA: Rochak Sachan

Following is the general form of a typical decision making structure found in most of the programming languages:

Chapter 2: Using Data

Programming. Syntax and Semantics

More Programming Constructs -- Introduction

Writing Program in C Expressions and Control Structures (Selection Statements and Loops)

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Part I Part 1 Expressions

CS1150 Principles of Computer Science Loops (Part II)

The Basic Parts of Java

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

13 th Windsor Regional Secondary School Computer Programming Competition

Learning the Java Language. 2.1 Object-Oriented Programming

CGS 3066: Spring 2015 JavaScript Reference

Computer Components. Software{ User Programs. Operating System. Hardware

Simple Java Reference

Pace University. Fundamental Concepts of CS121 1

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

Java Bytecode (binary file)

CS260 Intro to Java & Android 03.Java Language Basics

Language Fundamentals Summary

Accelerating Information Technology Innovation

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Operators. Java operators are classified into three categories:

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

CT 229. Java Syntax 26/09/2006 CT229

Transcription:

Objectives Distinguish between instance and local variables 4 Expressions & Flow Control Describe how instance variables are initialized Identify and correct a Possible reference before assignment compiler error Recognize, describe, and use Java operators Distinguish between legal and illegal assignments of primitive types Identify boolean expressions and their requirements in control constructs 102 103 Variables and Scope Recognize assignment compatibility and required casts in fundamental types Use if, switch, for, while, and do constructions and the labeled forms of break and continue as flow control structures in a program Local variables are Variables which are defined inside a method and are called local, automatic, temporary, or stack variables Created when the method is executed and destroyed when the method is exited Variables that must be initialized before they are used or compile-time errors will occur 104 105 Variable Scope Example # 1 Variable Scope Example # 2 { public class ScopeExample { int x = 12; /* only x available */ { int q = 96; /* both x & q available */ /* only x available */ /* q is out of scope */ private int i=1 ; public void firstmethod(){ int i=4, j=5 ; this.i = i + j ; secondmethod(7) ; public void secondmethod(){ int j=8 ; this.i = i + j ; 106 107 1

public class TestScoping { public static void main(string []args){ ScopeExample scope = new ScopeExample(); scope.firstmethod() ; Initializing Variables variables defined outside of a method are initialized automatically boolean false char \u0000 (null) byte (byte)0 short (short)0 int 0 long 0L float 0.0f double 0.0d 108 109 Initializing Variables While variables defined outside of a method are initialized automatically, local variables must be initialized manually before use: public class docomputation { int x = (int) (Math.random() * 100) ; int y ; int z ; if (x > 50){ y = 9 ; z = x + y ; Operators The Java operators are similar in style and function to those of C and C++: Separator. [] () ;, Associative Operators R to L ++ -- + - ~! (data type) L to R * / % L to R + - L to R << >> >>> L to R < > <= >= instanceof L to R ==!= 110 111 Associative Operators R to L & L to R ^ L to R L to R && L to R R to L?: R to L = *= /= %= += -= <<= >>= >>>= &= ^= = Logical Operators The boolean operators are:! NOT & AND OR ^ XOR The short-curcuit boolean operators are: && AND OR You can use these operators as follows: MyDate d ; if ((d!= null) && (d.day > 31)) { // do something with d 112 113 2

Most Java operators are taken from other languages and behave as expected. Relational and logical operators return a boolean result. The value 0 is not automatically interpreted as false and non-zero values are not automatically interpreted as true. int i = 1 ; if (i) // generates a compile error if (i!= 0) // correct MyDate d ; if ((d!= null) && (d.day > 31)) { // do something with d The second sub-expression is skipped when the first subexpression is false if ( ( d!= null ) && ( d.day > 31 ) ) is SAFE if ( ( d!= null ) & ( d.day > 31 ) ) is NOT safe 114 115 Bitwise Logical Operators import java.io.* ; a=0 public class Evaluate { public static void main(string[] args) { int a=1,b=1,c=3,d=10,y ; y = b + ( a==1 ++b==d ++d==11? b : d ) + 1 ; System.out.println("y=") ; System.out.println(y) ; The integer bitwise operators are: ~ Complement & AND ^ XOR Byte-sized examples: ~ 0 1 0 0 1 1 1 1 1 0 1 1 0 0 0 0 OR & 0 0 1 0 1 1 0 1 0 1 0 0 1 1 1 1 0 0 0 0 1 1 0 1 116 117 ^ 0 0 1 0 1 1 0 1 0 1 0 0 1 1 1 1 0 1 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 0 1 1 1 1 0 1 1 0 1 1 1 1 Right-Shift Operators >> and >>> Arithmetic or signed right-shift (>>) is used as follows: 128 >> 1 returns 128/2 1 =64 256 >> 4 returns 256/2 4 =16-256 >> 4 returns -256/2 4 =-16 The sign bit is copied during the shift. A logical or unsigned right-shift (>>>) is: Used for bit patterns. The sign bit is not copied during the shift. 1 0 1 0 1 1 0 1 >> 2 = 1 1 1 0 1 0 1 1 1 0 1 0 1 1 0 1 >>> 2 = 0 0 1 0 1 1 0 1 118 119 3

Left-Shift Operator (<<) Shift Operator Examples Left-shift (<<) works as follows: 128 << 1 returns 128*2 1 =256 16 << 2 returns 16*2 2 =64 1537 1537 >> 5 >> 5 1537 >>> 5 >>> 5 1537 << 5 << 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 0 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 0 1 1 0 0 1 1 0 0 0 0 0 120 121 String Concatenation With + Casting The + operator Performs String concatenation Produces a new String: String salutation = "Dr."; String name = "Pete " + " " + "Seymour"; String title = salutation + " " + name; One argument must be a String object Non-strings are converted to String objects automatically If information is lost in an assignment, the programmer must confirm the assignment with a typecast. The assignment between long and int requires an explicit cast. long bigvalue = 99L; int squashed = bigvalue; //Wrong, needs a cast int squashed = (int) bigvalue; // OK int squashed = 99L; //Wrong, needs a cast int squashed = (int) 99L; // OK, but... int squashed = 99; // default integer literal 122 123 Promotion and Casting of Expressions Assignment compatibility between integer types Variables are automatically promoted to a longer form (such as int to long) Expression is assignment compatible if the variable type is at least as large (the same number of bits) as the expression type. long bigval = 6 ; // 6 is an int type,, OK int smallval = 99L ; // 99L is a long,, illegal double z = 12.414F; // 12.414F is float,, OK float z1 = 12.414; // 12.414 is double,, illegal to byte char short int long from byte char Assignable Cast needed short int long 124 125 4

short a, b, c ; a = 1 ; b = 2 ; c = a + b ; c = (short( short) ) (a + b) ; For binary operators, such as the + operator, when the two operands are of primitive numeric types, the result is at least an int and has a value calculated by promoting the operands to the result type or promoting the result to the wider type of the operands. This might result in overflow or loss of precision. Branching Statements The if, else statement syntax: if (boolean expression) { { else { 126 127 Example int count ; count = getcount() ; if (count<0) { System.out.println( Error: count value is negative. ); else if (count > getmaxcount()) { System.out.println( Error: count value is too big. ); else { System.out.println( There will be +count+ people for lunch today. ); if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( x is <= 5" ); if ( x > 5 ){) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" ); 128 129 Branching Statements Common Programming Error The switch statement syntax is: switch (expr1) { case expr2: statements; case expr3: statements; default: statements; int i = 1 ; switch (i) { case 1: System.out.println( bir ) ; case 2: System.out.println( iki ) ; case 3: System.out.println( uc ) ; case 4: System.out.println( dort ) ; default: System.out.println( on ) ; 130 131 5

Looping Statements Looping Statements The for statement The while loop: for (init_expr; boolean testexpr; alter_expr) { int faktoriyel,i,i; for(i=1, i=1,faktoriyel=1;i<=9;i++ i++) faktoriyel *= i; System.out out.println( 9!= 9!= + faktoriyel) ) ; while (boolean test) { 132 133 int faktoriyel = 1, i=1; while ( i <= 9 ){ faktoriyel *= i; Looping Statements The do/while loop: i++; System.out.println( 9!= 9!= + faktoriyel); true i <= 9 faktoriyel *= i ; false while (boolean test); int faktoriyel = 1, i=1; faktoriyel *= i; i++ ; while ( i <= 9 ); System.out out.println( 9!= 9!= + faktoriyel) 134 135 Special Loop Flow Control break [label]; The break statement: continue [label]; label: statement; // where statement should // be a loop. while (boolean expression); 136 137 6

The break statement with a label named outer: The continue statement: continue; while (boolean expression); outer: break outer; while (boolean expression); while (boolean expression); Statement; 138 139 The continue statement with a label named test: test: continue test; while (boolean expression); while (boolean expression); 3# Identifiers, Keywords, and Types Exercise-1: Using Loops and Branching Statements Exercise-2: Modifying the withdraw Method Exercise-3: Using Nested Loops 140 141 An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number because 6=1+2+3. Write a main function that determines all the perfect numbers between 1 and 5000. Print the factors of each perfect number to confirm that the number is indeed perfect. import java.io.* ; public class PerfectNumber { public static void main(string[] args) { int i,j,sum ; for(j=2;j<5001;j++){ sum = 1 ; for(i=2 ;i<=j/2;i++) if( (j % i) == 0 ) sum += i ; if(sum == j){ System.out.print("\n"+j + " is a perfect number, since "+j+"= "); for(i=1;i<=j/2;i++) if ( (j%i) == 0 ) System.out.print(i+" "); 142 143 7