SlideShare a Scribd company logo
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 4 – Fundamental Data Types
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
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
 To understand the proper use of constants
 To write arithmetic expressions in Java
 To use the String type to manipulate character strings
 To write programs that read input and produce formatted output
Copyright © 2014 by John Wiley & Sons. All rights reserved. 3
Physical Memory Layout
https://en.wikipedia.org/wiki/6264
0x000
0x000
0x002
0x003
0x004
0x005
0x006
0x007
0x008
0x009
0x00A
0x00B
0x00C
0x00D
0x00E
0x00F
0x010
0x011
0x012
8 bits
12-bit
addresses
Copyright © 2014 by John Wiley & Sons. All rights reserved. 4
Memory Layout for 16-bit int’s
000100000x000
000001000x000
0x002
0x003
0x004
0x005
0x006
0x007
000001000x008
000100000x009
0x00A
0x00B
0x00C
0x00D
0x00E
0x00F
0x010
0x011
0x012
8 bits
int foo = 1040;
1040 (10) = 00000100 00010000 (2)
Little Endian (Intel)
Big Endian (Motorola)
Alignment is usually required to be at
addresses that are multiples of number
of bytes.
E.g. 2-byte objects aligned at even addresses
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
Memory Layout for 64-bit long’s
x000004100x000
x000000000x000
0x002
0x003
0x004
0x005
0x006
0x007
x000000000x008
x000004100x009
0x00A
0x00B
0x00C
0x00D
0x00E
0x00F
0x010
0x011
0x012
32 bits
long foo = 1040;
Alignment is usually required to be at
addresses that are multiples of number
of bytes.
E.g. 2-word objects aligned at even addresses
1040 (10) = 0x00000410(16)
Little Endian (Intel)
Big Endian (Motorola)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
Number Types
 Every value in Java is either:
• a reference to an object
• one of the eight primitive types
 Java has eight primitive types:
• four integer types
• two floating-point types
• two other
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
Memory Layout for Objects (Little Endian)
0x000000080x000
0x000000000x001
0x002
0x003
0x004
0x005
0x006
0x007
0x008
header
0x009
slot1 = 0x2
0x00A
filler
0x00B
slot2lo = 0x4
0x00C
Slot2hi = 0x0
0x00D
slot3lo = 0x0
0x00E
slot3hi = 0x0
0x00F
0x010
0x011
0x012
32 bits
Public class Foo {
public int slot1 = 2;
public long slot2 = 4;
public Foo slot3;
}
Foo fooObject1 = new Foo();
fooObject1
Object Reference
fooObject1
Object Itself
header
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
Memory Layout for Objects (Little Endian)
0x000000080x000
0x000000000x001
0x002
0x003
0x004
0x005
0x006
0x007
0x008
header
0x009
slot1 = 0x2
0x00A
filler
0x00B
slot2lo = 0x4
0x00C
Slot2hi = 0x0
0x00D
slot3lo = 0x0
0x00E
slot3hi = 0x0
0x00F
0x010
0x011
0x012
32 bits
Public class Foo {
public int slot1 = 2;
public long slot2 = 4;
public Foo slot3;
}
Foo fooObject1 = new Foo();
Foo fooObject2 = new Foo();
fooObject1
Object Reference
fooObject1
Object Itself
header
header
slot1 = 0x2
filler
slot2lo = 0x4
Slot2hi = 0x0
slot3lo = 0x0
header
0x0000000C
0x00000000
fooObject2
Object Reference
fooObject2
Object Itself
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
Memory Layout for Objects (Little Endian)
0x000000080x000
0x000000000x001
0x002
0x003
0x004
0x005
0x006
0x007
0x008
header
0x009
slot1 = 0x2
0x00A
filler
0x00B
slot2lo = 0x4
0x00C
Slot2hi = 0x0
0x00D
slot3lo = 0x0
0x00E
slot3hi = 0x0
0x00F
0x010
0x011
0x012
32 bits
Public class Foo {
public int slot1 = 2;
public long slot2 = 4;
public Foo slot3;
}
Foo fooObject1 = new Foo();
Foo fooObject2 = new Foo();
fooObject2 = fooObject1;
fooObject1
Object Reference
fooObject1
Object Itself
header
header
slot1 = 0x2
filler
slot2lo = 0x4
Slot2hi = 0x0
slot3lo = 0x0
header
0x00000008
0x00000000
fooObject2
Object Reference
“Garbage”
ALIASING
Multiple references to same object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
Memory Layout for Objects (Little Endian)
0x000000080x000
0x000000000x001
0x002
0x003
0x004
0x005
0x006
0x007
0x008
header
0x009
slot1 = 0x2
0x00A
filler
0x00B
slot2lo = 0x4
0x00C
Slot2hi = 0x0
0x00D
slot3lo = 0x0
0x00E
slot3hi = 0x0
0x00F
0x010
0x011
0x012
32 bits
Public class Foo {
public int slot1 = 2;
public long slot2 = 4;
public Foo slot3;
}
Foo fooObject1 = new Foo();
Foo fooObject2 = fooObject1;
fooObject1
Object Reference
fooObject1
Object Itself
header
0x00000008
0x00000000
fooObject2
Object Reference
ALIASING
Multiple references to same object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
Primitive Types
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
Two’s Complement Encoding for Ints
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
Number Literals
 A number that appears in your code
 If it has a decimal, it is floating point
 If not, it is an integer
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Number Literals
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Overflow
 Generally use an int for integers
 Overflow occurs when
