Java-Builtin-Types-Emoon

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Basic building blocks

• Built-in types of data


• Conditionals and loops
• Functions objects

• OOP functions
• Data Abstraction
conditionals and loops

text I/O

built-in data types assignment statements

1
Basic building blocks of
Java
Built-in data types

https://introcs.cs.princeton.edu/java/12types/
Built-in data types
A data type is a set of values and a set of operations defined on those values.

type set of values examples of values examples of operations

char characters 'A' compare


'@'
"Hello World"
String sequences of characters concatenate
"CS is fun"

int integers 17 add, subtract, multiply, divide


12345

double floating-point numbers 3.1415 add, subtract, multiply, divide


6.022e23

boolean truth values true false and, or, not

Java's built-in data types 3

Robert Sedgewick | Kevin Wayne


Check point

Q. What is a data type?

Robert Sedgewick | Kevin Wayne


Basic Definitions
A variable is a name that refers to a value.
A literal is a programming-language representation of a value.
A declaration statement associates a variable with a type.
An assignment statement associates a value with a variable.

Q. Match terminologies above to the following code fragment:

int a;
int b;
a = 1234;
b = 99;
int c = a + b;
Basic Definitions
A variable is a name that refers to a value.
A literal is a programming-language representation of a value.
A declaration statement associates a variable with a type.
An assignment statement associates a value with a variable.

variables

int a;
declaration statements
int b;
a = 1234;
assignment statements
b = 99;
int c = a + b;
combined declaration
and assignment statement

literals

Robert Sedgewick | Kevin Wayne


Variables, literals, declarations, &
assignments example: exchange values

public class Exchange { A trace is a table of variable values


public static void main(String[] args) { after each statement.
int a = 1234; a b t
int b = 99;
u n d e c la re d u n d e c la re d u n d e c la re d

int t = a; int a = 1234; 1234 u n d e c la re d u n d e c la re d

a = b; This code exchanges


int b = 99; 1234 99 u n d e c la re d
b = t; the values of a and b.
int t = a; 1234 99 1234
}
a = b; 99 99 1234
}
b = t; 99 1234 1234

Q. What does this program do?

A. I t doe s e xch ange (W e n eed out put t o con firm i t doe s e xch an g e). 8

elice>Week 1-2> Exchange


Robert Sedgewick | Kevin Wayne
Data type for computing with strings: String
String data type
values sequences of characters

typical literals "Hello, " "1 " " "


Important note:
operation concatenate
Character interpretation depends on context!
operator + character

Ex 1: plus sign s "1234" + " + " + "99"


Examples of String operations (concatenation)
operator operator
expression value
"Hi, " + "Bob" "Hi, Bob" Output: 1234 + 99
"1" + " 2 " + "1" "1 2 1"
"1234" + " + " + "99" "1234 + 99" Ex 2: spaces "1234 " + " 99"
"1234" + "99" "123499"
space
characters
You can easily convert a value of any type to a String value;
Output: 1234 99
whenever you use + operator with a String as one of its operands.
• Typical use: Input and output. 9

Robert Sedgewick | Kevin Wayne


Example of computing with strings:
subdivisions of a ruler
public class Ruler {

public static void main(String[] args) {


String ruler1 = "1";
String ruler2 = ruler1 + " 2 " + ruler1;
String ruler3 = ruler2 + " 3 " + ruler2;
String ruler4 = ruler3 + " 4 " + ruler3;
all + ops are concatenation
Relative height of the marks
System.out.println(ruler4); on a ruler.
}
} Output:
121312141213121

ruler1 ruler2 ruler3 ruler4


undeclared undeclared undeclared undeclared
ruler1 = "1"; 1 undeclared undeclared undeclared
ruler2 = ruler1 + " 2 " + ruler1; 1 121 undeclared undeclared
ruler3 = ruler2 + " 3 " + ruler2; 1 121 1213121 undeclared
ruler4 = ruler3 + " 4 " + ruler3; 121312141213121
10

We will re-visit this program.


Robert Sedgewick | Kevin Wayne
Input & Output
is necessary for us to provide data to our programs and to learn the result of computations.
Input from the
input device
Humans prefer to work with strings.
Programs work more efficiently with numbers. Java
program

standard
Output output
Bird's eye view of a Java program
• Java automatically converts numbers to strings for output.

You can put any base types, such as int and double.
Methods for output
• System.out.print(String s): Print the string s.
• System.out.println(String s): Print the given string s, followed by the newline character.

