Chapter 2: Objects and Primitive Data The following concepts are important to object- oriented programming: object attribute method class encapsulation.

Download Chapter 2: Objects and Primitive Data The following concepts are important to object- oriented programming: object attribute method class encapsulation.

Post on 18-Jan-2016




0 download


Chapter 2: Objects and Primitive Data

Chapter 2: Objects and Primitive Data The following concepts are important to object-oriented programming:objectattributemethodclassencapsulationinheritancepolymorphism

2006 Pearson Education22.0 - Introduction to ObjectsAn object represents something with which we can interact in a program (manipulated)An objects attributes are the values it stores internally which represent its state.A class represents a concept, an object is an instance of a classA method is a set of instructions defining a behavior or activity for an object.

2006 Pearson EducationEncapsulation is also known as data hiding. private vs public data fields. We can use a class or methods of a class without knowing how they do the job this is called abstraction.Classes can be created from other classes through the use of inheritance. Inheritance is a form of code reuse between parent and child classes.Polymorphism is the idea that we can refer to objects of different but related types in the same way.

3 2006 Pearson Education4A Little more on AbstractionWe don't have to know how the println method works in order to invoke itA human being can manage only seven (plus or minus 2) pieces of information at one timeBut if we group information into chunks (such as objects) we can manage many complicated pieces at onceClasses and objects help us write complex software

2006 Pearson Education52.1 - 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.");objectmethodinformation provided to the method(parameters) 2006 Pearson Education6The 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 (page 61) 2006 Pearson Education7//********************************************************************// Author: Lewis/Loftus/Cocking//// Demonstrates the difference between print and println.//********************************************************************

