Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 480


Previous 1060 Stories (530 Pages, 2 Per Page) Next

Java Lecture 10: Characters and strings

Go to all tips in Java Lectures by Anatoliy Malyarenko

Characters and strings

Abstract

Contents of the lecture.

  • Characters.
  • Why two string classes?
  • Creating strings and string buffers.
  • Accessor methods.
  • Modifying string buffers.
  • Converting objects to strings.
  • Converting strings to numbers.
  • Strings and the Java compiler.

Introduction

The Java platform contains three classes that you can use when working with character data:

  • Character -- A class whose instances can hold a single character value. This class also defines handy methods that can manipulate or inspect single-character data.
  • String -- A class for working with immutable (unchanging) data composed of multiple characters.
  • StringBuffer -- A class for storing and manipulating mutable data composed of multiple characters.

Characters

An object of Character type contains a single character value. You use a Character object instead of a primitive char variable when an object is required -- for example, when passing a character value into a method that changes the value or when placing a character value into a data structure, such as a vector, that requires objects. The following sample program, CharacterDemo, creates a few character objects and displays some information about them:

Code:

public class CharacterDemo {
   public static void main(String args[]) {
      Character a = new Character(’a’);
      Character a2 = new Character(’a’);
      Character b = new Character(’b’);
      int difference = a.compareTo(b);
      if (difference == 0) {
         System.out.println("a is equal to b.");
      } else if (difference < 0) {
         System.out.println("a is less than b.");
      } else if (difference > 0) {
         System.out.println("a is greater than b.");
      }
      System.out.println("a is "
         + ((a.equals(a2)) ? "equal" : "not equal")
         + " to a2.");
      System.out.println("The character " + a.toString()
         + " is " + (Character.isUpperCase(a.charValue()) ?
         "upper" : "lower") + "case.");
   }
}

The following is the output from this program:

a is less than b.
a is equal to a2.
The character a is lowercase.

The CharacterDemo program calls the following constructors and methods provided by the Character class:

Character(char)

The Character class's only constructor, which creates a Character object containing the value provided by the argument. Once a Character object has been created, the value it contains cannot be changed.

compareTo(Character)

An instance method that compares the values held by two character objects: the object on which the method is called (a in the example) and the argument to the method (b in the example). This method returns an integer indicating whether the value in the current object is greater than, equal to, or less than the value held by the argument. A letter is greater than another letter if its numeric value is greater.

equals(Object)

An instance method that compares the value held by the current object with the value held by another. This method returns true if the values held by both objects are equal.

toString()

An instance method that converts the object to a string. The resulting string is one character in length and contains the value held by the character object.

charValue()

An instance method that returns the value held by the character object as a primitive char value.

isUpperCase(char)

A class method that determines whether a primitive char value is uppercase. This is one of many Character class methods that inspect or manipulate character data.

Why two string classes?

The Java platform provides two classes, String and StringBuffer, that store and manipulate strings -- character data consisting of more than one character. The String class provides for strings whose value will not change. For example, if you write a method that requires string data and the method is not going to modify the string in any way, pass a String object into the method. The StringBuffer class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change. You typically use string buffers for constructing character data dynamically: for example, when reading text data from a file. Because strings are constants, they are more efficient to use than are string buffers and can be shared. So it's important to use strings when you can.

Following is a sample program called StringsDemo, which reverses the characters of a string. This program uses both a string and a string buffer.

Code:

public class StringsDemo {
   public static void main(String[] args) {
      String palindrome = "Dot saw I was Tod";
      int len = palindrome.length();
      StringBuffer dest = new StringBuffer(len);
      for (int i = (len - 1); i >= 0; i--) {
         dest.append(palindrome.charAt(i));
      }
      System.out.println(dest.toString());
   }
}

The output from this program is:

doT saw I was toD

Creating strings and string buffers

A string is often created from a string literal -- a series of characters enclosed in double quotes. For example, when it encounters the following string literal, the Java platform creates a String object whose value is Gobbledygook.

"Gobbledygook"

The StringsDemo program uses this technique to create the string referred to by the palindrome variable:

Code:

   String palindrome = "Dot saw I was Tod";

