Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To.

Slides:



Advertisements
Similar presentations
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
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.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
03 Data types1June Data types CE : Fundamental Programming Techniques.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Lecture 4 Types & Expressions COMP1681 / SE15 Introduction to Programming.
Datalogi A 3: 26/9. Java Concepts chapter 4 Fundamental Data Types int (long and short) double (and float) boolean char String.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Variable Declaration  It is possible to declare multiple variables of the same data type on the same line.  Ex. double hours, rate, total;  Variables.
1 Number Types  Every value in Java is either: 1.a reference to an object or 2.one of the eight primitive types  eight primitive types: a.four integer.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 4: Fundamental Data Types. To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware.
Chapter 4 Numeric types & arithmetic Strings: reading & writing.
Chapter 4 Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 4 – Fundamental Data Types.
Ch4 Data Types Every value has a type associated with it. The computer needs to know how much memory to allocate. Every value is either a primitive type.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 2: Using Data.
Week 5 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. int: integers, no fractional part: 1, -4, 0 double : floating-point.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Four: Fundamental Data Types.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
The Math Class Methods Utilizing the Important Math Operations of Java!
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Two: Fundamental Data Types Slides by Evan Gallagher.
Data Types, Variables, and Arithmetic Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by.
Announcements Quiz 1 Next Monday. int : Integer Range of Typically –2,147,483,648 to 2,147,483,647 (machine and compiler dependent) float : Real Number.
Data Types and Conversions, Input from the Keyboard CS303E: Elements of Computers and Programming.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
1 Review for exam 1 CS 101 Aaron Bloomfield. 2 Today’s lecture An overview of the “review” sections of chapters 1-3 Stop me if you want me to go over.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Variables and Constants Chapter 4 Review. Declaring Variables A variable is a name for a value stored in memory. Variables and constants are used in programs.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
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.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
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.
CompSci 230 S Programming Techniques
Chapter 2 More on Math More on Input
Chapter 4 – Fundamental Data Types
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2: Basic Elements of Java
IFS410 Advanced Analysis and Design
Primitive Types and Expressions
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Chapter 4 – Fundamental Data Types

Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To recognize the limitations of the numeric types To recognize the limitations of the numeric types To become aware of causes for overflow and roundoff errors To become aware of causes for overflow and roundoff errors To understand the proper use of constants To understand the proper use of constants To write arithmetic expressions in Java To write arithmetic expressions in Java To use the String type to define and manipulate character strings To use the String type to define and manipulate character strings To learn how to read program input and produce formatted output To learn how to read program input and produce formatted output

4.1 Number Types Recall: All values are either references to objects or one of 8 primitives Recall: All values are either references to objects or one of 8 primitives A numeric computation overflows if the result falls outside the range for the number type A numeric computation overflows if the result falls outside the range for the number type int n = ; System.out.println(n * n); // prints

Primitives So far: 6 number types So far: 6 number types byte, short, int, long for whole numbers byte, short, int, long for whole numbers float, double for reals float, double for reals Numbers can have overflow(value too large) Numbers can have overflow(value too large) Reals can also have underflow(rounding errors) Reals can also have underflow(rounding errors) double f = 4.35; System.out.println(100 * f); // prints

Conversion 2 types of conversion – increase in precision, decrease in precision 2 types of conversion – increase in precision, decrease in precision int +/- 2E9 double +/- 1E308 Increase in precision Java won’t complain Decrease in precision Java will say it’s an error

Type casting Error is because compiler wants us to know that we are going to possibly lose information Error is because compiler wants us to know that we are going to possibly lose information 4.0 to 4, not a big deal 4.0 to 4, not a big deal 0.99 to 0, is a big deal 0.99 to 0, is a big deal To override this (i.e. tell the compiler to convert anyways) we must use the type cast operator To override this (i.e. tell the compiler to convert anyways) we must use the type cast operator

Type casting ( ) expression Example double balance = 12.45; int dollar = (int) balance; //stores 12 Truncates, removes fractional part Truncates, removes fractional part Can cast to any type you want (including objects) Can cast to any type you want (including objects)

Rounding What if you want to round instead of truncate? What if you want to round instead of truncate? 2 solutions: 2 solutions: Hack: add 0.5 to number then truncate Hack: add 0.5 to number then truncate Real solution: Use Math.round() Real solution: Use Math.round() long rounded = Math.round(balance);

4.2 Constants In math, equations have variables and constants In math, equations have variables and constants Constants are numbers that do not change but have specific meanings are important Constants are numbers that do not change but have specific meanings are important Randomly placed numbers in a program can be confusing (and hard to change later), so we give them symbolic names Randomly placed numbers in a program can be confusing (and hard to change later), so we give them symbolic names

