Basic Programming Elements

Size: px
Start display at page:

Download "Basic Programming Elements"

Transcription

1 Chapter 2 Basic Programming Elements Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, ISBN: Permission is hereby granted to use these lecture slides in conjunction with the book. Modified: 14/11/08 JACT 2: Basic Programming Elements 2-1/30

2 Overview Printing to the terminal window Local variables Numerical data types Arithmetic expressions and operators Formatted output Reading numbers from the keyboard JACT 2: Basic Programming Elements 2-2/30

3 Printing to the terminal window Java programs can calculate values and print them directly to the terminal window literals System.out.println(9+7); standard out expression print and terminate the line Key concepts: Standard out - the System.out object, connected to terminal window by default println() prints values followed by newline print() prints values and allows printing to continue on the same line Literal - value written directly in the source code, e.g. an integer or a string Expression - a combination of values and operators, e.g. addition of two integers JACT 2: Basic Programming Elements 2-3/30

4 Printing to the terminal window Program 2.1 illustrates use of the print() and println() methods... System.out.print("The value of is "); // (4) System.out.println(9+7); // (5)... Compile and run with > javac SimplePrint.java > java -ea SimplePrint Exercise: Compile and run Program 2.1. Check that you get the same output as in the book. JACT 2: Basic Programming Elements 2-4/30

5 Printing to the terminal window Printing several strings on the same line // Alt.1: using the print() method to continue on the same line System.out.print("This text continues "); System.out.print("on the same line "); System.out.println("until terminated by a newline."); // Alt.2: using the + operator to print all text in one call System.out.println("This text continues " + "on the same line " + "until terminated by a newline."); Both code snippets above produce the same output: This text continues on the same line until terminated by a newline. Exercise: Enter the code lines above into a Java source code file. Compile and run the program. Check that your output matches with the above output. JACT 2: Basic Programming Elements 2-5/30

6 Printing to the terminal window Potential pitfall: Printing strings and numerical values in the same call System.out.println("The value of is " + (9+7)); Best practice: Ensure your numeric expressions are placed within parentheses when printing strings and numerical values together. JACT 2: Basic Programming Elements 2-6/30

7 Local variables Variables allow locations in memory to be named and accessed in a program A variable declared inside a method is called a local variable. Declaring a variable: declaration comment int numberofcourses; // number of courses this semester type variable name Key concepts: Variable name - unique name of the memory location Data type (or type) - defines what kind of values the variable can hold Comment - describes its purpose, helps in understanding the program Best practice: Choose names that makes the purpose of the variable easy to understand. Write a short comment for each variable unless the purpose is obvious from its name. JACT 2: Basic Programming Elements 2-7/30

8 Declaring and initialising a variable: declaration assignment int numberofcourses = 2; Local variables type variable name initial value Key concepts: Assignment - placing a value in the memory location referred to by the variable Initialisation - the first assignment to a variable Size of an int value 10 0x (address) Name: sum Type: int value ("content") int sum = 10; is equivalent to int sum; sum = 10; JACT 2: Basic Programming Elements 2-8/30

9 Local variables Best practice: Declare a local variable where it is first assigned a value. This ensures each variable is properly initialised, and reduces the risk of incorrect use or modification. Choosing variable names: Remember what Java accepts as valid names Names can contain letters and digits, but cannot start with a digit. Underscore (_) is allowed, also as the first character of a name. Java distinguishes between upper and lower case letters in names. Keywords like int cannot be used as variable names. Keep in mind conventions for variable names Use lower case letters for single-word names, and upper case letters for the first character of each consecutive word. Use all upper case letters for constants, and separate words with underscore. Exercise: Determine which of the following names are valid and follow conventions. Propose valid/better names if needed. int teamid, Team_Leader, 24x7, bestguess!, MAX_COUNT; JACT 2: Basic Programming Elements 2-9/30