public class OutputExample {


public static void main(String[] args) {
System.out.print("This is a print method.");
System.out.println("CS is fun!");
} 11
}

Robert
ThisSedgewick | Kevin method.CS
is a print Wayne is fun! See Goodrich et al’s text pp. 38 - 40
Input using Scanner class
• The input from the standard input device, which by default is
the computer keyboard echoing its characters in the Java
console at run time.

• Scanner class has a number of methods that read from the


given input stream.
Scanner varName = new Scanner(System.in);
• Java provides a special object, called System.in, for performing
input from the console window.
• System.in object is an object associated with the standard
input device.

12
Methods in the Scanner class
• Q. How do we give an integer as an input at run time?
• A. Need to call the method nextInt() to convert the strings to integers.

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Input and output warmup: exchange values
import java.util.*;

public class Exchange {

public static void main(String[] args) {


Scanner input = new Scanner(System.in); Enter two integers of your
System.out.println("Enter two integers of your interest: ");
int a = input.nextInt(); interest:
int b = input.nextInt(); 5
System.out.println("You entered: "+a+" "+b); 99
You entered: 5 99
int t = a;
a = b; We exchanged two integers: 99 5
b = t;

System.out.println("We exchanged two integers: “+a+” “+b);

} Java automatically converts int


} values to String for output

Q. What does this program do?

A. Reads two integers from the input device, then prints them out in the opposite order. 38

Robert Sedgewick | Kevin Wayne elice>Week 1-2> I/O warm up: Exchange
Data type for computing with integers: int
int data type
values integers between −2 3 1 and 2 3 1 −1
Important note:
typical literals 1234 99 0 1000000
Only 2 3 2 different intvalues.
operations add subtract multiply divide remainder

operator + − / % not quite the same as integers

Examples of int operations


expression value comment Precedence
5+3 8 expression value comment
5-3 2 3 5-2 13 ha s precedence
5 3 15 3+5/2 5 /ha s precedence
5/3 1 drop fractional part
3-5-2 -4 left associative
5%3 2 remainder
(3-5) -2 -4 better style
1/0 runtime error
java.lang.ArithmeticException: / by zero
15
Typical usage: Math calculations; specifying programs (stay tuned).

Robert Sedgewick | Kevin Wayne


Example of computing with integers and
strings, with type conversion
import java.util.Scanner;

public class IntOps {

public static void main(String[] args) { 5


Scanner input = new Scanner(System.in); 2
5 + 2 = 7
int a = input.nextInt(); 5 * 2 = 10
int b = input.nextInt(); 5 / 2 = 2
5 % 2 = 1
5 = 2 * 2 + 1
int sum = a + b; 1234
int prod = a * b; 99
int quot = a / b; 1234 + 99 = 1333
int rem = a % b; 1234 * 99 = 122166
1234 / 99 = 12
1234 % 99 = 46
System.out.println(a + " + " + b + " = " + sum);
1234 = 12 * 99 + 46
System.out.println(a + " * " + b + " = " + prod);
System.out.println(a + " / " + b + " = " + quot); Note: 1234 = 12*99 + 46
System.out.println(a + " % " + b + " = " + rem);
System.out.println(a + " = " + quot + " * " + b + " + " + rem);
}
} 16
Java automatically converts int values to String
for concatenation
Robert Sedgewick | Kevin Wayne elice>Week 1-2> int operations
Data type for computing with
floating point numbers: double
double data type
values real numbers
6.022 × 10 23
typical literals 3.14159 2.0 1.4142135623730951 6.022e23
double num = 1e6;
operations add subtract multiply divide remainder System.out.print(num);
operator + − / % //prints 1000000.0

Examples of double operations Examples:


expression value
n o doublevalue for π.
3.141 + .03 3.171
n o doublevalue for 2
3.141 - .03 3.111
n o doublevalue for 1/3.
6.02e23/2 3.01e23
5.0 / 3.0 1.6666666666666667 Typical double values are approximations,
10.0 % 3.141 0.577 and provides the finite number of the value.
Math.sqrt(2.0) 1.4142135623730951

Typical use: Scientific calculations. 17

Robert Sedgewick | Kevin Wayne


You can discard your
calculator now (please).

Excerpts from Java’s Math Library


public class Math
double abs(double a) absolute value of a
double max(double a, double b) maximum of aand b also defined for
int, long, and float
double min(double a, double b) minimum of aand b

double sin(double theta) sine function


double cos(double theta) cosine function inverse functions also available:
asin(), acos(), and atan()
double tan(double theta) tangent function
Degrees in radians. Use toDegrees() and toRadians() ) to convert.

