Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.

Slides:



Advertisements
Similar presentations
CSci 1130 Intro to Programming in Java
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Constants and Data Types Constants Data Types Reading for this class: L&L,
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
1 Fundamental Data Types. 2 Outline  Primitive Data Types  Variable declaration  Numbers and Constants  Arithmetic Operators  Arithmetic Operator.
Chapter Day 4. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 4 Return Signed Contracts Questions from last Class?? Problem set 1 Posted.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
Program Elements -- Introduction
Expressions, Data Conversion, and Input
***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
CSCI 1100/1202 January 16, Why do we need variables? To store intermediate results in a long computation. To store a value that is used more than.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyCopyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; Copyright © 2012 Pearson Education,
Mathematical Calculations in Java Mrs. C. Furman.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
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.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
2-1 Character Strings A string of characters can be represented as a string literal by putting double quotes around the text: Examples: "This is a string.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
© 2006 Pearson Education Chapter 2: Objects and Primitive Data Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Lecture 3 Java Operators.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
CSC 1051 – Data Structures and Algorithms I
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Escape Sequences What if we wanted to print the quote character?
Increment and Decrement
Lecture 3 Expressions Richard Gesick.
Objects and Primitive Data
Arithmetic Expressions & Data Conversions
Expressions and Assignment
Data Types and Expressions
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Primitive Data Types and Operations
Data Types and Expressions
Arithmetic Expressions & Data Conversions
Data Types and Expressions
Presentation transcript:

Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants operators and expressions data conversion syllabus basic programming concepts object oriented programming topics in computer science

Data representation question: how to represent information in the computer, using the java language? answer: java lets us represent information in 8 different ways these representation formats are called data types

Primitive Data Types A data type is defined by a set of values and the operators you can perform on them Each value stored in memory is associated with a particular data type; Java has several predefined types, called primitive data types The following reserved words represent eight different primitive types: byte, short, int, long float, double boolean char

Integers There are four separate integer primitive data types; they differ by the amount of memory used to store them Type byte short int long Storage 8 bits 16 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 Max Value 127 32,767 2,147,483,647 > 9 x 1018

reading from memory תא 1: 1 תא 4: 

Floating Point There are two floating point types: Approximate Min Value -3.4 x 1038 -1.7 x 10308 Approximate Max Value 3.4 x 1038 1.7 x 10308 Type float double Storage 32 bits 64 bits

Characters A char value stores a single character from the Unicode character set A character set is an ordered list of characters The Unicode character set uses 16 bits per character, allowing for 65,536 unique characters It is an international character set, containing symbols and characters from many world languages

Characters The ASCII character set is still the basis for many other programming languages ASCII is a subset of Unicode, including: uppercase letters lowercase letters punctuation digits special symbols control characters A B C … a b c … . , ; … 0 1 2 … & | \ … carriage return, tab, ...

Boolean A boolean value represents a true/false condition. It can also be used to represent any two states, such as a light bulb being on or off The reserved words true and false are the only valid values for a boolean type how many bytes does this datatype use?

Variables A variable is an identifier (שם) that represents a storage in memory that holds a particular type of data Variables must be declared before being used; the syntax of a variable declaration is: data-type variable-name; data type variable name int total;

variables in memory תא 1: } 1 total תא 4: 

Details of variable declaration Multiple variables can be declared on the same line: int total, count, sum; Variables can be initialized (given an initial value) in the declaration: int total = 0, count = 20; double unitPrice = 57.25;

Variables use public static void main (String[] args) { short weeks = 14; int numberOfStudents = 120; double averageFinalGrade = 78.6; System.out.println(weeks); System.out.println(numberOfStudents); System.out.println(averageFinalGrade); }

Constants A constant is similar to a variable except that it keeps the same value throughout its existence; Constants are specified using the reserved word final It is better to use constants than literals because: They make the code more readable by giving meaning to a value They facilitate change because the value is only specified in one place Q: assembler languages do not have constants; what do we do?

Example - Constants use // Reads the radius of a circle and prints // its circumference and area class ConstantsExample { static final double PI = 3.1415927; public static void main(String[] args) { double r, circumference, area; System.out.println(“Enter radius: “); r = EasyInput.readDouble (); circumference = 2*PI*r; area = PI*r*r; System.out.println(“Circumference: “ +circumference); System.out.println(“Area: “ + area); }

Assignment Statements An assignment statement takes the following form: variable-name = expression; The expression is evaluated and the result is stored in the variable, overwriting the value currently stored in the variable

Assignment Statements: example // Uses assignment to change a variable's value public static void main (String[] args) { int NumberOfStudents = 140; System.out.println(“Students in 2001:”); System.out.println(NumberOfStudents); NumberOfStudents = 170; System.out.println(" Students in 2000:”); }