10 Identifiers A name in a program is called an identifier. An identifier contains a sequence of characters that are either a letter, digit, underscore (_) or dollar-character ($), and cannot start with a digit. Local variables Literals denote a constant value Identifiers containing lower and upper case letters are different (case-sensitive). Defined: Number, number, sum_$, max_sum, bingo_, counter, $$_100 declared in the program. Keywords: float, if, true, while, for reserved words with specific meaning. Example of invalid identifiers: what?, 7UP Integers: Floating-point: E-1(=5x10-1 =0.5) Characters: 'a' '0' '+' '5' '\n' '\u000a' Boolean: true false String: "a piece of cake" "if" "\n" "0" "3.14" In addition there are special characters, like ( ) { } [ ] ;. and operators, such as + * - % = ==!= >= JACT 2: Basic Programming Elements 2-10/30

11 Local variables Identifiers, literals, operators and special character comprise what is called basic programming elements (tokens) in Java. A program in a source code file is a long sequence of characters. The compiler must divide the source code into basic programming elements to translate the program to byte code. In some cases basic programming elements must be separated in the source code by white spaces: sequences of space, tabulator, newline and formfeed characters. return 0; // must write a space between return and 0 return0; // invalid statement consisting of a single // identifier named return0. sum=sum+1; // not necessary to separate these basic elements However, use of white spaces can improve readability! JACT 2: Basic Programming Elements 2-11/30

12 Assignment operator identifier = expression Identifier gets the value of the expression. sum = 59; Identifier must be declared. 2 Identifier and expression must be of the same type Name: sum Type: int 2 cent = sum + 6; Name: count Type: int Name: sum Type: int JACT 2: Basic Programming Elements 2-12/30

13 Numerical data types Variables are used to store values. A variable has a name, type, size, value, and address. Primitive data type Integer: with sign and 2 scompliment Floating-point: IEEE standard Keyword in Java Value-size Example of literal Example of variable declaration byte 8-bits 29 byte b; short 16-bits short m,n; int 32-bits x1D int i,j,k; long 64-bits 29L 1L L long l; float 32-bits 1.5F 3.2e2F float r; double 64-bits e-2.1e2 3.14D double s,t; Character: char 16-bits 'a' '\t' '\u0009' char c; UNICODE Boolean/logical: boolean true false boolean v; JACT 2: Basic Programming Elements 2-13/30

14 Numerical data types Overview of primitive data types in Java: Primitive data types Boolean type Numerical data types Integral types Floating-point types Character type Integer types boolean char byte short int long float double JACT 2: Basic Programming Elements 2-14/30

15 Numerical data types A write operation overwrites the old value in memory with a new value, e.g. an assignment. A read operation does not change the value stored in memory, e.g. in a variable (operand) used in an expression. int i = 10, j = 20; i = 2 * j; // read: retrieving the value of j // write: i is assigned a new value (40) JACT 2: Basic Programming Elements 2-15/30

16 Arithmetic expressions and operators Common operators for numerical values Multiplication (*) Division (/) Addition (+) Subtraction (-) are all supported in Java. Operators and operands in arithmetic expressions: unary operator binary operator binary operator price + price * 0.23 operand operands operand operand operands binary operator A unary operator requires one operand. A binary operator requires two operands. JACT 2: Basic Programming Elements 2-16/30

17 Arithmetic expressions Arithmetic expressions can contain: Example: a number literal, 3.14 a variable, count a method call, Math.sin(90) an operator between two expressions (binary operator), phase + Math.sin(90) an operator applied to one expression (unary operator), -discount expressions in parentheses. (3.14-amplitude) Integer arithmetic yields results of type int unless at least on of the operands is of type long. Floating-point arithmetic yields results of type double if one of the operands is of type double. JACT 2: Basic Programming Elements 2-17/30

18 Arithmetic expressions and operators (Value) type Expression (has a value) of type T variable, literal method call type specific expression int count, 2, 97 Math.power(2,10), db.numberofcars() 8+count, (2*4)/3, 13%2 double price, vat, 3.14D, -0.5e5,.035, Math.cos(0.0), Math.sqrt( ) 8*price+vat, (2.0*4)/3 JACT 2: Basic Programming Elements 2-18/30