• The result of a computation exceeds the range for the number type
 Example
int n = 1000000;
System.out.println(n * n); // Prints –727379968, which is clearly wrong
• 1012 is larger that the largest int
• The result is truncated to fit in an int
• No warning is given
 Solution: use long instead
 Generally do not have overflow with the double data type
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
IEEE 754 Floating Point Standard
Images from: wikipedia.org
IEEE Single Precision = Java Float
IEEE Double Precision = Java Double
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
IEEE 754 Floating Point Standard
For a double-precision number, an exponent in the range −1022 .. +1023 is biased by
adding 1023 to get a value in the range 1 .. 2046 (0 and 2047 have special meanings).
http://www.binaryconvert.com/index.html
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
Rounding Errors
 Rounding errors occur when an exact representation of a
floating-point number is not possible.
 Floating-point numbers have limited precision. Not every value
can be represented precisely, and roundoff errors can occur.
 Example:
double f = 4.35;
System.out.println(100 * f); // Prints 434.99999999999994
 Use double type in most cases
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
IEEE 754 Floating Point Standard
Rounding errors may be caused by base-2 encoded mantissas
http://www.binaryconvert.com/index.html
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Relative Precision of Float/Double
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
Constants: final
 Use symbolic names for all values, even those that appear obvious.
 A final variable is a constant
• Once its value has been set, it cannot be changed
 Named constants make programs easier to read and maintain.
 Convention: use all-uppercase names for constants:
final double QUARTER_VALUE = 0.25;
final double DIME_VALUE = 0.1;
final double NICKEL_VALUE = 0.05;
final double PENNY_VALUE = 0.01;
payment = dollars + quarters * QUARTER_VALUE +
dimes * DIME_VALUE + nickels * NICKEL_VALUE +
pennies * PENNY_VALUE;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Constants: static final
 If constant values are needed in several methods,
• Declare them together with the instance variables of a class
• Tag them as static and final
• The static reserved word means that the constant belongs to the class
 Give static final constants public access to enable other classes
to use them.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Constants: static final
 Declaration of constants in the Math class
public class Math
{
. . .
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
}
 Using a constant
double circumference = Math.PI * diameter;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
Java Operators and their Precedence
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
Integer Division and Remainder
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Mathematical Methods
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
Syntax 4.2 Cast
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Arithmetic Expressions
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
Calling Static Methods
 Can not call a method on a number type double
root = 2.sqrt(); // Error
 Use a static method instead.
 A static method does not operate on an object:
double root = Math.sqrt(2); // Correct
 static methods are declared inside classes
 Calling a static method:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Reading Input
 When a program asks for user input
• It should first print a message that tells the user which input is expected
System.out.print("Please enter the number of bottles: "); // Display prompt
 This message is called a prompt
• Use the print method, not println, to display the prompt
• Leave a space after the colon
 System.in has minimal set of features
• Must be combined with other classes to be useful
 Use a class called Scanner to read keyboard input.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
Reading Input - Scanner
 To obtain a Scanner object:
