Sams Teach Yourself C in 21 Days

(singke) #1
Java Language Fundamentals 711

BD4


The following code sample provides some examples. The comments in the code explain
what’s going on.
Public class MyClass {
private int count; // Accessible only in this class.
long averageWeight; // Accessible in other classes in the same package.
protected boolean paymentReceived; // Accessible in other classes in the
// same package and in subclasses.
public double sumOfPayments; // Accessible anywhere the MyClass
// class is accessible.

public void someMethod () // This method can be called from
{ // anywhere the class is accessible.

short temporaryTotal; // Accessible only within someMethod.
}
private void anotherMethod () // This method can be called
{ // only from within the class.
short temporaryTotal; // Accessible only within anotherMethod.
// Totally separate from the same name
// variable in someMethod.
}

Storing String Data ........................................................................................

You may remember that both C and C++ store strings (text) in arrays of characters. Java
has significantly improved the way a program stores strings, providing the Stringclass
for this purpose. This approach offers the significant advantages of object-oriented pro-
gramming, and it also simplifies the programmer’s task. This is because a Stringobject
does a lot more than simply store string data—it also has an assortment of methods that
perform various actions on the stored data.

10 Working with Characters and Strings

As you do with the primitive data types, you must declare a Stringobject before you
can use it. Declaring a string is done in the same manner as declaring any other data
type:
String lastName;
After you have a Stringvariable, you assign data to it using the assignment operator:
lastName = “Smith”;
You can combine the declaration and assignment in one line, if desired:
String lastName = “Smith”;

39 448201x-Bonus4 8/13/02 11:19 AM Page 711

Free download pdf