19 Arithmetic expressions and operators T (Value) type variable, constant or literal method call Expression (has a value) of type type specific expression boolean finished, OK, true, false Character.isDigit(c), Character.isLetter(c), Character.isLowercase(c) Comparison operators: count == 3, i < 100 Boolean or logical operators: finished && OK, (i<100) (count == 1) char character, 'z', '\n', '\u000a' Character.toLowercase(c) String str, "a string\n", "\"aha\"", "" str.substring(start, stop+1) Concatenation: "Hi!" + " What s " + "up?.\n" JACT 2: Basic Programming Elements 2-19/30

20 Conversion between primitive data types Evaluation of an arithmetic expression can results in implicit conversion of values in the expression. See examples below. Conversion of a "narrower" data type to a "broader" data type is (usually) done without loss of information, while conversion the other way round may cause loss of information. The compiler will issue a error message if such a conversion is illegal. int i = 10; double d = 3.14; d = i; // OK! i = d; // Not accepted without explicit conversion (cast) i = (int) d; // Accepted by the compiler JACT 2: Basic Programming Elements 2-20/30

21 Precedence and associativity rules Used to unambiguously evaluate expressions. The rules can be overruled by means of parentheses, (). Problem: Does * 4 evaluate to 20 or 14? Precedence rules are used to decide which operator will be evaluated first, if there are two operators with different precedence following each other in the expression. The operator with highest precedence is evaluated first * 4 is interpreted as 2 + (3 * 4) (resulting in value 14) since * has higher precedence than +. Associativity rules are used to decide which operator will be evaluated first, if there two operators with same precedence following each other in the expression. Left associativity yields grouping from left to right is interpreted as ((1 + 2) - 3) since binary operators + and - are leftassociative. Right-associativity yields grouping from right to left is interpreted as (- (- 4)) (resulting in value 4) since unary operator - is rightassociative. JACT 2: Basic Programming Elements 2-21/30

22 Evaluation of arithmetic expressions Arithmetic operators Expression Evaluation: Determine operands. Evaluate left to right. Grouping () ((3 + 2) - 1) 4 Unary * 7 (2 + (6 * 7)) (((-5)+7)-(-6)) 8 Binary (modulo) * 2+4/5 (2+(4/5)) 2 / 13 % 5 (13 % 5) 3 % 10 / 0 ArithmeticException Unary operators associate from right to left. Binary operators associate from left to right. Precedence decreases downwards in the table. Operands are evaluated from left to right before the operator is applied. Value /5 (2.0+(4.0/5.0)) / 0.0 Inf JACT 2: Basic Programming Elements 2-22/30

23 Evaluation of arithmetic expressions Integer expressions: : * 7: : 8 2+4/5: 2 (integer division: truncation) 13 % 5: 3 (remainder) Floating-point expressions: 2+4.0/5: 2.8 (floating-point division) 2.0+4/5: 2.0 (integer division) 4.0 / 0.0: INF (Infinity) 0.0 / 0.0: NAN(004) (Not-a-Number) Number limits: Integer.MAX_VALUE: Integer.MIN_VALUE: Long.MAX_VALUE: Long.MIN_VALUE: Float.MAX_VALUE: e+38 Float.MIN_VALUE: e-45 (Also applies to negative floating-point values.) Double.MAX_VALUE: e+308 Double.MIN_VALUE: e-308 Float.POSITIVE_INFINITY: INF Float.NEGATIVE_INFINITY: -INF Number over/underflow is not signaled! (NB! "Wrap-around" for integers.) Integer.MAX_VALUE +1: Integer.MIN_VALUE -1: Long.MAX_VALUE +1: Long.MIN_VALUE -1: Float.MAX_VALUE +1: e+38 Float.MIN_VALUE +1: 1.0 Double.MAX_VALUE +1: e+308 Double.MIN_VALUE +1: 1.0 Float.POSITIVE_INFINITY +1: INF Float.NEGATIVE_INFINITY -1: -INF JACT 2: Basic Programming Elements 2-23/30

