The While Statement. If boolean expression is true execute statement; continue to execute statement so long as boolean expression is true.

Size: px
Start display at page:

Download "The While Statement. If boolean expression is true execute statement; continue to execute statement so long as boolean expression is true."

Transcription

1 Variables and Loops

2 The While Statement while ( boolean-expression ) statement If boolean expression is true execute statement; continue to execute statement so long as boolean expression is true.

3 While Statement Example public class GoToEnd public static void main( String[] args ) Vic.reset( args ); Vic tim = new Vic(); while ( tim.seesslot() ) tim.moveon();

4 The While Statement and Blocks To do more than one thing in a while loop use a compound statement: public class GoToEnd public static void main( String[] args ) Vic.reset( args ); Vic tim = new Vic(); while ( tim.seesslot() ) tim.moveon(); tim.say( "try again" );

5 1. Textbook, Chapter 3, page 3 3: Exercises Exercises

6 The String Type To declare a String object, use String followed by an identifier followed optionally by an initial value: public class Test public static void main( String[] args ) String str = "this is a very clever string"; System.out.println( str );

7 Testing Strings for Equality To test two strings for equality use the.equals( String ) method: public class Test public static void main (String[ ] args) String fred = "See spot run!"; String wilma = "Run spot, run!"; String betty = "See spot run!"; Question: what is the type of.equals? System.out.println( fred.equals( wilma ) ); System.out.println( fred.equals( betty ) );

8 Vic Method: Get Position This method returns a String which tells you which position an "arm" is. public static void main( String[] args ) Vic tim = new Vic(); String pos = tim.getposition(); tim.say( pos ); or public static void main( String[] args ) Vic tim = new Vic(); tim.say( tim.getposition() );

9 Has Some Filled Slot This method will return true if there is a CD at or after the current position. On completion, the arm will return to the position it started in. public class VicPlus extends Vic public boolean hassomefilledslot() String savepos = getposition(); while ( seesslot() &&!seescd() ) moveon(); boolean rval = seesslot(); while (!savepos.equals( getposition() ) ) backup(); return rval;

10 Go To Last CD public boolean gotolastcd() String pos = getposition(); boolean rval = false; while ( seesslot() ) if ( seescd() ) rval = true; pos = getposition(); moveon(); This method will return true if there is a CD anywhere in its sequence. On completion, the arm will be at the position of the last CD, or at its original position if no CD is found. while (!pos.equals( getposition() ) ) backup(); return rval;

11 1. Textbook, Chapter 3, page 3 7: Exercises Exercises

12 Practice: Move To Front public class MoveToFront public static void main( String[] args ) Vic.reset( args ); Vic tim = new Vic(); String pos = tim.getposition(); while ( tim.seesslot() ) tim.takecd(); tim.moveon(); Move all CDs in a row to the front of the row. while (!pos.equals( tim.getposition() ) ) tim.backup(); while ( Vic.stackHasCD() ) tim.putcd(); tim.moveon();

13 1. Textbook, Chapter 3, page 3 8: Exercise Exercises

14 The Looper Class: Back Up To Given a Vic position (from the Vic getposition() method) back up until the position is reached: public class Looper extends Vic private void backupto( String pos ) while (!pos.equals( getposition() ) ) backup(); This is a private method; it can only be used by other methods in the Looper class.

15 The Looper Class: Fill Slots Fill all slots in a sequence from the current position forward, then return to the original position. public void fillslots() String pos = getposition(); while ( seesslot() ) putcd(); moveon(); backupto( pos ); Question: what object do putcd and backupto refer to?

16 The Looper Class: Clear Slots To Stack Take all the CDs from the current position forward and put them on the stack, then return to the original position. public void clearslotstostack() String pos = getposition(); while ( seesslot() ) takecd(); moveon(); backupto( pos );

