650 likes | 706 Views
Java – Software Solutions…. Chapter 2: Objects and Primitive Data. Objects and Primitive Data. Now we can explore some more fundamental programming concepts Chapter 2 focuses on: predefined objects primitive data the declaration and use of variables
E N D
Java – Software Solutions…. Chapter 2: Objects and Primitive Data
Objects and Primitive Data • Now we can explore some more fundamental programming concepts • Chapter 2 focuses on: • predefined objects • primitive data • the declaration and use of variables • expressions and operator precedence • creating and using objects • class libraries
Introductory Notions • Need ability to create and use objects. • Provide ‘services’ • Objects are fundamental to writing programs in an OOP language. • Objects ‘do’ all the things we want: • Manipulate strings • Make computations • Do input/output • Draw shapes…
Introduction to Objects • An object represents something with which we can interact in a program • An object provides a collection of services that we can tell it to perform for us • The services are defined by methods in a class that defines the object • A class represents a concept, and an object represents the embodiment of a class • A class can be used to create multiple objects
Introduction to Objects • Objects also manage data • Maybe primitive; maybe complex (like integers, floats…) • Most complex data consists if primitive data… • A data type defines a set of values and operations that can be performed on those values. • Think: integers; +, -, *, /, no division by zero… • Objects is definedby a class – an abstraction; a generalization. Objects are ‘instances’ of a class. • Operations (methods) are defined by methods in the class. • Methods – a collection of programming statements with a given name that perform some kind of operation
A class (the concept) Class = BankAccount An object (a realization) (an ‘instantiation’) BankAccount John’s Bank Account Balance: $5,257 Bill’s Bank Account Balance: $1,245,069 Multiple objects from the same class Mary’s Bank Account Balance: $16,833 Objects and Classes . Has attributes (data) . Has methods (operations) Classes ‘encapsulate’ attributes and methods.
Account ChargeAccount BankAccount SavingsAccount CheckingAccount Inheritance • One class can be used to derive another via inheritance • Classes can be organized into inheritance hierarchies Think: Gender Men Women Mothers non-Mothers
object method information provided to the method (parameters) Using Objects • The System.outobject represents a destination to which we can send output • In the Lincoln program, we invoked the printlnmethod of the System.out object: System.out.println ("Whatever you are, be a good one."); Notice the ‘notation’ for referencing the method: object.method We are SENDING A MESSAGE to the object, System.out. We are requesting that the object perform a ‘service’ for us by invoking. the services of its method, println.
Countdown System.out println main The print Method • The System.out object provides another service as well • The print method is similar to the println method, except that it does not advance to the next line • Therefore anything printed after a print statement will appear on the same line • See Countdown.java (page 65) • Sending a message (fig. 2.2) //println //lprint // others…
Abstraction • An abstraction hides (or suppresses) the right details at the right time. We ‘abstract out’ common characteristics. • An object is abstract in that we don't have to think about its internal details in order to use it. • encapsulate attributes and methods and provide services (have ‘responsibilities’) to other objects through the sending of messages. • For example, we don't have to know how the println method inside the object System.out actually works in order to invoke it. • We know when we send a message to the object System.out (we send messages by invoking its ‘methods’) with the parameters (“ “) the object will print out the contents enclosed in quotes.
Abstraction (continued) • Of course, we have ‘levels’ of abstraction – germane to the problem at hand. • Car • Ford • Mustang • Red Mustang that belongs to ….. • Are all levels of abstraction! Each is more and more specific, but all have the ‘is-a’ characteristics. • More later….. • Classes and their objects help us write complexsoftware
Character Strings • Every character string is an object in Java, defined by the Stringclass • Every string literal, delimited by double quotation marks, represents a String object • Two fundamental string operations: • 1) The string concatenation operator (+) is used to append one string to the end of another • It can also be used to append a number to a string • A string literal cannot be broken across two lines in a program
String Concatenation • The plus operator (+) is also used for arithmetic addition • The function that the + operator performs depends on the type of the information on which it operates • If both operands are strings, or if one is a string and one is a number, it performs string concatenation • If both operands are numeric, it adds them • The + operator is evaluated left to right (associativity) • Parentheses can be used to force the operation order • See Addition.java (page 70); Let’s look at some code:
//********************************************************************//******************************************************************** // Facts.java Author: Lewis/Loftus // // Demonstrates the use of the string concatenation operator and the // automatic conversion of an integer to a string. //******************************************************************** public class Facts { //----------------------------------------------------------------- // Prints various facts. //----------------------------------------------------------------- public static void main (String[] args) { // Strings can be concatenated into one long string System.out.println ("We present the following facts for your " + "extracurricular edification:"); System.out.println (); // A string can contain numeric digits System.out.println ("Letters in the Hawaiian alphabet: 12"); // A numeric value can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " + 1515); System.out.println ("Speed of ketchup: " + 40 + " km per year"); } // end main } // end class Facts Everything prints out in a straight line. See page 68 in textbook….
Overloading Operators • Operators can be ‘overloaded’ • Have different meanings depending on context. • “+” can mean concatenation or addition depending…. • Remember the + operator ‘associates’ left to right AND • Remember parentheses always override the ‘normal’ hierarchical evaluation (later…)
Escape Sequences • 2) Second fundamental characteristic on Strings: the escape sequence. • What if we wanted to print a double quote character? • The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); This is a problem
Escape sequences (continued) • An escape sequence is a series of characters that represents a special character – usually a single character. • An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way System.out.println ("I said \"Hello\" to you."); Discuss…
Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash Escape Sequences • Some Java escape sequences: • Make sure you understand these, especially \n, \t, \” and maybe a couple of others… • Let’s look at Roses.java
Public Directory for Roses.java • //******************************************************************** • // Roses.java Author: Lewis/Loftus • // • // Demonstrates the use of escape sequences. • //******************************************************************** • public class Roses • { • //----------------------------------------------------------------- • // Prints a poem (of sorts) on multiple lines. • //----------------------------------------------------------------- • public static void main (String[] args) • { • System.out.println ("Roses are red,\n\tViolets are blue,\n" + • "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" + • "So I'd rather just be friends\n\tAt this point in our " + • "relationship."); • } // end main • } // end class Roses
data type variable name Variables • A variable is a name for a location in memory • A variable must be declared by specifying the variable's name and the type of information that it will hold int total; int count, temp, result; Multiple variables can be created in one declaration
Variables • A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; // note syntax… • When a variable is referenced in a program, its current value is used • Look over PianoKeys.java (page 73) on your own.
Assignment • An assignment statement changes the value of a variable • The assignment operator is the = sign total = 55; • The expression on the right is evaluated and the result is stored in the variable on the left • The value that was in total is overwritten • You can only assign a value to a variable that is consistent with the variable's declared type • See Geometry.java (page 74) – will do….
Geometry example… • /******************************************************************** • // Geometry.java Author: Lewis/Loftus • // • // Demonstrates the use of an assignment statement to change the • // value stored in a variable. • //******************************************************************** • public class Geometry • { • //----------------------------------------------------------------- • // Prints the number of sides of several geometric shapes. • //----------------------------------------------------------------- • public static void main (String[] args) • { • int sides = 7; // declaration with initialization • System.out.println ("A heptagon has " + sides + " sides."); • sides = 10; // assignment statement • System.out.println ("A decagon has " + sides + " sides."); • sides = 12; • System.out.println ("A dodecagon has " + sides + " sides."); • } • }
Constants • A constant is an identifier that is similar to a variable except that it holds one value while the program is active • The compiler will issue an error if you try to change the value of a constant during execution • In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; Note: constants are written in caps to distinguish themselves from other ‘variables’ whose values can change. • give names to otherwise unclear literal values • facilitates updates of values used throughout a program • prevent inadvertent attempts to change a value • (Discuss: final float RATE = 0.15; only change value…)
Primitive Data • There are exactly eight primitive data types in Java • Four represent integers: • byte, short, int, long (no fractions) • Two represent floating point numbers: • float, double (contain decimals) • One represents characters: char • One represents boolean values: boolean • All have different ‘sizes’ and ‘ranges’…..
Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018 Numeric Primitive Data • Sizes and Ranges of storable values below. • Use size as ‘appropriate’ but if in doubt, be generous.
Numeric Primitive Data • Default: int is 32 bits; but 45L or 45l => long • Default: for decimal data: • assumes all literals are type double. • To make ‘float’ 45.6F or 45.6f • Can say, if desired, 45.6D or 45.6d, but unnecessary.
Characters • A char variable stores a single character from the Unicode character set • A character set is an ordered list of characters, and each character corresponds to a unique number • The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters • It is an international character set, containing symbols and characters from many world languages • Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' ‘7’ is not equivalent to 7 is not equivalent to “7”
uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, \, … carriage return, tab, ... Characters • The ASCII character set is older and smaller than Unicode, but is still quite popular • Has evolved to eight-bits per byte. • (char is a ‘primitive data type’; String is a class) • Because String is a class, it has many methods (operations) that can be performed on String objects!) • The ASCII characters are a subset of the Unicode character set, including:
Boolean • A boolean value represents a true or false condition • A boolean also can be used to represent any two states, such as a light bulb being on or off • The reserved words true and false are the only valid values for a boolean type boolean done = false;
2.5 Arithmetic Expressions (p. 80) • An expression is a combination of one or more operands and their operators • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % (modulus operator in C) • If operands are mixed, results are ‘promoted.’ • 4.5 + 2 = 6.5 (double) • Sometimes called “widened.”
Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 4 14 / 3equals? 8 / 12equals? 0 • If both or either parts are floating point, results are floating point. 14/3.0 = 14.0/3 = 14.0/3.0 = 3.5 • The remainder operator (%) returns the remainder after dividing the second operand into the first and takes the sign of the numerator; only integers also -14 % 3equals? -2 8 % -12equals? 8 16.0 % 4.0 equals invalid operands
Operator Precedence • Operators can be combined into complex expressions (variables or literals – doesn’t matter) result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right (‘associate left to right’) • Parentheses can be used to force the evaluation order • Can be nested too…..
Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1
Assignment Revisited • The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 What’s this? Then the result is stored in the variable on the left hand side NOTE: the ‘assignment operator (again) IS an operator – (merely has lower precedence than arithmetic operators….)
Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value) KNOW THE OPERATOR PRECEDENCE TABLE ON PAGE 82. It will grow significantly!
Data Conversions • Sometimes it is convenient to convert data types • For example, we may want to treat an integer as a floating point value during a computation • Be careful with conversions. Can lose information! (Why is one byte not enough to store 1000?) • Widening conversions; safest; tend to go from a small data type to a larger one (such as a short to an int) (more space (magnitude) normally; can lose precision – (int or long to float; long to double…) WHY? • Narrowing conversions can lose information; they tend to go from a large data type to a smaller one (such as an int to a short) (Can lose magnitude & precision!)
Data Conversions • In Java, data conversions can occur in three ways: • assignment conversion • arithmetic promotion • casting • Assignment conversion occurs when a value of one type is assigned to a variable of another • Only widening (promoting) conversions can happen via assignment • Arithmetic promotion happens automatically when operators in expressions convert their operands. • But be aware that this does NOT change the permanent value! Only changes it for the calculation.
Data Conversions • Casting is the most powerful, and dangerous, technique for conversion • Both widening and narrowing conversions can be accomplished by explicitly casting a value • To cast, the type is put in parentheses in front of the value being converted • For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total: result = (float) total / count; DISCUSS!
2.6 Creating Objects (p. 87) • A variable holds either a primitive type or a referenceto an object • A class name can be used as a type to declare an object reference variable String title; • No object is created with this declaration • Object reference variables hold memoryaddresses of object (point to the objects) • The object itself must be created separately
Creating Objects - Constructors • Generally, use new ‘operator’ to create an object title = new String ("Java Software Solutions"); This calls the String constructor - a special method that sets up the object. So, this statement allocates space for an object and initializes it via its constructor. (Constructor method is the same name as the class.) • Creating an object is called instantiation • An object is an instanceof a particular class (here, String) • Can combine these operations: (FREQUENTLY DONE!) of creating a reference variable and also the object itself with value in a single declaration… String title = new String (“Java Software Solutions”); • The ‘object reference variable’ (title) stores the address of where the object physically resides in memory.
Creating Objects • Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; • This is special syntax that works only for Strings • Once an object has been instantiated, we can use the dot operator to invoke its methods (format: object.method() ) title.length() as in count = title.length(); (returns integer value of number of characters in the string, title – assigns that number to count. (assumes int count; ) Remember: the Constructor IS a method in all classes. When an object is created, its ‘constructor’ is called to set it up, initialize values, etc…. (Much more later on constructors)
String Methods • The Stringclass has several methods that are useful for manipulating strings. (Recall, classes have attributes and methods) • Many of the methods return a value, such as an integer - like length() or a new String object… • Some return a new String or a boolean value...when the lengths of strings are compared or their values are compared…. • See the list of String methods on page89 and in Appendix M
// ************************************************************************* // String Manipulation Example // ************************************************************************* public class StringManipulation { // ------------------------------------------------------ // Prints a string and several mutations of it // ------------------------------------------------------ public static void main (String [ ] args ); { String phrase = new String (“Change is inevitable”); // what does this do? String mutation1, mutation2, mutation3, mutation4; // what does this do? System.out.println (“Original string: \”” + phrase + \”” ); System.out.println (“Length of string: “ + phrase.length() ); mutation1 = phrase.concat (“, except from vending machines. “); // Note: many methods of objects of type String return new objects!! // See page 89. This is what is going on here…. mutation2 = mutation1.toUpperCase(); mutation3 = mutation1.replace(‘E’ , ‘X’); mutation4 = mutation1.substring(3,30); // Print out results System.out.println (“Mutation #1: “ + mutation1); System.out.println (“Mutation #2: “ + mutation2); System.out.println (“Mutation #3: “ + mutation3); System.out.println (“Mutation #4: “ + mutation4); System.out.println (“Mutated length: “ + mutation1.length()); }// end of main procedure } // end of public class StringManipulation
2.7 Class Libraries (p.91) • A class library is a collection of classes that we can use when developing programs • The Java standard class library is part of any Java development environment – but NOT part of Java language. • Other class libraries can be obtained through third party vendors, or you can create them yourself • Class library = clusters of related classes, called Java APIs or Application Programmer Interface. Look these over!!! • Many “APIs” like the Java Database API which contains sets of classes that help us when we are dealing with databases. • Java Swing API – helps us when we are dealing with GUIs…
Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support // Always get this. No need to import Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities - will use this a lot XML document processing Packages • Classes of the Java standard class library are organized into packages • The package organization is more fundamental and language-based than the API names. Use packages extensively!!!! • Some packages in the standard class library are:
The import Declaration • To use class(es) from a package, we must ‘import’ the package. • import java.util.*; • (imports package and all of its classes) • Or you can import only the class you are interested in: import java.util.Random; (imports the class Random from the package, util) • Import all classes in a particular package, you can use the * wildcard character. (Need > 1? Import entire package.)
The import Declaration • All classes of the java.lang package are imported automatically into all programs • So, String and System weren’t explicitly imported… and didn’t need to import them in earlier examples. • The Random class is part of java.util package • Among other things, java.util package has a Random class that generates pseudorandom numbers if needed. (very popular class)
Random Class from java.util package • Be certain to study figure 2.12 and listing 2.9 for public class RandomNumbers. • Be sure to understand how this works! • Note: There is a Random class in java.util. • Generates a ‘pseudo random number’ Seeded! • Some Random methods: (page 96) • Random () – Constructor; creases a new pseudorandom number generator. • float nextFloat() – returns a random number between 0.0 and 1.0 (exclusive) (Can cast to get an int, …) • int nextInt () – returns a random number ranging over all positive and negative values • int nextInt (int num) Returns a random number in range of 0 to num-1.
2.8 Class Methods (p. 98) • Some methods can be invoked through the class name, instead of through an object of the class • Means you can use them directly and do not have to have objects of that class declared to get methods! • Called class methods or static methods (have class variables too…) • Method must be defined as static in the class though….and note (p. 99) all methods are static and ‘double.’ • The Math class contains many static methods, providing various mathematical functions, such as absolute value, trigonometry functions, square root, etc. temp = Math.cos(90) + Math.sqrt(delta); Note: there is a random() static method in Math class. cos is a class or static method. Notation: class.method. Note: double temp;