Operators An operator is a mapping that maps one or more values to a single value examples: +, -, *, / Java operators can be either: Unary operators - takes a single value (e.g., -) Binary operators - takes two values (e.g., +) All Java binary operators are written in the infix notation: operand1 operator operand2

Operators arithmetic increment and decrement logical assignment conditional

Arithmetic operators Java defines 5 arithmetic operators that are valid between every two numerical types a + b add a and b a - b subtract b from a a * b multiply a and b a / b divide a by b a % b the remainder of dividing a by b

Operators Operators can act differently on different data types 5.0 / 2.0 5 / 2.0 5.0 / 2 5 / 2 Essentially these are different operators 5.0 / 2.0 5 / 2.0 2.5 5.0 / 2 5 / 2 5.0 / 2.0 2.5 5 / 2.0 5.0 / 2 5 / 2 5.0 / 2.0 5 / 2.0 5.0 / 2 2.5 5 / 2 5.0 / 2.0 5 / 2.0 5.0 / 2 5 / 2 2

Expressions An expression can consist of a combination of operators and operands Operands can be literal values, variables, or expressions by themselves Examples of expressions: 4 + 5 x * 2.73 a - (7 - b) x

Expression example public static void main (String[] args) { int numberOfBooks = 30; double bookPrice = 45.90; double totalPrice; totalPrice = numberOfBooks * bookPrice; System.out.println( “The total price is:”); System.out.println(totalPrice); }

Operator Precedence The order in which operands are evaluated in an expression is determined by a well-defined precedence hierarchy Operators at the same level of precedence are evaluated according to their associativity (right to left or left to right) Parentheses can be used to force precedence

Operator Precedence Multiplication, division, and remainder have a higher precedence than addition and subtraction Both groups associate left to right Expression: Order of evaluation: Result: 5 + 12 / 5 - 10 % 3 3 1 4 2 6

Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1

Assignment Revisited The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side

Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value)

String Concatenation The ‘+’ operator between strings has the meaning of String concatenation When we apply ‘+’ upon a String and a value of another type, that value is first converted into a String and the result is the concatenation of the two Strings

String Concatenation Output: public static void main(String[] args) { System.out.print(“The international “ + “dialing code”); System.out.println(“for Israel is “ + 972); } Output: The international dialog code for Israel is 972

Data Conversions Sometimes it is convenient to convert data from one type to another; e.g., we may want to treat an integer as a floating point value during a computation Conversions must be handled carefully to avoid losing information: Widening conversions are safest because they tend to go from a specific data type to a general one (such as int to float) Narrowing conversions can lose information because they tend to go from a general data type to a more specific one (such as float to int)

Data Conversions In Java, data conversions can occur in three ways: Assignment conversion occurs when a value of one type is assigned to a variable of another; only widening conversions can happen via assignment Arithmetic promotion happens automatically when operators in expressions convert their operands Casting

Data Conversions: casting Casting is the most powerful, and dangerous, technique for conversion Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted int total, count; result = (float) total / count;

The Increment and Decrement Operators The increment operator (++) adds one to its integer or floating point operand The decrement operator (--) subtracts one The statement count++; is essentially equivalent to count = count + 1;

The Increment and Decrement Operators The increment and decrement operators can be applied in prefix (before the variable) or postfix (after the variable) form When used alone in a statement, the prefix and postfix forms are basically equivalent. That is, count++; is equivalent to ++count;

The Increment and Decrement Operators When used in a larger expression, the prefix and postfix forms have a different effect In both cases the variable is incremented (decremented) But the value used in the larger expression depends on the form Expression count++ ++count count-- --count Operation add 1 subtract 1 Value of Expression old value new value

The Increment and Decrement Operators If count currently contains 45, then total = count++; assigns 45 to total and 46 to count total = ++count; assigns the value 46 to both total and count

The Increment and Decrement Operators If sum contains 25, then the statement System.out.println (sum++ + " " + ++sum + " " + sum + " " + sum--); prints the following result: and sum contains after the line is complete 25 27 27 27 26

Assignment Operators Often we perform an operation on a variable, then store the result back into that variable Java provides assignment operators that simplify that process For example, the statement sum += value; is equivalent to sum = sum + value;

Assignment Operators There are many such assignment operators, always written as op= , such as: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y

Assignment Operators The right hand side of an assignment operator can be a complete expression The entire right-hand expression is evaluated first, then combined with the additional operation Therefore result /= (total-MIN) % n; is equivalent to result = result / ((total-MIN) % n);

How many different ways to do... int x=0,y=0;  x=1; y=2; int x=1;y=1;  x=2; y=2;

What you should be able to do... write programs which have variables perform simple arithmetic operations and store the output value for further use