Scanner in = new Scanner(System.in);
 Use the Scanner's nextInt method to read an integer value:
System.out.print("Please enter the number of bottles: ");
int bottles = in.nextInt();
 When the nextInt method is called,
• The program waits until the user types a number and presses the Enter
key;
• After the user supplies the input, the number is placed into the bottles
variable;
• The program continues.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
Reading Input - Scanner
 Use the nextDouble method to read a floating-point number:
System.out.print("Enter price: ");
double price = in.nextDouble();
 To use the Scanner class, import it by placing the following at
the top of your program file:
import java.util.Scanner;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
Syntax 4.3 Input Statement
Copyright © 2014 by John Wiley & Sons. All rights reserved. 59
Formatted Output
 Use the printf method to specify how values should be
formatted.
 printf lets you print this
Price per liter: 1.22
 Instead of this
Price per liter: 1.215962441314554
 This command displays the price with two digits after the
decimal point:
System.out.printf("%.2f", price);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
Formatted Output
 You can also specify a field width:
System.out.printf("%10.2f", price);
 This prints 10 characters
• Six spaces followed by the four characters 1.22
 This command
System.out.printf("Price per liter:%10.2f", price);
 Prints
Price per liter: 1.22
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
Formatted Output
Copyright © 2014 by John Wiley & Sons. All rights reserved. 63
Formatted Output
 You can print multiple values with a single call to the printf
method.
 Example
System.out.printf("Quantity: %d Total: %10.2f",
quantity, total);
 Output explained:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 83
String Type
 A string is a sequence of characters.
 You can declare variables that hold strings
String name = "Harry";
 A string variable is a variable that can hold a string
 String literals are character sequences enclosed in quotes
 A string literal denotes a particular string
"Harry"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 84
String Type
 String length is the number of characters in the string
• The length of "Harry" is 5
 The length method yields the number of characters in a string
• int n = name.length();
 A string of length 0 is called the empty string
• Contains no characters
• Is written as ""
Copyright © 2014 by John Wiley & Sons. All rights reserved. 85
Concatenation
 Concatenating strings means to put them together to form a
longer string
 Use the + operator
 Example:
String fName = "Harry”;
String lName = "Morgan”;
String name = fName + lName;
 Result:
"HarryMorgan"
 To separate the first and last name with a space
String name = fName + " " + lName;
 Results in
"Harry Morgan"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 86
Concatenation
 If one of the arguments of the + operator is a string
• The other is forced to become to a string:
• Both strings are then concatenated
 Example
String jobTitle = "Agent”;
int employeeId = 7;
String bond = jobTitle + employeeId;
 Result
"Agent7"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 87
Concatenation in Print Statements
 Useful to reduce the number of System.out.print instructions
System.out.print("The total is "); System.out.println(total);
versus
System.out.println("The total is " + total);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 88
String Input
 Use the next method of the Scanner class to read a string
containing a single word.
System.out.print("Please enter your name: ");
String name = in.next();
 Only one word is read.
 Use a second call to in.next to get a second word.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 90
Strings and Characters
 A string is a sequences of Unicode characters.
 A character is a value of the type char.
• Characters have numeric values
 Character literals are delimited by single quotes.
• 'H' is a character. It is a value of type char
 Don't confuse them with strings
• "H" is a string containing a single character. It is a value of type String.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 91
Strings and Characters
 String positions are counted starting with 0.
 The position number of the last character is always one less
than the length of the string.
 The last character of the string "Harry" is at position 4
 The charAt method returns a char value from a string
 The example
String name = "Harry”;
char start = name.charAt(0);
char last = name.charAt(4);
• Sets start to the value 'H' and last to the value 'y'.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 92
Substrings
 Use the substring method to extract a part of a string.
 The method call str.substring(start, pastEnd)
• returns a string that is made up of the characters in the string str,
• starting at position start, and
• containing all characters up to, but not including, the position pastEnd.
 Example:
String greeting = "Hello, World!”;
String sub = greeting.substring(0, 5); // sub is "Hello”
Copyright © 2014 by John Wiley & Sons. All rights reserved. 93
Substrings
 To extract "World"
String sub2 = greeting.substring(7, 12);
 Substring length is “past the end” - start
Copyright © 2014 by John Wiley & Sons. All rights reserved. 94
Substrings
 If you omit the end position when calling the substring method,
