DATA TYPES AND EXPRESSIONS

Similar documents
MODULE 02: BASIC COMPUTATION IN JAVA

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Variables and data types

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

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

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

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

Full file at

Basics of Java Programming

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

Basic Computation. Chapter 2

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

1.1 Your First Program

Zheng-Liang Lu Java Programming 45 / 79

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

Full file at

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

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

Lecture 2: Intro to Java

4 Programming Fundamentals. Introduction to Programming 1 1

CONDITIONAL EXECUTION

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

Chapter 3: Operators, Expressions and Type Conversion

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

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Program Fundamentals

Chapter 2: Data and Expressions

1.1 Your First Program

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

Building Java Programs

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

Chapter 2: Data and Expressions

Building Java Programs

Basic Computation. Chapter 2

CIS133J. Working with Numbers in Java

Chapter 2: Data and Expressions

Eng. Mohammed S. Abdualal

Building Java Programs

Ex: If you use a program to record sales, you will want to remember data:

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

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

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

CMPT 125: Lecture 3 Data and Expressions

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Calculations, Formatting and Conversions

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CEN 414 Java Programming

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Chapter 2 Primitive Data Types and Operations. Objectives

JAVA OPERATORS GENERAL

Chapter 1 Introduction to java

1.1 Your First Program

Basics of Java Programming variables, assignment, and input

AP Computer Science A

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

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

Getting started with Java

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

A Java program contains at least one class definition.

Declaration and Memory

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

ECE 122 Engineering Problem Solving with Java

Algorithms and Programming I. Lecture#12 Spring 2015

Reserved Words and Identifiers

More Programming Constructs -- Introduction

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

1.1 Your First Program

Chapter 2 Elementary Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Java Basic Programming Constructs

Types and Expressions. Chapter 3

Chapter 2 ELEMENTARY PROGRAMMING

Advanced Computer Programming

Datatypes, Variables, and Operations

Lecture Set 4: More About Methods and More About Operators

1.1 Your First Program! Naive ideal. Natural language instructions.

1.1 Your First Program

Object-Oriented Programming

What did we talk about last time? Examples switch statements

Programming with Java

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Lecture Set 4: More About Methods and More About Operators

Lecture 2: Intro to Java

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

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

Visual C# Instructor s Manual Table of Contents

Operators in java Operator operands.

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

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

Building Java Programs Chapter 2

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

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

Transcription:

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 Boolean

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 in a variable is called its value. The value is stored in the memory location. Its value can be changed. In Java, we always have to declare (define) a variable before we can use it We need to tell Java what type of data it is and its name x

Variables: Naming Convention A variable's name should suggest its use e.g. taxrate, count, sum, etc. that is, it should be meaningful Begin with lowercase, uppercase each new word int totalwidgets; Called lower camel case

Data Types A primitive type is used for simple, non-decomposable values such as an individual number or individual character. int, double, and char are primitive types. 3.1415 is a value of type double 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 DEFINITION A data type is a set of values and the legal operations on those values.

Variables Variables and Data Types Stores information your program needs Each has a unique name Each has a specific type Java built-in type what it stores example values operations int integer values 42 1234 double floating-point values 9.95 3.0e8 char characters 'a', 'b', '!', '2' compare add, subtract, multiply, divide, remainder, compare, increment, decrement add, subtract, multiply, divide, compare String sequence of characters boolean truth values true false "Hello world!" "I love this!" concatenate and, or, not 6

Data Types: Integers Java built-in type what it stores example values int integer values 42 1234 public class Integers public static void main(string[] args) int i = 23; int j = 5; operations add, subtract, multiply, divide, remainder, compare, increment, decrement System.out.println("Addition: " + (i + j)); System.out.println("Subtraction: " + (i - j)); System.out.println("Multiplication: " + (i * j)); System.out.println("Division: " + (i / j)); System.out.println("Remainder: " + (i % j)); System.out.println("i greater than j? " + (i > j)); System.out.println("i less than j? " + (i < j)); System.out.println("i equal to j? " + (i == j)); System.out.println("i not equal to j? " + (i!= j)); System.out.println("i + 1 " + (i++)); System.out.println("j - 1 " + (j--));

