# Basic Computation. Chapter 2

Size: px
Start display at page:

Transcription

1 Walter Savitch Frank M. Carrano Basic Computation Chapter 2

2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style

3 Variables Variables store data such as numbers and letters. Think of them as places to store data. They are implemented as memory locations. The data stored by a variable is called its value. The value is stored in the memory location. Its value can be changed as a program runs

5 Naming and Declaring Variables Choose names that are helpful such as count or speed, but not c or s. When you declare a variable, you provide its name and type. int numberofbaskets,eggsperbasket; A variable's type determines what kinds of values it can hold (int, double, char, etc.). A variable must be declared before it is used.

6 Syntax and Examples Syntax type variable_1, variable_2, ; (variable_1 is a generic variable called a syntactic variable) Examples int stylechoice, numberofchecks; double balance, interestrate; char jointorindividual;

7 Data Types A class type is used for a class of objects and has both data and methods. "Java is fun" is a value of class type String A primitive type is used for simple, nondecomposable values such as an individual number or individual character. int, double, and char are primitive types.

8 Primitive Types Figure 2.1 Primitive Types

9 Java Identifiers An identifier is a name, such as the name of a variable. Identifiers may contain only Letters Digits (0 through 9) The underscore character (_) And the dollar sign symbol (\$) which has a special meaning The first character cannot be a digit.

10 Java Identifiers Identifiers may not contain any spaces, dots (.), asterisks (*), or other characters: 7-11 netscape.com util.* (not allowed) Identifiers can be arbitrarily long. Since Java is case sensitive, stuff, Stuff, and STUFF are different identifiers.

11 Keywords or Reserved Words Words such as if are called keywords or reserved words and have special, predefined meanings. Cannot be used as identifiers. See Appendix 1 for a complete list of Java keywords. Example keywords: int, public, class

12 Naming Conventions Class types begin with an uppercase letter (e.g. String). Primitive types begin with a lowercase letter (e.g. int). Variables of both class and primitive types begin with a lowercase letters (e.g. myname, mybalance). Multiword names are "punctuated" using uppercase letters.

13 Where to Declare Variables Declare a variable Just before it is used or At the beginning of the section of your program that is enclosed in {}. public static void main(string[] args){ /* declare variables here */... }

14 Primitive Types Four integer types (byte, short, int, and long) int is most common Two floating-point types (float and double) double is more common One character type (char) One boolean type (boolean)

15 Examples of Primitive Values Integer types Floating-point types Character type 'a' 'A' '#' ' ' Boolean type true false

16 Assignment Statements An assignment statement is used to assign a value to a variable. answer = 42; average = sum / count; firstinitial = 'W'; done = true;

17 Initializing Variables A variable that has been declared, but no yet given a value is said to be uninitialized. Uninitialized class variables have the value null. Uninitialized primitive variables may have a default value. It's good practice not to rely on a default value.

18 Initializing Variables To protect against an uninitialized variable (and to keep the compiler happy), assign a value at the time the variable is declared. Examples: int count = 0; char grade = 'A';

19 Assignment Evaluation The expression on the right-hand side of the assignment operator (=) is evaluated first. The result is used to set the value of the variable on the left-hand side of the assignment operator. score = numberofcards + handicap; eggsperbasket = eggsperbasket - 2;

20 Simple Input Download EggBasket2.java Keyboard input can be done using a Scanner object At the top of the source file: import java.util.*; Data can be entered from the keyboard using Scanner keyboard = new Scanner(System.in); followed, for example, by eggsperbasket = keyboard.nextint();

21 Simple Screen Output System.out.println("The count is " + count); Outputs the string literal "the count is " Followed by the current value of the variable count.

22 Constants Literal expressions such as 2, 3.7, or 'y' are called constants. Integer constants can be preceded by a + or - sign, but cannot contain commas.

23 Named Constants Java provides mechanism to Define a variable Initialize it Fix the value so it cannot be changed public static final Type Variable = Constant; Example public static final int MAX_ENTRIES = 100;