then all characters from the starting position to the end of the
string are copied.
 Example
String tail = greeting.substring(7); // Copies all characters from position 7 on
 Result
• Sets tail to the string "World!".
Copyright © 2014 by John Wiley & Sons. All rights reserved. 95
Substrings
 To make a string of one character, taken from the start of first
first.substring(0, 1)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 96
section_5/Initials.java
1 import java.util.Scanner;
2
3 /**
4 This program prints a pair of initials.
5 */
6 public class Initials
7 {
8 public static void main(String[] args)
9 {
10 Scanner in = new Scanner(System.in);
11
12 // Get the names of the couple
13
14 System.out.print("Enter your first name: ");
15 String first = in.next();
16 System.out.print("Enter your significant other's first name: ");
17 String second = in.next();
18
19 // Compute and display the inscription
20
21 String initials = first.substring(0, 1)
22 + "&" + second.substring(0, 1);
23 System.out.println(initials);
24 }
25 } Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 97
section_5/Initials.java
Program Run
Enter your first name: Rodolfo
Enter your significant other's first name: Sally
R&S
Copyright © 2014 by John Wiley & Sons. All rights reserved. 98
String Operations

More Related Content

What's hot

Icom4015 lecture13-f16
Icom4015 lecture13-f16Icom4015 lecture13-f16
Icom4015 lecture13-f16
BienvenidoVelezUPR
 
Icom4015 lecture12-s16
Icom4015 lecture12-s16Icom4015 lecture12-s16
Icom4015 lecture12-s16
BienvenidoVelezUPR
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
BienvenidoVelezUPR
 
Icom4015 lecture3-f17
Icom4015 lecture3-f17Icom4015 lecture3-f17
Icom4015 lecture3-f17
BienvenidoVelezUPR
 
Icom4015 lecture9-f16
Icom4015 lecture9-f16Icom4015 lecture9-f16
Icom4015 lecture9-f16
BienvenidoVelezUPR
 
Icom4015 lecture4-f17
Icom4015 lecture4-f17Icom4015 lecture4-f17
Icom4015 lecture4-f17
BienvenidoVelezUPR
 
CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17
BienvenidoVelezUPR
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
BienvenidoVelezUPR
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
BienvenidoVelezUPR
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
BienvenidoVelezUPR
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
Eduardo Bergavera
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
Blue Elephant Consulting
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
imypraz
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
Mahmoud Ouf
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
simarsimmygrewal
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
07slide
07slide07slide
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
Gus Sandoval
 

What's hot (20)

Icom4015 lecture13-f16
Icom4015 lecture13-f16Icom4015 lecture13-f16
Icom4015 lecture13-f16
 
Icom4015 lecture12-s16
Icom4015 lecture12-s16Icom4015 lecture12-s16
Icom4015 lecture12-s16
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Icom4015 lecture3-f17
Icom4015 lecture3-f17Icom4015 lecture3-f17
Icom4015 lecture3-f17
 
Icom4015 lecture9-f16
Icom4015 lecture9-f16Icom4015 lecture9-f16
Icom4015 lecture9-f16
 
Icom4015 lecture4-f17
Icom4015 lecture4-f17Icom4015 lecture4-f17
Icom4015 lecture4-f17
 
CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
07slide
07slide07slide
07slide
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
 

Similar to Icom4015 lecture3-f16

Core java
Core javaCore java
Core java
Shivaraj R
 
Core java
Core javaCore java
Core java
Sun Technlogies
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
MohammedAlYemeni1
 
Introductionof c
Introductionof cIntroductionof c
Introductionof c
Phanibabu Komarapu
 
02slide_accessible.pptx
02slide_accessible.pptx02slide_accessible.pptx
02slide_accessible.pptx
MattMarino13
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
Ali Raza Jilani
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
Rakesh Roshan
 
Variables and Data Types
Variables and Data TypesVariables and Data Types
Variables and Data Types
Infoviaan Technologies
 
TeelTech - Advancing Mobile Device Forensics (online version)
TeelTech - Advancing Mobile Device Forensics (online version)TeelTech - Advancing Mobile Device Forensics (online version)
TeelTech - Advancing Mobile Device Forensics (online version)
Mike Felch
 
Training report anish
Training report anishTraining report anish
Training report anish
Anish Yadav
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
PurvaShyama
 