double exp(double a) exponential (ea)


double log(double a) natural log (loge a, or ln a) Math.log10(10)
double pow(double a, double b) raise a to the bth power (ab) --Returns the base 10 logarithm
of a double value
long round(double a) round to the nearest integer
double random() random number in [0. 1)
double sqrt(double a) square root of a

double E value of e (constant)


double PI value of π (constant) System.out.println(Math.PI);

Robert Sedgewick | Kevin Wayne https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html


Example of computing with floating
point numbers: quadratic equation
From algebra: the roots of x2 + bx + c −𝑏 ± 𝑏 2 − 4𝑐
𝑥=
2
import java.util.*;

public class Quadratic { –3.0 2.0 x2 — 3x + 2 = (x-1)(x-2);


public static void main(String[] args) { 2.0
Scanner input = new Scanner(System.in); 1.0

–1.0 –1.0
x2 — x -1
double b = input.nextDouble(); 1.618033988749895
double c = input.nextDouble(); -0.6180339887498949

1.0 1.0 x2 + x + 1
double discriminant = b*b - 4.0*c;
NaN
double d = Math.sqrt(discriminant);
//implement here.
double root1 = (-b+d)/2.0;
NaN

double root2 = (-b-d)/2.0; 1.0 hello


Exception in thread "main"
java.util.InputMismatchException
System.out.println(root1);
System.out.println(root2);
}
}
19

Robert Sedgewick | Kevin Wayne elice>Week 1-2> Quadratic equation


Other built-in numeric types
shortdata type longdata type

values integers between −2 1 5 and 2 1 5 − 1 values integers between −2 6 3 and 2 6 3 − 1

operations [ same as int ] operations [ same as int ]

floatdata type

values real numbers

operations [ same as double ]

Why different numeric types?


• Tradeoff between memory use and range for integers.
• Tradeoff between memory use and precision for real numbers.
Strategy:
▪ Use the int type when you know the integer values will be fewer than ten digits. 21
▪ Use the long type when you think the integer values might get to be ten digits or more.

Robert Sedgewick | Kevin Wayne


Data type for computing with true and false:
boolean
booleandata type Truth-table definitions

values true false a !a a b a && b a || b

literals true false true false false false false false

false true false true false true


operations and or not
true false false true
operator && || ! true true true true

Proof a b !a && b a && !b (!a && b) || (a && !b)


Q. aXOR b?
false false false false false
A. (!a && b) || (a && !b)
false true true false true

true false false true true

true true false false false

Typical usage: Control logic and flow of a program .


22

Robert Sedgewick | Kevin Wayne


Comparison operators
Fundamental operations that are defined for each primitive type allow u s to compare values.
• Operands: two expressions of the same type.
• Result: a value of type boolean.

operator meaning true false


== equal 2 == 2 2 == 3
!= not equal 3 != 2 2 != 2
< less than 2 < 13 2<2
<= less than or equal 2 <= 2 3 <= 2
> greater than 13 > 2 2 < 13
>= greater than or equal 3 >= 2 2 >= 3

Examples non-negative discriminant? ( b * b - 4.0 * a * c ) >= 0.0

beginning of a century? ( year % 100 ) == 0

Valid value for month? ( month >= 1 ) && ( month <= 12 )


23

Robert Sedgewick | Kevin Wayne


Example of computing with booleans:
Leap year test
Q. Is a given year a leap year?
A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100.

public class LeapYear {


public static void main(String[] args) { 2016
Scanner input = new Scanner(System.in);
int year = input.nextInt(); True
boolean isLeapYear;

// divisible by 4 1900
isLeapYear = (year % 4 == 0); false
// divisible by 4 and not 100
isLeapYear = isLeapYear && (year % 100 != 0); 1993
// divisible by 4 and not 100 unless divisible by 400 false
isLeapYear = isLeapYear || (year % 400 == 0);

System.out.println(isLeapYear); 2019
} false
}
24

elice>Week 1-2> Exercise: Leap year


Robert Sedgewick | Kevin Wayne
Building blocks of
Java
Built-in data types
• Type conversion
Type checking
Types of variables involved in data-type operations always must match the definitions.

