The following is from the Java tutorial
- What is a Class?
- "In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.""
- And an object is an instance of a class
- The following Bicycle class is one possible implementation of a bicycle:
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
Java String class
- A String is a sequence of characters
- In Java, Strings are objects or instances of the
String
class String
literals in Java programs are implemented as instances of the String class such as
String s = “abcd”;
- This creates a new
String
object representing the string "abcd" - Take a look at the Java documentation for String
- Java has numerous constructors for the
String
classString()
, construct aString
representing the empty character sequenceString(byte[] bytes)
, construct a newString
consisting of the bytes in thebyte
arraybytes
String(char[] chars)
, construct a newString
consisting of the characters of the character arraychars
String("abcd")
- There are plenty more
- Strings are immutable or constant, so any changes you make to an existing
String
will create a newString
- Strings can be shared, in theory there should be a single copy of any
String
in your program, but don't count on it if they are created dynamically during the running of the program. There is a separate memory area "String space" and theintern()
method returns a shared copy that is put into the "String space" - The class
String
also has numerous methods - Getting a
byte
array for the bytes in theString
- Getting a
char
array for the characters in theString
- Changing the case
- Converting various primitive types to a
String
- The "+" sign can be used for concatenation
"abc" + "def"
is theString
"abcdef"
StringBuilder
andStringBuffer
StringBuffer
is thread safe and is a mutable sequence of charactersStringBuilder
is API compatible withStringBuffer
, but it not thread safe- Should be faster than
StringBuffer
in single-thread applications