You can also create String objects as you would any other Java object: using the new keyword and a constructor. The String class provides several constructors that allow you to provide the initial value of the string, using different sources, such as an array of characters, an array of bytes, or a string buffer.

Here's an example of creating a string from a character array:

Code:

char[] helloArray = { ’h’, ’e’, ’l’, ’l’, ’o’ };

String helloString = new String(helloArray);
System.out.println(helloString);

The last line of this code snippet displays: hello.

You must always use new to create a string buffer. The StringsDemo program creates the string buffer referred to by dest, using the constructor that sets the buffer's capacity:

Code:

   String palindrome = "Dot saw I was Tod";
   int len = palindrome.length();
   StringBuffer dest = new StringBuffer(len);

This code creates the string buffer with an initial capacity equal to the length of the string referred to by the name palindrome. This ensures only one memory allocation for dest because it's just big enough to contain the characters that will be copied to it.

By initialising the string buffer's capacity to a reasonable first guess, you minimise the number of times memory must be allocated for it. This makes your code more efficient because memory allocation is a relatively expensive operation.

Getting the length of a string or a string buffer

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with both strings and string buffers is the length method, which returns the number of characters contained in the string or the string buffer.

After the following two lines of code have been executed, len equals 17:

Code:

   String palindrome = "Dot saw I was Tod";
   int len = palindrome.length();

In addition to length, the StringBuffer class has a method called capacity, which
returns the amount of space allocated for the string buffer rather than the amount of space
used. For example, the capacity of the string buffer referred to by dest in the StringsDemo
program never changes, although its length increases by 1 for each iteration of the loop. The
following figure shows the capacity and the length of dest after nine characters have been
appended to it.

A string buffer's length is the number of characters it contains; a string buffer's capacity is the number of character spaces that have been allocated. The String class doesn't have a capacity method, because a string cannot change.

Getting characters by index from a string or string buffer

You can get the character at a particular index within a string or a string buffer by using the charAt accessor. The index of the first character is 0; the index of the last is length()-1.

For example, the following code gets the character at index 9 in a string:

Code:

   String anotherPalindrome = "Niagara. O roar again!";
   char aChar = anotherPalindrome.charAt(9);

Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:

Use the charAt method to get a character at a particular index. The figure also shows that to compute the index of the last character of a string, you have to subtract 1 from the value returned by the length method.

If you want to get more than one character from a string or a string buffer, you can use the substring method. The substring method has two versions, as shown in the following table:

Method Description

String substring(int)

String substring(int,int)

Returns a new string that is a substring of this string or string buffer. The first integer argument specifies the index of the first
character.

The second integer argument is the index of the last character -1. The length of the substring is therefore the first int
minus the second int. If the second integer is not present, the substring extends to the end of the original string.

The following code gets from the Niagara palindrome the substring that extends from index 11 to index 15, which is the word "roar":

Code:

   String anotherPalindrome = "Niagara. O roar again!";
   String roar = anotherPalindrome.substring(11, 15);

Use the substring method to get part of a string or string buffer. Remember that indices begin at 0.

More accessor methods for the String class

The String class provides two accessors that return the position within the string of a specific character or string: indexOf and lastIndexOf. The indexOf method searches forward from the beginning of the string, and lastIndexOf searches backward from the end of the string.

The indexOf and lastIndexOf methods are frequently used with substring, which returns a substring of the string. The following class illustrates the use of lastIndexOf and substring to isolate different parts of a filename.

Note: The methods in the following Filename class don't do any error checking
and assume that their argument contains a full directory path and a filename with
an extension. If these methods were production code they would verify that their
arguments were properly constructed.

Code:

// This class assumes that the string used to initialise
// fullPath has a directory path, filename, and extension.
// The methods won’t work if it doesn’t.
public class Filename {
   private String fullPath;
   private char pathSeparator, extensionSeparator;
   public Filename(String str, char sep, char ext) {
      fullPath = str;
      pathSeparator = sep;
      extensionSeparator = ext;
   }
   
   public String extension() {
      int dot = fullPath.lastIndexOf(extensionSeparator);
      return fullPath.substring(dot + 1);
   }
   