24 Formatted output We can call the method printf() in the System.out object to print a formatted string to the terminal window, using a format string and an argument-list: printf(string formatstring, Object... argumentlist) A format string can contain both fixed text and format specifications. When calling the printf()-method, all arguments in the argument list will be sent to the method and formatted according to the format specifications in the format string. JACT 2: Basic Programming Elements 2-24/30

25 Example: Formatted output System.out.printf("Formatted output %6d %8.3f kr. %.2f %6s%n", 2004, Math.PI, , "hi!"); Output (with Norwegian locale as default): Formatted output ,142 kr. 1234,04 hi! The format string is the first parameter in the method call. The argument list consists of all parameters after the format string. In this case, there are 4 parameters: 2007, Math.PI, , "hi!". The format string contains 5 format specifications: %6d, %8.3f, %.2f, %6s and %n. The format specification specifies how the arguments will be processed, and the sequence says where the result of each argument will be placed in the format string. Type Format specification Argument Result Integer Integer Floating-point String %6d %8.3f %.2f %5s 2007 Math.PI "hi!" " 2007" " 3,142" "1234,04" " hi!" The format specification %n yields a newline where it occurs in the format string. JACT 2: Basic Programming Elements 2-25/30

26 It's now or never Flam ing Sta r S u spious M A n gel inds Reading numbers from the keyboard Any input the user writes on the keyboard is shown in the terminal window. How can a program read the input that the user types on the keyboard? This is called reading from the keyboard. System.in identifies the object that reads bytes from the keyboard. The class java.util.scanner offers methods for converting bytes to primitive data values. main() IntegerReader new Scanner(System.in) keyboard:scanner nextint() Screen 1 2 Keyboard Enter-key pressed JACT 2: Basic Programming Elements 2-26/30

27 Reading numbers from the keyboard How to read values from the keyboard: import java.util.scanner; // Imports Scanner-class.... Scanner keyboard = new Scanner(System.in); // Coupling a Scanner // to standard-in. // We can now call methods of the Scanner-class to read values from // the keyboard. int i = keyboard.nextint(); // Read an integer. double d = keyboard.nextdouble();// Read a floating-point value. String str = keyboard.nextline();// Read (rest of) the line as string.... JACT 2: Basic Programming Elements 2-27/30

28 Reading numbers from the keyboard Exercise: Extend Program 2.7 to read the sides of a cube, and calculate its volume. The user dialogue may look like the following, where user input is shown in bold: Enter the cube length [integer]: 12 Enter the cube breadth [integer]: 4 Enter the cube height [integer]: 7 A cube of length 12 cm, breadth 4 cm and height 7 cm has volume 336 cubic cm. JACT 2: Basic Programming Elements 2-28/30