Data Types: Floating Point Numbers Java built-in type double what it stores example values operations floating-point values 9.95 3.0e8 add, subtract, multiply, divide, compare public class Doubles public static void main(string[] args) double i = 23.5; double j = 5.5; System.out.println("Addition: " + (i + j)); System.out.println("Subtraction: " + (i - j)); System.out.println("Multiplication: " + (i * j)); System.out.println("Division: " + (i / j)); System.out.println("i greater than j? " + (i > j)); System.out.println("i less than j? " + (i < j)); System.out.println("i equal to j? " + (i == j)); System.out.println("i not equal to j? " + (i!= j));

Data Types: Characters Java built-in type what it stores example values operations char characters 'a', 'b', '!', '2' compare public class Chars public static void main(string[] args) char c = h ; char d = i ; System.out.println("Addition: " + (c + d)); System.out.println( c greater than d? " + (c > d)); System.out.println( c less than d? " + (c < d)); System.out.println( c equal to d? " + (c == d)); System.out.println( c not equal to d? " + (c!= d));

Data Types: Strings (of Characters) Java built-in type String what it stores example values operations sequence of characters "Hello world!" "I love this!" concatenate, length() public class Strings public static void main(string[] args) String c = "Hello "; String d = "World!"; char e = '!'; System.out.println("Concatenation: " + (c + d)); String result = c + d + e; System.out.println(result); System.out.println(result.length());

Concatenating Strings with Other Types public class StringConcat public static void main(string[] args) String s = "";// An empty string String r = s;// Another empty string s = s + (3 + 4); r = s + 2; System.out.println(s); System.out.println(r); System.out.println(r + " Trombones"); System.out.println(r + 3.41512); System.out.println(3.41512 + r); Double quotes with nothing in between, an empty String 11

Data Types: Boolean / Logical Java built-in type public class Booleans public static void main(string[] args) boolean t = true; boolean f = false; what it stores example values operations boolean truth values true false System.out.println("And: " + t + " and " + t + " is " + (t && t)); System.out.println("And: " + t + " and " + f + " is " + (t && f)); System.out.println("And: " + f + " and " + t + " is " + (f && t)); System.out.println("And: " + f + " and " + f + " is " + (f && f)); System.out.println(); System.out.println("Or: " + t + " or " + t + " is " + (t t)); System.out.println("Or: " + t + " or " + f + " is " + (t f)); System.out.println("Or: " + f + " or " + t + " is " + (f t)); System.out.println("Or: " + f + " or " + f + " is " + (f f)); System.out.println(); and, or, not System.out.println("Not:!" + t + " is " +!t); System.out.println("Not:!" + f + " is " +!f);

Booleans!a Is a set to false? a && b Are both a and b set to true? a b Is either a or b (or both) set to true? logical AND logical OR &&! logical NOT a b a && b a b false false false false false true false true a!a true false false true true false false true true true true true 13

Data Types: Constants Sometimes you have a value that should not change e.g. pi, my favorite number, the speed of light Values that shouldn t change are called constants. Numeric constants can be preceded by a + or - sign (but never use commas) Floating-point constants can be written With digits after a decimal point or Using e notation. Naming convention All upper case, use _ between words final double SPEED_LIGHT = 3.0e8;

Creating and Initializing a Primitive Variable byte x = 7; x primitive value x 011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000001110101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101010101010101010101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101 15

Changing the Value of a Primitive Variable byte x = 7; x = x + 1; x primitive value x 011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101010101010101010101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101 16

Mathematical Expressions: Parentheses and Precedence Parentheses can change 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.

Boolean Expressions: Comparisons Given two numbers return a boolean operator meaning true example false example == equal 7 == 7 7 == 8!= not equal 7!= 8 7!= 7 < less than 7 < 8 8 < 7 <= less than or equal 7 <= 7 8 <= 7 > greater than 8 > 7 7 > 8 >= greater than or equal 8 >= 2 8 >= 10 Is the sum of a, b and c equal to 0? (a + b + c) == 0 Is grade in the B range? (grade >= 80.0) && (grade < 90.0) Is sumitems an even number? (sumitems % 2) == 0 18

Leap Year Example Years divisible by 4 but not by 100 leap year Years divisible by 400 leap year public class LeapYear public static void main(string [] args) int year = Integer.parseInt(args[0]); boolean isleapyear; // Leap year if divisible by 4 but not by 100 isleapyear = (year % 4 == 0) && (year % 100!= 0); // But also leap year if divisible by 400 isleapyear = isleapyear (year % 400 == 0); System.out.println(isLeapYear); % java LeapYear 2000 true 19

Assignment Compatibilities Java is said to be strongly typed. You can't assign a floating point value to a variable declared to store an integer. Sometimes conversions between numbers are possible: double doublevariable = 7; A value of one type can be assigned to a variable of that uses more memory, but not vice versa byte --> short --> int --> long --> float --> double This is called automatic type conversion

Creating and Initializing a Primitive Variable byte x = 7; x = x + 1; short y = 7; x primitive values y x y 011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101000000000000011101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101 21

You can't put a big cup into a small one You may know 7 can fit in a byte, but compiler doesn't! byte x = 7; x = x + 1; short y = 7; x = y; x primitive values y x y 011010101010100101010101110101010101010101010111010101 000101010101010111101010101010101010101001001101010101 010010101010110000010000101010101011101010100010101010 101011110101010101010101010100100110101010101001010101 011101000000000000011101110101010001010101010101111010 101010101010101010010011010101010100101010101110101010 101010101010111010101000101010101010111101010101010101 010101001001101010101010010101010111010101010101010101 22

Type Casting A type cast temporarily 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) The value of (int)distance is 9, The value of distance, both before and after the cast, is 9.0. Any nonzero value to the right of the decimal point is truncated rather than rounded.

Type Conversion Java is strongly typed Helps protect you from mistakes (aka "bugs") public class TypeExample0 public static void main(string [] args) int ordertotal = 0; double costitem = 29.95; ordertotal = costitem * 1.06; System.out.println("total=" + ordertotal); % javac TypeExample0.java TypeExample0.java:7: possible loss of precision found : double required: int ordertotal = costitem * 1.06; ^ 24

Type Conversion Converting from one type to another: Manually using a cast A cast is accomplished by putting a type inside ()'s Casting to int drops fractional part Does not round! public class TypeExample1 public static void main(string [] args) int ordertotal = 0; double costitem = 29.95; ordertotal = (int) (costitem * 1.06); System.out.println("total=" + ordertotal); % java TypeExample1 total=31 25

Type Conversion Automatic conversion Numeric types: If no loss of precision automatic promotion public class TypeExample2 public static void main(string [] args) double ordertotal = 0.0; int costitem = 30; ordertotal = costitem * 1.06; System.out.println("total=" + ordertotal); % java TypeExample2 total=31.8 26

Type Conversion Automatic conversion String concatenation using the + operator converts numeric types to also be a String public class TypeExample3 public static void main(string [] args) double costitem = 29.95; String message = "The widget costs "; message = message + costitem; message = message + "!"; System.out.println(message); % java TypeExample3 The widget costs 29.95! 27

Static Methods Java has lots of helper methods (static methods) Things that take value(s) and return a result e.g. Math functions: Math.abs(-3.5) 3.5 e.g. Type conversion: Integer.parseInt( 42 ) 42 Double.parseDouble() double e.g. Random number generation: Math.rand() Live in some particular Java library class e.g. Math, Integer or Double Call using class name followed by dot 28

Type Conversion Quiz Automatic: no loss of precision int will convert to a double if need be double cannot automatically convert to int Manual: cast or using a static method expression resulting type resulting value (int) 3.14159 Math.round(3.6) 2 * 3.0 2 * (int) 3.0 (int) 2 * 3.0 29

String Conversion Quiz String conversion, using: Integer.parseInt() Double.parseDouble() expression resulting type resulting value Integer.parseInt("30") Double.parseDouble("30") Integer.parseInt("30.1") Double.parseDouble("30.1") Integer.parseInt("$30") Double.parseDouble(3.14) 30

String Concatenation Quiz + is addition for numeric types + is concatenation for String type numeric types convert to String if needed Strings never (automatically) go back to number expression resulting type resulting value "testing " + 1 + 2 + 3 "3.1" + 4159 "2" + " + " + "3" 1 + 2 + 3 + "66" 31

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. // comment to end of line /* multi-line comment /* /** * javadoc comment */

Summary Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment Mathematical Boolean