public class Countdown{ //----------------------------------------------------------------- // Prints two lines of output representing a rocket countdown. //----------------------------------------------------------------- public static void main (String[] args) { System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... ");

System.out.println ("Liftoff!"); // appears on first output line System.out.println ("Houston, we have a problem."); }}

2006 Pearson EducationOutputThreeTwoOneZeroLiftoff!Houston, we have a problem.8 2006 Pearson Education92.2 Character StringsEvery character string is an object in Java, defined by the String classEvery string literal, delimited by double quotation marks, represents a String objectThe 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 programSee (page 64) 2006 Pearson Education10 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"); }}

2006 Pearson Education11String 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 rightParentheses can be used to force the operation orderSee (page 65) 2006 Pearson Education12// Author: Lewis/Loftus/Cocking//// Demonstrates the difference between the addition and string// concatenation operators.

public class Addition{public static void main (String[] args) { System.out.println ("24 and 45 concatenated: " + 24 + 45);

System.out.println ("24 and 45 added: " + (24 + 45)); }}

2006 Pearson Education13Escape SequencesWhat 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.");

An escape sequence is a series of characters that represents a special characterAn 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.");

2006 Pearson Education14Escape SequencesSome Java escape sequences:See (page 67)Escape Sequence


backspacetabnewlinecarriage returndouble quotesingle quotebackslash 2006 Pearson Education15// Author: Lewis/Loftus/Cocking//// Demonstrates the use of escape sequences.

public class Roses{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."); }}

2006 Pearson Education16AssignmentRead and take notes on Sections 2.0, 2.1, and 2.2Textbook AssignmentM.C. (2.1 2.3)T/F (2.1 2.3)S.A. (2.2 2.5) 2006 Pearson Education172.3 - 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 declarationdata typevariable name 2006 Pearson Education18VariablesA variable can be given an initial value in the declarationWhen a variable is referenced in a program, its current value is usedSee (page 68)int sum = 0;int base = 32, max = 149; 2006 Pearson Education19// Author: Lewis/Loftus/Cocking///* Demonstrates the declaration, initialization, and use of aninteger variable. */

public class PianoKeys{public static void main (String[] args) { int keys = 88;

System.out.println ("A piano has " + keys + " keys."); }}

2006 Pearson Education20Assignment Operator (=)/StatementAn assignment statement changes the value of a variableThe assignment operator is the = signint total;total = 55;The value that was in total is overwrittenYou can assign only a value to a variable that is consistent with the variable's declared typeSee (page 70)The expression on the right is evaluated and the result is stored in the variable on the left 2006 Pearson Education21public 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."); }}

2006 Pearson Education22ConstantsA 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;Constants:give names to otherwise unclear literal valuesfacilitate updates of values used throughout a programprevent inadvertent attempts to change a value 2006 Pearson Education232.4 - Primitive DataThere are exactly eight primitive data types in JavaFour of them represent integers:byte, short, int, longTwo of them represent floating point numbers:float, doubleOne of them represents characters:charAnd one of them represents boolean values:booleanOnly three are in the AP subset: int, double, & boolean 2006 Pearson Education24Numeric Primitive DataThe difference between the numeric primitive types is their size and the values they can store.The int type stores only integer numbers while double includes a decimal place.Type



32 bits

64 bitsMin Value


+/- 1.7 x 10308 with 15 significant digitsMax Value

2,147,483,647 2006 Pearson Education25BooleanA 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; 2006 Pearson Education26CharactersA 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' 2006 Pearson Education27CharactersThe ASCII character set is older and smaller than Unicode, but is still quite popularThe ASCII characters are a subset of the Unicode character set, including:uppercase letterslowercase letterspunctuationdigitsspecial symbolscontrol charactersA, B, C, a, b, c, period, semi-colon, 0, 1, 2, &, |, \, carriage return, tab, ... 2006 Pearson Education28AssignmentRead and take notes on Sections 2.3 & 2.4 2006 Pearson Education292.5 - Arithmetic ExpressionsAn 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%If either or both operands associated with an arithmetic operator are floating point, the result is a floating point 2006 Pearson Education30Division and RemainderIf both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded)The remainder operator (%) returns the remainder after dividing the second operand into the first14 / 3 equals?8 / 12 equals?4014 % 3 equals?8 % 12 equals?28 2006 Pearson Education31Operator PrecedenceOperators can be combined into complex expressionsresult = 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 rightParentheses can be used to force the evaluation order 2006 Pearson Education32Operator 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 2006 Pearson Education33Assignment Operator 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 thevariable on the left hand sideanswer = sum / 4 + MAX * lowest;1432 2006 Pearson Education34Assignment Operator (=) 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; 2006 Pearson Education35Data ConversionsSometimes it is convenient to convert data from one type to anotherFor example, we may want to treat an integer as a floating point value during a computationConversions must be handled carefully to avoid losing informationWidening conversions are safest because they usually do not lose information (int to double)Narrowing conversions can lose information (double to int) 2006 Pearson Education36Data 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 widening conversions can happen via assignmentArithmetic promotion happens automatically when operators in expressions convert their operands

2006 Pearson Education37Data ConversionsCasting is the most powerful, and dangerous, technique for conversionBoth widening and narrowing conversions can be accomplished by explicitly casting a valueTo cast, the type is put in parentheses in front of the value being convertedFor example, if total and count are integers, but we want a floating point result when dividing them, we can cast total:result = (double) total / count; 2006 Pearson Education2.6 - Enumerated Types38Enumerated Types: creating our own types to represent a fixed set of values.enum Season {winter, spring, summer, fall}enum Grades {A, B, C, D, F}** Aminus & Aplus has to be used for A- & A+ because they are not valid Java identifiers.See IceCream on pg.81 2006 Pearson Education39AssignmentRead and take notes on Sections 2.5 & 2.6Textbook AssignmentM.C. (2.4 2.6)T/F (2.4 - 2.7)S.A. (2.6 - 2.8) 2006 Pearson Education402.7 - Creating ObjectsA variable holds either a primitive type or a reference to an objectA class name can be used as a type to declare an object reference variableString title;No object is created with this declarationAn object reference variable holds the address of an objectThe object itself must be created separately 2006 Pearson Education41Creating ObjectsGenerally, we use the new operator to create an objecttitle = new String ("Java Software Solutions");This calls the String constructor, which isa special method that sets up the objectCreating an object is called instantiationAn object is an instance of a particular class 2006 Pearson Education42Creating ObjectsBecause strings are so common, we don't have to use the new operator to create a String objecttitle = "Java Software Solutions";This is special syntax that works only for stringsOnce an o...


View more >