CS计算机代考程序代写 jvm compiler Java gui flex interpreter 2_OOP

2_OOP

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 1

• Object-Oriented Programming
Object-oriented programming (OOP) enables you to develop large-scale software and Graphical User
Interfaces (GUIs) effectively. It is essentially a technology for developing reusable software. Having
learned Java programming language in the previous courses, you are able to solve many computer
solvable problems using selections, loops, methods, and arrays. However, these Java features are not
sufficient for developing GUI and large-scale software systems.

• Class and object
A class defines the properties and behaviors for objects. OOP involves programming using objects. An
object represents an entity in the real world that can be distinctly identified, tangible or intangible. For
example, a student, a desk, a circle, a building, a loan, or an event can all be viewed as objects. An object
has a unique identity, state, and behavior, depending on how you model it based on requirements.
The state of an object (also known as its properties or attributes) is represented by data fields with their
current values. A circle object, for example, has a data field radius, which is the property that
characterizes a circle. A rectangle object, for example, has the data fields width and height, which are
the properties that characterize a rectangle.
The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an
object is to ask the object to perform an action, which is to manipulate the data fields. For example, you
may define methods named getArea() and getPerimeter() for circle objects. A circle object may invoke
getArea() to return its area and getPerimeter() to return its perimeter. You may also define the
setRadius(radius) method. A circle object can invoke this method to change its radius.

Objects of the same type are defined using a common class. A class is a template, blueprint, or contract
that defines what an object’s data fields and methods will be. An object is an instance of a class. You
can create many instances of a class and every instance has its own “state”. Creating an instance is
referred to as instantiation. The terms object and instance are often interchangeable. The relationship
between classes and objects is analogous to that between an apple-pie recipe and apple pies: You can
make as many apple pies as you want from a single recipe.

Class name

circle1
radius: 4

Each instance of the Circle class has different states.

Attribute (instance variable)

Operations (instance methods)

circle2
radius: 5

circle3
radius: 6

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 2

• Class and Object Implementation with Java
Unlike C++, Java is a pure object-oriented programming language. A Java class uses variables to define
data fields and methods to define actions. In addition, a class provides methods of a special type, known
as constructors, which are invoked to create a new object. A constructor can perform any actions.
However, constructors are mainly designed to perform initializing actions, such as initializing the data
fields of objects. It is a good software development practice to always define the data fields as “private”
to better protect the data. In this case, the private data fields are only “visible” within the class, meaning
the data fields can be directly accessed within the class without the instantiation of an object.

For example, the Circle class below is a template for creating circle objects (instances) with different
radius values. Note that, if the Circle class doesn’t have a “main” method, it cannot be run by itself.
However, a “testbed main” can be created as a driver for the purpose of unit testing the class. In other
cases, the Circle class can be used by a client class, which may include a main method as the starting
point of program execution.

// Circle class is a template for circle objects with different radius values.
public class Circle {
private double radius; //data are private; no direct access from outside the class

/** Default constructor; create a circle object with a default value */
public Circle() {
radius = 1.0; // set radius to the default value
}

/** Parameterized Constructor; create a circle object with a specified radius */
public Circle(double radius) {
this.radius = radius;
}

/** Return the value of the radius */
public double getRadius() {
return radius;
}

/** Set the radius of a circle object to a given value. */
public void setRadius(double radius) {
this.radius = radius;
}

/** Compute and return the area of the circle object. */
public double getArea() {
return radius * radius * Math.PI;
}

/** Compute and return the perimeter of the circle object */
public double getPerimeter() {
return 2 * radius * Math.PI;
}
//testbed main as a driver to exercise the code in this class
public static void main(String[] args) {
Circle circle1 = new Circle(4.0);
System.out.println(“The area of circle1 with radius ” + circle1.radius + ” is ”
+ circle1.getArea());
Circle circle2 = new Circle(5.0);
System.out.println(“The area of circle2 with radius ” + circle2.radius + ” is ”
+ circle2.getArea());
Circle circle3 = new Circle(6.0);
System.out.println(“The area of circle3 with radius ” + circle3.radius + ” is ”
+ circle3.getArea());
}
}

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 3

Program output for test running the Circle class.

