Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding.

Similar presentations


Presentation on theme: "Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding."— Presentation transcript:

1 Chapter 4 – Fundamental Data Types

2 Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding of the fundamental data types and their properties and limitations Understanding strings Understanding strings Dealing with user input, and program output Dealing with user input, and program output

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

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

5

6 Conversion 2 types of conversion – increase in precision, decrease in precision 2 types of conversion – increase in precision, decrease in precision Increase in precision( int to long, byte to float ) Increase in precision( int to long, byte to float ) More memory being used More memory being used Allowed in Java – Java does this automatically Allowed in Java – Java does this automatically Ex. Ex. int dollars = 100; double balance = dollars; //OK

7 Conversoin Decrease in precision Decrease in precision Representing a number with less memory Representing a number with less memory Error in Java – the compiler will yell at you Error in Java – the compiler will yell at you Example: Example: double balance = 13.75; int dollars = balance; //ERROR!

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

9 Type Casting: Syntax ( ) expression Example double balance = 12.45; int dollar = (int) balance; //stores 12 Truncates (removes fractional part) when going from real (ie double ) to whole number (ie int ) Truncates (removes fractional part) when going from real (ie double ) to whole number (ie int ) Can cast to any type you want (including objects) Can cast to any type you want (including objects)

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

11 Constants In math, equations have variables and constants In math, equations have variables and constants In programming, the same In programming, the same Already learned about variables Already learned about variables Numbers that do change but have specific meanings are important Numbers that do change but have specific meanings are important Randomly placed numbers in a program can be confusing, so we give them symbolic names Randomly placed numbers in a program can be confusing, so we give them symbolic names

12 Constants Use a constant to hold the value Use a constant to hold the value Can’t change after assigned when declared Can’t change after assigned when declared Use reserved word final to modify declaration Use reserved word final to modify declaration final double PI = 3.14159; final double PI = 3.14159; Naming Convention for constants Naming Convention for constants USE_ALL_CAPS_WITH_UNDERSCORES USE_ALL_CAPS_WITH_UNDERSCORES

13 Constants Constants often used for important numbers Constants often used for important numbers Make meaning of code easier to understand Make meaning of code easier to understand Make changes to code a lot easier Make changes to code a lot easier

14 Constants: Example public double getPay () { double pay = numHours * 6.70; return pay; } What is 6.70 doing? Why is it there?

15 Constants: Example public double getPay () { final int PAY_RATE = 6.70; double pay = numHours * PAY_RATE; return pay; } Much easier to understand now when reading the code Much easier to understand now when reading the code Much easier to change now as well Much easier to change now as well

16 Class Constants Often, we want to use the same constant across several methods in a class Often, we want to use the same constant across several methods in a class To do this, make a constant instance field To do this, make a constant instance field

17 Class Constants Differences in the declaration Differences in the declaration Make it public since we don’t have to worry about the value being changed Make it public since we don’t have to worry about the value being changed Add static modifier to make it part of the class, so all objects of that class share it (more on this later) Add static modifier to make it part of the class, so all objects of that class share it (more on this later) public class Math { … public static final double E = 2.71828 public static final double PI = 3.14159 …}

18 Class Constants One copy of the variable (static) One copy of the variable (static) Available to all classes (public) Available to all classes (public) Example: You have a class where you want to calculate circumference Example: You have a class where you want to calculate circumference double circumference = Math.PI * diameter

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

20

21

22

23 Constants So when should I use a constant? So when should I use a constant? In general if the number has significance, give it a symbolic name (make it a constant identifier) In general if the number has significance, give it a symbolic name (make it a constant identifier) Example Example time = duration * 60; Is this converting minutes to seconds or hours to minutes?

24 Assignment, Increment, and Decrement = is the assignment operator = is the assignment operator On the left, place the variable On the left, place the variable On the right, place the expression/value On the right, place the expression/value Not an equality sign!!! Not an equality sign!!! Action is to copy the right side to the variable on the left side Action is to copy the right side to the variable on the left side

25 Interesting twists on = items = items + 1; Expression to right is always computed first Expression to right is always computed first Add items + 1; Add items + 1; The value of the expression is assigned to the variable afterwards The value of the expression is assigned to the variable afterwards

