Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)

Slides:



Advertisements
Similar presentations
1 Variables and Data Types. 2 Variable Definition a location in memory, referenced by a name (identifier), where data of a given type can be stored, changed,
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
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.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
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.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
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.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Object-Oriented Programming
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
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.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Classes CS 21a: Introduction to Computing I First Semester,
Chapter 2: Using Data.
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.
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.
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.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Operations on Strings. 8/8/2005 Copyright 2006, by the authors of these slides, and Ateneo de Manila University. All rights reserved L: String Manipulation.
Copyright Curt Hill Variables What are they? Why do we need them?
String and Scanner CS 21a: Introduction to Computing I First Semester,
Chapter 2 Variables.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
COMP Primitive and Class Types Yi Hong May 14, 2015.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.
M105 - Week 2 Chapter 3 Numerical Data 1 Prepared by: M105 Team - AOU - SAB.
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.
Chapter 2 Variables.
Chapter 2 Basic Computation
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Type Conversion, Constants, and the String Object
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Classes CS 21a: Introduction to Computing I
In this class, we will cover:
Primitive Types and Expressions
Presentation transcript:

Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 2 Types in Java Recall: variables in Java must be associated with a type such as int or double e.g., double balance; In the tester programs we have written, there are variables whose types are classes e.g., BankAccount b;

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 3 Two kinds of Java types Primitive types: one of the 8 built-in types in Java int, double, long, short, byte, float, char, boolean Variables of primitive types hold values acceptable under these types Object types: classes Some of these types are “built-in” (present in the Java library) such as String or Graphics, the rest are user- defined such as BankAccount Variables of object types hold references to objects

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 4 Understanding primitive types Important components of a primitive data type: Range of values Literals (how constant values under the type are written) Operations that can be carried out with values under that type

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 5 The int Data Type Range: -2,147,483,648 to 2,147,483,647 The range is limited because these are the numbers that can be represented by a 32-bit binary number (4 bytes) Literals sequence of digits Examples: 22, 16, 1, 426, 0, Operations: usual arithmetic operations +, -, *, /, % (note: integer division is performed for / and %) negative numbers obtained using - as prefix

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 6 Binary Numbers Humans can naturally count up to 10 values, But computers can count only up to 2 values (OFF and ON, or 0 and 1) Humans use decimal, computers use binary Example: an 8-bit number is called a byte b0b b1b1 1 2 b2b b3b b4b b5b b6b b7b = = = Range 0 to 2 n - 1 Note: In Java, a byte is actually signed, and has a range of -128 to The last bit has a place value of -128 instead of 128. More on this later…

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 7 The double Data Type Values: decimal numbers Range: +/- 4.94e-324 to 1.80e+308 Limited precision: n.nnnnnnnnnnnnnn X 10 (+/-)mmm Even though you can specify up to , you don’t actually get 308 digits of precision, just a few (about 15 digits) Again, this is because we are limited (to 64 bits or 8 bytes) Literals (examples) 100.5, , E10 ( ), 2.1e-3 (0.0021) Operations: arithmetic operations (“true” division performed) float: lower precision (fewer digits)

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 8 Other primitive types Alternatives to int short: 2 bytes, to long: 8 bytes, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 byte: 1 byte, -128 to 127 Alternative to double float: 4 bytes, maximum around 1e38, 7 digits of precision (less precise than a double)

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 9 Other primitive types char: represents characters found in the keyboard or printed on an output device Literals: ′A′, ′b′, ′5′, ′ \n′, ′ \u0009′ Values come from the Unicode character set (subsumes the ASCII character set) boolean: used for conditions Possible values: true or false More on this when we discuss decision statements

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 10 Operations and numeric types Most arithmetic operations are binary operations Requires two numeric operands, returns a result Examples: balance miles/efficiency There are some that are unary operations Unary operators: Example: negation int value = 10; int negated = -value; // assigns -10

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 11 Operations and numeric types Arithmetic operations follow precedence rules Negations are performed before multiplications and divisions, which are performed before additions and subtractions Parentheses can be used to override these precedence rules Operations performed sometimes depend on the types of the operands (e.g., /) Division where both operands are ints => integer division is performed (integer quotient retruned, remainder discarded) Regular division is performed (returns a floating point number) when at least one operand is a float or double

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 12 Built-in Functions Provided in Java to provide for more complex operations Example 1: Math.pow() double result = Math.pow( 5.5, 3.0 ); can be viewed as a binary operation that calculates some power of a number Example 2: Math.sqrt() double result = Math.sqrt( 2.0 ); can be viewed as a unary operation that calculates the squareroot of the given operand javap java.lang.Math prints a list of available math functions These are static methods (methods called on the Math class)

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 13 Expressions Expression a sequence of variables, literals, operators, and method calls (like calls to Math.pow() ); has a return value and type Uses Right operand of an assignment; e.g., pesos = dollars * fee; ans = Math.sqrt( b*b – 4.0*a*c ); Argument for an output statement; e.g., System.out.println( (-b + ans)/(2*a) );

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 14 Image taken from Horstmann’s lecture notes

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 15 Floating point values For the double and float types, the value stored or computed is often not exact Because of binary storage and precision constraints, values are rounded double num = 4.35; double val = 100 * num; System.out.println( val ); Can assign an int value to a double but not the other way around int i = 10; double d = 5.0; d = i; // ok, d gets 10.0 (automatic type conversion) i = d; // compile error prints

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 16 Casts and rounding Use a cast to “force” a conversion There may be some data/precision loss during the conversion Syntax: (type) expression Example: int x = (int) 5.65; // assigns 5, discards 0.65 May be used when converting doubles to floats or longs to ints Use Math.round() to carry out rounding of floating point numbers to whole numbers float f = 5.65; double d = 4.44; int i = Math.round( f ); // assigns 6 long l = Math.round( d ); // assigns 4

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 17 Increment and decrement operators Unary operators that require a variable as an operand: performs an increment or a decrement Increment operator: ++ Decrement operator: -- Examples: int a = 5; a++; // same as a = a + 1; a--; // same as a = a - 1; Operator can be placed after the variable: ++a; // same as a = a + 1; --a; // same as a = a - 1;

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 18 Post-increment Operator: ++ Example: number++ Operands Unary operator Operand must be a variable Returns: the original value of the operand Effect: variable is incremented Note: the variable is incremented after its value is returned

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 19 Pre-increment Operator: ++ Example: ++number Operands Unary operator Operand must be a variable Returns: the new (incremented) value of the operand Effect: variable is incremented Note: the variable is incremented before its value is returned

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 20 About ++ Notice that a++; and ++a; are similar return value is ignored in both cases could be used as shorthands for a = a + 1; But they are not the same! Difference is seen when the return value is useda = 5; b = a++;b = ++a;// values of a & b?

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 21 Constants Literal values in a program Appear often enough and may be associated with an appropriate name Declare at the level of the methods (right after the opening curly brace for the class); so that it can be used inside any of the methods Prefix the declaration with public static final Examples (note naming convention) public static final int MAX = 100; public static final double PI = ; public static final double DIME_VALUE = 0.10;

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 22 Primitive type variables versus object variables Primitive type variables directly contain values int x = 5; Object variables contain references BankAccount b = new BankAccount(); 5 x b balance 0

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 23 Primitive type variables and assignment int x = 1000; 1000 x

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 24 Primitive type variables and assignment int x = 1000; int y = x; 1000 x y

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 25 Primitive type variables and assignment int x = 1000; int y = x; y = y - 100; System.out.println( x ); System.out.println( y ); 1000 x 900 y Prints:

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 26 Object variables and assignment BankAccount b = new BankAccount( 1000 ); b balance 1000

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 27 Object variables and assignment BankAccount b = new BankAccount( 1000 ); BankAccount c = b; b balance 1000 c

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 28 Object variables and assignment BankAccount b = new BankAccount( 1000 ); BankAccount c = b; c.withdraw( 100 ); System.out.println( b.getBalance() ); System.out.println( c.getBalance() ); b balance 900 c Prints:900

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 29 The null reference Assign null to an object variable to indicate that the variable is currently not referring to an object Example: b = null; null b

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 30 Garbage collection Because object variables are references, it is possible to have “stale” objects in memory— objects that have no variables that refer to them Example: BankAccount b = new BankAccount( 100 ); b = new BankAccount( 200 ); BankAccount c = new BankAccount( 300 ); c = null; /* at this point, only the bank account whose balance is 200 has a variable referring to it */ Stale objects (two of them in the above example) are automatically garbage collected

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 31 The Balloon Analogy xyz (null) BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; Think of Objects as balloons! references are like strings (aka “handles”) Idea from “Beginning Java Objects” by Jacquie Barker (Wrox)

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 32 The Balloon Analogy xyz (null) BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z;

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 33 The Balloon Analogy xyz BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z;

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 34 The Balloon Analogy BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; xyz

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 35 The Balloon Analogy BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; xyz

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 36 The Balloon Analogy BankAccount x, y, z; x = new BankAccount(); y = x; z = new BankAccount(); y = z; x = z; xyz If there is no reference pointing to an object anymore, it gets “garbage collected”

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 37 Method calls A method is invoked on an object variable but acts on the object that the variable is referring to b balance 1000 BankAccount b = new BankAccount(1000);

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 38 Method calls A method is invoked on an object variable but acts on the object that the variable is referring to b balance 1250 BankAccount b = new BankAccount(1000); b.deposit( 250 ); deposit(250)

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 39 Method calls on null Calling a method on an object variable whose value is null results in an error (NullPointerException) null b deposit(250) ??? BankAccount b = null; b.deposit( 250 );

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 40 The String class String: a built-in class in Java Methods on String objects: javap java.lang.String for a complete list public int length() public String toUpperCase() public String substring( int first, int last ) Note: strings are immutable (no mutator methods) String objects have a special treatment in Java To enable string literals, string display, and string concatenation

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 41 Using strings String literal example: ″Hello, World″ String variable: String message = ″Hey″; // same as String message = new String(″Hey″); Using strings: System.out.println( ″Hello, World″ ); System.out.println( message ); System.out.println( message.length() ); String caps = message.toUpperCase(); System.out.println( caps ); Prints: Hello, World Hey 3 HEY

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 42 Strings are objects String variables contain object references String s = ″Hey″; Calling length() on a string returns an int. int x = s.length(); s “Hey” length()3

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 43 Strings are objects Calling toUpperCase() on a string returns another string String caps = s.toUpperCase(); Note that the state of the String object does not change in this case “Hey” toUpperCase() “HEY”

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 44 String concatenation Recall that operators may behave differently depending on the type of the operands The + operator causes a concatenation if the operands are strings System.out.println( ″basket″ + ″ball″ ); If only one operand is a string, the other operand is first converted to a string and then a concatenation is performed int ans = 5; System.out.println( ″The answer is ″ + ans ); Prints: basketball Prints: The answer is 5

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 45 Converting between Strings and number types Suppose int i = 5; double d = 10.0; String s = ″7″; From String to number i = Integer.parseInt( s ); // assigns 7 to i d = Double.parseDouble( s ); // assigns 7.0 to d From number to String s = Integer.toString( i ); // assigns ″5″ to s s = Double.toString( d ); // assigns ″10.0″ to s Can also use concatenation; e.g., s = ″″ + d;

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 46 The substring method public String substring( int first, int last ) Each character in a String object has a position (starting with 0); the parameters for substring indicate: first: the starting letter of the substring of interest last: the position following the ending letter of the substring This way, (last-first) = the length of the resulting substring Example: String s = ″Ateneo de Manila″; String a = s.substring( 0, 6 ); // ″Ateneo″ String b = s.substring( 6, 9 ); // ″ de″ String c = s.substring( 10,16 ); // ″Manila″

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 47 Reading keyboard input and the Scanner class To enable keyboard input: Before the declaration of the application class, type: import java.util.Scanner; At the beginning of the main method of the Java application, define a scanner object: Scanner in = new Scanner( System.in ); Then, invoke methods on the Scanner object int i = in.nextInt(); double d = in.nextDouble(); String s = in.nextLine(); // reads an entire line of input String w = in.next(); // reads one word only

Copyright 2008, by the authors of these slides, and Ateneo de Manila University. All rights reserved Types Slide 48 Input example import java.util.Scanner; public class DollarToPesoConversion { public static void main( String args[] ) { Scanner in = new Scanner( System.in ); System.out.print( "Type dollar amount: " ); int dollars = in.nextInt(); System.out.print( "Conversion rate: " ); double rate = in.nextDouble(); System.out.print( "Pesos:" ); System.out.println( dollars*rate ); }