29 Example: Reading numbers from the keyboard import java.util.scanner; /* Celsius to Fahrenheit: * 9 x celsius * * 5 */ public class Temperature { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Input temperature in degrees Celsius:"); double celsius = keyboard.nextdouble(); double fahr = (9.0 * celsius)/ ; System.out.println(celsius + " degrees Celsius corresponds to " + fahr + " degrees Fahrenheit."); } } JACT 2: Basic Programming Elements 2-29/30

30 Reading numbers from the keyboard Running the program: Input temperature in Celsius: 23, degrees Celsius corresponds to 74.3 degrees Fahrenheit. Note: The user inputs floating-point values using comma for decimal point because the program is using the Norwegian locale as default. The methods print() and println() print floating-point values using dotnotation. Exercise: Write a program that calculates the corresponding temperature in degrees Celsius when a temperature in degrees Fahrenheit is input by the user. The following formula converts a Fahrenheit temperature to Celsius: celsius = (fahr ) * 5.0 / 9.0; Check that the program behaves as expected by using a few Fahrenheit temperatures calculated by the Temperature class as input. JACT 2: Basic Programming Elements 2-30/30

Program Control Flow

Program Control Flow Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Program Control Flow

Program Control Flow Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

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

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

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 April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types

More information

More on control structures

More on control structures Lecture slides for: Chapter 5 More on control structures Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Computational Expression

Computational Expression Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

More information

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

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

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them

More information

CEN 414 Java Programming

CEN 414 Java Programming CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

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

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

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

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

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

More information

Chapter 2. Elementary Programming

Chapter 2. Elementary Programming Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

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

Elementary Programming

Elementary Programming Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

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

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

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

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

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

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 Java Foundations Introduction to Program Design and Data Structures 4th Edition Lewis TEST BANK Full download at : https://testbankreal.com/download/java-foundations-introduction-toprogram-design-and-data-structures-4th-edition-lewis-test-bank/

More information

Data Conversion & Scanner Class

Data Conversion & Scanner Class Data Conversion & Scanner Class Quick review of last lecture August 29, 2007 ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor: Alexander Stoytchev Numeric Primitive Data Storing

More information

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 ELEMENTARY PROGRAMMING Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple

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

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on: Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

More information

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming Lecture slides for: Chapter 6 Arrays Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 28. ISBN: 978-1-84448-933-2 http://www.ii.uib.no/~khalid/jac/

More information

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon

More information

Chapter 02: Using Data

Chapter 02: Using Data True / False 1. A variable can hold more than one value at a time. ANSWER: False REFERENCES: 54 2. The int data type is the most commonly used integer type. ANSWER: True REFERENCES: 64 3. Multiplication,

More information

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents Variables in a programming language Basic Computation (Savitch, Chapter 2) TOPICS Variables and Data Types Expressions and Operators Integers and Real Numbers Characters and Strings Input and Output Variables

More information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

More information

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 02 Data Types and Statements MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Constants Data Types

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

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

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical

More information

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 2 Elementary Programming 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems

More information

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution Chapter 2: Elementary Programming CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations In the preceding chapter, you learned how to

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

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

Introduction to Java Applications; Input/Output and Operators

Introduction to Java Applications; Input/Output and Operators www.thestudycampus.com Introduction to Java Applications; Input/Output and Operators 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text 2.3 Modifying Your First Java Program 2.4 Displaying

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Walter Savitch Frank M. Carrano Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers

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

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 August 21, 2017 Chapter 2: Data and Expressions CS 121 1 / 51 Chapter 1 Terminology Review

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

CS 302: Introduction to Programming

CS 302: Introduction to Programming CS 302: Introduction to Programming Lectures 2-3 CS302 Summer 2012 1 Review What is a computer? What is a computer program? Why do we have high-level programming languages? How does a high-level program

More information

COMP 110 Introduction to Programming. What did we discuss?

COMP 110 Introduction to Programming. What did we discuss? COMP 110 Introduction to Programming Fall 2015 Time: TR 9:30 10:45 Room: AR 121 (Hanes Art Center) Jay Aikat FB 314, aikat@cs.unc.edu Previous Class What did we discuss? COMP 110 Fall 2015 2 1 Today Announcements

More information

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

BASIC INPUT/OUTPUT. Fundamentals of Computer Science BASIC INPUT/OUTPUT Fundamentals of Computer Science Outline: Basic Input/Output Screen Output Keyboard Input Simple Screen Output System.out.println("The count is " + count); Outputs the sting literal

More information

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java Chapter 3 Syntax, Errors, and Debugging Objectives Construct and use numeric and string literals. Name and use variables and constants. Create arithmetic expressions. Understand the precedence of different

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

Peer Instruction 1. Elementary Programming

Peer Instruction 1. Elementary Programming Peer Instruction 1 Elementary Programming 0 Which of the following variable declarations will not compile? Please select the single correct answer. A. int i = 778899; B. double x = 5.43212345; C. char

More information

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 02 Data Types and Statements MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Data Types Arithmetic

More information

COMP6700/2140 Operators, Expressions, Statements

COMP6700/2140 Operators, Expressions, Statements COMP6700/2140 Operators, Expressions, Statements Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU 3 March 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140 Operators,

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

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 2 Primitive Data Types and Operations. Objectives Chapter 2 Primitive Data Types and Operations Prerequisites for Part I Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs,

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

These are reserved words of the C language. For example int, float, if, else, for, while etc.

These are reserved words of the C language. For example int, float, if, else, for, while etc. Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Welcome to the Primitives and Expressions Lab!

Welcome to the Primitives and Expressions Lab! Welcome to the Primitives and Expressions Lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 2 terms. 2. Describe declarations, variables, literals and constants for primitive

More information

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.

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

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

More information

CS110: PROGRAMMING LANGUAGE I

CS110: PROGRAMMING LANGUAGE I CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 4: Java Basics (II) A java Program 1-2 Class in file.java class keyword braces {, } delimit a class body main Method // indicates a comment.

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

Input. Scanner keyboard = new Scanner(System.in); String name;

Input. Scanner keyboard = new Scanner(System.in); String name; Reading Resource Input Read chapter 4 (Variables and Constants) in the textbook A Guide to Programming in Java, pages 77 to 82. Key Concepts A stream is a data channel to or from the operating system.

More information

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

Arithmetic and IO. 25 August 2017

Arithmetic and IO. 25 August 2017 Arithmetic and IO 25 August 2017 Submissions you can submit multiple times to the homework dropbox file name: uppercase first letter, Yourlastname0829.java the system will use the last submission before

More information

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

More information

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals Chapter Four: Fundamental Data Types Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware of causes for overflow and roundoff

More information

STUDENT LESSON A7 Simple I/O

STUDENT LESSON A7 Simple I/O STUDENT LESSON A7 Simple I/O Java Curriculum for AP Computer Science, Student Lesson A7 1 STUDENT LESSON A7 Simple I/O INTRODUCTION: The input and output of a program s data is usually referred to as I/O.

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 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

Building Java Programs

Building Java Programs Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 2 Data and expressions reading: 2.1 3 The computer s view Internally, computers store everything as 1 s and 0

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 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

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved. Chapter 4 Fundamental Data Types ICOM 4015: Advanced Programming Lecture 4 Reading: Chapter Four: Fundamental Data Types Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

More information

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved. Chapter 4 Fundamental Data Types Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware of causes for overflow and roundoff errors

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

double float char In a method: final typename variablename = expression ;

double float char In a method: final typename variablename = expression ; Chapter 4 Fundamental Data Types The Plan For Today Return Chapter 3 Assignment/Exam Corrections Chapter 4 4.4: Arithmetic Operations and Mathematical Functions 4.5: Calling Static Methods 4.6: Strings

More information

I. Variables and Data Type week 3

I. Variables and Data Type week 3 I. Variables and Data Type week 3 variable: a named memory (i.e. RAM, which is volatile) location used to store/hold data, which can be changed during program execution in algebra: 3x + 5 = 20, x = 5,

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

2.5 Another Application: Adding Integers

2.5 Another Application: Adding Integers 2.5 Another Application: Adding Integers 47 Lines 9 10 represent only one statement. Java allows large statements to be split over many lines. We indent line 10 to indicate that it s a continuation of

More information

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Topics 1. Expressions 2. Operator precedence 3. Shorthand operators 4. Data/Type Conversion 1/15/19 CSE 1321 MODULE 2 2 Expressions

More information

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long Primitive Types Four integer types: byte short int (most common) long Two floating-point types: float double (most common) One character type: char One boolean type: boolean 1 2 Primitive Types, cont.

More information

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14 int: integers, no fractional part 1, -4, 0 double: floating-point numbers (double precision) 0.5, -3.11111, 4.3E24, 1E-14 A numeric computation overflows if the result falls outside the range for the number

More information

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Computer Programming, I. Laboratory Manual. Experiment #3. Selections Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3

More information

CIS 110: Introduction to Computer Programming

CIS 110: Introduction to Computer Programming CIS 110: Introduction to Computer Programming Lecture 3 Express Yourself ( 2.1) 9/16/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline 1. Data representation and types 2. Expressions 9/16/2011

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

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

Chapter. Let's explore some other fundamental programming concepts

Chapter. Let's explore some other fundamental programming concepts Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

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

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13 CHAPTER 2 Define a method vs. calling a method Line 3 defines a method called main Line 5 calls a method called println, which is defined in the Java library You will learn later how to define your own

More information

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information