   public String filename() {
      int dot = fullPath.lastIndexOf(extensionSeparator);
      int sep = fullPath.lastIndexOf(pathSeparator);
      return fullPath.substring(sep + 1, dot);
   }
   
   public String path() {
      int sep = fullPath.lastIndexOf(pathSeparator);
      return fullPath.substring(0, sep);
   }
}

Here’s a small program that constructs a Filename object and calls all of its methods:

Code:

public class FilenameDemo {
   public static void main(String[] args) {
      Filename myHomePage = new Filename
         ("/home/mem/index.html",’/’, ’.’);
      System.out.println("Extension = " + myHomePage.extension());
      System.out.println("Filename = " + myHomePage.filename());
      System.out.println("Path = " + myHomePage.path());
   }
}

And here's the output from the program:

Extension = html
Filename = index
Path = /home/mem

The extension method uses lastIndexOf to locate the last occurrence of the period (.) in the filename. Then substring uses the return value of lastIndexOf to extract the filename extension -- that is, the substring from the period to the end of the string. This code assumes that the filename actually has a period in it; if the filename does not have a period , then lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException.

Also, notice that extension uses dot + 1 as the argument to substring. If the period character is the last character of the string, then dot + 1 is equal to the length of the string which is one larger than the largest index into the string (because indices start at 0). However, substring accepts an index equal to but not greater than the length of the string and interprets it to mean "the end of the string."

Try this: Inspect the other methods in the Filename class and notice how the lastIndexOf and substring methods work together to isolate different parts of a filename.

While the methods in the example above use only one version of the lastIndexOf method, the String class actually supports four different versions of both the indexOf and lastIndexOf methods. The four versions work as follows:

indexOf(int character)
lastIndexOf(int character)

Return the index of the first (last) occurrence of the specified character.

indexOf(int character, int from )
lastIndexOf(int character, int from )

Return the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.

indexOf(String string)
lastIndexOf(String string)

Return the index of the first (last) occurrence of the specified String.

indexOf(String string, int from )
lastIndexOf(String string, int from )

Return the index of the first (last) occurrence of the specified String, searching forward (backward) from the specified index.

More accessor methods for the StringBuffer class

Like String, StringBuffer provides length and charAt accessor methods. In addition to these two accessors, StringBuffer also has a method called capacity. The capacity method differs from length in that it returns the amount of space currently allocated
for the StringBuffer, rather than the amount of space used. For example, the capacity of the StringBuffer in the reverseIt method shown here never changes, while the length of the StringBuffer increases by one for each iteration of the loop:

Code:

public class ReverseString {
   public static String reverseIt(String source) {
      int i, len = source.length();
      StringBuffer dest = new StringBuffer(len);
      for (i = (len - 1); i >= 0; i--)
         dest.append(source.charAt(i));
      return dest.toString();
   }
}

Modifying string buffers

The reverseIt method uses StringBuffer's append method to add a character to the end of the destination string: dest.

Code:

public class ReverseString {
   public static String reverseIt(String source) {
      int i, len = source.length();
      StringBuffer dest = new StringBuffer(len);
      for (i = (len - 1); i >= 0; i--)
         dest.append(source.charAt(i));
      return dest.toString();
   }
}

If the appended character causes the size of the StringBuffer to grow beyond its current capacity, the StringBuffer allocates more memory. Because memory allocation is a relatively expensive operation, you can make your code more efficient by initialising a StringBuffer's capacity to a reasonable first guess, thereby minimising the number of times memory must be allocated for it. For example, the reverseIt method constructs the StringBuffer with an initial capacity equal to the length of the source string, ensuring only one memory allocation for dest.

The version of the append method used in reverseIt is only one of the StringBuffer methods that appends data to the end of a StringBuffer. There are several append methods that append data of various types, such as float, int, boolean, and even Object, to the end of the StringBuffer. The data is converted to a string before the append operation takes place.

Inserting and setting characters

At times, you may want to insert data into the middle of a StringBuffer. You do this with one of StringBufffer's insert methods. This example illustrates how you would insert a string into a StringBuffer:

Code:

StringBuffer sb = new StringBuffer("Drink Java!");
sb.insert(6, "Hot ");
System.out.println(sb.toString());

This code snippet prints:

Drink Hot Java!

