0% found this document useful (0 votes)
54 views

Chapter 4: Some Standard Classes: Object Class's Methods

The document discusses standard classes in Java including Object, String, wrapper classes like Integer and Double, and the Math class. Object is the universal superclass of all classes and provides default methods like toString() and equals(). String is an immutable sequence of characters that can be constructed and manipulated using methods like concatenation. Wrapper classes like Integer and Double "box" primitive types into objects to allow them to be used where objects are required. They provide value-retrieval methods like intValue() and doubleValue(). The Math class contains common mathematical methods like absolute value, power, square root, and more.

Uploaded by

Aditya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Chapter 4: Some Standard Classes: Object Class's Methods

The document discusses standard classes in Java including Object, String, wrapper classes like Integer and Double, and the Math class. Object is the universal superclass of all classes and provides default methods like toString() and equals(). String is an immutable sequence of characters that can be constructed and manipulated using methods like concatenation. Wrapper classes like Integer and Double "box" primitive types into objects to allow them to be used where objects are required. They provide value-retrieval methods like intValue() and doubleValue(). The Math class contains common mathematical methods like absolute value, power, square root, and more.

Uploaded by

Aditya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Chapter 4: Some Standard Classes

The Universal Superclass


Object is the universal superclass of every class in a program. It is the direct or indirect superclass of every object in a
class hierarchy tree.

The reason the Object class exists is to provide default methods to all of its subclasses. It is not an abstract class, and
all of its methods have implementations. If any of the methods that Object provides are not suitable, then they are
simply overriden by one of the subclasses.

Object Class's Methods

The toString Method:


All this method does is returns a version of the object in String form. The default toString method is quite useless,
however. When you attempt to print an object, it will invoke the toString method and give you a result like this

Line 1 SavingsAccount s = new SavingsAccount(500);

Line 2 System.out.println(s);

Output: SavingsAccount@fea485c4, where the output just informs the user the memory location of where that
SavingsAccount is located. It is quite useless. In order for a more useful output, the method must be overridden.

The equals Method:


All classes inherit this method from the Object class as well. IT returns true if the object and the other are the same
object, and false otherwise.

The equals method does not indicate if all the instance variables belonging to two objects are equal. This means
that if I have two Student objects, and they both have one instance variable "public name," and that name is equal, I
will not get true from the equals method.

You will only get true from the equals method if two reference variables are referencing the same object, meaning
if two reference variables represent the same object. Only then will the equals method give you a true.

Syntax: If d1 and d2 are objects, you can invoke the equals Method by stating:

(d1.equals(d2)) or (d2.equals(d1))

In addition, the equals method's implementation is equivalent to the == relation for objects. This means that we could
also have said:

(d1 == d2 or (d2 == d1

NOTE The difference between the equals Method and the == operator:

The .equals() method checks for content comparison and the == operator checks for reference comparison.

The String Class

String Objects:
An object of type String is a sequence of characters. Strings are non - primitive data types, as their memory locations
can expand to fit the entire length of the String.

Chapter 4 Some Standard Classes 1


The quotes are not part of the string object, and the string literal consists of zero or more characters, including
escape sequences. A string literal is implemented as an instance of the String class. In this way, they work as objects.

Immutable: This means not able to be changed. String objects are immutable. However, you can created a new String
that is a mutated form of an existing String.

Constructing String Objects:


They can be initialized as a primitive type, or the way an object is initialized using the new keyword. Either way has the
same effect, creating a String object with the contents defined.

Although if there is a currently existing string object, you cannot change (mutate) it, because it is immutable, what you
can do is reassign that String reference to another string. Simple!

String s = "abc"; // Method 1 for constructing a string (as primitive)


String s = new String("abc"); // Method 2 for constructing a string (as object)

String s = "John";
s = "Harry"; // Here the string is redefined, NOT MUTATED!

String s = new String("John");


s = new String("Harry"); // Here the string is redefined, NOT MUTATED, in a different

// You can reassign the String reference variable s using the concatenation operator.
s = s + " Windsor";

// Finally, you can do this as well...


String s1 = null; // s1 is a null reference
String s2 = new String(); // s2 is an empty character sequence

The Concatenation Operator:


The concatenation operator, also known as the "+" operator, operates on String objects. Its purpose is to concatenate
two different strings, and is quite easy to use. Simply take two string objects, and put the "+" operator in between, and
the output will be the strings concatenated.

It is important to note that as long as one of the operands is a string, the rest can be integers, doubles, or any
primitive type. Here, the non - String operand is converted to a String, and concatenation occurs.

Let's say that you want to concatenate two non - String operands. How do you do this? Well, simply use the dot
operator along with the toString() method to first convert the operands to strings, and then concatenate using the
Concatenation Operator.

Comparison of String Objects:


 Use the equals method (not the == operator) to compare String objects. It returns true if the content of the String
objects is the same.

 Use the compareTo method. If you use it with the dot operator, you will have a couple of different possible outputs.
Let's examine them here:

 If string1.compareTo(string2 < 0, it means that string1 precedes string2

 If string1.compareTo(string2 > 0, it means that string1 is follows string2

 If string1.compareTo(string2 == 0, it means that string1 equals string2

 Characters are compared according to their position in the ASCII chart. You need to know that all digits precede
capital letters, which precede all lowercase letters themselves. In addition, if the strings have identical characters, but
one ends before the other one, the string that ends first comes before the longer string.

Chapter 4 Some Standard Classes 2


Other String Methods:
int length()

Return the length of the string

String substring(int startIndex)

Returns a new string that is a substring, starting from startIndex.

String substring(int startIndex, int endIndex)

New string, starts at startIndex, ends at endIndex - 1. startIndex is the first character in the substring where it
should start, and endIndex is the first character that you do not want.

int indexOf(String str)

Returns the index of the first occurrence of str within this string. If str is not a substring, 1 is returned.

Wrapper Classes
The wrapper class takes an existing object or a value of primitive type and "wraps or "boxes" it in an object, while
providing a new set of methods for that type.

It can be used in generic Java methods that require objects as parameters.

It can be used in Java container classes that require the items to be objects.

The wrapper class allows the construction of an object from a single value through wrapping or boxing the primitive in
a wrapper object, as well as retrieval of the primitive value by unwrapping or unboxing from the wrapper object.

The Integer Class


Wraps a value of type int in an object.

There are a couple of important integer methods you should know.

Integer(int value)

Constructs an Integer object from an int (boxing).

int compareTo(Integer other)

Returns 0 if the value of this Integer is equal to the value of other, a negative integer if it is less than the value
of other, and a positive integer if it is greater than the value of other.

int intValue()

Returns the value of this Integer object as an int (unboxing).

boolean equals(Object obj)

Returns true if and only if this Integer has the same int value as obj.

String toString()

Returns a String representing the value of this Integer

The Double Class


Double(double value)

Constructs a Double object form a double Boxing).

Chapter 4 Some Standard Classes 3


double doubleValue()

Returns the value of this Double as a double Unboxing).

int compareTo(Double other)

Returns 0 if the double values are equal, a negative integer if the double is less than the the value of other, and a
positive integer if the double is greater than the value of other.

boolean equals(Object obj)

Overrides equals in class Object and throws a ClassCastException if obj is not a Double or a double. Otherwise, it
returns true if and only if this Double has the same double value as obj.

String toString()

Returns a String representing the value of this Double.

The Math Class


static int abs(int x)

static double abs(double x)

static double pow(double base, double exp), returning base^exp, assuming base > 0, or base = 0 and exp > 0, or base
< 0 and exp is an integer.

static double sqrt(double x), returning √x as long as x ≥ 0.

static double random(), returning a random number r, where 0.0 ≤ r < 1.0.

The Math Class Syntax


Due to the fact that there are no Math objects, and all Math class methods are static, we know that when calling a
Math Class method, the syntax must use the dot operator to signify that static class is from Math.

Example: int a = Math.pow(2, 8; and the result is a = 256;

Little Technicality: Sometimes, it is tedious to always call Math Class functions everytime you use them. Thus, it is
possible to use the static import construct to use the static members of a class without the name prefix.

Example: import static java.lang.Math.*;

Random Numbers
The Math.random(); method produces a random real number r from 0.0 ≤ r < 1.0. In order to shift the range of the
random numbers, linear transformations can be made. The general structure for doing a linear shift is:

Example: Range lowV ≤ x < highV, where double x = (highV - lowV * Math.random() + lowV; V = Value)

Random Integers
Random integers are also very simple (at least for me) to understand. They can be created by using the
Math.random(); method and then downcasting its boolean value to int. Then, linear shifting can be applied.

Remember, however, when downcasting using (int), the new integers do not round. Take account of this.

Example: int num = (int) Math.random() * (highValue - lowValue + 1 + lowValue;

Chapter 4 Some Standard Classes 4

You might also like