Constants Use a constant to hold the value Use a constant to hold the value Value cannot change once it is set Value cannot change once it is set Use reserved word final to modify declaration Use reserved word final to modify declaration final double PI = final double PI = Remember Naming Convention Remember Naming Convention USE_ALL_CAPS_WITH_UNDERSCORES USE_ALL_CAPS_WITH_UNDERSCORES

Uses Constants often used for important numbers Constants often used for important numbers Make meaning of code easier to understand Make meaning of code easier to understand Ex. Go back to BankAccount Ex. Go back to BankAccount Want to add something to withdraw method Want to add something to withdraw method

public void withdraw(double amount) { double newBalance = balance – amount - 5; balance = newBalance; } What is the 5 doing? Why is it there?

public void withdraw(double amount) { final int BANK_FEE = 5; double newBalance = balance – amount – BANK_FEE; balance = newBalance; }

Constant Fields Often, we want to use the same constant across several methods in a class Often, we want to use the same constant across several methods in a class Make a constant field (class constant) Make a constant field (class constant)

Constant Fields Two differences Two differences Make it public since we don’t have to worry about the value being changed Make it public since we don’t have to worry about the value being changed Add static modifier to make it part of the class, so all objects of that class share it (more later) Add static modifier to make it part of the class, so all objects of that class share it (more later) public class Math{ … public static final double E = public static final double PI = …}

public static final int BANK_FEE = 5; public void withdraw(double amount) { double newBalance = balance – amount – BANK_FEE; balance = newBalance; }

Constant Definition In a method (local constant) In a method (local constant) final = ; final int HOURS_IN_DAY = 24; In a class (class constant) In a class (class constant) static final = ; static final = ; public static final int HOURS_IN_DAY = 24;

Magic Numbers So when should I use a constant? So when should I use a constant? In general if the number has significance, give it a symbolic name (make it a constant identifier) In general if the number has significance, give it a symbolic name (make it a constant identifier)Ex. time = duration * 60; Is this converting minutes to seconds? Hours to minutes?

items = items + 1; Expression to right is always computed first Expression to right is always computed first Add items + 1; Add items + 1; The value of the expression is assigned to the variable afterwards The value of the expression is assigned to the variable afterwards 4.3 Assignment, Increment, and Decrement

Increment Net result is to increment items by 1 Net result is to increment items by 1 Increment is so common, java uses a shorthand for it Increment is so common, java uses a shorthand for it Increment items by one Increment items by one items++; Decrement (subtract) by one Decrement (subtract) by one items--;

Other Shortcuts Arithmetic modifications to a variable can use shorthand operations Arithmetic modifications to a variable can use shorthand operations items = items + 5;  items += 5; items = items * 2;  items *= 2; items = items – 2*5;  items -= 2*5; items = items / x;  items /= x;

Modulo Returns remainder of division Returns remainder of division 23 % 5 = 3 23 % 5 = 3 4 % 2 = ? 4 % 2 = ? Mainly used for integers (possible for reals also, but not as useful) Mainly used for integers (possible for reals also, but not as useful)

Precedence High Subexpressions ( ) unary operators- (negative) multiplicative operators*, /, % additive operators+, - Low

Integer Division When dividing two integers, only the whole number is returned When dividing two integers, only the whole number is returned Has its advantages Has its advantages int totalTime = 503; int MINUTES_PER_HOUR = 60; int hours = totalTime / MINUTES_PER_HOUR; int minutes = totalTime % MINUTES_PER_HOUR;

Math Class Provided automatically (package java.lang ) Provided automatically (package java.lang ) Power Power Math.pow(x,n)  x n Squareroot Squareroot Math.sqrt(x)  x 0.5

In Java In Java (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a) or (-b + Math.sqrt(Math.pow(b,2) - 4 * a * c)) / (2 * a)

Check What is the value of 1729 / 100? Of 1729 % 100? What is the value of 1729 / 100? Of 1729 % 100? Computing Average: Is this correct? Computing Average: Is this correct? double average = s1 + s2 + s3 / 3; What do we have to worry about if s1, s2, s3 are integers? What do we have to worry about if s1, s2, s3 are integers?

Avoid Redundant Code Important property for good programming – never have to lines of code doing the exact same thing Important property for good programming – never have to lines of code doing the exact same thing Won’t be heavily enforced, but good to get practice Won’t be heavily enforced, but good to get practice Inefficient – making computer do work twice Inefficient – making computer do work twice Error prone – when there is a bug, you may only fix it one place Error prone – when there is a bug, you may only fix it one place