24 Assignment Compatibilities Java is said to be strongly typed. You can't, for example, assign a floating point value to a variable declared to store an integer. Sometimes conversions between numbers are possible. doublevariable = 7; is possible even if doublevariable is of type double, for example.

25 Type Casting A type cast temporarily changes the value of a variable from the declared type to some other type. For example, double distance = 9.5; int points = (int) distance; //truncates Illegal without (int)

26 Arithmetic Operators Arithmetic expressions can be formed using the +, -, *, and / operators together with variables or numbers referred to as operands. When both operands are of the same type, the result is of that type. When one of the operands is a floating-point type and the other is an integer, the result is a floating point type.

27 Arithmetic Operations Example If hoursworked is an int to which the value 40 has been assigned, and payrate is a double to which 8.25 has been assigned hoursworked * payrate is a double with a value of

28 The Division Operator The division operator (/) behaves as expected if one of the operands is a floating-point type. When both operands are integer types The result is also an integer type The result is truncated, not rounded. Hence, 99/100 has a value of 0. Try it out in the interactions pane: 99 / / 5

29 The mod Operator The mod (%) operator is used with operators of integer type to obtain the remainder after integer division. 14 divided by 4 is 3 with a remainder of 2. Hence, 14 % 4 is equal to 2. The mod operator has many uses, including determining if an integer is odd or even determining if one integer is evenly divisible by another integer.

30 Parentheses and Precedence Parentheses can communicate the order in which arithmetic operations are performed examples: (cost + tax) * discount cost + (tax * discount) Without parentheses, an expressions is evaluated according to the rules of precedence.

31 Precedence Rules Figure 2.2 Precedence Rules

32 Precedence Rules Even when parentheses are not needed, they can be used to make the code clearer. balance + (interestrate * balance) Spaces also make code clearer balance + interestrate*balance but spaces do not dictate precedence.

33 Sample Expressions Figure 2.3 Some Arithmetic Expressions in Java

34 Specialized Assignment Operators Assignment operators can be combined with arithmetic operators ( -, +, *, /, and %). amount = amount + 5; can be written as amount += 5; yielding the same results.

35 Specialized Assignment Operators Try it out: int amount = 20; amount -= 5; amount *= 3;

36 Increment and Decrement Operators Used to increase (or decrease) the value of a variable by 1 Easy to use, important to recognize The increment operator count++ or ++count The decrement operator count-- or --count

37 Increment and Decrement Operators equivalent operations count++; ++count; count = count + 1; count--; --count; count = count - 1;

38 Increment and Decrement Operators in Expressions after executing int m = 4; int result = 3 * (++m); result has a value of 15 and m has a value of 5 after executing int m = 4; int result = 3 * (m++); result has a value of 12 and m has a value of 5 Avoid using ++ and -- in expressions

39 The Class String We've used constants of type String already. "Enter a whole number from 1 to 99." A value of type String is a Sequence of characters Treated as a single item.

40 String Constants and Variables Declaring String greeting; greeting = "Hello!"; or String greeting = "Hello!"; or String greeting = new String("Hello!"); Printing System.out.println(greeting);

41 Concatenation of Strings Two strings are concatenated using the + operator. String greeting = "Hello"; String sentence; sentence = greeting + " officer"; System.out.println(sentence); Any number of strings can be concatenated using the + operator.

42 Concatenating Strings and Integers String solution; solution = "The answer is " + 42; System.out.println (solution); The temperature is 72 The answer is 42

43 String Methods An object of the String class stores data consisting of a sequence of characters. Objects have methods as well as data The length() method returns the number of characters in a particular String object. String greeting = "Hello"; int n = greeting.length();

44 The Method length() The method length() returns an int. You can use a call to method length() anywhere an int can be used. int count = command.length(); System.out.println("Length is " + command.length()); count = command.length() + 3;

45 Figure 2.4 String Indices Positions start with 0, not 1. The 'J' in "Java is fun." is in position 0 A position is referred to an an index. The 'f' in "Java is fun." is at index 8.

46 String Methods Follow the Java API link on the course webpage Find the String class Try out these methods length charat indexof substring equals and equalsignorecase touppercase and tolowercase

47 String Processing No methods allow you to change the value of a String object. But you can change the value of a String variable. Download, compile, and run StringDemo.java

48 Escape Characters How would you print "Java" refers to a language.? The compiler needs to be told that the quotation marks (") do not signal the start or end of a string, but instead are to be printed. System.out.println( "\"Java\" refers to a language.");

49 Escape Characters Figure 2.6 Each escape sequence is a single character even though it is written with two symbols.

50 Examples System.out.println("abc\\def"); abc\def System.out.println("new\nline"); new line char singlequote = '\''; System.out.println (singlequote); '

51 The Unicode Character Set Java uses the Unicode character set which includes characters from many different alphabets. Each character has a 4-digit hex (base 16) code 043f A useful website for looking up unicodes Example: printing the small letter u with circumflex System.out.println("\u043f");

52 Screen Output We've seen several examples of screen output already. System.out is an object that is part of Java. println() is one of the methods available to the System.out object. Use print when the next item printed should continue on the same line Use println when the next item printed should start on a new line

53 Screen Output The concatenation operator (+) is useful when everything does not fit on one line. System.out.println("Lucky number = " "Secret number = " + number); Do not break the line except immediately before or after the concatenation operator (+).

54 Screen Output Print One, two, three, four. : System.out.print("One, two,"); System.out.println(" three, four."); OR System.out.println("One, two," + " three, four."); ILLEGAL to continue string on next line: System.out.println("One, two, three, four.");

55 Keyboard Input Java's Scanner class has reasonable facilities for handling keyboard input. The Scanner class is part of the java.util package. A package is a library of classes.

56 Using the Scanner Class Near the beginning of your program, insert import java.util.scanner; Create an object of the Scanner class Scanner keyboard = new Scanner (System.in); Read data (an int or a double, for example) int n1 = keyboard.nextint(); double d1 = keyboard.nextdouble(); Download, compile and run ScannerDemo.java

57 Scanner Methods The next method simply reads all the characters up to the next whitespace There is a nextx method for each of the primitive types (nextint, nextboolean, nextdouble...) skip whitespace, including newlines, until a nonwhitespace character is encountered read the characters up to the next whitespace convert the characters read to the appropriate type (int, boolean, double...)

58 nextline()method Caution The nextline() method reads The remainder of the current line, Even if it is empty.

59 nextline()method What gets printed? import java.util.*; public class SandBox { public static void main(string[] args) { int n; String s1, s2; Scanner keyboard = new Scanner(System.in); } } n = keyboard.nextint(); s1 = keyboard.nextline(); s2 = keyboard.nextline(); System.out.println(n); System.out.println(s1); System.out.println(s2); 42 and don't you forget it. 42 is the answer and don't you forget it.

60 nextline()method What gets printed? import java.util.*; public class SandBox { public static void main(string[] args) { int n; String s1, s2; Scanner keyboard = new Scanner(System.in); n = keyboard.nextint(); keyboard.nextline(); s1 = keyboard.nextline(); s2 = keyboard.nextline(); 42 is the answer and don't you forget it. } } System.out.println(n); System.out.println(s1); System.out.println(s2); 42 and don't you forget it.

61 Exercise Write a program called AddressReader that reads keyboard data in the following format: lastname age address then prints all 3 data values on separate lines. Sample input: Smith 21 Hauptstr 4, Kleindorf

62 Exercise import java.util.*; public class AddressReader { public static void main(string[] args) { int age = 0; String lastname = "", address = ""; Scanner keyboard = new Scanner(System.in); lastname = keyboard.next(); age = keyboard.nextint(); keyboard.nextline(); address = keyboard.nextline(); } } System.out.println(age + "\n" + lastname + "\n" + address);

63 The Empty String A string can have any number of characters, including zero. The string with zero characters is called the empty string. The empty string is useful and can be created in many ways including String s3 = "";

64 The Empty String Not allowed to call methods on a null object Try this out in the interactions pane: String str; int strlen; strlen = str.length(); //NullPointerException str = ""; strlen = str.length(); // strlen is now 0

65 Documentation and Style Most programs are modified over time to respond to new requirements. Programs which are easy to read and understand are easy to modify. Even if it will be used only once, you have to read it in order to debug it.

66 Meaningful Variable Names A variable's name should suggest its use. Observe conventions in choosing names for variables. Use only letters and digits. "Punctuate" using uppercase letters at word boundaries (e.g. taxrate, firstname). Start variables with lowercase letters. Start class names with uppercase letters.

67 Comments The best programs are self-documenting. Clean style Well-chosen names Comments are written into a program as needed to explain the program. They are useful to the programmer, but they are ignored by the compiler.

68 Comments A comment can begin with //. Everything after these symbols and to the end of the line is treated as a comment and is ignored by the compiler. double radius; //in centimeters

69 Comments A comment can begin with /* and end with */ Everything between these symbols is treated as a comment and is ignored by the compiler. /* This program should only be used on alternate Thursdays, except during leap years, when it should only be used on alternate Tuesdays. */

70 When to Use Comments Begin each program file with an explanatory comment What the program does The name of the author Contact information for the author Date of the last modification. Provide only those comments which the expected reader of the program file will need in order to understand it.

71 javadoc Comments A javadoc comment, begins with /** and ends with */. It can be extracted automatically from Java software. /** * method change requires the * number of coins to be * nonnegative */

72 javadoc Comments Add the following javadoc comment right above the class definition in the program you wrote earlier: /** * Program to practice using a Scanner. */ Add this javadoc comment right above the main method: /** * Read stuff from the keyboard. Uses * nextline to skip remainder of a line. */ Tools -> Javadoc -> Preview Javadoc for Current Document

73 Indentation Programs have a lot of structure Methods are a part of class definitions Variable declarations and code are parts of a method We say that some parts are nested within others Indentation should be consistent and communicate nesting clearly.

74 DrJava configuration IDEs like drjava can be configured to act the way we want them to: Edit -> Preferences Miscellaneous Indent Level : 4 check box: Automatically Close Block Comments Resource Locations set web browser (/usr/bin/konqueror???) Display Options check box: Show All Line Numbers Notifications

75 Indentation with DrJava Indent a single line of code: Press the tab key Indent the whole program: Type Strg-a (or choose Edit->Select All) Press the tab key (or choose Edit->Indent Lines(s)

76 Using Named Constants To avoid confusion, always name constants. area = PI * radius * radius; is clearer than area = * radius * radius; Place constants near the beginning of the program (not inside a method).

77 Named Constants Once the value of a constant is set (or changed by an editor), it can be used (or reflected) throughout the program. public static final double INTEREST_RATE = 6.65; If a literal (such as 6.65) is used instead, every occurrence must be changed, with the risk that another literal with the same value might be changed unintentionally.

78 Declaring Constants Syntax public static final Type Name = Value; Examples public static final double PI = ; public static final String MOTTO = "The customer is always right."; By convention, uppercase letters are used for constants. Compare CircleCalculation.java and CircleCalculation2.java

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

### Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

Basic Computation Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly Parentheses and Precedence Parentheses can communicate the order in which arithmetic operations are performed examples: (cost +

### Basic Computation. Chapter 2

Basic Computation Chapter 2 Increment and Decrement Operators Used to increase (or decrease) the value of a variable by 1 Easy to use, important to recognize The increment operator count++ or ++count The

### Objectives. Primitive Types, Strings, and Console I/O. Variables and Values. Outline. Naming and Declaring Variables. Variables and Values

Objectives Primitive Types, Strings, and Console I/O Chapter 2 become familiar with Java primitive types (numbers, characters, etc.) learn about assignment statements and expressions learn about strings

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

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

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

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

### MODULE 02: BASIC COMPUTATION IN JAVA

MODULE 02: BASIC COMPUTATION IN JAVA Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment

### PROGRAMMING STYLE. Fundamentals of Computer Science I

PROGRAMMING STYLE Fundamentals of Computer Science I Documentation and Style: Outline Meaningful Names Comments Indentation Named Constants Whitespace Compound Statements Documentation and Style Most programs

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

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

### DATA TYPES AND EXPRESSIONS

DATA TYPES AND EXPRESSIONS Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment Mathematical

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

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

### CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]

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

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

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

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

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

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

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

### Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,

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

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

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

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

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

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

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

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

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

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

### CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

CSE 1001 Fundamentals of Software Development 1 Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 Identifiers, Variables and Data Types Reserved Words Identifiers in C Variables and Values

### COMP String and Console I/O. Yi Hong May 18, 2015

COMP 110-001 String and Console I/O Yi Hong May 18, 2015 Announcements Labs 0 & 1 are due today by 11:59pm Homework 0 grades are posted Office hours are fixed: MW 3-4pm, or by appointment Review of How

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

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

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

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

### COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

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

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

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

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

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

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

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

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

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

### Chapter 2 Primitive Data Types and Operations

Chapter 2 Primitive Data Types and Operations 2.1 Introduction You will be introduced to Java primitive data types and related subjects, such as variables constants, data types, operators, and expressions.

### Introduction to Software Development (ISD) David Weston and Igor Razgon

Introduction to Software Development (ISD) David Weston and Igor Razgon Autumn term 2013 Course book The primary book supporting the ISD module is: Java for Everyone, by Cay Horstmann, 2nd Edition, Wiley,

### What did we talk about last time? Examples switch statements

Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

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

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

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

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

### Basic Programming Elements

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, 2008. ISBN: 978-1-844480-933-2

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

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

### CHAPTER 2 Java Fundamentals

CHAPTER 2 Java Fundamentals Copyright 2016 Pearson Education, Inc., Hoboken NJ Chapter Topics Chapter 2 discusses the following main topics: The Parts of a Java Program The print and println Methods, and

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

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

### TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

### Oct Decision Structures cont d

Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

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

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

### Chapter 4: Conditionals and Recursion

Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Agenda The modulus operator Random Number Generation Conditional Execution Alternative

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

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

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

### COMP 202. Java in one week

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

### Chapter 1 Introduction to java

Chapter 1 Introduction to java History of java Java was created by by Sun Microsystems team led by James Gosling (1991) It was mainly used for home appliance, it later became a general purpose programming

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

### Important Java terminology

1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as

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

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

### Datatypes, Variables, and Operations

Datatypes, Variables, and Operations 1 Primitive Type Classification 2 Numerical Data Types Name Range Storage Size byte 2 7 to 2 7 1 (-128 to 127) 8-bit signed short 2 15 to 2 15 1 (-32768 to 32767) 16-bit

### Program Elements -- Introduction

Program Elements -- Introduction We can now examine the core elements of programming Chapter 3 focuses on: data types variable declaration and use operators and expressions decisions and loops input and

### Flow of Control. Chapter 3

Walter Savitch Frank M. Carrano Flow of Control Chapter 3 Outline The if-else statement The Type boolean The switch statement Flow of Control Flow of control is the order in which a program performs actions.

### Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ 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

### Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

### BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

### We now start exploring some key elements of the Java programming language and ways of performing I/O

We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects

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

### Darrell Bethea May 25, 2011

Darrell Bethea May 25, 2011 Yesterdays slides updated Midterm on tomorrow in SN014 Closed books, no notes, no computer Program 3 due Tuesday 2 3 A whirlwind tour of almost everything we have covered so

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

### Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

### STUDENT LESSON A10 The String Class

STUDENT LESSON A10 The String Class Java Curriculum for AP Computer Science, Student Lesson A10 1 STUDENT LESSON A10 The String Class INTRODUCTION: Strings are needed in many programming tasks. Much of

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

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

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

### Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

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

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

### 2: Basics of Java Programming

2: Basics of Java Programming CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### What methods does the String class provide for ignoring case sensitive situations?

Nov. 20 What methods does the String class provide for ignoring case sensitive situations? What is a local variable? What is the span of a local variable? How many operands does a conditional operator

### FUNDAMENTAL DATA TYPES

CHAPTER 2 FUNDAMENTAL DATA TYPES Copyright 2013 by John Wiley & Sons. All rights reserved. Slides by Donald W. Smith TechNeTrain.com Final Draft Oct. 15, 2011 Chapter Goals To declare and initialize variables