Core java
Core javaCore java
Core java
Mallikarjuna G D
 
How To Code in C#
How To Code in C#How To Code in C#
How To Code in C#
David Ringsell
 
Complete c programming presentation
Complete c programming presentationComplete c programming presentation
Complete c programming presentation
nadim akber
 
Java Programming For Android
Java Programming For AndroidJava Programming For Android
Java Programming For Android
TechiNerd
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
vijayapraba1
 
TDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 editionTDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 edition
Hendrik Neumann
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
Mufaddal Nullwala
 
Zaridah lecture2
Zaridah lecture2Zaridah lecture2
Zaridah lecture2
Aziz Sahat
 

Similar to Icom4015 lecture3-f16 (20)

Core java
Core javaCore java
Core java
 
Core java
Core javaCore java
Core java
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
Introductionof c
Introductionof cIntroductionof c
Introductionof c
 
02slide_accessible.pptx
02slide_accessible.pptx02slide_accessible.pptx
02slide_accessible.pptx
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
Variables and Data Types
Variables and Data TypesVariables and Data Types
Variables and Data Types
 
TeelTech - Advancing Mobile Device Forensics (online version)
TeelTech - Advancing Mobile Device Forensics (online version)TeelTech - Advancing Mobile Device Forensics (online version)
TeelTech - Advancing Mobile Device Forensics (online version)
 
Training report anish
Training report anishTraining report anish
Training report anish
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
 
Core java
Core javaCore java
Core java
 
How To Code in C#
How To Code in C#How To Code in C#
How To Code in C#
 
Complete c programming presentation
Complete c programming presentationComplete c programming presentation
Complete c programming presentation
 
Java Programming For Android
Java Programming For AndroidJava Programming For Android
Java Programming For Android
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
 
TDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 editionTDD in the ABAP world - sitNL 2013 edition
TDD in the ABAP world - sitNL 2013 edition
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Zaridah lecture2
Zaridah lecture2Zaridah lecture2
Zaridah lecture2
 

Recently uploaded

DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
Madan Karki
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
gray level transformation unit 3(image processing))
gray level transformation unit 3(image processing))gray level transformation unit 3(image processing))
gray level transformation unit 3(image processing))
shivani5543
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
sachin chaurasia
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 

Recently uploaded (20)

DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
gray level transformation unit 3(image processing))
gray level transformation unit 3(image processing))gray level transformation unit 3(image processing))
gray level transformation unit 3(image processing))
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 