The Java compiler is your friend : it checks for type errors in your code.

public class BadCode


{
public static void main(String[]
args)
{
String s = "123" * 2;
}
}
operator cannot be applied to java.lang.String,int String s = "123"*2;
^
1 error

When appropriate, we often convert a value from one type to another to make types match.
26

Robert Sedgewick | Kevin Wayne


Type conversion with built-in types
Type conversion is an essential aspect of programming.

expression type value


Automatic
• Convert number to string for "+". "x: " + 99

11 0.25
String

double
"x: 99"

2.75
• Make numeric types match if n o loss of precision. 11 is converted to a double and then, the result
of multiplying two doubles is a double.
Function call.
Integer.parseInt("123") int 123
Ex. Integer.parseInt(String s) Math.round(2.71828) long 3
https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html

Explicit Cast for values that belong to multiple types. (int) 2.71828 int 2
• Ex: small integers can be short, int, or long. (int) Math.round(2.71828) int 3

• Ex: double values can be truncated to int values. 11 (int) 0.25 int 0

Type conversion can give counterintuitive results


Pay attention to the type of your data.
but gets easier to understand with practice 27

Robert Sedgewick | Kevin Wayne


Check point on type conversion
Q. Give the type and value of each of the following expressions.

a. ( 7 / 2 ) 2.0

b. ( 7 / 2.0 ) 2

c. "3" + 2

d. 3.0 + "2"

e. Integer.parseInt("1010", 2) 28

Robert Sedgewick | Kevin Wayne


Example of type conversion put to good use:
pseudo-random integers
System method Math.random()returns a pseudo-random doublevalue in [0, 1).

Problem: Given N, generate a pseudo-random integer between 0 and N − 1.

import java.util.Scanner;

public class RandomInt {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// take a positive integer at run time.
int n = input.nextInt();

// a pseudo-random real between 0.0 and 1.0 10


double r = Math.random(); 9

// a pseudo-random integer between 0 and n-1 12


int value = (int) (r * n); 2

int to Double (automatic) 10000


System.out.println(value);
} 8856
30
} From double to int (explicit cast)

Robert Sedgewick | Kevin Wayne elice>Week 1-2> Random int


An instructive story about type conversion
Why different numeric types?
• Tradeoff between memory use and range for integers.
• Tradeoff between memory use and precision for floating-point.

A conversion may be impossible.


• Example: (short) 70000.
• Short values must be between −2 1 5 and 2 1 5 − 1 = 3 2 7 6 7 .

What to do with an impossible conversion?


• Approach 1: Avoid doing it in the first place.
• Approach 2: Crash.

31
First launch of Ariane 5, 1996
A rocket exploded in midair because of
Robert Sedgewick | Kevin Wayne a type-conversion problem.
An instructive story about type conversion
Ariane 5 rocket. Ariane 5 rocket exploded 40
seconds after being launched by European Space
Agency. Maiden voyage after a decade and 7 billion
dollars of research and development. Sensor
reported acceleration that so was large that it
caused an overflow in the part of the program
responsible for recalibrating inertial guidance. 64-
bit floating point number was converted to a 16-bit
signed integer, but the number was larger than
32,767 and the conversion failed. Unanticipated
overflow was caught by a general systems
diagnostic and dumped debugging data into an
area of memory used for guiding the rocket's
motors. Control was switched to a backup
computer, but this had the same data. This resulted
in a drastic attempt to correct the nonexistent
problem, which separated the motors from their
mountings, leading to the end of Ariane 5. First launch of Ariane 5, 1996
A rocket exploded in midair because of
a type-conversion problem.
Summary
A data type is a set of values and a set of operations on those values.

Commonly-used built-in data types in Java


• String, for computing with sequence of characters, for input and output.
• int, for computing with integers, for math calculations in programs.
• double, for computing with floating point numbers, typically for science and math apps.
• boolean, for computing with true and false, for decision making in programs.

In Java you must:


•Declare the types of your variables.
•Convert from one type to another when necessary.
•Identify and resolve type errors in order to compile your code.
Pay attention to the type of your data.

The Java compiler is your friend :


it will help you identify and fix type errors in your code.
You will have much more reliable programs as a result. 33

Robert Sedgewick | Kevin Wayne


Check point
• What are the three ways to convert between data types
in Java?

• What is the range of Math.random( )?

You might also like