With StringBuffer's many insert methods, you specify the index before which you want the data inserted. In the example, "Hot " needed to be inserted before the 'J' in "Java". Indices begin at 0, so the index for 'J' is 6. To insert data at the beginning of a StringBuffer, use an index of 0. To add data at the end of a StringBuffer, use an index equal to the current length of the StringBuffer or use append.

Another useful StringBuffer modifier is setCharAt, which replaces the character at a specific location in the StringBuffer with the character specified in the argument list. setCharAt is useful when you want to reuse a StringBuffer.

The toString method

It's often convenient or necessary to convert an object to a String because you need to pass it to a method that accepts only String values. The reverseIt method uses StringBuffer's toString method to convert the StringBuffer to a String object before
returning the String.

Code:

public class ReverseString {
   public static String reverseIt(String source) {
      int i, len = source.length();
      StringBuffer dest = new StringBuffer(len);
      for (i = (len - 1); i >= 0; i--)
         dest.append(source.charAt(i));
      return dest.toString();
   }
}

All classes inherit toString from the Object class and many classes in the java.lang package override this method to provide an implementation that is meaningful to that class.

For example, the "type wrapper" classes -- Character, Integer, Boolean, and the others -- all override toString to provide a String representation of the object.

The valueOf method

As a convenience, the String class provides the class method valueOf. You can use valueOf to convert variables of different types to Strings. For example, to print the value of pi:

Code:

   System.out.println(String.valueOf(Math.PI));

Converting strings to numbers

The String class itself does not provide any methods for converting a String to a floating point, integer, or other numerical type. However, four of the "type wrapper" classes (Integer, Double, Float, and Long) provide a class method named valueOf that converts a String to an object of that type. Here's a small, contrived example of the Float class's valueOf:

Code:

   String piStr = "3.14159";
   Float pi = Float.valueOf(piStr);

Literal strings

In Java, you specify literal strings between double quotes:

"Hello World!"

You can use literal strings anywhere you would use a String object. For example, System.out.println accepts a String argument, so you could use a literal string in place of a String there.

Code:

   System.out.println("Might I add that you look lovely today.");

You can also use String methods directly from a literal string.

Code:

   int len = "Goodbye Cruel World".length();

Because the compiler automatically creates a new String object for every literal string it encounters, you can use a literal string to initialise a String.

Code:

   String s = "Hola Mundo";

The above construct is equivalent to, but more efficient than, this one, which ends up creating two Strings instead of one:

Code:

   String s = new String("Hola Mundo");

The compiler creates the first string when it encounters the literal string "Hola Mundo!", and the second one when it encounters new String.

Concatenation and the + operator

In the Java programming language, you can use + to concatenate Strings together:

Code:

   String cat = "cat";
   System.out.println("con" + cat + "enation");

This is a little deceptive because, as you know, Strings can't be changed. However, behind the scenes the compiler uses StringBuffers to implement concatenation. The above example compiles to:

Code:

<p>  String cat = "cat";<br />
   System.out.println(new
         StringBuffer().append("con").
         append(cat).append("enation").toString());

You can also use the + operator to append values to a String that are not themselves Strings:

Code:

   System.out.println("Java's Number " + 1);

The compiler converts the non-String value (the integer 1 in the example) to a String object before performing the concatenation operation.

Summary of the String class

Method or Constructor Purpose

String()

String (byte[])
String (byte[], int, int)
String (byte[], int, int, String)
String (byte[], String)
String (char[])
String (char[], int, int)
String (String)
String (StringBuffer)

Creates a new string object. For all
constructors that take arguments, the first
argument provides the value for the string.

23444 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 0
Posted by jalex on Sunday, October 15, 2006 (20:00:00) (18975 reads)

Easy Java Lecture 9: The life cycle of an object. Teach/learn online

Go to all tips in Java Lectures by Anatoliy Malyarenko

The life cycle of an object

by: Anatoliy Malyarenko

Abstract

  • Contents of the lecture.
  • Creating objects.
  • Using objects.
  • Cleaning up unused objects.
  • Summary of creating and using objects.

Objects

