Class 101
Java has 8 primitive types such as int
, double
, and boolean
for numbers and simple true/false values. Everything else
is some kind of object. The definition for an object type is called a
class.
Java provides a number of predefined classes: we have used System
to access the standard output stream and we have also seen the String
class for text.
As with the primitive data types, you must declare a variable of a class in order to use it:
String message;
Also, just as with primitives, you must initialize the variable. A variable whose type is a class can store a reference to an object which is an instance of that class. In the case of String
, it is easy to construct a new instance: we can just put some text in quotes:
message = "Hello, world!"; System.out.println(message);
Invoking methods
Most classes also define operations, called methods, that allow you to examine or modify the data in each instance. You can invoke or call a method using the dot operator on an instance of the class.
For example, the class String
has many methods available. A commonly used method is length
, which retrieves the length of a string.
int theLength = message.length(); System.out.println(theLength);
In your lab2
package, write a class named StringTest
with a main
method to try this out. Consult the previous lab if you do not remember to how create a class and main
method. Run it and inspect the output.