Example – Quadratic Eqn x1 = (-b + Math.sqrt(b * b – 4 * a * c)) / (2 * a); x2 = (-b - Math.sqrt(b * b – 4 * a * c)) / (2 * a); versus double root = Math.sqrt(b * b – 4 * a * c); x1 = (-b + root) / (2 * a); x1 = (-b - root) / (2 * a);

4.5 Calling Static Methods So far we have been discussing classes as templates and objects as the entities So far we have been discussing classes as templates and objects as the entities All the methods and instance fields for the BankAccount class belonged to an individual object All the methods and instance fields for the BankAccount class belonged to an individual object Each had its own balance Each had its own balance A method call was on the object itself A method call was on the object itself harrysChecking.getBalance() different then myChecking.getBalance() harrysChecking.getBalance() different then myChecking.getBalance()

Static Methods Has everything we’ve used been an object? Has everything we’ve used been an object? System System Math Math Both of these are classes, yet we made calls on them to either fields ( System.out ) or methods ( Math.sqrt() ) Both of these are classes, yet we made calls on them to either fields ( System.out ) or methods ( Math.sqrt() ) We never created an instance Math of the class or System class We never created an instance Math of the class or System class

Other Math Class Methods

Static Methods The calls on the Math class were unique The calls on the Math class were unique They were static – belonging to the class, not an individual object They were static – belonging to the class, not an individual object In other words, these methods did not depend on an object In other words, these methods did not depend on an object Math.sqrt() will ALWAYS do the same thing, so why create an object whenever we use it? Math.sqrt() will ALWAYS do the same thing, so why create an object whenever we use it?

Static Methods Static methods are defined in the classes like normal methods Static methods are defined in the classes like normal methods They do not operate on object, and don’t have any internal data to deal with They do not operate on object, and don’t have any internal data to deal with Static means the method/variable “belongs” to the class Static means the method/variable “belongs” to the class Non-static (instance) means the method/variable “belongs” to the object Non-static (instance) means the method/variable “belongs” to the object

Syntax ClassName.methodName(parameters) Example: Math.sqrt(4)Purpose: To invoke a static method (a method that does not operate on an object) and supply its parameters

4.6 Strings(Revisted) Along with numbers, the most commonly used data type in programming Along with numbers, the most commonly used data type in programming Unlike numbers, Strings are objects Unlike numbers, Strings are objects Already learned about length() method Already learned about length() method Empty String (length is 0)  "" Empty String (length is 0)  ""

Number to String Converting from number to String is easy Converting from number to String is easy int number = 15; String strnum = "" + number; How about the reverse? How about the reverse? int result = Integer.parseInt(someString); double result = Double.parseDouble(someString); Similar for all other number types

Parsing Only works if entire string is a number Only works if entire string is a number "19" // Works for parseInt() & parseDouble() "15.23"// Works for parseDouble() only "123a" // Error for both

substring String subString() method String subString() method String greeting = "Hello, World!"; String sub = greeting.subString(0,5); //sub is "Hello“ Note that the first parameter is the first letter you want (zero based indexing) and the second parameter is the first letter you DON’T want

4.7 Reading Input All examples so far have been pretty basic All examples so far have been pretty basic Do not vary, we code in all values when testing Do not vary, we code in all values when testing Most useful programs interact with a user of the terminal (computer) to get data input and perform operations on that data Most useful programs interact with a user of the terminal (computer) to get data input and perform operations on that data

Output is System.out Output is System.out You would think Input should then be System.in You would think Input should then be System.in Exists, but not very powerful Exists, but not very powerful Takes in only one byte of information at a time, when all characters on the keyboard are 2 bytes! Takes in only one byte of information at a time, when all characters on the keyboard are 2 bytes!

Scanner Can be associated with files, but for now we will learn about keyboard input Can be associated with files, but for now we will learn about keyboard input A Scanner object must be created, associated with System.in as follows: A Scanner object must be created, associated with System.in as follows: Scanner in = new Scanner(System.in);

Scanner To read numbers from user To read numbers from user nextInt(), nextDouble() When called, these methods wait for the user to type input and then hit the enter key. The number inputted is returned When called, these methods wait for the user to type input and then hit the enter key. The number inputted is returned Usually, the program will prompt the user for information – give instructions via System.out Usually, the program will prompt the user for information – give instructions via System.out

Get String To get a String, use To get a String, usenextLine() Allows user to type as much as they want. When they hit enter, all characters typed are returned as a String object Allows user to type as much as they want. When they hit enter, all characters typed are returned as a String object To read just one word (not entire line) To read just one word (not entire line)next()

Example Scanner stdin = new Scanner(System.in); System.out.print("Enter name: "); String name = stdin.nextLine(); System.out.print("Enter age: "); int age = stdin.nextInt();