A typical Java program creates many objects, which interact with one another by sending each other messages. Through these object interactions, a Java program can implement a GUI, run an animation, or send and receive information over a network. Once an object has completed the work for which it was created, it is garbage-collected and its resources are recycled for use by other objects.

Here's a small program, called CreateObjectDemo, that creates three objects: one Point object and two Rectangle objects. You will need all three source files to compile this program.

Code:

public class CreateObjectDemo {
   public static void main(String[] args) {
      // create a point object and two rectangle objects
      Point origin_one = new Point(23, 94);
      Rectangle rect_one = new Rectangle(origin_one, 100, 200);
      Rectangle rect_two = new Rectangle(50, 100);

      // display rect_one’s width, height, and area
      System.out.println("Width of rect_one: " +
                           rect_one.width);
      System.out.println("Height of rect_one: " +
                           rect_one.height);
      System.out.println("Area of rect_one: " +
                           rect_one.area());

      // set rect_two’s position
      rect_two.origin = origin_one;

      // display rect_two’s position
      System.out.println("X Position of rect_two: " +
                                    rect_two.origin.x);
      System.out.println("Y Position of rect_two: " +
                                    rect_two.origin.y);
      
      // move rect_two and display its new position
      rect_two.move(40, 72);
      System.out.println("X Position of rect_two: " +
                                    rect_two.origin.x);
      System.out.println("Y Position of rect_two: " +
                                    rect_two.origin.y);
   }
}
After creating the objects, the program manipulates the objects and displays some information about them. Here's the output from the program:

Width of rect_one: 100
Height of rect_one: 200
Area of rect_one: 20000
X Position of rect_two: 23
Y Position of rect_two: 94
X Position of rect_two: 40
Y Position of rect_two: 72

Creating objects

As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object:

Code:

Point origin_one = new Point(23, 94);
Rectangle rect_one = new Rectangle(origin_one, 100, 200);
Rectangle rect_two = new Rectangle(50, 100);

The first line creates an object from the Point class and the second and third lines each create an object from the Rectangle class.

Each statement has three parts:

  • Declaration. The code set in bold in the previous listing are all variable declarations that associate a name with a type. When you create an object, you do not have to declare a variable to refer to it. However, a variable declaration often appears on the same line as the code to create an object.
  • Instantiation. new is a Java operator that creates the new object (allocates space for it).
  • Initialisation. The new operator is followed by a call to a constructor. For example, Point(23, 94) is a call to Point's only constructor. The constructor initialises the new object.

Declaring a variable to refer to an object

To declare a variable, you write:

type name

This notifies the compiler that you will use name to refer to data whose type is type.

In addition to the primitive types, such as int and boolean, provided directly by the Java platform, classes and interfaces are also types. So to declare a variable to refer to an object, you can use the name of a class or an interface, as the variable's type. The sample program uses both the Point and the Rectangle class names as types to declare variables.

Code:

Point origin_one = new Point(23, 94);
Rectangle rect_one = new Rectangle(origin_one, 100, 200);
Rectangle rect_two = new Rectangle(50, 100);

Declarations do not create new objects. The code Point origin one does not create a new Point object; it just declares a variable, named origin one, that will be used to refer to a Point object. The reference is empty until assigned, as illustrated in the next figure. An empty reference is known as a null reference.

To create an object you must instantiate it with the new operator.

Instantiating an object

The new operator instantiates a class by allocating memory for a new object. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initialises the new object.

The new operator returns a reference to the object it created. Often, this reference is assigned to a variable of the appropriate type. If the reference is not assigned to a variable, the object is unreachable after the statement in which the new operator appears finishes executing.

Here's the code for the Point class:

Code:

public class Point {
   public int x = 0;
   public int y = 0;
   //A constructor!
   public Point(int x, int y) {
      this.x = x;
      this.y = y;
   }
}

This class contains a single constructor. You can recognise a constructor because it has the same name as the class and has no return type. The constructor in the Point class takes two integer arguments, as declared by the code (int x, int y). The following statement provides 23 and 94 as values for those arguments:

Code:

   Point origin_one = new Point(23, 94);

The effect of the previous line of code can be illustrated in the next figure:

Here's the code for the Rectangle class, which contains four constructors:

Code:

public class Rectangle {
   public int width = 0;
   public int height = 0;
   public Point origin;