17 The Looper Class: Fill Odd Slots Beginning at the current position, fill all the odd numbered slots with CDs from the stack, then return to the original position. public void filloddslots() String pos = getposition(); while ( seesslot() && stackhascd() ) putcd(); moveon(); if ( seesslot() ); moveon(); backupto( pos );

18 The Looper Class: Sees All Filled Returns true if all slots from the current position forward are filled, false otherwise. At completion, the arm will be left at the original position. public boolean seesallfilled() String pos = getposition(); while ( seesslot() && seescd() ) moveon(); boolean rval =!seesslot(); backupto( pos ); return rval; Questions: 1. What is the type of seesallfilled? 2. Is this an instance method? Why?

19 Private Methods Declaring a method private means it is for internal use only; programmers of other classes cannot access. This is called data hiding, and it makes maintaining your code easier. private void backupto( String pos ) while (!pos.equals( getposition() ) ) backup();

20 Method Parameters Method Parameters make your methods more versatile; it enables the same logic can be applied to many different objects. private void backupto( String pos ) while (!pos.equals( getposition() ) ) backup(); Every parameter has a type. When you invoke a method, you must provide an argument of a compatible type.

21 Exercises 1. Enter and compile the code for the Looper class. 2. Textbook, Chapter 3, page 3 13: Exercise

22 Variables Local variables can be declared inside a method s braces: public void mymethod() Vic tim; // local variable declaration Turtle socrates; // local variable declaration...

23 Parameters Parameters can be declared inside a method s parentheses; when you invoke a method, you must pass arguments (values) of a compatible type. private void backupto( String pos ) while (!pos.equals( getposition() ) ) backup(); public void loopermethod() String spot = getposition();... backupto( spot ); parameter argument

24 Using Parameters (1) The method hasasmanyslotsas returns true if this Vic object has the same number of slots as another Vic object. public class TwoVicUser extends Vic public boolean hasasmanyslotsas( Vic parm ) String pos = getposition(); while ( seesslot() && parm.seesslot() ) moveon(); parm.moveon(); (continued on next slide)

25 Using Parameters (2) (continued from previous slide) boolean rval =!seesslot() &&!parm.seesslot(); while (!pos.equals( getposition() ) ) backup(); parm.backup(); return rval;

26 Arguments A value passed to a method is called an argument. public class Test public static void main( String[] args ) Vic.reset( args ); TwoVicUser tim = new TwoVicUser(); TwoVicUser sam = new TwoVicUser(); if ( tim.hasasmanyslotsas( sam ) ) Vic.say( "slots same" ); else Vic.say( "slots different" );

27 Garbage Collection Every time you new something memory gets used. If you new too many objects without releasing the ones that you don't need anymore you will eventually run out of memory. Java has a mechanism called garbage collection that automatically looks for unused objects and deletes them.

28 1. Textbook, Chapter 3, page 3 17: Exercise 3.28, 3.29 Exercises

29 The Int Type An int is used to store and manipulate integers. It is declared using the int keyword and an optional initial value: int alice = 5; int jane = 5;

30 The Int Type: Limits An int object can hold values between approximately 2.1 billion and 2.1 billion.

31 The Increment Operator The increment operator (++) increases the value of an int object by one. The increment operator comes in two flavors, pre increment (++inx) and postincrement (inx++): int alice = 5; int jane = ++alice; // pre-increment int rabbit = alice++; // post-increment

32 The Pre Increment Operator When the pre increment operator is used on a variable in an expression, first the variable is incremented then the rest of the expression is evaluated: public static void main( String[] args ) int inx = 5; int jnx = 10; int knx = ++inx * jnx; System.out.println( inx ); // 6 System.out.println( knx ); // 60

33 The Post Increment Operator When the post increment operator is used on a variable in an expression, first the expression is evaluated, then the variable is incremented: public static void main( String[] args ) int inx = 5; int jnx = 10; int knx = inx++ * jnx; System.out.println( inx ); // 6 System.out.println( knx ); // 50

34 The Decrement Operator The decrement operator ( ) decreases the value of an int variable by one. It comes in two flavors, pre decrement ( inx) and post decrement (inx ). int inx = 5; int jnx = 10; int knx = --inx * jnx; System.out.println( inx ); // 4 System.out.println( knx ); // 40 int inx = 5; int jnx = 10; int knx = inx-- * jnx; System.out.println( inx ); // 4 System.out.println( knx ); // 50

35 Unary Operators The increment and decrement operators are called unary operators because they take a single argument. Another unary operator is negation ( ) which changes the sign of its argument: public class Test public static void main( String[] args ) int inx = -5; int jnx = 20; System.out.println( -inx ); //5 System.out.println( -jnx ); //-20

36 Binary Operators A binary operator is an operator that takes two arguments. Some of the common binary operators in java are: Operator Example Addition (+) int inx = 5; int jnx = inx + 15; // jnx = 20 Subtraction ( ) int inx = 15; int jnx = inx - 3; // jnx = 12 Multiplication (*) int inx = 15; int jnx = inx * 4; // jnx = 60 Division (/) int inx = 15; int jnx = inx / 2; // jnx = 7 Modulo (%) int inx = 25; int jnx = inx % 4; // jnx == 1

37 Integer Division When two integers are divided, the result is always an integer; any fractional remainder is discarded. public class Test public static void main (String[ ] args) System.out.println( 15 / 7 ); // 2 System.out.println( 20 / 7 ); // 2 System.out.println( 8 / 7 ); // 1

38 Modulo The expression: inx % jnx is read inx modulo jnx The value of A % B, where A and B are integers, is equal to the remainder of A / B. public class Test public static void main (String[ ] args) System.out.println( 15 % 7 ); // 1 System.out.println( 20 % 7 ); // 6 System.out.println( 8 % 7 ); // 1 System.out.println( 42 % 7 ); // 0

39 Comparison Operators The binary operators that perform comparisons are:: Operator Example Greater than (>) if ( inx > jnx ) do this Less than (<) if ( inx < jnx ) do this Equal to (==) if ( inx == jnx ) do this Not equal to (!=) if ( inx!= jnx ) do this Greater than or equal to (>=) Less than or equal to (<=) if ( inx >= jnx ) do this if ( inx <= jnx ) do this

40 Comparison Operator Example if ( inx == 0 ) System.out.println( the value is 0 ); boolean result = seesslot() && seescd();

41 The Conditional Expression Operator Choose between two outcomes depending on some condition: condition? outcome1 : outcome2 The above expression consists of one operator and three operands... If condition is true the value of the expression is outcome1, otherwise the value of the expression is outcome2. // Produce up to count lines of output, but no more than LIMIT. private static void printlines( int count ) int last = count < LIMIT? count : LIMIT; while ( last-- > 0 ) System.out.println( "Every good boy deserves favor" );

42 Exercises 1. Chapter 4, page Int 6: Exercise 1, 2, 3 (note: getnumslots is on page Int 1) 2. Download and complete ArithmeticActivity from the class web site.

43 String Concatenation Use the plus sign (+) to concatenate two Strings or a String and a number. public static void main( String[] args ) String prefix = "String demonstration: "; String demo1 = prefix + "concatenate two strings"; String demo2 = prefix + 25; int answer = 42; System.out.println( demo1 ); System.out.println( demo2 ); System.out.println( "The answer is: " + answer );

44 The For Statement (1) The for statement executes one statement (possibly a block statement) 0 or more times. for ( initialize ; test ; increment ) statement 1. Evaluates the initialization expression. 2. Evaluates the test expression. a. If the test is true goes to step 3; b. If the test is false goes to step Executes statement. 4. Evaluates the increment expression. 5. Goes back to step Terminates execution of the loop. // print 1 through 10 for ( int inx = 0 ; inx < 11 ; ++inx ) System.out.println( inx );

45 The For Statement (2) For statement example: public class Test public static void main( String[] args ) int fac = computefactorial( 10 ); System.out.println( "10! = " + fac ); static private int computefactorial( int num ) int rval = 1; int inx = 0; for ( inx = num ; inx > 0 ; --inx ) rval = rval * inx; return rval;

46 The For Statement (3) For statement example: public class Test public static void main( String[] args ) int fac = computefactorial( 10 ); System.out.println( "10! = " + fac ); static private int computefactorial( int num ) int rval = 1; for ( int inx = num ; inx > 0 ; --inx ) rval = rval * inx; return rval;

47 Exercises 1. Write a program that uses a for loop to print out the squares of the first 20 integers. 2. Textbook, Chapter 4, page Int 6: Exercise 4, 5

48 The For Statement (4) You can eliminate the initialization expression in a for loop: public static void main( String[] args ) Vic tim = new Vic(); int num = countfilledslots( tim ); System.out.println( "Tim has " + num + " filled slots" ); static private int countfilledslots( Vic parm ) int rval = 0; for ( ; parm.seesslot() ; parm.moveon() ) if ( parm.seescd() ) ++rval; return rval;

49 The For Statement (5) You can eliminate the increment expression in a for statement: public class Test public static void main( String[] args ) Vic tim = new Vic(); gotoend( tim ); static private void gotoend( Vic parm ) for ( ; parm.seesslot() ; ) parm.moveon();

50 The For Statement (6) To execute more than one statement in the body of a for loop use a block statement: for ( init ; test ; incr ) statement 1; statement 2;

51 The Do Statement The do statement is like the while statement, except: statement is always a block statement; statement always executes at least once. do statements while ( boolean expression ); 1. Executes the block statement. 2. Evaluates the Boolean expression. a) If boolean expression is true goes to step one. b) if boolean expression is false terminates the loop.

52 Do Statement Example do String prompt = "guess a number between 0 and 10"; System.out.println( prompt ); num = getusersguess(); System.out.println( "Your guess: " + num ); while ( num < 0 num > 10 );

53 Reference Types All objects are reference types. A properly initialized object value is a pointer to an area of memory where the object data is stored. public class Test At this point tim is not an public static void main( String[] args ) object. Turtle tim; tim = new Turtle(); current color current position current direction etc.

54 The Null Keyword The null keyword can be used to distinguish between a proper reference to a block of memory, and an object value that is not a proper reference. public static void main( String[] args ) String data; data = promptuser( null ); data = promptuser( "Enter a number: " ); private static String promptuser( String prompt ) String actprompt = "enter> "; if ( prompt!= null ) actprompt = prompt; System.out.println( "testing: " + actprompt ); return null;

55 Testing Strings For Equality (1) The output of the following code is not equal, even though both strings contain the same value. Can you explain why? public static void main( String[] args ) String test1 = "My string"; String test2 = "My "; test2 = test2 + "string"; System.out.println( "Test 1> " + test1 ); System.out.println( "Test 2> " + test2 ); if ( test1 == test2 ) System.out.println( "equal" ); else System.out.println( "not equal" );

56 Testing Strings For Equality (2) The String method equals determines if two String objects contain the same value (even though they may be different objects). public static void main( String[] args ) String test1 = "My string"; String test2 = "My "; test2 = test2 + "string"; System.out.println( "Test 1> " + test1 ); System.out.println( "Test 2> " + test2 ); if ( test1.equalsignorecase( test2 ) ) System.out.println( "equal" ); else System.out.println( "not equal" ); The output is equal.

57 Testing Strings For Equality (3) The String method equalsignorecase determines if two String objects contain the same value independent of capitalization. public static void main( String[] args ) String test1 = "My string"; String test2 = "MY STRing"; System.out.println( "Test 1> " + test1 ); System.out.println( "Test 2> " + test2 ); if ( test1.equalsignorecase( test2 ) ) System.out.println( "equal" ); else System.out.println( "not equal" ); The output is equal.

