Creating an Object

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

It counts the number of characters in that String.

Creating an Object

The Java virtual computer creates an object by following the description contained in its class. Here is a program that creates a String object:

class StringDemo1
{
  public static void main ( String[] args )
  {
    String str ;

    str = new String( "Elementary, my dear Watson!" );
  }
}

When the program runs, the expression

new String( "Elementary, my dear Watson!" )

creates a new String object by following the description contained in the String class. This description is contained in a standard software package that comes with Java. The particular object created in this case contains characters "Elementary, my dear Watson!". The new object contains all the methods and features that are described in the String class.

All objects of the same class contain the same methods. All objects of the same class contain the same types of data, although the values of the data will be different from object to object. For example, all String objects contain the same methods. All String objects contain a string of characters, but the characters will be different from object to object.

The program could now use the methods of this object to do some things with the characters. However, this program does nothing further. After it stops running, the object no longer exists. The memory out of which it was made can now be used for other purposes.

QUESTION 4:

Mentally change the program so that it creates a String object containing the characters "You know my methods, Watson."