   //Four constructors
   public Rectangle() {
      origin = new Point(0, 0);
   }
   
   public Rectangle(Point p) {
      origin = p;
   }
   
   public Rectangle(int w, int h) {
      this(new Point(0, 0), w, h);
   }

   public Rectangle(Point p, int w, int h) {
      origin = p;
      width = w;
      height = h;
   }

   //A method for moving the rectangle
   public void move(int x, int y) {
      origin.x = x;
      origin.y = y;
   }

   //A method for computing the area
   public int area() {
      return width * height;
   }
}

Each constructor lets you provide initial values for different aspects of the rectangle: the origin; the width, and the height; all three; or none. If a class has multiple constructors, they all have the same name but a different number of arguments or different typed arguments.

The Java platform differentiates the constructors, based on the number and the type of the arguments. When the Java platform encounters the following code, it knows to call the constructor in the Rectangle class that requires a Point argument followed by two integer arguments:

Code:

   Rectangle rect_one = new Rectangle(origin_one, 100, 200);

This call initialises the rectangle's origin variable to the Point object referred to by origin one. The code also sets width to 100 and height to 200. Now there are two references to the same Point object; an object can have multiple references to it, as shown in the next figure:

Multiple references can refer to the same object. The following line of code calls the constructor that requires two integer arguments, which provide the initial values for width and height. If you inspect the code within the constructor, you will see that it creates a new Point object whose x and y values are initialised to 0:

Code:

   Rectangle rect_two = new Rectangle(50, 100);

The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a no-argument constructor:

Code:

   Rectangle rect = new Rectangle();

If a class does not explicitly declare any constructors, the Java platform automatically provides a no-argument constructor, called the default constructor, that does nothing. Thus, all classes have at least one constructor.

Using objects

Once you've created an object, you probably want to use it for something. You may need information from it, want to change its state, or have it perform some action.

Objects give you two ways to do these things:

  • Manipulate or inspect its variables.
  • Call its methods.

Referencing an object's variables

The following is the general form of a qualified name, which is also known as a long name:

objectReference.variableName

You may use a simple name for an instance variable when the instance variable is in scope -- that is, within code for the object's class. Code that is outside the object's class must use a qualified name. For example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. So to refer to the origin, width, and height variables within the Rectangle object named rect one, the CreateObjectDemo class must use the names rect one.origin, rect one.width, and rect one.height, respectively.

The program uses two of these names to display the width and the height of rect one:

Code:

System.out.println("Width of rect_one: "
      + rect_one.width);
System.out.println("Height of rect_one: "
      + rect_one.height);

Attempting to use the simple names width and height from the code in the CreateObjectDemo class doesn't make sense -- those variables exist only within an object -- and results in a compiler error.

Later, the program uses similar code to display information about rect two. Objects of the same type have their own copy of the same instance variables. Thus, each Rectangle object has variables named origin, width, and height. When you access an instance variable through an object reference, you reference that particular object's variable. The two objects rect one and rect two in the CreateObjectDemo program have different origin, width, and height variables.

The first part of the variable's qualified name, objectReference, must be a reference to an object. You can use the name of a reference variable here, as in the previous examples, or you can use any expression that returns an object reference. Recall that the new operator returns a reference to an object. So you could use the value returned from new to access a new object's variables:

Code:

   int height = new Rectangle().height;

This statement creates a new Rectangle object and immediately gets its height. In essence, the statement calculates the default height of a Rectangle. Note that after this statement has been executed, the program no longer has a reference to the created
Rectangle, because the program never stored the reference in a variable. The object is unreferenced, and its resources can be recycled by the Java platform.

A word about variable access

The direct manipulation of an object's variables by other objects and classes is discouraged because it's possible to set the variables to values that don't make sense. For example, consider the Rectangle class from the previous section. Using that class, you can create a rectangle whose width and height are negative, which, for some applications, doesn't make sense.

Ideally, instead of allowing direct manipulation of variables, a class would provide methods through which other objects can inspect or change variables. These methods ensure that the values of the variables make sense for objects of that type. Thus, the Rectangle class would provide methods called setWidth, setHeight, getWidth, and getHeight for setting and getting the width and the height. The methods for setting the variables would report an error if the caller tried to set the width or the height to a negative number. The other advantage of using methods instead of direct variable access is that the class can change the type and the names of the variables it uses for storing the width and the height without affecting its clients.