Icom4015 lecture3-f16

  • 1. Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 4 – Fundamental Data Types
  • 2. Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 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  To understand the proper use of constants  To write arithmetic expressions in Java  To use the String type to manipulate character strings  To write programs that read input and produce formatted output
  • 3. Copyright © 2014 by John Wiley & Sons. All rights reserved. 3 Physical Memory Layout https://en.wikipedia.org/wiki/6264 0x000 0x000 0x002 0x003 0x004 0x005 0x006 0x007 0x008 0x009 0x00A 0x00B 0x00C 0x00D 0x00E 0x00F 0x010 0x011 0x012 8 bits 12-bit addresses
  • 4. Copyright © 2014 by John Wiley & Sons. All rights reserved. 4 Memory Layout for 16-bit int’s 000100000x000 000001000x000 0x002 0x003 0x004 0x005 0x006 0x007 000001000x008 000100000x009 0x00A 0x00B 0x00C 0x00D 0x00E 0x00F 0x010 0x011 0x012 8 bits int foo = 1040; 1040 (10) = 00000100 00010000 (2) Little Endian (Intel) Big Endian (Motorola) Alignment is usually required to be at addresses that are multiples of number of bytes. E.g. 2-byte objects aligned at even addresses
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 5 Memory Layout for 64-bit long’s x000004100x000 x000000000x000 0x002 0x003 0x004 0x005 0x006 0x007 x000000000x008 x000004100x009 0x00A 0x00B 0x00C 0x00D 0x00E 0x00F 0x010 0x011 0x012 32 bits long foo = 1040; Alignment is usually required to be at addresses that are multiples of number of bytes. E.g. 2-word objects aligned at even addresses 1040 (10) = 0x00000410(16) Little Endian (Intel) Big Endian (Motorola)
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 6 Number Types  Every value in Java is either: • a reference to an object • one of the eight primitive types  Java has eight primitive types: • four integer types • two floating-point types • two other
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 Memory Layout for Objects (Little Endian) 0x000000080x000 0x000000000x001 0x002 0x003 0x004 0x005 0x006 0x007 0x008 header 0x009 slot1 = 0x2 0x00A filler 0x00B slot2lo = 0x4 0x00C Slot2hi = 0x0 0x00D slot3lo = 0x0 0x00E slot3hi = 0x0 0x00F 0x010 0x011 0x012 32 bits Public class Foo { public int slot1 = 2; public long slot2 = 4; public Foo slot3; } Foo fooObject1 = new Foo(); fooObject1 Object Reference fooObject1 Object Itself header
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 8 Memory Layout for Objects (Little Endian) 0x000000080x000 0x000000000x001 0x002 0x003 0x004 0x005 0x006 0x007 0x008 header 0x009 slot1 = 0x2 0x00A filler 0x00B slot2lo = 0x4 0x00C Slot2hi = 0x0 0x00D slot3lo = 0x0 0x00E slot3hi = 0x0 0x00F 0x010 0x011 0x012 32 bits Public class Foo { public int slot1 = 2; public long slot2 = 4; public Foo slot3; } Foo fooObject1 = new Foo(); Foo fooObject2 = new Foo(); fooObject1 Object Reference fooObject1 Object Itself header header slot1 = 0x2 filler slot2lo = 0x4 Slot2hi = 0x0 slot3lo = 0x0 header 0x0000000C 0x00000000 fooObject2 Object Reference fooObject2 Object Itself
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 9 Memory Layout for Objects (Little Endian) 0x000000080x000 0x000000000x001 0x002 0x003 0x004 0x005 0x006 0x007 0x008 header 0x009 slot1 = 0x2 0x00A filler 0x00B slot2lo = 0x4 0x00C Slot2hi = 0x0 0x00D slot3lo = 0x0 0x00E slot3hi = 0x0 0x00F 0x010 0x011 0x012 32 bits Public class Foo { public int slot1 = 2; public long slot2 = 4; public Foo slot3; } Foo fooObject1 = new Foo(); Foo fooObject2 = new Foo(); fooObject2 = fooObject1; fooObject1 Object Reference fooObject1 Object Itself header header slot1 = 0x2 filler slot2lo = 0x4 Slot2hi = 0x0 slot3lo = 0x0 header 0x00000008 0x00000000 fooObject2 Object Reference “Garbage” ALIASING Multiple references to same object
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 10 Memory Layout for Objects (Little Endian) 0x000000080x000 0x000000000x001 0x002 0x003 0x004 0x005 0x006 0x007 0x008 header 0x009 slot1 = 0x2 0x00A filler 0x00B slot2lo = 0x4 0x00C Slot2hi = 0x0 0x00D slot3lo = 0x0 0x00E slot3hi = 0x0 0x00F 0x010 0x011 0x012 32 bits Public class Foo { public int slot1 = 2; public long slot2 = 4; public Foo slot3; } Foo fooObject1 = new Foo(); Foo fooObject2 = fooObject1; fooObject1 Object Reference fooObject1 Object Itself header 0x00000008 0x00000000 fooObject2 Object Reference ALIASING Multiple references to same object
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 11 Primitive Types
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 12 Two’s Complement Encoding for Ints
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 13 Number Literals  A number that appears in your code  If it has a decimal, it is floating point  If not, it is an integer
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 14 Number Literals
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 Overflow  Generally use an int for integers  Overflow occurs when • The result of a computation exceeds the range for the number type  Example int n = 1000000; System.out.println(n * n); // Prints –727379968, which is clearly wrong • 1012 is larger that the largest int • The result is truncated to fit in an int • No warning is given  Solution: use long instead  Generally do not have overflow with the double data type
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 16 IEEE 754 Floating Point Standard Images from: wikipedia.org IEEE Single Precision = Java Float IEEE Double Precision = Java Double
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 17 IEEE 754 Floating Point Standard For a double-precision number, an exponent in the range −1022 .. +1023 is biased by adding 1023 to get a value in the range 1 .. 2046 (0 and 2047 have special meanings). http://www.binaryconvert.com/index.html
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 Rounding Errors  Rounding errors occur when an exact representation of a floating-point number is not possible.  Floating-point numbers have limited precision. Not every value can be represented precisely, and roundoff errors can occur.  Example: double f = 4.35; System.out.println(100 * f); // Prints 434.99999999999994  Use double type in most cases
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 IEEE 754 Floating Point Standard Rounding errors may be caused by base-2 encoded mantissas http://www.binaryconvert.com/index.html
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 Relative Precision of Float/Double
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 Constants: final  Use symbolic names for all values, even those that appear obvious.  A final variable is a constant • Once its value has been set, it cannot be changed  Named constants make programs easier to read and maintain.  Convention: use all-uppercase names for constants: final double QUARTER_VALUE = 0.25; final double DIME_VALUE = 0.1; final double NICKEL_VALUE = 0.05; final double PENNY_VALUE = 0.01; payment = dollars + quarters * QUARTER_VALUE + dimes * DIME_VALUE + nickels * NICKEL_VALUE + pennies * PENNY_VALUE;
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 Constants: static final  If constant values are needed in several methods, • Declare them together with the instance variables of a class • Tag them as static and final • The static reserved word means that the constant belongs to the class  Give static final constants public access to enable other classes to use them.
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Constants: static final  Declaration of constants in the Math class public class Math { . . . public static final double E = 2.7182818284590452354; public static final double PI = 3.14159265358979323846; }  Using a constant double circumference = Math.PI * diameter;
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 34 Java Operators and their Precedence
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 Integer Division and Remainder
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Mathematical Methods
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 46 Syntax 4.2 Cast
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 47 Arithmetic Expressions
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 53 Calling Static Methods  Can not call a method on a number type double root = 2.sqrt(); // Error  Use a static method instead.  A static method does not operate on an object: double root = Math.sqrt(2); // Correct  static methods are declared inside classes  Calling a static method:
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 Reading Input  When a program asks for user input • It should first print a message that tells the user which input is expected System.out.print("Please enter the number of bottles: "); // Display prompt  This message is called a prompt • Use the print method, not println, to display the prompt • Leave a space after the colon  System.in has minimal set of features • Must be combined with other classes to be useful  Use a class called Scanner to read keyboard input.
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 Reading Input - Scanner  To obtain a Scanner object: Scanner in = new Scanner(System.in);  Use the Scanner's nextInt method to read an integer value: System.out.print("Please enter the number of bottles: "); int bottles = in.nextInt();  When the nextInt method is called, • The program waits until the user types a number and presses the Enter key; • After the user supplies the input, the number is placed into the bottles variable; • The program continues.
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 Reading Input - Scanner  Use the nextDouble method to read a floating-point number: System.out.print("Enter price: "); double price = in.nextDouble();  To use the Scanner class, import it by placing the following at the top of your program file: import java.util.Scanner;
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 58 Syntax 4.3 Input Statement
  • 34. Copyright © 2014 by John Wiley & Sons. All rights reserved. 59 Formatted Output  Use the printf method to specify how values should be formatted.  printf lets you print this Price per liter: 1.22  Instead of this Price per liter: 1.215962441314554  This command displays the price with two digits after the decimal point: System.out.printf("%.2f", price);
  • 35. Copyright © 2014 by John Wiley & Sons. All rights reserved. 60 Formatted Output  You can also specify a field width: System.out.printf("%10.2f", price);  This prints 10 characters • Six spaces followed by the four characters 1.22  This command System.out.printf("Price per liter:%10.2f", price);  Prints Price per liter: 1.22
  • 36. Copyright © 2014 by John Wiley & Sons. All rights reserved. 62 Formatted Output
  • 37. Copyright © 2014 by John Wiley & Sons. All rights reserved. 63 Formatted Output  You can print multiple values with a single call to the printf method.  Example System.out.printf("Quantity: %d Total: %10.2f", quantity, total);  Output explained:
  • 38. Copyright © 2014 by John Wiley & Sons. All rights reserved. 83 String Type  A string is a sequence of characters.  You can declare variables that hold strings String name = "Harry";  A string variable is a variable that can hold a string  String literals are character sequences enclosed in quotes  A string literal denotes a particular string "Harry"
  • 39. Copyright © 2014 by John Wiley & Sons. All rights reserved. 84 String Type  String length is the number of characters in the string • The length of "Harry" is 5  The length method yields the number of characters in a string • int n = name.length();  A string of length 0 is called the empty string • Contains no characters • Is written as ""
  • 40. Copyright © 2014 by John Wiley & Sons. All rights reserved. 85 Concatenation  Concatenating strings means to put them together to form a longer string  Use the + operator  Example: String fName = "Harry”; String lName = "Morgan”; String name = fName + lName;  Result: "HarryMorgan"  To separate the first and last name with a space String name = fName + " " + lName;  Results in "Harry Morgan"
  • 41. Copyright © 2014 by John Wiley & Sons. All rights reserved. 86 Concatenation  If one of the arguments of the + operator is a string • The other is forced to become to a string: • Both strings are then concatenated  Example String jobTitle = "Agent”; int employeeId = 7; String bond = jobTitle + employeeId;  Result "Agent7"
  • 42. Copyright © 2014 by John Wiley & Sons. All rights reserved. 87 Concatenation in Print Statements  Useful to reduce the number of System.out.print instructions System.out.print("The total is "); System.out.println(total); versus System.out.println("The total is " + total);
  • 43. Copyright © 2014 by John Wiley & Sons. All rights reserved. 88 String Input  Use the next method of the Scanner class to read a string containing a single word. System.out.print("Please enter your name: "); String name = in.next();  Only one word is read.  Use a second call to in.next to get a second word.
  • 44. Copyright © 2014 by John Wiley & Sons. All rights reserved. 90 Strings and Characters  A string is a sequences of Unicode characters.  A character is a value of the type char. • Characters have numeric values  Character literals are delimited by single quotes. • 'H' is a character. It is a value of type char  Don't confuse them with strings • "H" is a string containing a single character. It is a value of type String.
  • 45. Copyright © 2014 by John Wiley & Sons. All rights reserved. 91 Strings and Characters  String positions are counted starting with 0.  The position number of the last character is always one less than the length of the string.  The last character of the string "Harry" is at position 4  The charAt method returns a char value from a string  The example String name = "Harry”; char start = name.charAt(0); char last = name.charAt(4); • Sets start to the value 'H' and last to the value 'y'.
  • 46. Copyright © 2014 by John Wiley & Sons. All rights reserved. 92 Substrings  Use the substring method to extract a part of a string.  The method call str.substring(start, pastEnd) • returns a string that is made up of the characters in the string str, • starting at position start, and • containing all characters up to, but not including, the position pastEnd.  Example: String greeting = "Hello, World!”; String sub = greeting.substring(0, 5); // sub is "Hello”
  • 47. Copyright © 2014 by John Wiley & Sons. All rights reserved. 93 Substrings  To extract "World" String sub2 = greeting.substring(7, 12);  Substring length is “past the end” - start
  • 48. Copyright © 2014 by John Wiley & Sons. All rights reserved. 94 Substrings  If you omit the end position when calling the substring method, then all characters from the starting position to the end of the string are copied.  Example String tail = greeting.substring(7); // Copies all characters from position 7 on  Result • Sets tail to the string "World!".
  • 49. Copyright © 2014 by John Wiley & Sons. All rights reserved. 95 Substrings  To make a string of one character, taken from the start of first first.substring(0, 1)
  • 50. Copyright © 2014 by John Wiley & Sons. All rights reserved. 96 section_5/Initials.java 1 import java.util.Scanner; 2 3 /** 4 This program prints a pair of initials. 5 */ 6 public class Initials 7 { 8 public static void main(String[] args) 9 { 10 Scanner in = new Scanner(System.in); 11 12 // Get the names of the couple 13 14 System.out.print("Enter your first name: "); 15 String first = in.next(); 16 System.out.print("Enter your significant other's first name: "); 17 String second = in.next(); 18 19 // Compute and display the inscription 20 21 String initials = first.substring(0, 1) 22 + "&" + second.substring(0, 1); 23 System.out.println(initials); 24 } 25 } Continued
  • 51. Copyright © 2014 by John Wiley & Sons. All rights reserved. 97 section_5/Initials.java Program Run Enter your first name: Rodolfo Enter your significant other's first name: Sally R&S
  • 52. Copyright © 2014 by John Wiley & Sons. All rights reserved. 98 String Operations