26 Example

27 Example int items = 1; items = items + 1; Do right side first  2 Assign to items  items = 2

28 Increment Operator Net result is to increment items by 1 Net result is to increment items by 1 Increment is so common, Java uses a shorthand for it Increment is so common, Java uses a shorthand for it ++ operator increases the value of a variable by one ++ operator increases the value of a variable by one

29 Increment Operator items = items + 1; Postincrement:items++;Preincrement:++items;

30 Decrement Operator items = items - 1; Postdecrement:items--;Predecrement:--items;

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

32 Arithmetic Already seen some symbols, here are all Already seen some symbols, here are all Operators – mathematical operations +addition -Subtraction *Multiplication /Division %Modulo (Remainder) Operands – the values to which the operator is applied

33 Examples int x = 3 + 5;// 8 x = 10/2;// 5 x = 10 * 3 – 4;// 26 x = 12 % 5;// 2

34 Division Returns quotient Returns quotient When both operands are integers, an integer is returned When both operands are integers, an integer is returned x = 10/2 … x = ? x = 10/2 … x = ? y = 6/3 … y = ? y = 6/3 … y = ? When either or both operands are real, a real is returned When either or both operands are real, a real is returned z = 2.5/0.5 … z = ? z = 2.5/0.5 … z = ?

35 Integer Division When dividing two integers, only the whole number is returned When dividing two integers, only the whole number is returned Examples: Examples: 6/4 = ? 1/5 = ? -3/4 = ? 6/3 = ?

36 Integer Division Why does Java do this? Why does Java do this? Easier for the computer Easier for the computer Has it’s advantages: Has it’s advantages: int totalTime = 503; int MINUTES_PER_HOUR = 60; int hours = totalTime / MINUTES_PER_HOUR; int minutes = totalTime % MINUTES_PER_HOUR;

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

38 Precedence High subexpressions ( ) unary operators-, + multiplicative operators*, /, % additive operators+, - Low

39 Precedence Parenthesis take precedence Parenthesis take precedence (a + b) / 2 different than a + b /2

40 Math Class Provided automatically (it’s in the java.lang package) Provided automatically (it’s in the java.lang package) Exponentiation Exponentiation Math.pow(x,n)  x n Square Roots Square Roots Math.sqrt(x)  x 0.5

41 Math Class Translating expressions from mathematics to Java is a little different Translating expressions from mathematics to Java is a little different Java has no exponents, symbols, or fraction bars so we can’t write Java has no exponents, symbols, or fraction bars so we can’t write 6^3 6^3 √5 √5 Quadratic Equation Quadratic Equation (-b + Math.sqrt(b * b -4 * a * c)) / (2 * a) (-b + Math.sqrt(b * b -4 * a * c)) / (2 * a)

42 Math Class In mathematical notation: In mathematical notation: In Java: In Java: (-b + Math.sqrt(b*b - 4*a*c))/(2*a)

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

44 Precedence

45 Math Class

46 Questions What is the value of What is the value of 1729 / 100? 1729 / 100? 1729 % 100? 1729 % 100? Computing Average: Is this correct? Computing Average: Is this correct? double average = s1 + s2 + s3 / 3; What if s1, s2, s3 are integers? What if s1, s2, s3 are integers?

47 Style White space inside equations can go a far way – placing spaces before and after arithmetic symbols is very helpful White space inside equations can go a far way – placing spaces before and after arithmetic symbols is very helpful White space can also be helpful to group code White space can also be helpful to group code i.e. have 5 lines for calculating some information, then a blank line followed by a series of output i.e. have 5 lines for calculating some information, then a blank line followed by a series of output

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

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

50 Static Methods So far we have been discussing classes as templates and objects as the entities So far we have been discussing classes as templates and objects as the entities All the methods and instance fields for the Path class belonged to an individual object All the methods and instance fields for the Path class belonged to an individual object Each had its own xDistance, yDistance Each had its own xDistance, yDistance A method call was on the object itself A method call was on the object itself p.getX() different then q.getX() p.getX() different then q.getX()

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

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

53 Static Methods Static methods are defined in the classes like normal methods Static methods are defined in the classes like normal methods They do not operate on object, though They do not operate on object, though Don’t have any internal data to deal with Don’t have any internal data to deal with

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