58 Strings: Compare To Method The compareto method tells you in which order two strings would appear in a dictionary. private static void testguess( String str ) int result = str.compareto( "alligator" ); if ( result == 0 ) System.out.println( "equal to to the hidden word" ); else if ( result < 0 ) System.out.println( "less than the hidden word" ); else if ( result > 0 ) System.out.println( "greater than the hidden word" ); else System.out.println( shouldn t ever get here" );

59 Strings: Determining Order Comparing strings for magnitude is determined by the Unicode values of the individual characters: All lower case letters are greater than all upper case letters. All letters are greater than all numbers.

60 Strings: Compare To Ignore Case Method The method comparetoignorecase works like compareto except that it treats upper case and lower case letters as equal.

61 Strings: Contains Method The contains method tells whether one string contains another.. private static void testcontains( String str ) if ( str.contains( "coyote" ) ) System.out.println( "contains secret word" ); else System.out.println( "doesn t contain secret word" );

62 Strings: Ends With Method The endswith method tells whether one string ends with another.. static private void testdomain( String address ) if ( address.endswith( ".com" ) ) System.out.println( "company domain" ); else if ( address.endswith( ".mil" ) ) System.out.println( "military domain" ); else if ( address.endswith( ".edu" ) ) System.out.println( "education domain" ); else if ( address.endswith( ".org" ) ) System.out.println( "organization domain" ); else if ( address.endswith( ".gov" ) ) System.out.println( "government domain" ); else System.out.println( "unknown domain" );

63 More String Methods See the java API for complete documentation of the String class.

64 Exercises 1. Write a program that uses a for loop to print out the squares of the first twenty integers. Each printed line should look something like this: The square of 4 is Write a program that determines which of each of the following pairs of strings is greater than the other. For each pair print a line that looks something like this: string bravo is greater than string alpha Zulu Market Albatross market "200"

The Vic Class. a1 b e g end. a d2 end. a3 b e g3 h3 end. a d4 e4 end. GarthB LyleL stack

The Vic Class. a1 b e g end. a d2 end. a3 b e g3 h3 end. a d4 e4 end. GarthB LyleL stack Conditionals The Vic Class a1 b1 ---- ---- e1 ---- g1 ---- end a2 ---- ---- d2 end a3 b3 ---- ---- e3 ---- g3 h3 end GarthB LyleL stack a4 ---- ---- d4 e4 end The Vic Class 1. The Vic class simulates a

More information

Java Foundations: Unit 3. Parts of a Java Program

Java Foundations: Unit 3. Parts of a Java Program Java Foundations: Unit 3 Parts of a Java Program class + name public class HelloWorld public static void main( String[] args ) System.out.println( Hello world! ); A class creates a new type, something

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators Chapter 12 Variables and Operators Highlights (1) r. height width operator area = 3.14 * r *r + width * height literal/constant variable expression (assignment) statement 12-2 Highlights (2) r. height

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

SECTION II: LANGUAGE BASICS

SECTION II: LANGUAGE BASICS Chapter 5 SECTION II: LANGUAGE BASICS Operators Chapter 04: Basic Fundamentals demonstrated declaring and initializing variables. This chapter depicts how to do something with them, using operators. Operators

More information

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

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

Topics. Chapter 5. Equality Operators

Topics. Chapter 5. Equality Operators Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

More information

COMP Primitive and Class Types. Yi Hong May 14, 2015

COMP Primitive and Class Types. Yi Hong May 14, 2015 COMP 110-001 Primitive and Class Types Yi Hong May 14, 2015 Review What are the two major parts of an object? What is the relationship between class and object? Design a simple class for Student How to

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Java basics: Compilation vs Interpretation Program structure Statements Values Variables Types Operators and Expressions

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Simple Java Programming Constructs 4

Simple Java Programming Constructs 4 Simple Java Programming Constructs 4 Course Map In this module you will learn the basic Java programming constructs, the if and while statements. Introduction Computer Principles and Components Software

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data Declaring Variables Constant Cannot be changed after a program is compiled Variable A named location in computer memory that can hold different values at different points in time

More information

Section 2: Introduction to Java. Historical note

Section 2: Introduction to Java. Historical note The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence

More information

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators Basic C Elements Chapter 12 Variables and Operators Original slides from Gregory Byrd, North Carolina State University! Variables named, typed data items! Operators predefined actions performed on data

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Perl: Arithmetic, Operator Precedence and other operators. Perl has five basic kinds of arithmetic:

Perl: Arithmetic, Operator Precedence and other operators. Perl has five basic kinds of arithmetic: Perl: Arithmetic, Operator Precedence and other operators Robert A. Fulkerson College of Information Science and Technology http://www.ist.unomaha.edu/ University of Nebraska at Omaha http://www.unomaha.edu/

More information

CT 229. Java Syntax 26/09/2006 CT229

CT 229. Java Syntax 26/09/2006 CT229 CT 229 Java Syntax 26/09/2006 CT229 Lab Assignments Assignment Due Date: Oct 1 st Before submission make sure that the name of each.java file matches the name given in the assignment sheet!!!! Remember:

More information

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

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Prof. Navrati Saxena TA: Rochak Sachan

Prof. Navrati Saxena TA: Rochak Sachan JAVA Prof. Navrati Saxena TA: Rochak Sachan Operators Operator Arithmetic Relational Logical Bitwise 1. Arithmetic Operators are used in mathematical expressions. S.N. 0 Operator Result 1. + Addition 6.

More information

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU Week 21/02/2007-23/02/2007 Lecture Notes: ASCII 7 bits = 128 characters 8 bits = 256characters Unicode = 16 bits Char Boolean boolean frag; flag = true; flag

More information

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein PRIMITIVE VARIABLES CS302 Introduction to Programming University of Wisconsin Madison Lecture 3 By Matthew Bernstein matthewb@cs.wisc.edu Variables A variable is a storage location in your computer Each

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

M e t h o d s a n d P a r a m e t e r s

M e t h o d s a n d P a r a m e t e r s M e t h o d s a n d P a r a m e t e r s Objective #1: Call methods. Methods are reusable sections of code that perform actions. Many methods come from classes that are built into the Java language. For

More information

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

CHAD Language Reference Manual

CHAD Language Reference Manual CHAD Language Reference Manual INTRODUCTION The CHAD programming language is a limited purpose programming language designed to allow teachers and students to quickly code algorithms involving arrays,

More information

AP Computer Science A

AP Computer Science A AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive

More information

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1 topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is

More information

Variables and Operators 2/20/01 Lecture #

Variables and Operators 2/20/01 Lecture # Variables and Operators 2/20/01 Lecture #6 16.070 Variables, their characteristics and their uses Operators, their characteristics and their uses Fesq, 2/20/01 1 16.070 Variables Variables enable you to

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

1.00 Lecture 4. Promotion

1.00 Lecture 4. Promotion 1.00 Lecture 4 Data Types, Operators Reading for next time: Big Java: sections 6.1-6.4 Promotion increasing capacity Data Type Allowed Promotions double None float double long float,double int long,float,double

More information

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

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data

More information

Handout 4 Conditionals. Boolean Expressions.

Handout 4 Conditionals. Boolean Expressions. Handout 4 cs180 - Programming Fundamentals Fall 17 Page 1 of 8 Handout 4 Conditionals. Boolean Expressions. Example Problem. Write a program that will calculate and print bills for the city power company.

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

Zheng-Liang Lu Java Programming 45 / 79

Zheng-Liang Lu Java Programming 45 / 79 1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

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

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. OOP in Java 1 Outline 1. Getting started, primitive data types and control structures 2. Classes and objects 3. Extending classes 4. Using some standard packages 5. OOP revisited Parts 1 to 3 introduce

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

The Warhol Language Reference Manual

The Warhol Language Reference Manual The Warhol Language Reference Manual Martina Atabong maa2247 Charvinia Neblett cdn2118 Samuel Nnodim son2105 Catherine Wes ciw2109 Sarina Xie sx2166 Introduction Warhol is a functional and imperative programming

More information

Operators & Expressions

Operators & Expressions Operators & Expressions Operator An operator is a symbol used to indicate a specific operation on variables in a program. Example : symbol + is an add operator that adds two data items called operands.

More information

Operators in java Operator operands.

Operators in java Operator operands. Operators in java Operator in java is a symbol that is used to perform operations and the objects of operation are referred as operands. There are many types of operators in java such as unary operator,

More information

Information Science 1

Information Science 1 Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

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

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

More information

ECE 122 Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction Outline Problem: How do I input data and use it in complicated expressions Creating complicated expressions

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

CIS133J. Working with Numbers in Java

CIS133J. Working with Numbers in Java CIS133J Working with Numbers in Java Contents: Using variables with integral numbers Using variables with floating point numbers How to declare integral variables How to declare floating point variables

More information

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 Copyright 2009 by Pearson Education Data and expressions reading: 2.1 self-check: 1-4 videos: Ch. 2 #1 Copyright

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

GraphQuil Language Reference Manual COMS W4115

GraphQuil Language Reference Manual COMS W4115 GraphQuil Language Reference Manual COMS W4115 Steven Weiner (Systems Architect), Jon Paul (Manager), John Heizelman (Language Guru), Gemma Ragozzine (Tester) Chapter 1 - Introduction Chapter 2 - Types

More information

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Basic Operations jgrasp debugger Writing Programs & Checkstyle Basic Operations jgrasp debugger Writing Programs & Checkstyle Suppose you wanted to write a computer game to play "Rock, Paper, Scissors". How many combinations are there? Is there a tricky way to represent

More information

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

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Values and Variables 1 / 30

Values and Variables 1 / 30 Values and Variables 1 / 30 Values 2 / 30 Computing Computing is any purposeful activity that marries the representation of some dynamic domain with the representation of some dynamic machine that provides

More information

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( ) Sir Muhammad Naveed Arslan Ahmed Shaad (1163135 ) Muhammad Bilal ( 1163122 ) www.techo786.wordpress.com CHAPTER: 2 NOTES:- VARIABLES AND OPERATORS The given Questions can also be attempted as Long Questions.

More information

Information Science 1

Information Science 1 Topics covered Information Science 1 Terms and concepts from Week 8 Simple calculations Documenting programs Simple Calcula,ons Expressions Arithmetic operators and arithmetic operator precedence Mixed-type

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

DaMPL. Language Reference Manual. Henrique Grando

DaMPL. Language Reference Manual. Henrique Grando DaMPL Language Reference Manual Bernardo Abreu Felipe Rocha Henrique Grando Hugo Sousa bd2440 flt2107 hp2409 ha2398 Contents 1. Getting Started... 4 2. Syntax Notations... 4 3. Lexical Conventions... 4

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

Lecture 3. More About C

Lecture 3. More About C Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 3-1 Lecture 3. More About C Programming languages have their lingo Programming language Types are categories of values int, float, char Constants

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

C/C++ Programming for Engineers: Working with Integer Variables

C/C++ Programming for Engineers: Working with Integer Variables C/C++ Programming for Engineers: Working with Integer Variables John T. Bell Department of Computer Science University of Illinois, Chicago Preview Every good program should begin with a large comment

More information

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x ); Chapter 5 Methods Sections Pages Review Questions Programming Exercises 5.1 5.11 142 166 1 18 2 22 (evens), 30 Method Example 1. This is of a main() method using a another method, f. public class FirstMethod

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

COMP26120: Pointers in C (2018/19) Lucas Cordeiro COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

A variable is a name that represents a value. For

A variable is a name that represents a value. For DECLARE A VARIABLE A variable is a name that represents a value. For example, you could have the variable myage represent the value 29. Variables can be used to perform many types of calculations. Before

More information