When you run a Java program, the Java runtime system invokes the main method in the main class. You
can put two classes into one file, but only one class in the file can be the “public” class. The public class
must have the same name as the file name. For example, the Circle class above must be stored as
Circle.java since the Circle class is “public”.

Each class in the source code (.java file) is compiled into a .class file. When you compile Circle.java, a
Circle.class file is generated. Note that, Java uses a combination of a compiler and an interpreter. Java
programs are first compiled into bytecode, which is interpreted and run by JVM (Java Virtual Machine.
Java bytecode is portable and can be run on any platform running JVM.

As another example, consider television sets. Each TV is an object with states (current channel, current
volume level, and power on or off) and behaviors (change channels, adjust volume, and turn on/off).
You can use a class to model TV sets. Depending on the needs of the software you are developing, you
can also define a different set of attributes and associated operations for a TV object.

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 4

• Constructors
A constructor is invoked to create (instantiate) an object using the “new” operator. Constructors are a
special kind of method. They have three peculiarities:

1. A constructor must have the same name as the class itself.
2. Constructors do not have a return type—not even void.
3. Constructors are invoked using the “new” operator when an object is created. Constructors play

the role of initializing objects.
A constructor has exactly the same name as its defining class. Like regular methods, constructors can be
overloaded (i.e., multiple constructors can have the same name but different signatures), making it easy
to construct objects with different initial data values. There are 3 kinds of constructors.

1. Default constructor – no-parameter constructors.
2. Parameterized constructor – a various numbers of parameters are defined.
3. Copy constructor – to clone an object; a single parameter with the class type is defined.

Since data fields are “private” and cannot be accessed directly from outside of the class, constructors are
used to construct objects. To construct an object from a class, invoke a constructor of the class using the
“new” operator as follows: new ClassName(arguments); for example, new Circle() creates an object
of the Circle class using the first constructor (default constructor) defined in the Circle class, and new
Circle(25.0) creates an object using the second constructor (parameterized constructor) defined in the
Circle class. A class normally provides a default constructor (e.g., Circle()). A class may be defined
without any constructors. In this case, a public default constructor with an empty body is implicitly
defined. Note that, this constructor is provided automatically ONLY if not a single constructor has been
explicitly defined in the class. For example, even if a class defines a parameterized constructor without
defining a default constructor, Java will NOT generate a default constructor for the class.

• Accessing Objects
An object’s data and methods can be accessed through the dot (.) operator via the object’s reference
variable. Newly created objects are allocated in the memory. They can be accessed via reference
variables. Objects are accessed via the object’s reference variables, which contain references to the
objects. A class is essentially a programmer-defined type. A class is a reference type, which means that
a variable of the class type can reference an instance of the class. You can write a single statement that
combines the declaration of an object reference variable, the creation of an object, and the assigning of
an object reference to the variable with the following syntax:
ClassName objectVariable = new ClassName();
An object reference variable that appears to hold an object actually contains a reference to that object.
Strictly speaking, an object reference variable and an object are different, but most of the time the
distinction can be ignored. Therefore, it is fine, for simplicity, to say that myCircle is a Circle object
rather than use the long-winded description that myCircle is a variable that contains a reference to a
Circle object.
In OOP terminology, an object’s members refer to its data fields and methods. After an object is created,
its data can be accessed and its methods can be invoked using the dot operator (.), also known as the
object members access operator. For example, in the Circle class, the data field radius is referred to
as an instance variable because it is dependent on a specific instance. For the same reason, the

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 5

method getArea() is referred to as an instance method because you can invoke it only on a specific
instance. The object on which an instance method is invoked is called a calling object.

Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the
Math class. Can you invoke getArea() using Circle.getArea()? The answer is NO. All the methods in
the Math class are static methods, which are defined using the “static” keyword. However, getArea()
is an instance method, and thus non-static. It must be invoked from an object using
objectVariable.methodName(arguments) (e.g., myCircle.getArea()).
Usually you create an object and assign it to a variable, then later you can use the variable to reference
the object. Occasionally, an object does not need to be referenced later. In this case, you can create an
object without explicitly assigning it to a variable using the syntax:
System.out.println(“Area is ” + new Circle(5.0).getArea());
The former statement creates a Circle object. The latter creates a Circle object and invokes its getArea
method to return its area. An object created in this way is known as an anonymous object. The data
fields can be of reference types. For example, the following Student class contains a data field name of
the String type. String is a predefined Java class.
public class Student {

private String name; // name has the default value null
private int age; // age has the default value 0

private boolean isScienceMajor; // isScienceMajor has default value false
private char gender; // gender has default value ‘\u0000’
}

If a data field of a reference type does not reference any object, the data field holds a special Java
value, null, which is a literal just like true and false. While true and false are Boolean literals, null is a
literal for a reference type. The default value of a data field is null for a reference type, 0 for a numeric
type, false for a boolean type, and \u0000 for a char type. However, Java assigns no default value to a
local variable inside a method. The following code displays the default values of the data fields name,
age, isScienceMajor, and gender for a Student object. However, not assigning values to local variables
and trying to print the content of the variables will cause compile errors.

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 6

NullPointerException is a common runtime error. It occurs when you invoke a method on a reference
variable with a null value. Make sure you assign an object reference to the variable before invoking the
method through the reference variable.
Every variable represents a memory location that holds a value. When you declare a variable, you are
telling the compiler what type of value the variable can hold. For a variable of a primitive type, the value
is of the primitive type. For a variable of a reference type, the value is a reference to a memory location
where an object is stored.

When you assign one variable to another, the other variable is set to the same value. For a variable of a
primitive type, the real value of one variable is assigned to the other variable. For a variable of a reference
type, the reference of one variable is assigned to the other variable.

/myArray

myArray

Heapnull

ref.

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 7

For example, in the above figure, after the assignment statement c1 = c2, c1 points to the same object
referenced by c2. The object previously referenced by c1 is no longer accessible and therefore is now
known as garbage. Garbage occupies memory space, so the Java runtime system detects garbage and
automatically reclaims the space it occupies. This process is called garbage collection.

• Using Java library classes
One of the benefits of using Java language is the well-established Java library classes. There are many
existing Java classes that can be used to solve problems without writing new classes from scratch. For
example, the Date class is commonly used by many software developlers.

You can use the default constructor in the Date class to create an instance for the current date and time,
the getTime() method to return the elapsed time in milliseconds since January 1, 1970, GMT, and
the toString() method to return the date and time as a string. For example, the following code generates
the output below.

As another example, the Random class is commonly used by software developers to generate random
numbers for different purposes.

When you create a Random object, you have to specify a seed or use the default seed. A seed is a number
used to initialize a random number generator. The default constructor creates a Random object using the
current elapsed time as its seed. If two Random objects have the same seed, they will generate identical

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 8

sequences of numbers. The ability to generate the same sequence of random values is useful in software
testing and many other applications. In software testing, oftentimes you need to reproduce the test cases
from a fixed sequence of random numbers.
You can generate random numbers using the java.security.SecureRandom class rather than the
Random class. The random numbers generated from the Random are deterministic and they can be
predicated by hackers. The random numbers generated from the SecureRandom class are
nondeterministic and are more secure.

For a list of Java API library classes (version 14), please visit:
https://docs.oracle.com/en/java/javase/14/docs/api/index.html

• Static variables, constants and methods
A static variable is shared by all objects of the class. A static method cannot access instance members
(i.e., instance data fields and methods) of the class.

The data field radius in the circle class is known as an instance variable. An instance variable is tied to
a specific instance of the class; it is not shared among objects of the same class. If you want all the
instances of a class to share data, use static variables, also known as class variables. Static variables
store values for the variables in a common memory space. Because of this common location, if one
object changes the value of a static variable, all objects of the same class are affected. Java supports
static methods as well as static variables. Static methods can be called without creating an instance of
the class. To declare a static variable or define a static method, add the modifier static to the variable or
method declarations.
Constants in a class are shared by all objects of the class. Thus, constants should be declared as final
static. For example, the constant PI in the Math class is defined as follows:
final static double PI = 3.14159;

The main method is static as well. Static variables and methods can be accessed without creating objects.
Use ClassName.methodName(arguments) to invoke a static method and ClassName.staticVariable
to access a static variable. This improves readability because this makes static methods and data easy to
spot.

An instance method can invoke an instance or static method and access an instance or static data field.
A static method can invoke a static method and access a static data field. However, a static method of a
class cannot invoke an instance method or access an instance data field without creating an object, since
instance methods and instance data fields must be associated with a specific object. The relationship
between static and instance members is summarized in the following table.

Static/or non-static Invoke instance methods
Access instance

variables
Invoke static

methods
Access static

variables

Instance methods Ö Ö Ö Ö

Static methods X X Ö Ö

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 9

How do you decide whether a variable or a method should be instance or static? A variable or a method
that is dependent on a specific instance of the class should be an instance variable or method. A variable
or a method that is not dependent on a specific instance of the class should be a static variable or method.
For example, every circle has its own radius, so the radius is dependent on a specific circle object.
Therefore, radius is an instance variable of the Circle class. Since the getArea() method is dependent on
a circle object’s radius value, it is also an instance method. None of the methods in the Math class, such
as random, pow, sin, and cos, is dependent on a specific instance. Therefore, these methods are static
methods. The main method of a class is static and can be invoked directly from a class. It is a common
design error to define an instance method that should have been defined as static. For example, the
method factorial(int n) should be defined as static, because it is independent of any specific instance.

• Visibility Modifiers
Visibility modifiers can be used to specify the visibility of a class and its members. You can use the
“public” modifier for classes, methods, and data fields to denote that they can be accessed from any other
classes. If no visibility modifier is used, then by default the classes, methods, and data fields are
accessible by any class in the same package. This is known as package-private or package-access.

Packages are used to organize classes. To do so, you need to add the following line as the first non-
comment and nonblank statement in the program.
package packageName;

If a class is defined without the package statement, it is said to be placed in the default package. Java
recommends that you place classes into packages rather than using a default package.

In addition to the public and default visibility modifiers, Java provides the private and protected
modifiers for class members. The private modifier makes methods and data fields accessible only from
within its own class. If a class is not defined as public, it can be accessed only within the same package.
Using the modifiers public and private on local variables would cause a compile error.

In most cases, constructors should be public. However, if you want to prohibit the client class from
creating an instance of a class, define the constructor as private. In this case, private constructors are
hidden from the external client classes and can only be invoked from within the class. For example, there
is no reason to create an instance of the Java Math class, because all of its data fields and methods are

Within the
Class

Within
Subclasses in
the Same
Package

Within
Subclasses in
Other
Packages

Everywhere

public ü ü ü ü

protected ü ü ü

package ü ü

private ü

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 10

static. To prevent the user from creating the objects of the Math class, the default constructor of the
java.lang.Math is defined as follows.

private Math() {
}

• Data Encapsulation
Making data fields private protects data and makes the class easy to maintain.

1. Data may be tampered with if the data is made public where everyone has the direct access. This
means the update of data is not well-controlled and it is difficult to trace the changes. For
example, numberOfObjects is to count the number of objects created, but it may be mistakenly
set to an arbitrary value (e.g., Circle.numberOfObjects = 10). The class becomes difficult to
maintain and vulnerable to bugs.

2. Suppose that you want to modify the Circle class to ensure that the radius is nonnegative after
other programs have already used the class. You have to change not only the Circle class but also
the programs that use it because the client classes may have modified the radius directly.

To prevent direct modifications of data fields from other classes, you should always declare the data
fields as private using the private modifier. This is known as data encapsulation.

A private data field cannot be accessed by an object from outside the class that uses the private data
field. However, a client class often needs to retrieve and modify a data field. To make a private data field
accessible, provide a “getter” method to return its value. To enable a private data field to be updated,
provide a “setter” method to set a new value. A getter method is also referred to as an accessor and a
setter to a mutator.

• Passing Objects to Methods
Passing an object to a method is to pass the reference of the object. You can pass objects to methods.
Like passing an array, passing an object is actually passing the reference of the object. For example,
The following code passes the circle object as an argument to the printCircle() method:

public void printCircle(int times, Circle c) { }

public static void main(String[] args) {
int n = 5;
Circle circle = new Circle(4.0);
circle.printCircle(n, circle);

}

Pass-by-value refers to the situation where the method call is passing the value of an argument of a
primitive data type. In the above example, the value of n (i.e., 5) is passed to the parameter times. In the
printCircle() method, if the content of the variable times is changed, the value of n in the main method
remains unchanged. When passing an argument of a reference type, the reference of the object is passed.
In this case, c contains the same reference to the circle object. Therefore, changing the data values of the
circle object through c in the printCircle() method has the same effect as doing so outside the method

Pass by value
Pass by reference

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 11

through the variable “circle”. Pass-by-reference can be best described semantically as pass-by-sharing;
that is, the object referenced in the method is the same as the object being passed.

• Array of Objects
An array of objects is actually an array of references. Thus, invoking circleArray[1].getArea() involves
two levels of referencing, as shown below. Circle[] circleArray = new Circle[10]; declares an
array of Circle objects with a size of 10. The circleArray contains a reference to the beginning address
of a consecutive memory block that is allocated for storing 10 object references of the Circle class. Each
array element stores a reference to an instance of Circle class. For example, circleArray[1] references
the second element of the array, which is a reference to a Circle object. Similarly,
circleArray[1].getArea() invokes the method of the second Circle object in the array. Note that, an
array occupies a block of consecutive memory addresses; however, the memory addresses that are
storing the actual circle objects are not necessarily consecutive. When an array of objects is created using
the new operator, each element in the array is a reference variable with a default value of null.

• Immutable Objects and Classes
You can define immutable classes to create immutable objects. The contents of immutable objects cannot
be changed. Normally, you create an object and allow its contents to be changed later. However,
occasionally it is desirable to create an object whose contents cannot be changed once the object has
been created. We call such an object as immutable object and its class as immutable class. The String
class, for example, is immutable. If you deleted the setter method in the Circle class, the class would be
immutable because radius is private and cannot be changed without a setter method.
If a class is immutable, then all its data fields must be private, and it cannot contain public setter methods
for any data fields. A class with all private data fields and no mutators is not necessarily immutable. For
example, the following Employee class has all private data fields and no setter methods, but it is not an
immutable class. The data field hired is returned using the getDateHired() method. This is a reference
to a Date object. Through this reference, the content for hired can be changed. To make the Employee
class an immutable class, one can convert the Date object to a string then return the string instead of
returning the reference.

reference 1

reference 2

reference 3

circleArray

circleArray[0]

circleArray[1]

circle
object

circle
object

circle
object

circleArray[9]

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 12

For a class to be immutable, it must meet the following requirements:
1. All data fields must be private.
2. There can’t be any mutator methods for data fields.
3. No accessor methods can return a reference to a data field that is mutable.

• Scope of Variables
The scope of instance and static variables is the entire class, regardless of where the variables are
declared. Instance and static variables in a class are referred to as the class’s variables or data fields. A
variable defined inside a method is referred to as a local variable. The scope of a class’s variables is the
entire class, regardless of where the variables are declared. A class’s variables and methods can appear
in any order in the class. The exception is when a data field is initialized based on a reference to another
data field. In such cases, the other data field must be declared first. For example, the getArea() method
in the Circle class can be declared before the data field radius; however, the integer i must be declared
before the integer j.

public class Circle {
public double getArea() {
return radius * radius * Math.PI;
}
private double radius = 1.0;
}
public class Foo {

private int i = 1;
private int j = i + 1;

}

public class Employee {
private int id;
private String name;
private java.util.Date hired;

public Employee (int id, String name) {
this.id = id;
this.name = name;
hired = new java.util.Date();
}

public int getId() {
return id;
}

public String getName() {
return name;
}

//this method returns the reference to the calling method, thus is mutable.
public java.util.Date getDateHired() {
return hired;
}
}

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 13

You can declare a class’s variable only once, but you can declare the same variable name in a method
many times in different non-nesting blocks. If a local variable has the same name as a class’s variable,
the local variable takes precedence and the class’s variable with the same name is hidden. For example,
in the following program, x is defined both as an instance variable and as a local variable in the method.
To avoid confusion and mistakes, DO NOT use the names of instance or static variables as local variable
names, except for method parameters.

public class Foo {
private int x = 0; //an instance variable
private int y = 0;
public Foo() {
}
public void myMethod() {
int x = 1; //a local variable
System.out.println(“x = “ + x); //reference to the local variable x
System.out.println(“y = ” + y);
}

}

• The Keyword this
The keyword this refers to the object itself. It can also be used inside a constructor to invoke another
constructor of the same class. The this keyword is the name of a reference that an object can use to refer
to itself. You can use the this keyword to reference the object’s instance members. For example, the
this reference is omitted for brevity in the following code. However, the this reference is needed to
reference a data field hidden by a method or constructor parameter, or to invoke an overloaded
constructor.

It is a good practice to use the data field as the parameter name in a setter method or a constructor to
make the code easy to read and to avoid creating unnecessary names. In this case, you need to use the
this keyword to reference the data field in the setter method. For example, the setRadius() method below
use the same variable names for the instance variable and the local variable defined as a parameter. It
would be wrong if the statement is written as radius = radius;

public void setRadius(double radius) {
this.radius = radius;
}

public double getArea() {
return radius * radius * Math.PI;
// the above statement is equivalent to
// return this.radius * this.radius * Math.PI;
}

instance variable

local variable

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 14

The this keyword can be used to invoke another constructor of the same class. For example, you can
rewrite the default constructor of the Circle class as follows. The default contractor invokes the
parameterized constructor to initialize the radius. Note that, Java requires that the this(arg-list) statement
appear first in the constructor before any other executable statements.

public Circle(double radius) {
this.radius = radius;
}

public Circle() {
this(1.0);
}

If a class has multiple constructors, it is better to implement them using this(arg-list) as much as
possible. In general, a constructor with no or fewer arguments can invoke a constructor with more
arguments using this(arg-list). This syntax often simplifies coding and makes the class easier to read and
to maintain.

• Wrapper Classes
A primitive-type value is not an object, but it can be wrapped in an object using a wrapper class in the
Java API. Owing to performance considerations, primitive data type values are not objects in Java.
Because of the overhead of processing objects, the language’s performance would be adversely affected
if primitive data type values were treated as objects. However, many Java methods require the use of
objects as arguments. Java offers a convenient way to incorporate, or wrap, a primitive data type value
into an object (e.g., wrapping an int into an Integer object, wrapping a double into a Double object, and
wrapping a char into a Character object). By using a wrapper class, you can process primitive data type
values as objects. Java provides Boolean, Character, Double, Float, Byte, Short, Integer, and Long
wrapper classes in the java.lang package for primitive data types. The Boolean class wraps a Boolean
value true or false. This section uses Integer and Double as examples to introduce the numeric wrapper
classes. Most wrapper class names for a primitive type are the same as the primitive data type name with
the first letter capitalized. The exceptions are Integer for int and Character for char. The instances of all
wrapper classes are immutable; this means that, once the objects are created, their internal values
cannot be changed. Numeric wrapper classes are very similar to each other. Each contains the methods
doubleValue(), floatValue(), intValue(), longValue(), shortValue(), and byteValue(). These methods
“convert” objects into primitive-type values. The key features of Integer and Double are shown below.

o java.lang.Double

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 15

o java.lang.Integer

Each numeric wrapper class has the constants MAX_VALUE and MIN_VALUE. MAX_VALUE
represents the maximum value of the corresponding primitive data type. For Byte, Short, Integer, and
Long, MIN_VALUE represents the minimum byte, short, int, and long values. Float and Double,
MIN_VALUE represents the minimum positive float and double values. The numeric wrapper classes
contain the compareTo method for comparing two numbers and returns 1, 0, or –1, if this number is
greater than, equal to, or less than the other number.

The numeric wrapper classes have a useful static method, valueOf(String s). This method creates a new
object initialized to the value represented by the specified string. Each numeric wrapper class has two

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 16

overloaded parsing methods to parse a numeric string into an appropriate numeric value based on 10
(decimal) or any specified radix (e.g., 2 for binary, 8 for octal, and 16 for hexadecimal).

A primitive-type value can be automatically converted to an object using a wrapper class, and vice versa,
depending on the context. Converting a primitive value to a wrapper object is called boxing. The reverse
conversion is called unboxing. Java allows primitive types and wrapper classes to be converted
automatically. The compiler will automatically box a primitive value that appears in a context requiring
an object and unbox an object that appears in a context requiring a primitive value. This is called
autoboxing and autounboxing.

There are BigInteger and BigDecimal classes can be used to represent integers or decimal numbers of
any size and precision. If you need to compute with very large integers or high-precision floating-point
values, you can use the BigInteger and BigDecimal classes in the java.math package. Both are
immutable. The largest integer of the long type is Long.MAX_VALUE (i.e., 9223372036854775807).
An instance of BigInteger can represent an integer of any size. You can use new BigInteger(String) and
new BigDecimal(String) to create an instance of BigInteger and BigDecimal, use the add, subtract,
multiply, divide, and remainder methods to perform arithmetic operations, and use the compareTo
method to compare two big numbers.

• String class
A String object is immutable; its contents cannot be changed once the string is created.
String newString = new String(stringLiteral);

The argument stringLiteral is a sequence of characters enclosed in double quotes. The following
statement creates a String object message for the string literal “Welcome to Java”:
String message = new String(“Welcome to Java”);

Java treats a string literal as a String object. Thus, the following statement is valid:
String message = “Welcome to Java”;

You can also create a string from an array of characters. For example, the following statements create
the string “Good Day”:
char[] charArray = {‘G’, ‘o’, ‘o’, ‘d’, ‘ ‘, ‘D’, ‘a’, ‘y’};
String message = new String(charArray);

A String variable holds a reference to a String object that stores a string value. Strictly speaking, the
terms String variable, String object, and string value are different, but most of the time the distinctions
between them can be ignored. For simplicity, the term string will often be used to refer to String variable,
String object, and string value. A String object is immutable; its contents cannot be changed. Does the
following code change the contents of the string?
String s = “Java”;
s = “HTML”;

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 17

The answer is NO. The first statement creates a String object with the content “Java” and assigns its
reference to s. The second statement creates a new String object with the content “HTML” and assigns
its reference to s. The first String object still exists after the assignment, but it can no longer be accessed,
because variable s now points to the new object, as shown below.

Because strings are immutable and are ubiquitous in programming, the JVM uses a unique instance for
string literals with the same character sequence in order to improve efficiency and save memory. Such
an instance is called an interned string. For example, the following statements:

s1 == s2 is false
s1 == s3 is true

In the preceding statements, s1 and s3 refer to the same interned string—”Welcome to Java”—so s1 ==
s3 is true. However, s1 == s2 is false, because s1 and s2 are two different string objects, even though
they have the same contents. Strings are not arrays, but a string can be converted into an array and vice
versa. To convert a string into an array of characters, use the toCharArray method. Another way of
converting a number into a string is to use the overloaded static valueOf method. This method can also
be used to convert a character or an array of characters into a string.

The String class contains the static format method to return a formatted string. This method is similar to
the printf method except that the format method returns a formatted string, whereas the printf method
displays a formatted string.

CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Lily Chang

Page 18

String s = String.format(“%7.2f%6d%-4s”, 45.556, 14, “AB”);
System.out.println(s);


console output: –45.56—-  14AB– 

The StringBuilder and StringBuffer classes are similar to the String class except that the String class is
immutable. In general, the StringBuilder and StringBuffer classes can be used wherever a string is
used. StringBuilder and StringBuffer are more flexible than String. You can add, insert, or append new
contents into StringBuilder and StringBuffer objects, whereas the value of a String object is fixed once
the string is created. The StringBuilder class is similar to StringBuffer except that the methods for
modifying the buffer in StringBuffer are synchronized, which means that only one task is allowed to
execute the methods. Use StringBuffer if the class might be accessed by multiple tasks concurrently,
because synchronization is needed in this case to prevent corruptions to StringBuffer. Using
StringBuilder is more efficient if it is accessed by just a single task, because no synchronization is
needed in this case. The constructors and methods in StringBuffer and StringBuilder are almost the
same. You can replace StringBuilder in all occurrences in this section by StringBuffer. The program
can compile and run without any other changes. For more information, visit
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/StringBuilder.html