COMP 250
INTRODUCTION TO COMPUTER SCIENCE
Week 2-1: Primitive Data Types and Strings
Giulia Alberini, Fall 2020
WHAT ARE WE GOING TO DO IN THIS VIDEO?
Primitive data types char
String
type conversion
PRIMITIVE DATA TYPES
PRIMITIVE TYPES
A primitive type is
predefined by the language, and named by a reserved keyword
Java supports 8 primitive data types.
THE 8 TYPES SUPPORTED
byte short
int
long float double boolean char
Integer values
Real Numbers
true or false One character
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
HOW MANY VALUES?
How many values can you represent with: 1 bit?
2 bits?
3 bits?
And what about 𝑛 bits?
2𝑛
HOW MANY BITS?
And how many bits do you need to represent: 2 different values?
4 different values?
5 different values?
And what about 𝑥 different values?
log2 𝑥
So, how many bits do you need to store a boolean?
HOW MANY BITS N DO WE NEED TO REPRESENT A POSITIVE INTEGER m? 𝑁−1
𝑚 = 𝑏 2𝑖 𝑖
𝑖=0
What is the relationship between 𝑚 and N ?
GEOMETRIC SERIES
Recall that,
That is, if 𝑥 = 2,
𝑁−1 𝑥𝑁 −1 𝑥𝑖 =1+𝑥+𝑥2 +𝑥3 +⋯+𝑥𝑁−1 = 𝑥−1
𝑖=0
𝑁−1
2𝑖 = 2𝑁 − 1 𝑖=0
HOW MANY BITS N DO WE NEED TO REPRESENT A POSITIVE INTEGER m?
Thus,
𝑚 < 2𝑁
To solve for 𝑁, we take the log (base 2) of both sides and obtain the following equation:
Lower bound
𝑁 > log2 𝑚
HOW MANY BITS N DO WE NEED TO REPRESENT A POSITIVE INTEGER m? Now, let’s assume that 𝑁 − 1 is the index 𝑖 of the leftmost bit 𝑏𝑖 such that
𝑏𝑖 = 1.
e.g. We ignore leftmost 0’s of the binary representation of 𝑚, (… 00000010011)2 Then,
Taking the log (base 2) of both sides,
Upper Bound
HOW MANY BITS N DO WE NEED TO REPRESENT A POSITIVE INTEGER m? We proved that,
log2 𝑚 < 𝑁 ≤ (log2 𝑚) + 1
Thus, 𝑁 must be equal to the largest integer less than or equal to (log2 𝑚) + 1.
We write,
𝑁=𝑓𝑙𝑜𝑜𝑟 log2𝑚 +1 = log2𝑚 +1 where 𝑓𝑙𝑜𝑜𝑟 means "round down to the nearest integer".
WHY DIFFERENT TYPES?
It turns out that the difference between the types storing integer values and real numbers is the number of bits reserved for those values. For more info: COMP 273
Description
Keyword
Size
Values
Very Small Integer
byte
8-bits
[−128, 127]
Small Integer
short
16-bits
15 15 [−2 , 2 −1]
Integer
int
32-bits
[−231,231 −1]
Big Integer
long
64-bits
[−263,263 −1]
Low Precision Reals
float
32-bits
-
High Precision Reals
double
64-bits
-
True/False
boolean
1-bit
[true, false]
One character
char
16-bits
-
OVERFLOW AND UNDERFLOW
Variables of type int store values between 231 − 1 and −231. 231 − 1 = 2147483647 (Integer.MAX_VALUE)
−231= −2147483648 (Integer.MIN_VALUE)
What happens if:
int x = 2147483647;
System.out.println(x+1);
int y = -2147483648; System.out.println(y-1);
Output:-2147483648
Output 2147483647
STORING INTEGER AND OVERFLOW
Let's pretend that we only have 8 bits.
7 bits are used to store the number, and the left most bit for the sign.
0 means positive and 1 means negative.
0111 1111 = 127 What happens if we add 1?
STORING INTEGER AND OVERFLOW
Let's pretend that we only have 8 bits.
7 bits are used to store the number, and the left most bit for the sign.
0 means positive and 1 means negative. 0111 1111 = 127
What happens if we add 1?
1000 0000 = −128
Note that negative numbers are stored a little bit differently. For more info see: https://en.wikipedia.org/wiki/Two's_complement
EXAMPLES
EXAMPLES
Therac-25, radiation machine
• overflow during safety
checks
• metal target would not be
moved into place.
• result: beams 100 times
higher than intended were
fired into patients.
• 6 known cases causing the
death of 4 patients.
FLOATING POINT
In java the default floating point type is double.
All standard arithmetic operations can be done on floating point.
NOTE: Java distinguishes between 1 and 1.0.
If you write .0 after an integer, it will be considered to be a double.
int x = 3.0;
int x = 3;
double x = 3.0;
BE CAREFUL!
Java automatically converts one type to the other (e.g. int to double) if need be AND if no loss of information would occur.
double x = 1; // legal, but bad style!
If the mathematical operators are used with at least one operand of type double, then java will convert the other operands to double and it will output a values of type double. BUT, if all the operands are integers, the output of the operator will also be an integer!!
int x = 1.0/2; // compiler error!
double y = 1/4; // no compiler error, but is it correct?
CHAR and UNICODE
CHAR DATA TYPE
We have seen char as one of the primitive data types that we have in Java. We can declare and initialize a variable of type char as follows:
char letter = 'a';
Character literals appears in single quotes
Character literals can only contain a single character
ESCAPE SEQUENCES
Escape sequence: a sequence of characters that represents a special character.
Examples:
\n represents the character newline \" or \' represent quotation marks \t represents a tab.
Escape sequences are legal characters because they represent a single character
char nl = '\n';
UNICODE
A character set is an ordered list of character, where each character corresponds to a unique number.
Unicode is an international character set. Java uses Unicode to represent characters.
Variables of type char have 16 bits reserved in the memory to store a value.
Each character is represented by an integer. Note: not every integer represent a character!
ASCII VS UNICODE
ASCII: 7 bits.It can represent 128 characters. UNICODE: 16 bits 65536 characters.
It is a superset of ASCII: the numbers 0-127 map to the same characters both in ASCII and Unicode.
ASCII TABLE
CHARACTER ARITHMETIC
Since every character is practically an integer, we can perform arithmetic operations on variables of type char.
char first = 'a';
char second = (char) (first + 1);
What is the value of second? 'b'
Note the typecasting!
first is automatically converted into an integer, and first + 1 evaluates to 98.
Then the typecasting converts the int into a char, and stores 'b' in second.
COMPARING CHARS
char letter = 'g';
if(letter == 'a') {
System.out.println("first letter of the alphabet");
} else if (letter == 'z') {
System.out.println("Last letter of the alphabet");
} else if (letter > ‘a’ && letter < 'z') {
System.out.println("Another letter of the alphabet");
} else {
System.out.println("Not a lower case letter of the alphabet");
}
What prints?
Another letter of the alphabet
TRY IT! - charRightShift
Write a method called charRightShift which takes a character and an integer n as inputs, and returns a character. If the character received as input is a lower case letter of the English alphabet, the method returns the letter of the alphabet which is n positions to the right on the alphabet. If the character received as input is not a lower case letter of the English alphabet, then the method returns the character itself with no modifications.
For example:
charRightShift('g', 2 )returns'i', charRightShift('#', 2 )returns'#' charRightShift('z', 27 )returns'a'
TYPE CASTING
TYPECASTING
We can convert back and forth between variables of different types using typecasting. (or casting, for short)
int x = 3;
double y = 4.56;
int n = (int) y; double m = (double) x;
What are the values of x, y, n, and m?
x = 3, y = 4.56, n = 4, m = 3.0
PRIMITIVE TYPE CONVERSION – INT ↔ DOUBLE
When going from int to double, an explicit cast is NOT
necessary.
When going from double to int, you will get a compile-time error if you don't have an explicit cast.
PRIMITIVE TYPE CONVERSION – IN GENERAL
wider
Here, wider usually
(but not always)
means more bytes.
type number of bits
double 64
float 32 long 64 int 32 char 16 short 16 byte 8
narrower
NOTE: char is "special"... see the following slides.
EXAMPLES
int i = 3;
double d = 4.2;
d = i; // widening (implicit casting)
EXAMPLES
int i = 3;
double d = 4.2;
d = i; // widening (implicit casting)
d = 5.3 * i; // widening(by "promotion")
EXAMPLES
int i = 3;
double d = 4.2;
d = i; // widening (implicit casting)
d = 5.3 * i; // widening(by "promotion")
i = (int)d; // narrowing(by casting)
float f = (float) d; // narrowing (by casting)
EXAMPLES
int i = 3;
double d = 4.2;
d = i; // widening (implicit casting)
d = 5.3 * i; // widening(by "promotion")
i = (int)d; // narrowing(by casting)
float f = (float) d; // narrowing (by casting)
• For primitive types, both widening and narrowing change the bit representation. (See COMP 273.)
• For narrowing conversions, you get a compiler error if you don't cast.
EXAMPLES WITH CHAR
char c = 'q';
int x = c // widening
EXAMPLES WITH CHAR
char c = 'q';
int x = c // widening
c = (char) x; // narrowing
EXAMPLES WITH CHAR
char c = 'q';
int x = c // widening
c = (char) x; // narrowing
short y = 12;
c = y; // compile time error!! (need explicit casting)
y = c; // compile time error!! Narrowingneed explicit casting
STRINGS
STRING
Recall that a String is sequence of characters.
String is a Class and a string literal is an Object.
(more on classes and objects in the following weeks)
We cannot use on Strings the same operators we use on primitive data types.
There's a set of methods provided to manipulate characters and they can be called on values of type String.
DOCUMENTATION
You can find it here:
https://docs.oracle.com/java se/7/docs/api/java/lang/Stri ng.html
COMPARING STRINGS
To compare two strings you can use one of the following methods
equals is case sensitive, use equalsIgnoreCase if you don't want to distinguish between upper and lower case.
Note that there's no keyword static!
This means that the methods need to be called on a specific value/variable of type String and not on the name of the class (like, for instance, the method abs from the Math library).
EXAMPLES
String course = "COMP 250";
String course2 = "comp 250";
boolean a = course.equals(course2);
boolean b = course.equalsIgnoreCase(course2);
The value of a is false The value of b is true
BE CAREFUL!
If you try to use == or != on Strings you program will compile and run.
It is not doing what you think it's doing though.
Always use equals or equalsIgnoreCase if you want to compare strings.
OTHER METHODS
Let s be a variable of type String. Then some useful methods include: s.length()
It takes no inputs and returns the number of characters in the String s.
s.charAt(i)
It takes an integer as input and returns the character in the String s which has index equal to i. The index determines the position of the character in the String. Note that the first character is in position 0.
If in the String s there's no character with index i, then we will get a run-time error. (StringIndexOutOfBoundsException)
EXAMPLE
String s = "Another string"; System.out.println(s.length());
What prints?
14
EXAMPLE
String s = "Another string"; System.out.println(s.charAt(2));
What prints?
o
EXAMPLE
String s = "Another string"; System.out.println(s.charAt(0)=='a');
What prints?
false
REVIEW – METHODS FROM THE STRING CLASS
String s = "Review";
Example – method call
Input type
Return type
Return value
s.equals("review")
String
boolean
false
s.equalsIgnoreCase("review")
String
boolean
true
s.length()
none
int
6
s.charAt(2)
int
char
'v'
s.toLowerCase()
none
String
"review"
s.toUpperCase()
none
String
"REVIEW"
CONVERTING TYPES WITH STRINGS
You cannot use a cast when converting from a String.
To convert from int/double to a String, just concatenate the
number with the empty String ("").
To convert from a String to an int, use:
String s = "" + 4;
int x = Integer.parseInt("54"); String s = "5";
int y = Integer.parseInt(s);
To convert from a String to a double, use:
double z = Double.parseDouble("5.4");
TRY IT!
1. Write a method that takes a String as input and prints true if the String received is equal to a password (you, the programmer, can choose the password). The method should print false otherwise.
2. Write a method that takes a String s and an int i as input. The method should return true if the character at index i is a vowel, false otherwise.
In the next video we will be talking about arrays and reference types.