However, in practical situations, it sometimes makes sense to allow direct access to an object's variables. For example, both the Point class and the Rectangle class allow free access to their member variables by declaring them public. This keeps these classes small and simple. Also, it keeps them generally useful. Some applications might allow rectangles with negative widths and heights.

The Java programming language provides an access control mechanism whereby classes can determine what other classes can have direct access to its variables. A class should protect variables against direct manipulation by other objects if those manipulations could result in values that don't make sense for objects of that type. Changes to these variables should be controlled by method calls. If a class grants access to its variables, you can assume that you can inspect and change those variables without adverse effects.

Calling the object's methods

You also use qualified names to call an object's method. To form the qualified name of a method, you append the method name to an object reference, with an intervening period (.).

Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.

objectReference.methodName(argumentList);

or

objectReference.methodName();

The Rectangle class has two methods: area to compute the rectangle's area and move to change the rectangle's origin. Here's the CreateObjectDemo code that calls these two methods:

Code:

System.out.println("Area of rect_one: "
      + rect_one.area());
      ...
      rect_two.move(40, 72);

The first statement calls rect one's area method and displays the results. The second line moves rect two because the move method assigns new values to the object's origin.x and origin.y.

As with instance variables, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. The new operator returns an object reference, so you can use the value returned from new to call a new object's methods:

Code:

   new Rectangle(100, 50).area()

The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As shown, you can use the dot notation to call the new Rectangle's area method to compute the area of the new rectangle.

Some methods, such as area, return a value. For methods that return a value, you can use the method call in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned by area to a variable:

Code:

   int areaOfRectangle = new Rectangle(100, 50).area();

Remember, invoking a method on a particular object is the same as sending a message to that object. In this case, the object that area is invoked on is the rectangle returned by the constructor.

The methods in our Point and Rectangle classes are all declared public, so they are accessible to any other class. Sometimes, a class needs to restrict access to its methods. For example, a class might have a method that only subclasses are allowed to call. A class can use the same mechanism to control access to its methods as it uses to control access to its variables.

Cleaning up unused objects

Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error prone. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null. Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.

The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically, although, in some situations, you may want to run the garbage collection explicitly by calling the gc method in the System class. For instance, you might want to run the garbage collector after a section of code that creates a large amount of garbage or before a section of code that needs a lot of memory.

Finalisation

Before an object gets garbage-collected, the garbage collector gives the object an opportunity to clean up after itself through a call to the object's finalize method. This process is known as finalisation.

Most programmers don't have to worry about implementing the finalize method. In rare cases, however, a programmer might have to implement a finalize method to release resources, such as native peers, that aren't under the control of the garbage collector.

The finalize method is a member of the Object class, which is the top of the Java platform's class hierarchy and a superclass of all classes. A class can override the finalize method to perform any finalisation necessary for objects of that type. If you override finalize, your implementation of the method should call super.finalize as the last thing it does.

Summary of creating and using objects

You create an object from a class by using the new operator and a constructor. The new operator returns a reference to the object that was created. You can assign the reference to a variable or use it directly.

A class controls access to its instance variables and methods by using the Java platform's access mechanism. Instance variables and methods that are accessible to code outside of the class that they are declared in can be referred to by using a qualified name. The qualified name of an instance variable looks like this:

objectReference.variableName

The qualified name of a method looks like this:

objectReference.methodName(argumentList)

or

objectReference.methodName()

The garbage collector automatically cleans up unused objects. An object is unused if the program holds no more references to it. You can explicitly drop a reference by setting the variable holding the reference to null.

by Anatoliy Malyarenko


20559 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 0
Posted by jalex on Thursday, October 12, 2006 (20:00:00) (6910 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490| 489| 488| 487| 486| 485| 484| 483| 482| 481|
480
| 479| 478| 477| 476| 475| 474| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394| 393| 392| 391| 390| 389| 388| 387| 386| 385| 384| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331| 330| 329| 328| 327| 326| 325| 324| 323| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312| 311| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294| 293| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy