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

Size: px
Start display at page:

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

Transcription

1 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 store information You can think of them like boxes They hold values The value of a variable is its current contents Note that this differs from variable in math In math, a variable is an unknown Solving an equation reveals its value In programming, variables are place holders for values Their current value is always known The program changes their values to achieve a goal CS 160, Spring Semester Data Types Variables are like boxes: they hold values But you can t put an elephant in a shoe box Different boxes hold different types of things Therefore, variables have data types The data type describes the set of values a variable might contain The value of a variable is a member of the set defined by its data type Examples: int, char, double, boolean, String Java is a strongly typed language only values of the correct type can be put into a variable Creating Variables You create new variables through declarations. Examples: int daysperyear; char vowel; You assign values to variables using the assignment operator =. Examples: daysperyear = 365; vowel = a ; Declaration and assignment can be combined. Examples: int price = 25; char c = & ; CS 160, Spring Semester CS 160, Spring Semester

2 More about Variables Literals An uninitialized variable is useless So it s good practice to initialize when declaring variables can be done with one statement: int daysperyear = 365; Variables can be re-used: int daysperyear = 365; // random code here daysperyear = 110; Literals are values that are directly recognized by Java: numbers 237, 10, 9, 1.5, 5.8, characters a, Z, 0, \$ strings hello, there CS 160, Spring Semester CS 160, Spring Semester Java Identifiers 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. 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. CS 160, Spring Semester CS 160, Spring Semester

3 Keywords or Reserved Words Naming Conventions 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. Examples: int, public, class 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. CS 160, Spring Semester CS 160, Spring Semester Where to Declare Variables Java Types 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 */... /* code starts here */... In Java, there are two kinds of data types: Primitive data types Hold a single, indivisible piece of data Let s start with these Pre-defined by the language Examples: int, char, double, boolean Classes Hold complex combinations of data Programs may define new classes Examples: String, System CS 160, Spring Semester CS 160, Spring Semester

4 Primitive Types Primitive Data Types Integer types: byte, short, int, and long int is most common Floating-point types: float and double double is more common Character type: char Boolean type: boolean The 4 most common primitive data types Data Type Description Example int - integer values 5 double - floating-point values 3.14 char - characters J boolean - either true or false true CS 160, Spring Semester Notice there are no quotes around true! CS 160, Spring Semester Primitive Types Assignment Statements An assignment statement is used to assign a value to a variable. answer = 42; The "equal sign" is called the assignment operator. We say, "The variable named answer is assigned a value of 42," or more simply, "answer is assigned 42. General rule: Var = expression; CS 160, Spring Semester CS 160, Spring Semester

5 Building expressions: operators Operators can act on numbers and primitive data types + adds two numbers * multiplies two numbers - subtracts two numbers / divides two numbers == tests for equality and returns a Boolean Operators can also act on other expressions build arbitrarily complicated expressions (just like math) Expressions A program is a sequence of statements Well, it also needs a header But the program body lists statements Simplest statement is an assignment A simple expression looks like: var1 op var2; Where var1 and var2 are variables op is any operator (e.g. +, -, *) CS 160, Spring Semester CS 160, Spring Semester Variations on Expressions Variables can be re-used across and even within expressions: int x = 7; x = x + 1; x = x + x; Right hand side is evaluated and the result is assigned to the lhs variable CS 160, Spring Semester More variations on expressions The right hand side of an assignment can be any mathematical expression: int y = x + (2 * z); When more than one operator appears Parenthesis disambiguate See above Without parenthesis, operator precedence rules apply e.g., multiply before add, left before right Better to rely on parentheses CS 160, Spring Semester

6 Integers Integer Arithmetic Operations Numbers without fractional parts 3, 47, -12 Variables store integers with an assignment statement int size = 7; Integer variables may be used like integer literals (i.e., number), e.g., size = size + 1; Symbol Operation Example Evaluates to + Addition Subtraction * Multiplication 7000 * / Division 13 / 7 1 % Remainder 13 % 7 6 CS 160, Spring Semester CS 160, Spring Semester Remainder reminder: % and / Integer Math For any pair of integers, x and y, there always exist two unique integers, q and r, such that x = qy + r and 0 r < y q is called the quotient, r is the remainder when x is divided by y The operators, % and / compute them: r = x % y and q = x / y Java isn t mathematically correct for negative numbers CS 160, Spring Semester int i = 10/3; What s i =? int j = 10 % 3; What s j =? int k = 13 % 5 / 2; What s k =? CS 160, Spring Semester

7 Additional Integer Operators Specialized Assignment Operators Self-assignment int temperature = 32; temperature = temperature + 10; What is temperature? 42 Increment cent++; equivalent to cent = cent + 1; Decrement cent--; equivalent to cent = cent 1; Assignment operators can be combined with arithmetic operators including -, *, /, %. amount = amount + 5; can be written as amount += 5; yielding the same results. CS 160, Spring Semester CS 160, Spring Semester Parentheses and Precedence Precedence Rules 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. Figure 2.2 Precedence Rules CS 160, Spring Semester CS 160, Spring Semester

8 Precedence Rules Sample Expressions The binary arithmetic operators *, /, and %, have lower precedence than the unary operators +, -, ++, --, and!, but have higher precedence than the binary arithmetic operators + and -. When binary operators have equal precedence, the operator on the left acts before the operator(s) on the right. CS 160, Spring Semester CS 160, Spring Semester Real Numbers double Arithmetic Operations Also called floating-point numbers Numbers with fractional parts , 7.12, 9.0, 0.5e001, -16.3e+002 Declared using the data type double double priceperpound = 3.99, taxrate = 0.05, shippingcost = 5.55; double pctprofit = ; Symbol Operation Example + Addition Subtraction * Multiplication 70.0 * 3.0 / Division 96.0 / 2.0 CS 160, Spring Semester CS 160, Spring Semester

9 Numbers in Java Numbers in Java int is of fixed size; a value that is too large to be stored in an int variable will not match the mathematical value. Example: int x = * ; out.println( x ); Numerical overflow! Will print: No warning messages! It is not always possible to test double expressions for equality and obtain a correct result because of rounding errors (called floating point error ). Should public class ProblemDoublePrecision be zero! public static void main( String[ ] args ) double val = 1.0/ / / ; System.out.println( val ); CS 160, Spring Semester CS 160, Spring Semester Numbers in Java How should you handle floating point error? Test to see if the value is within a margin of error public class CheckDoubleEquality public static void main( String[ ] args ) double val = 1.0/ / / ; if ( Math.abs(val) < ) val = 0; System.out.println( val ); Tolerance up to CS 160, Spring Semester Assignment Compatibilities Java is strongly typed. You can't, for example, assign a floating point value to a variable declared to store an integer. But for convenience, some conversions between numbers are possible doublevariable = 7; is possible even if doublevariable is of type double, for example. CS 160, Spring Semester

10 Assignment Compatibilities Type Casting A value of each following type can be assigned to a variable of type to the right: byte à short à int à long à float à double but not to a variable of any type to the left. You can assign a value of type char to a variable of type int. except through type casting CS 160, Spring Semester A type cast changes the value of a variable from the declared type to some other type. For example, double distance; distance = 9.0; int points; points = (int)distance; Illegal without (int) CS 160, Spring Semester Type Casting Mixing Numeric Data Types The value of (int)distance is 9, The value of distance, both before and after the cast, is 9.0. The fractional part (to the right of the decimal point) is truncated rather than rounded. CS 160, Spring Semester Widening conversion Java will automatically convert int expressions to double values without loss of information int i = 5; double x = i ; double y = i; Arithmetic promotion of i to largest data type double assignment promotion of i Narrowing conversion To convert double expressions to int requires a typecasting operation and truncation will occur i = 20 : the.6 is truncated i = (int) (10.3 * 2); To round-up instead of truncating add 0.5 i = (int) (10.3 * x + 0.5); CS 160, Spring Semester

11 Characters Important Literal Characters Any key you type on the keyboard generates a character which may or may not be displayed on the screen (e.g., nonprinting characters) Characters are a primitive type in Java and are not equivalent to Strings Examples char vitamin = A, chromosome = y, middleinitial = N ; A,, Z Uppercase letters a,, z Lowercase letters 0,, 9 Digits.,,,!,,etc. Punctuation Marks Blank \n New line \t Tab \\ Backslash \ Single Right Quote CS 160, Spring Semester CS 160, Spring Semester The other meta-type: Classes A primitive data type is indivisible They have no meaningful subparts The primitives are defined by the language int, char, double, etc. A class is a data type that contains many bits of information For example, Strings (many primitive chars) Many classes defined by the language You can also define new ones Classes Classes have data and methods The data may be primitives or collections of primitives, other even classes. Methods are used instead of operators The period (. ) accesses methods of a class: String greeting = hello ; char c = greeting.charat(0); // c now equals h CS 160, Spring Semester CS 160, Spring Semester

12 More about Strings String is defined in the java.lang package The java.lang package is automatically included in all programs, so you do not need to import it. String literals are defined in double-quotes; Examples: String t1 = To be ; String t2 = or not to be ; System.out.println(t1.concat(t2)); // prints To be or not to be CS 160, Spring Semester Name int length() String Methods int indexof(string s) String substring (int beginx, int endx) String touppercase() Description Returns the length of this string Returns the index within the string of the first occurrence of the string s. Returns the substring beginning at index beginx and ending at index endx-1 Converts all characters of the string to uppercase String concat(string s) Concatenates the string s to the end of the original string char charat(int index) Returns the character at the index, which must be between 0 and length of string - 1 CS 160, Spring Semester Syntax: primitives vs classes String Method Examples Operators act on primitive variables Examples: +. -, *, % Standard math in-fix notation x + y; y / 7; Methods act on class variables Example: length() Notation: class.method(arguments) String s1 = foo ; int x = s1.length(); CS 160, Spring Semester CS 160, Spring Semester

13 Object Examples Input/Output (I/O) Scanner instance is an object (not primitive) Methods for the Scanner class include nextint ß returns next sequence as integer nextdouble ß returns next sequence as double next ß returns next sequence of chars read until the next whitespace (spaces, tabs, end of line) nextline ß returns next line up until enter key reads Q: Without a graphical user interface (GUI), how does a program communicate with user? A: Must use the console for output, keyboard for input. Console Output Keyboard Input CS 160, Spring Semester CS 160, Spring Semester Console We've seen several examples of console output already. System.out is the output object in Java. Question: Is there a System.in for input? println() is one of the methods available to the System.out object. print() is another method, which is identical to println() without line termination. Screen Output The concatenation operator (+) is useful when everything does not fit on one line. System.out.println( "Lucky number = " "Secret number = " + number); Beware of dual use of + for addition and concatenation: System.out.println( 5+3= ); CS 160, Spring Semester CS 160, Spring Semester

14 Keyboard Input Using the Scanner Class Java has reasonable facilities for handling keyboard input. These facilities are provided by the Scanner class in the java.util package. A package is a library of classes. 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(); CS 160, Spring Semester CS 160, Spring Semester More Scanner Class Some Scanner Class Methods From util package import java.util.scanner; System.in refers to the keyboard Create a new instance: Scanner in = new Scanner( System.in ); Input (depends on data type reading in) String input = in.next( ); String line = in.nextline( ); int intval = in.nextint( ); double dblval = in.nextdouble( ); CS 160, Spring Semester CS 160, Spring Semester

15 Reading Integers Reading Strings import java.util.*; public class getinput public static void main( String[ ] args ) Scanner in; int intval; in = new Scanner( System.in ); System.out.println("Enter an integer: "); intval = in.nextint( ); import java.util.*; public class getstringinput public static void main( String[ ] args ) Scanner in; String name; in = new Scanner( System.in ); System.out.println("Enter your name: "); name = in.next( ); System.out.println( intval ); CS 160, Spring Semester System.out.println( name ); CS 160, Spring Semester nextline()method Caution nextline Method Caution The nextline() method reads The remainder of the current line, Even if it is empty. CS 160, Spring Semester Example given following declaration. int n; String s1, s2; n = scan(); s1 = scan.nextline(); s2 = scan.nextline(); Assume input shown n is set to 42 but s1 is set to the empty string and s2 is set to next line 42 next line another line CS 160, Spring Semester

16 Printing Integers Formatting Output with printf public class Forecast public static void main (String args[]) System.out.print("The temperature will be "); System.out.print(-10); System.out.print(" degrees "); System.out.println(" and that s cold,folks!"); What happens if you use println each time? CS 160, Spring Semester Java has a method named printf() that applies a specific format to output. The printf()method similar to the print()/println()methods. System.out.printf can have any number of arguments! The first argument contains one or more format specifiers for the remaining arguments All the arguments except the first are values to be output to the screen CS 160, Spring Semester printf Format Specifier The following code double price = 19.8; System.out.print("\$"); System.out.printf("%6.2f", price); System.out.println(" each"); will output the line \$ each The format specifier "%6.2f" is interpreted as follows: Display up to 6 right-justified characters (field width is 6) Display exactly 2 digits after the decimal (precision is 2) Display a floating point number (conversion character is f) CS 160, Spring Semester Multiple arguments with printf The following code contains a printf statement having three arguments double price = 19.8; String name = apple ; System.out.printf("\$%6.2f per %s., price, name); System.out.println(); System.out.println("Wow"); will output \$ per apple. Wow Note that the first argument is a format string containing two format specifiers (%6.2f and %s) These format specifiers match up with the two arguments that follow (price and name) CS 160, Spring Semester

17 Line Breaks with printf Ref Format Specifiers for System.out.printf Line breaks can be included in a format string using %n or \n The code System.out.printf("%n\n!"); System.out.println("Wow"); will output!wow CS 160, Spring Semester CS 160, Spring Semester Ref The printf Method (Part 1 of 3) Ref The printf Method (Part 2 of 3) CS 160, Spring Semester CS 160, Spring Semester

18 Ref The printf Method (Part 3 of 3) Legacy Code Code that is "old fashioned" but too expensive to replace is called legacy code Sometimes legacy code is translated into a more modern language The Java method printf is just like a C language function of the same name This was done intentionally to make it easier to translate C code into Java CS 160, Spring Semester CS 160, Spring Semester What could go wrong? What else could go wrong? If you mis-type a variable name or a data type When you try to compile & run it in Eclipse 1. Eclipse will tell you there was an error 2. The editor will put a red x at the left of the line with the error This is an example of a compile-time error You can specify an illegal operation E.g. try to divide a string by a string Again, a compile-time error with a red x You can forget a ; or a Same as above CS 160, Spring Semester CS 160, Spring Semester

19 More Errors Capitalization errors Java is case sensitive, identifier names must use the same capitalization rules each time Logic Errors Program appears to run correctly, but on closer inspection the wrong output is displayed Debugging Hints Let Eclipse help you! Gives suggestions on methods to use Provides warning and error messages as you type even provides suggestions of how to fix the problem. Add debugging statements to check the computation System.out.println( ); CS 160, Spring Semester CS 160, Spring Semester

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

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

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

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

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

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

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

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

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

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

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

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,

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

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

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

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

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

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

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

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;

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

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,

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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,

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

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,

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

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

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.

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

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

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

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

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

Using Java Classes Fall 2018 Margaret Reid-Miller

Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class

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

Course Outline. Introduction to java

Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

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

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Java Programming, Eighth Edition 2-1 Chapter 2 Using Data A Guide to this Instructor s Manual: We have designed this Instructor s Manual to supplement and enhance your teaching experience through classroom

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

Big Java Fifth Edition Cay Horstmann Chapter 3 Fundamental Data Types Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware of

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

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.

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

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

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

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

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

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

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,

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

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose

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

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 Programming Constructs -- Introduction

More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

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

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

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

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

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,

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,

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,

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . \$, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

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

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

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

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/

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

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

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:

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

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.

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

JAVA Programming Fundamentals

Chapter 4 JAVA Programming Fundamentals By: Deepak Bhinde PGT Comp.Sc. JAVA character set Character set is a set of valid characters that a language can recognize. It may be any letter, digit or any symbol

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

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

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

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