55 Static Methods How can we tell if methods are static? How can we tell if methods are static? Java follows conventions: for example, Math is capitalized, so we know it’s a class Java follows conventions: for example, Math is capitalized, so we know it’s a class Look at javadocs - static methods will be listed with the static modifier Look at javadocs - static methods will be listed with the static modifier

56 Strings Along with numbers, the most commonly used data type in programming Along with numbers, the most commonly used data type in programming Unlike numbers, Strings are objects Unlike numbers, Strings are objects Already learned about length() method Already learned about length() method String str = “four”; String str = “four”; System.out.println(str.length())  4 System.out.println(str.length())  4 “” is the empty string “” is the empty string

57 Strings Strings are sequences of characters Strings are sequences of characters Each character is stored at an index of the string Each character is stored at an index of the string Indexing begins at 0! Indexing begins at 0! The charAt method returns the character at the specified index The charAt method returns the character at the specified index Donna 0 1 2 3 4

58 Concatenation Putting strings together Putting strings together If either left or right side is a String, the result is String (no matter what the other side is) If either left or right side is a String, the result is String (no matter what the other side is) Works left to right Works left to right How does Java interpret: How does Java interpret: A + B + C "A" + "B" + "C" 1 + 2 + 3 "1" + 2 + 3 "(1+2+3)" 1 + 2 + "3"

59 Concatenation Concatenation is useful for outputting results Concatenation is useful for outputting results System.out.print(“My age is ”); System.out.println(age);vs. System.out.println(“My age is ” + age);

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

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

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

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

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

65 Reading Input Input used to be a pain in Java (relatively speaking) Input used to be a pain in Java (relatively speaking) BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); int a = Integer.parseInt(buf.readLine()); Java 5.0 now includes a Scanner class Java 5.0 now includes a Scanner class Easily connect to keyboard to get input Easily connect to keyboard to get input Scanner stdin = new Scanner(System.in); int a = stdin.nextInt();

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

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

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

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

70 Characters char stores one character (one letter or one digit or one symbol) char stores one character (one letter or one digit or one symbol) Computer thinks of everything as numbers including characters Computer thinks of everything as numbers including characters ‘0’ (48) + ‘A’ (65) is equal to ‘q’ (113) ‘0’ (48) + ‘A’ (65) is equal to ‘q’ (113) How do we know what numbers different characters correspond to? How do we know what numbers different characters correspond to?

71 Characters Encodings: specify what number a character is Encodings: specify what number a character is ASCII – basic 128 characters ASCII – basic 128 characters Stores only English letters, digits, and a few symbols Stores only English letters, digits, and a few symbols Unicode – every symbol used on computers Unicode – every symbol used on computers Stores accented characters, Chinese characters, Greek letters, etc Stores accented characters, Chinese characters, Greek letters, etc ASCII is a subset of Unicode ASCII is a subset of Unicode Java uses Unicode, but we’re really only concerned with ASCII in this course Java uses Unicode, but we’re really only concerned with ASCII in this course

72 Escape Sequences Backslashs signal escape sequences Backslashs signal escape sequences Suppose you wanted to print Suppose you wanted to print He said, “We need more cows” What’s the problem with What’s the problem withSystem.out.println( “He said, “We need more cows””);

73 Escape Sequences Solution: Solution:System.out.println( “He said, \“We need more cows\””); Other useful escape sequences: Other useful escape sequences: \nnew line \nnew line \ttab \ttab \’single quote \’single quote

74 Formatting Numbers println() will print out all available digits for a real number println() will print out all available digits for a real number To change, new method printf() is available in the PrintStream class ( System.out ) To change, new method printf() is available in the PrintStream class ( System.out ) System.out.printf(“Total:%5.2f”, total); Used in other programming languages Used in other programming languages

75 Productivity Hint Those error messages you get for runtime errors can actually be your friend! Those error messages you get for runtime errors can actually be your friend! Provide two pieces of information Provide two pieces of information The error (interpreting will be easier later in the semester) The error (interpreting will be easier later in the semester) More importantly: The line of the error! More importantly: The line of the error!


Download ppt "Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding."

Similar presentations


Ads by Google