1 / 78

Java Primitive Data Types and Variables

This chapter provides an overview of using primitive data types and variables in Java. It covers topics such as data types, literals, syntax, arithmetic operators, assignment statements, type casting, operator precedence, and introduction to methods.

orrin
Download Presentation

Java Primitive Data Types and Variables

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2 • Overview • Using Primitive Data Types • Using Classes • Anatomy of a Program • Will use JOptionPane and Math classes

  2. Data Types • Tells compiler what type of data is stored in each memory cell. • Data Type represents a particular kind of information. • Some come with Java • Primitive Data Types are not stored as objects • The String class is a data type which stores Objects • Some are defined by Programmers

  3. Variables • Variables serve 2 purposes • Reference objects • Store values in memory • Declaration Statement • Defines a variable name and its associated data type.

  4. Data Types • Java has 8 built-in primitive data types • We will be using 4 of these • int • double • char • boolean • As noted before, these primitive data types are not stored as objects

  5. Example declarations • int kids = 2; • double bankBalance = 500.45; • char firstLetter = ‘a’; • boolean married = true;

  6. Literals • Example of declaration (with initialization) int kids = 2;the variable is kidsthe primitive type is intthe initial value is the literal 2 • What are the literals in the declarations below? • double bankBalance = 500.45; • char firstLetter = ‘a’; • boolean married = true;

  7. Values stored • Table page 37 of text • int • double • char • boolean

  8. Syntax Display • Form:typeName variableName [ = value ]; • Everything inside of [] is optional. • You need to be comfortable reading this syntax display, it will help you learn the Java language (and it’s good practice for learning the syntax of other languages).

  9. Primitive Type int • Positive or negative whole numbers. • No sign is assumed to be positive • Can perform math functions on these • Add, subtract, multiply, divide • Do not use commas when writing numbers in Java • 1,000 • 1000

  10. Primitive type double • Real number • Has integer part • Has fractional part • Can express via scientific notation • 1.23 x 105 • In Java as • 1.23e5 • 1.23e+5

  11. Primitive Type boolean • Has only 2 possible values • true • false • Used to represent conditional values • Will use more later in the semester

  12. Primitive type char • Represents a single character value • letter, digit, special character • All character literals are enclosed in ‘’ • why?? • Can you add ‘5’ + ‘6’ ? • How about special characters that are not on keyboard • See table page 39.

  13. Data types enable Error Detection • Java is a strongly typed language • Unlike C++ • Can not add 2 boolean values • Can not store a boolean in a character • Some you can, for instance an integer into a double

  14. Section 2.2 Processing Numeric Data • Arithmetic Operators:

  15. Division • Integer division is very different than with real numbers. • If both numbers are integers then integer division is performed. • If one or both numbers are reals then real number division is performed.

  16. Assignment Statement • Form: variable = expression; • Example: x = y + z; • Read x is assigned the value of y + z. • See Example 2.2 Page 42 • See Example 2.3 Page 43

  17. Result of mixed type • If one or more operands are double, result is double. • If both operands are int, result is int. • Mixed type assignment statements. • Result is calculated, then assigned. • int can be assigned to a double • See example 2.4 page 44

  18. Type Casting • Can use this to create one type from another. • double x = 7.8; • int m; • m = (int) x; • Can also be used for doubles • (double) m;

  19. Operator Precedence • My Dear Aunt Sally • x = 4 + 3 * 2 • is it 10 or 14? • Uses 2 rules to decide • Parentheses rule • Operator precedence rule • Left associative rule (equal then left to right) • We will consistently use fully parenthesized equations.

  20. Examples • Review the examples on pages 46 –47 • Must be able to convert math formulas into Java syntax • See examples page 48 • Look at code on Page 49 running in JBuilder

  21. Section 2.3 Introduction to Methods • Methods of a class determine operations that can be performed by the class. • The previous code example (Page 49) contains 2 methods • main() • println() • Methods are called to do some task.

  22. Calling (activate) methods • Call methods for multiple reasons • Change state of object. • Calculate a result • Retrieve a data item stored in an object • Get data from the user • Display the results of an operation

  23. Returning results • Methods that: • calculate result • retrieve a data item • these are said to “return a result” • The main method is automatically called by the operating system. It is the initial method to run, you then write the code in that method to perform your work.

  24. println method • Used to display output in the console window. • Provided for you by java. • Is part of the System.out object.

  25. Calling a method • Call a method using dot notation: • objectName.methodName(); • System.out.println(); • We can pass data to methods via the argument list: • objectName.methodName(argumentList); • Can be single or multiple values • See Page 49 println calls

  26. Method arguments are like function arguments • In algebra f(x) means function f with argument x. • f(x) is x2 + x + 1 • f(0) is 1 (0 + 0 + 1) • f(1) is 3 (1 + 1 + 1) • f(2) is 7 (4 + 2 + 1) • Can also have f(x, y) (bottom pg 53)

  27. Instance versus class methods • Java has 2 different types of methods • instance • class • println is an instance method, it belongs to an instance of System.out • Class methods belong to a class, not an instance of the class Math.sqrt(15.0) is class method. • Use name of class (Math) rather than instance name.

  28. Section 2.4 the String Class • Strings are a sequence of characters. • Used to store, names, addresses, ……. • String is not a primitive data type in Java • One powerful feature of object orientation is the ability to create your own data types.

  29. The String Class • Working with objects is similar but slightly different than primitive data types. • Declare string variables: • String name; • String flower; • These can reference a String object, but have no value • Notice that it is String not string.

  30. Creating String objects • Use Constructors to create String object • name = new String(“Dustin”); • name = new String(“Rose”); • The new operator creates a new instance of the string object. • This is called an instantiation. • Object is an instance of a class

  31. Constructor • The new operator calls the constructor for the object. • The constructor is a special method with the same name as the class. • Gets called automatically when create an new instance of the class. • We pass an argument to the constructor method (“Dustin”)

  32. Class instantiation • Form: variableName = new className(arguments); • Example: flower = new String(“rose”); • Can declare variable and instantiate it at the same time: • String flower = new String(“rose”);

  33. Reference Variable • Primitive data type storage locations contain the value of the data type. • A reference variable storage location contains an address of where the object is stored. • See Page 57 top

  34. Strings Properties • Strings slightly different than classes you create. • Can create string via: • String flower = “Rose”; • Can use + with String (concatenation) • name + “ “ + flower • concatenates 3 strings together

  35. Concatenate Strings with Primitive Types • System.out.println(“First number is “ + num1); • Concatenates one string and one double • See examples Page 59-60

  36. String Methods • See table String Methods Page 60 • length • charAt • subString • indexOf • See examples pages 60 - 61

  37. subString() method • Gets a portion of a string • One argument gets from that position to end of String • Two arguments gets from first position for the length in second argument. • See examples page 62-63

  38. Storing result of method call • Method must return a value • int posBlank = text.indexOf(“ “); • first blank in string text • if Mickey Mantle returns 6 • String firstName = text.subString(0, posBlank) • pulls out first name • See example page 64

  39. Display results of method call • System.out.printLn(“The First blank is at position “ + text.indexOf(“ “));

  40. Section 2.5 Input/Output • Will be using the following 2 approaches to Input/Output • JOptionPane • printLn()

  41. Packages • Packages are created for you to reuse existing code. • Contain many useful functions • A large number of packages exist to extend the functionality of Java • Strong feature of Java

  42. import Statement • Used to import and use an existing package. • import javax.swing.*; • This imports the swing package which facilitates creating GUIs. • This gives access to all classes in swing • To only use JOptionPane can do • import javax.swing.JOptionPane;

  43. JOptionPane.showInputDialog() • Part of swing package. • Always easy input and output. • Input reading in data from user • Output presenting results for user • String name = JOptionPane.showInputDialog(“Enter your name”); • Displays dialog box, see page 67 • Stores result in name

  44. Examples Input dialog box • See examples on page 67 - 68

  45. Displaying results in Console Window • System.out.println(“what ever”); • See example page 68 bottom

  46. Display results in dialog box • JOptionPane.showMessageDialog(); • See example pages 69 - 70

  47. Running code • See TwoNumbersDialog in JBuilder

  48. Section 2.6 Problem Solving • For each assignment you turn in you must also turn in Documentation. • This documentation revolves around what is presented in the text book: • Problem • Analysis • Design • Implementation • Testing

  49. Section 2.7 Anatomy of program • Comments • 2 types of comments exist: • // means a comment to end of line • /* comments in here */ comment delimiter • Used to make program easier to understand • Use to clarify difficult code

  50. Comments for each program • At the beginning of the program include at a minimum • Name • Date • Class • Assignment • Program purpose

More Related