Java – Software Solutions…. Chapter 2: Objects and Primitive Data.

Download Java – Software Solutions…. Chapter 2: Objects and Primitive Data.

Post on 01-Jan-2016

216 views

Category:

Documents

0 download

TRANSCRIPT

  • Java Software Solutions. Chapter 2: Objects and Primitive Data

  • Objects and Primitive DataNow we can explore some more fundamental programming conceptsChapter 2 focuses on:predefined objectsprimitive datathe declaration and use of variablesexpressions and operator precedencecreating and using objectsclass libraries

  • Introductory NotionsNeed ability to create and use objects.Provide servicesObjects are fundamental to writing programs in an OOP language.Objects do all the things we want:Manipulate stringsMake computationsDo input/outputDraw shapes

  • Introduction to ObjectsAn object represents something with which we can interact in a programAn object provides a collection of services that we can tell it to perform for usThe services are defined by methods in a class that defines the objectA class represents a concept, and an object represents the embodiment of a classA class can be used to create multiple objects

  • Introduction to ObjectsObjects also manage dataMaybe primitive; maybe complex (like integers, floats)Most complex data consists if primitive dataA data type defines a set of values and operations that can be performed on those values.Think: integers; +, -, *, /, no division by zero

    Objects is defined by 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

  • Objects and Classes. Has attributes (data). Has methods (operations)Classes encapsulate attributes and methods.

  • InheritanceOne class can be used to derive another via inheritanceClasses can be organized into inheritance hierarchiesThink: Gender

    Men Women

    Mothers non-Mothers

  • Using ObjectsThe System.out object represents a destination to which we can send outputIn the Lincoln program, we invoked the println method of the System.out object:

    System.out.println ("Whatever you are, be a good one.");Notice the notation for referencing the method: object.methodWe 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.

  • The print MethodThe System.out object provides another service as wellThe print method is similar to the println method, except that it does not advance to the next lineTherefore anything printed after a print statement will appear on the same lineSee Countdown.java (page 65)Sending a message (fig. 2.2)

    //println//lprint// others

  • AbstractionAn 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.CarFordMustangRed 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 complex software

  • Character StringsEvery character string is an object in Java, defined by the String classEvery string literal, delimited by double quotation marks, represents a String objectTwo fundamental string operations:1) The string concatenation operator (+) is used to append one string to the end of anotherIt can also be used to append a number to a stringA string literal cannot be broken across two lines in a program

  • String ConcatenationThe plus operator (+) is also used for arithmetic additionThe function that the + operator performs depends on the type of the information on which it operatesIf both operands are strings, or if one is a string and one is a number, it performs string concatenationIf both operands are numeric, it adds themThe + operator is evaluated left to right (associativity)Parentheses can be used to force the operation orderSee Addition.java (page 70); Lets 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 OperatorsOperators can be overloadedHave different meanings depending on context.+ can mean concatenation or addition depending.Remember the + operator associates left to right ANDRemember parentheses always override the normal hierarchical evaluation (later)

  • Escape Sequences2) 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 SequencesSome Java escape sequences:Make sure you understand these, especially \n, \t, \ and maybe a couple of othersLets 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

  • VariablesA variable is a name for a location in memoryA variable must be declared by specifying the variable's name and the type of information that it will holdint total;int count, temp, result;Multiple variables can be created in one declaration

  • VariablesA variable can be given an initial value in the declarationWhen a variable is referenced in a program, its current value is usedLook over PianoKeys.java (page 73) on your own.int sum = 0;int base = 32, max = 149; // note syntax

  • AssignmentAn assignment statement changes the value of a variableThe assignment operator is the = signtotal = 55;The value that was in total is overwrittenYou can only assign a value to a variable that is consistent with the variable's declared typeSee Geometry.java (page 74) will do.The expression on the right is evaluated and the result is stored in the variable on the left

  • 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."); }}

  • ConstantsA constant is an identifier that is similar to a variable except that it holds one value while the program is activeThe compiler will issue an error if you try to change the value of a constant during executionIn Java, we use the final modifier to declare a constantfinal 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 valuesfacilitates updates of values used throughout a programprevent inadvertent attempts to change a value(Discuss: final float RATE = 0.15; only change value)

  • Primitive DataThere are exactly eight primitive data types in JavaFour represent integers: byte, short, int, long (no fractions)Two represent floating point numbers:float, double (contain decimals)One represents characters: charOne represents boolean values: booleanAll have different sizes and ranges..

  • Numeric Primitive DataSizes and Ranges of storable values below.Use size as appropriate but if in doubt, be generous.

  • Numeric Primitive DataDefault: 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.6fCan say, if desired, 45.6D or 45.6d, but unnecessary.

  • CharactersA char variable stores a single character from the Unicode character setA character set is an ordered list of characters, and each character corresponds to a unique numberThe Unicode character set uses sixteen bits per character, allowing for 65,536 unique charactersIt is an international character set, containing symbols and characters from many world languagesCharacter literals are delimited by single quotes:'a' 'X' '7' '$' ',' '\n' 7 is not equivalent to 7 is not equivalent to 7

  • CharactersThe ASCII character set is older and smaller than Unicode, but is still quite popularHas 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:

  • BooleanA boolean value represents a true or false conditionA boolean also can be used to represent any two states, such as a light bulb being on or offThe reserved words true and false are the only valid values for a boolean typeboolean done = false;

  • 2.5 Arithmetic Expressions (p. 80)An expression is a combination of one or more operands and their operatorsArithmetic 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 RemainderIf both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded)

    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 also14 / 3 equals?8 / 12 equals?40-14 % 3 equals?8 % -12 equals?-2 8 16.0 % 4.0 equals invalid operands

  • Operator PrecedenceOperators can be combined into complex expressions (variables or literals doesnt matter)result = total + count / max - offset;Operators have a well-defined precedence which determines the order in which they are evaluatedMultiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenationArithmetic operators with the same precedence are evaluated from left to right (associate left to right)Parentheses can be used to force the evaluation orderCan be nested too..

  • Operator PrecedenceWhat is the order of evaluation in the following expressions?a + b + c + d + e1432a + b * c - d / e3241a / (b + c) - d % e2341a / (b * (c + (d - e)))4123

  • Assignment RevisitedThe assignment operator has a lower precedence than the arithmetic operatorsFirst the expression on the right handside of the = operator is evaluatedThen the result is stored in the variable on the left hand sideNOTE: the assignment operator (again) IS an operator (merelyhas lower precedence than arithmetic operators.)answer = sum / 4 + MAX * lowest;1432Whats this?

  • Assignment RevisitedThe right and left hand sides of an assignment statement can contain the same variableFirst, one is added to theoriginal value of countThen the result is stored back into count(overwriting the original value)count = count + 1;KNOW THE OPERATOR PRECEDENCE TABLE ON PAGE 82. It will grow significantly!

  • Data ConversionsSometimes it is convenient to convert data types For example, we may want to treat an integer as a floating point value during a computationBe 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 ConversionsIn Java, data conversions can occur in three ways:assignment conversionarithmetic promotioncastingAssignment conversion occurs when a value of one type is assigned to a variable of anotherOnly...

Recommended

View more >