Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
68 views

Notes On Java Programming Liang

This document provides an overview of the first 10 chapters of an introduction to Java programming textbook. It summarizes key concepts from each chapter, including Java bytecode, the Java Development Kit, data types, operators, selection statements, loops, methods, arrays, and classes. The document gives code examples and explanations of fundamental Java concepts to set the foundation for an introductory programming course.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Notes On Java Programming Liang

This document provides an overview of the first 10 chapters of an introduction to Java programming textbook. It summarizes key concepts from each chapter, including Java bytecode, the Java Development Kit, data types, operators, selection statements, loops, methods, arrays, and classes. The document gives code examples and explanations of fundamental Java concepts to set the foundation for an introductory programming course.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Page 1 of 25

Notes on – Introduction to Java Programming:


Comprehensive Edition, 11th Edition -- by Y. Daniel Liang

Chapter 1: Introduction to Computers, Programs, and Java ........................................................................ 3


Java's Magic: The Bytecode ...................................................................................................................... 3
The Java Development Kit......................................................................................................................... 3
Comments in a Java Source File ................................................................................................................ 3
Blocks of Code ........................................................................................................................................... 3
Chapter 2: Elementary Programming ........................................................................................................... 4
Printing Outputs to Console...................................................................................................................... 4
Formatted Output using printf() ........................................................................................................... 4
Data Types................................................................................................................................................. 4
A Closer Look at Variables......................................................................................................................... 6
Operators .................................................................................................................................................. 6
Relational and Logical Operators .............................................................................................................. 8
Shorthand Assignments ............................................................................................................................ 9
Type Conversion in Assignments .............................................................................................................. 9
Expressions................................................................................................................................................ 9
Chapter 3: Selections .................................................................................................................................. 11
The if Statement ..................................................................................................................................... 11
The Traditional Switch Statement........................................................................................................... 11
Conditional Statements .......................................................................................................................... 12
Chapter 4: Mathematical Functions, Characters, and Strings .................................................................... 13
4.2 Common Mathematical Functions.................................................................................................... 13
4.4 The String Type ................................................................................................................................. 14
Chapter 5 Loops .......................................................................................................................................... 16
The for Loop ............................................................................................................................................ 16
Some Variations on the for Loop ............................................................................................................ 16
The while Loop ........................................................................................................................................ 16
The do-while Loop .................................................................................................................................. 16
Use break to Exit a Loop ......................................................................................................................... 17
Use continue ........................................................................................................................................... 17
Chapter 6: Methods .................................................................................................................................... 18
Chapter 7: Single-Dimensional Arrays ........................................................................................................ 19
Page 2 of 25

7.2 Array Basics ....................................................................................................................................... 19


Declaring an array variable ................................................................................................................. 19
Creating arrays .................................................................................................................................... 19
Initializing arrays ................................................................................................................................. 19
Array Size ............................................................................................................................................ 19
Accessing Elements of an Array in a for loop or “foreach” loop......................................................... 19
7.5 Copying Arrays .................................................................................................................................. 20
7.6 Passing Arrays to Methods ............................................................................................................... 20
7.7 Returning an Array from a Method .................................................................................................. 21
7.12 The Arrays Class ......................................................................................................................... 21
Array sorting........................................................................................................................................ 21
Array equals() method ........................................................................................................................ 21
Search for an element in an Array ...................................................................................................... 21
7.13 Command-Line Arguments ............................................................................................................. 22
Chapter 8: Multidimensional Arrays ........................................................................................................... 23
8.2 Two-Dimensional Array Basics .......................................................................................................... 23
8.4 Passing Two-Dimensional Arrays to Methods .................................................................................. 23
Chapter 9: Objects and Classes ................................................................................................................... 24
9.2 Defining Classes for Objects.............................................................................................................. 24
9.4 Constructing Objects Using Constructors ......................................................................................... 24
9.5 Accessing Objects via Reference Variables ....................................................................................... 25
Page 3 of 25

Chapter 1: Introduction to Computers, Programs, and Java


Java's Magic: The Bytecode
• The key that allows Java to be both secure and portable is that the output of Java compiler is not
executable code; it is bytecode.
• Bytecode is a highly optimized set of instructions that is designed to be executed on the Java
Virtual Machine (JVM), which is part of the Java Runtime Environment (JRE).
• Advantages
o Portability -- a unique JRE needs to be implemented on each platform. But all Java code
will run on any JRE.
o Security
• Since a Java program is executed by the JVM, the JVM controls program
execution.
• The JVM creates a sandbox -- a restricted execution environment.

The Java Development Kit


• Download Java from Oracle or from open source
o Oracle: https://www.oracle.com/java/technologies/downloads/
o Open source: https://jdk.java.net/
• The JDK has two primary programs:
o javac -- The Java compiler
o java -- The standard Java interpreter / application launcher
• In Windows, a Java program can be compiled and executed from the command prompt.
o java -version gives the version of Java installed
o javac -version gives the version of javac installed
• Entering and compiling a program
o The Java compiler requires that the source file have a .java extension.
o Each source file contains one or more class definitions. Filename = name of public class.
o To compile the source file, type
javac Example.java
o Each individual class within the source file gets compiled into a separate file named after the
class, with a .class extension.
o Then, to run the program, pass the name of the main class to the Java interpreter.
java Example

Comments in a Java Source File


o Multiline comments -- begins with a "/*" and ends with a "*/".
o Single-line comments -- "//" -- anything on the line after the "//" is ignored.

Blocks of Code
A code block is a grouping of two or more statements, enclosed between opening and closing curly
brackets. A code block is a logical unit that can be used anywhere a single statement can.
Page 4 of 25

Chapter 2: Elementary Programming


Printing Outputs to Console
Use any one of three methods to print text output to the screen (console):
• System.out.println(): Prints out a string and appends a newline character.
• System.out.print(): Prints out a string without appending a newline.
• System.out.printf(): Prints out a string created by passing arguments to a “format.”
For the println() and print() methods, you can pass a complete string literal, for example
System.out.println(“Hello World”); // Includes a newline
System.out.print(“Hello World”); // No newline
Or, you can concatentate string literals, numeric literals, and variable values using a + sign:
System.out.println(“Here is an integer: “ + 6 + “ and here is a
floating-point value: “ + 3.14159265);

Formatted Output using printf()


The general form of a printf() statement:
System.out.printf(“Format string”, arg-1, arg-2, …);
Table 1: Placeholders in printf Format

Specifier Output Example


%d A decimal integer 350
%s A string “Hello, World”
%f A floating-point number 3.14159265
%c A single character ‘d’
%b A Boolean value true or false
%e A floating-point in scientific notation 1.65e4

Example:
int count = 15;
double x = -5.96;
String hello = “Hello World”;
System.out.printf(“count = %d, x = %f, the string is %s\n”,
count, x, hello);

Data Types
• In Java, all variables have a type.
• Two categories of built-in data types
o Object-oriented types -- defined by classes
Page 5 of 25

o Non-object-oriented types -- primitive data types


• Java's built-in primitive data types

Type Meaning Bits Range


boolean Represents true /
false values
byte 8-bit integer 8 -27 to 27-1: -128 to +127
char Character
double Double-precision 64
floating point
float Single-precision 32
floating point
int Integer 32 -231 to 231-1 : -2,147,483,648 to +2,147,483,647
long Long integer 64 -263 to 263-1 : -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
short Short integer 16 -215 to 215-1 : -32,768 to +32,767

Character Type
• Assign a value to a character type variable as follows
char xch;
xch = 'X'; // use single-quotes to assign a specific character
xch = 75; // Assign the character at ASCII code 75 to xch

Boolean Type
• The boolean type represents true / false values.
• Java defines the value using the keywords true and false.
• The outcome of a relational operator is a boolean value. E.g.

System.out.println("10 > 9 is " + (10 > 9));

Character Escape Sequences

Escape Sequence Description

\' Single quote

\" Double quote

\\ Backslash

\r Carriage return
Page 6 of 25

\n New line

\f Form feed

\t Tab

\b Backspace

\ddd Octal constant (where ddd is an Octal literal)

\uxxxx Hexadecimal constant

\s Space

\endofline Continue line

• String literals
o A string is a set of characters enclosed by double quotes. E.g.

"this is a test"
o In addition to normal characters, a string literal can include any of the escape sequences listed
above.

A Closer Look at Variables


• An initial value can be assigned to a variable at the time it is declared. E.g.

int a = 9;
double x, y = -4.5, z = 0.25, w; // y and z are assigned initial
values

• It is possible to define a variable and initialize it dynamically, using any element valid at the time
of initialization, including literals, other variables, and even calls to methods. E.g.

double volume = 3.14159*pow(radius,2)*height;

Operators
• A operator is a symbol that tells the compiler to perform a specific mathematical or logical
manipulation.

Arithmetic Operators

Operator Meaning

+ Addition (and unary plus)


Page 7 of 25

- Subtraction (and unary minus)

* Multiplication

/ Division

% Modulus

++ Increment

-- Decrement

• When the division (/) operator is applied to two integer operands, the remainder will be
truncated.
• The modulus operator (%) applied to two integers will return the remainder.
• Thus, for integers a and b

a = (a/b)*b + (a%b)

• Increment and Decrement operators


o The increment operator (++) adds 1 to the operand.
o The decrement operator (--) subtracts 1 from the operand.
o Either operator and precede (prefix) or follow (postfix) the operand.
• Note that on a single line, the pre-increment/decrement and post-
increment/decrement are identical.
E.g. x++; and ++x; are identical
• However, in an expression in which one or more operands are incremented or decremented,
▪ The pre-incremented/decremented operands are incremented / decremented before
the right-hand side of the expression is evaluated.
▪ The post-incremented/decremented operands are incremented / decremented after
the right-hand side of the expression is evaluated.
Page 8 of 25

Relational and Logical Operators


• Relational operators

Operator Meaning

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

• Logical operators

Operator Meaning

& AND

| OR

^ XOR

&& Short-circuit AND

|| Short-circuit OR

! NOT
Page 9 of 25

Shorthand Assignments
• The shorthand assignment operators are really compound statements

Operator Example of Use

+= x += 5 is equivalent to x = x + 5

-= x -= y is equivalent to x = x - y

*= x *= -6 is equivalent to x = x * (-6)

/= x /= 2 is equivalent to x = x/2

%= x % 3 is equivalent to x = x % 3

&= A &= B is equivalent to A = A & B

|= A |= B is equivalent to A = A | B

^= A ^= B is equivalent to A = A ^ B

Type Conversion in Assignments


• When compatible types are mixed in an assignment, the value of the right-hand side is
automatically converted to the type of the left-hand side.
o This only works if the types are compatible.
• For cases where an automatic type conversion will not occur, you have to use a cast to do the
conversion.
• A cast is an instruction to the compiler to convert from one type to another.

(target-type) expression

o Examples
double x, y;
int i;

i = (double) (x / y); // Parentheses were needed around the


whole expression (x/y) to force conversion of the entire
thing.

i = (double) x / y; // Will produce an error, since the cast


is only applied to x.

• When a cast involves a narrowing operation (e.g. int cast to a byte), information may be lost.

Expressions
Type Conversion in Expressions
Page 10 of 25

o Within an expression, it is possible to combine two or more data types, as long as they are
compatible with each other.
o When mixing two or more data types in an expression, all are converted to the same type, using
Java's type promotion rules.
• char, byte, short are all converted to int.
• If one of the items is long, then all are converted to long.
• If one is float, then all are converted to float.
• If one is double, then all are converted to double.

All objects can be compared for equality and inequality.


However, only objects that support an ordering relationship can be compared using the other relational
operators.

The outcome of the relational and logical operators is a boolean value.

The standard logical operators (&, |, and ^) evaluate both operands, even if the first operand
determines the outcome of the operation.

The short-circuit logical operators will skip evaluation of the second operand, if the first operand
determines the outcome.

In some cases, the shorthand assignment may be more efficient for the JVM to execute.
Page 11 of 25

Chapter 3: Selections
The if Statement
• The complete form of the if statement is

if (condition)
{
Statements …
}
else
{
More statements …
}

• The statement following the condition can be a single statement, in which case you do not need
to include brackets.
• An if-else-if ladder can be created as follows:

if (condition)
{
Statements …
}
else if (condition 2)
{
Statements 2 …
}
else if (condition 3)
{
Statements 3 …
}

else
{
More statements …
}

The Traditional Switch Statement


• The switch statement provides for a multiway branch.
• More efficient than a series of nested or laddered if statements.
• The value of an expression is successively tested against a list of constants.
• General form

switch (expression) {
case constant1:
statement sequence …
break;
Page 12 of 25

case constant 2:
statement sequence …
break;
..
default:
statement sequence …
}

• Expression can be of type byte, short, int, char, or String


• The default statement sequence is executed if the expression does not match the constant in
any of the previous cases.
• The break statement at the end of each case causes the remainder of the code to be ignored.
Without a break, when the expression matches one of the case constant values, that statement
sequence and all of the following statement sequences are executed, unless another break is
encountered.
• Nested Switch statements are supported.

Conditional Statements
General format for conditional assignment statements
variable-name = (expression) ? value_1 : value_2;
The expression must evaluate to either a boolean value.
• Assign value_1 to variable-name if the expression is true.
• Assign value_2 to variable-name if the expression is false.
Example
y = (x < 0) ? -1 : 1;
In this example, if x < 0, y is assigned -1. Otherwise, it is assigned 1.
Page 13 of 25

Chapter 4: Mathematical Functions, Characters, and Strings


4.2 Common Mathematical Functions
All of the methods in this section are part of the java.lang.Math package

Method Description
Trigonometric Methods
sin(radians)
cos(radians)
tan(radians)
asin(radians)
acos(radians)
atan(radians)
toRadians(degree)
toDegree(radians)
PI Static variable (constant)
Exponent Methods
exp(x) e raised to the power x
log(x) Natural logarithm
log10(x) Base-10 logarithm
pow(a, b) a^b
sqrt(x)
Rounding Methods
ceil(x) Returns double; x rounded up
floor(x) Returns double; x rounded down
rint(x) Returns double; rounds up or down
to nearest integer
round(x) Returns int if x is float, and long if x is
double. Value = Math.floor(x +
0.5)
min, mx, and abs Methods
min(a,b) Works with int, long, float, double
max(a,b)
abs(a,b)
Page 14 of 25

random Method
random() Returns a random double between ≥
0 and < 1.

4.4 The String Type


A string is an object of the built-in String class.
Two ways to create a string:
• Shorthand
String refName = “String primitive”;
• Call to String class
String refName = new String(“String primitive”);
In both cases, the variable refName is a reference variable that points to the string object.
The following table contains a list of methods in the String class.

Method Description
Simple Methods
int length() Returns the number of characters in the string
char charAt(index) Returns the character at the specified index (first index
is 0) of the string.
String concat(s1) Returns a string that concatenates string s1 to the
current string.
String toUpperCase() Returns a string with all characters of the original
string converted to upper case.
String toLowerCase() Returns a string with all characters of the original
string converted to lower case.
String trim() Returns a string that eliminates whitespace characters
at both ends of the string (‘ ‘, \t, \f, \r, or \n).
Comparing Strings
boolean equals(s1) Compares the contents of the current string to the
contents of s1
boolean
equalsIgnoreCase(s1)
Page 15 of 25

int compareTo(s1) Compares the current string to s1 lexicographically


(i.e. in order of how they would appear in a dictionary)
◼ less than 0: current string < s1
◼ equal to 0: current string = s1
◼ greater than 0: current > s1
The absolute value returned depends on the first index
at which the string contents are different.
int
compareToIgnoreCase(s1)
boolean
startsWith(prefix)
boolean endsWith(prefix)
boolean contains(s1) Returns true if s1 is a substring of this string.
Substring methods
String Returns a string that either
substring(beginIndex)
◼ Begins at index beginIndex and goes to the
String end of this string.
substring(beginIndex,
endIndex) ◼ Begins at index beginIndex and goes to
endIndex-1 of this string. (The character at
endIndex is not part of the substring).

Examples
String message = “Welcome to Java”;
int I = message.length(); // I = 15
char c = message.charAt(0); // c = ‘W’
String s3 = s1.concat(s2);
alternatively, Java provides the following shorthand for concatenating strings
String s3 = s1 + s2;
String s3 = message.toUpperCase(); // s3 = “WELCOME TO JAVA”
Note that to compare the contents of two strings, you should use the equals() method, rather than
the == operator.
s2 == s1; // True if and only if s2 and s1 point to the same
object.
s1.equals(s2); // True if and only if s1 and s2 point to strings
containing the same content.
Page 16 of 25

Chapter 5 Loops
The for Loop
• The for loop will work with a single statement, or a block of statements, enclosed in brackets.
• The general form of a for loop is as follows:

for (initialization; condition; iteration)


{
statement sequence …
}

• The initialization is usually an assignment statement that sets the initial value of the loop
control variable.
• The condition is a boolean expression that determines whether or not the loop will repeat.
• The iteration expression defines the increment of the loop control variable each time the loop is
repeated.
• The loop will continue to execute as long as the condition is true.
• The conditional expression is always tested at the top of the loop; the statement sequence
inside the loop will not be executed at all of the condition is not true to begin with.

Some Variations on the for Loop


• Multiple loop control variables may be used. E.g.
for (i = 0, j = 0; i < j; i++, j--) {
}
• It is possible for any or all of the initialization, condition, and iteration portions of the for loop to
be missing.
• If a loop control variable is declared inside the for loop, then its value will not be retained after
the loop exits.

The while Loop


• The general form of a while loop is

while (condition) {
statement sequence …
}

• The condition may be any valid boolean expression.


• The condition is tested at the top of the loop, and the loop continues while the condition is true.

The do-while Loop


• The general form of a do-while loop is

do {
statement sequence …
Page 17 of 25

} while (condition);

• The condition is not checked until the end of the loop, so the do-while loop is guaranteed to
execute at least once.

Use break to Exit a Loop


• Use break to force an intermediate exit from a loop, bypassing any remaining code in the loop's
body, and also bypassing the conditional test.
• The break is also used to skip the remaining statements following a selected case in a switch
statement.
o The break that terminates a switch statement only affects the switch statement, and not
any enclosing loops.
• When used with nested loops, the break will only break out of the innermost loop.

Use continue
• Use control to force an early iteration of a loop, bypassing the remaining statements in the body
of the loop.
• For while and do-while loops, continue causes the program flow to go straight to the conditional
test.
• For a for loop, continue triggers the iteration and then the conditional test.

Ex. Print the even numbers between 0 and 100

int i;
for (i = 0; i <= 100; i++) {
if (i % 2 != 0) continue;
System.out.println(i);
}
Page 18 of 25

Chapter 6: Methods
Methods are subroutines that manipulate the data defined by the class, and in many cases provide
access to that data.
Methods must be members of a class.
• General form of a method
{Optional modifiers} return-type methodName(parameter-list) {
// body of method
return val; // only if return-type is not void
}
• Use the return statement to exit a method and return a specific value. The value must be of
the type return-type.
• If the method has no value to return, then its return type must be void.
It is possible to pass one or more values, called parameters, to a method when it is called.
• The parameter values can be used within the method to calculate the return value or to modify
the instance variables of the class of which the method is a member.
The {Optional modifiers} in the general form include public and static:
• A public method is one that is visible outside of the class and package in which it was defined.
• A static method is one that can be called without creating an object of the class in which it is
defined.

Examples
public static int sum(int i1, int i2) {
int result = 0;
for (int i = i1; i <= i2; i++) result += i;
return result;
}

boolean isFactor(int a, int b) {


if ((b%a) == 0){
return true;
}
else {
return false;
}
}
Page 19 of 25

Chapter 7: Single-Dimensional Arrays


7.2 Array Basics

Declaring an array variable


elementType[] arrayRefVar; // Dimensions not specified

Creating arrays
o Separate statement following array variable declaration:
arrayRefVar = new elementType[arraySize];
o Alternatively, combine the declaration and assignment into one statement:
elementType[] arrayRefVar = new elementType[arraySize];
or
elementType arrayRefVar[] = new elementType[arraySize];

Examples of array variable declaration and array creation:


double[] myList;
myList = new double[10];

double[] myList = new double[10];

Initializing arrays
o First way: assign values after array has been created. For example
myList[0] = 5.6;
myList[1] = 4.5;

myList[9] = -11.6;
o Alternatively, we can use the array initializer shorthand
double[] myList = {1.9, 2.9, 3.4, -3.5};

Array Size
Getting array size from the length variable. Returning to the previous example
myList.length // myList.length has the value 10

Accessing Elements of an Array in a for loop or “foreach” loop


For loops are widely used to access / modify elements of an array.
For example, we can loop through the array index as follows:
for(int i = 0; i < myList.length; i++) {
myList[i] = 2*myList[i]; // multiplies each element by 2
}
Page 20 of 25

Note that Java provides another type of for loop – called a “foreach” loop – which traverses the
elements in the array without an explicit reference to the index of each element.
For example,
for(double elem : myList) {
System.out.println(elem); // Prints out each element
}

7.5 Copying Arrays


We can copy one array to another by using a loop, for example
double[] myList2 = new double[myList.length];
for(int i = 0; i < myList.length; i++) {
myList2[i] = myList[i];
}
A more concise way to do this is by using the System.arraycopy() method.
The general syntax for this method is
System.arraycopy(srcArray, srcPosition, targetArray,
targetPosition, copyLength);
Returning to our example, the following command will copy all elements of myList to myList2.
System.arraycopy(myList, 0, myList2, 0, myList.length);

7.6 Passing Arrays to Methods


Key Idea: When passing an array to a method, the reference of the array is passed to the method.
Example
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Page 21 of 25

7.7 Returning an Array from a Method


To return an array from a method, simply define the array within the method and return it. Note that
the return type of the method should be an array.
For example,
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}

7.12 The Arrays Class


The java.util.Arrays class contains useful methods for common array operations such as sorting
and searching.

Array sorting
Arrays.sort(arrayName); // sorts the entire array
/* To sort only a subset of indices, use the following */
Arrays.sort(arrayName, fromIndex, toIndex);

Array equals() method


Use the Arrays.equals() method to determine whether the contents of two arrays are equal:
int[] list1 = {2, 4, 7, 10}; int[] list2 = {2, 4, 7, 10}; int[]
list3 = {4, 2, 7, 10};
System.out.println(java.util.Arrays.equals(list1, list2)); //
true
System.out.println(java.util.Arrays.equals(list2, list3)); //
false

Search for an element in an Array


Use the Arrays.binarySearch() method. Note that the array must be sorted in ascending order
to use this method.
Arrays.binarySearch(arrayName, keyValue);
This method returns the index of the first element of the array which contains keyValue. It will return a
negative value if none of the elements of the array equals keyValue.
Page 22 of 25

7.13 Command-Line Arguments


The main method can receive string arguments from the command line.
If command-line arguments are present, the args[] array is a string array that contains the
arguments. Note that args[0] contains the program name itself.
For example, if the following program is run at the command line
java TestProg arg1 arg2 arg3
then, in the main() method
args[0] = “TestProg”
args[1] = “arg1”
args[2] = “arg2”
args[3] = “arg3”
Page 23 of 25

Chapter 8: Multidimensional Arrays


8.2 Two-Dimensional Array Basics
• Delcaring two-dimensional array
elementType[][] arrayRefVar;
arrayRefVar = new elementType[numRows][numCols];
or
elementType[][] arrayRefVar = new elementType[numRows][numCols];

• Access or assign a specific element


Example
matrix[2][1] = 7;
• Example of using an array initializer

• Sizes of row and column dimensions


arrayRefVar.length gives the number of rows (outer dimension) of the array, while
arrayRefVar[0].length gives the number of columns in row 1.
• Ragged arrays – rows in a two-dimensional array can have different lengths.

8.4 Passing Two-Dimensional Arrays to Methods


Just as for a one-dimensional array, a two-dimensional array is passed to a method by reference.
Example of method that accepts a two-dimensional array as input:
public static int sum(int[][] m) {
// Method definition
}
Example of calling this method:
int a = sum(m);
Example of a method that returns a two-dimensional array:
public static int[][] getArray() {
// Method definition. Define elements of array m[i][j]
return m;
}
Page 24 of 25

Chapter 9: Objects and Classes


An object represents an entity in the real world that can be distinctly identified.
The state of an object (also known as its properties or attributes) is represented by data fields with their
current values.
The behavior of an object (also known as actions) is defined by its methods.
Objects of the same type are defined using a class, which is a template that defines what the object’s
data fields and methods will be.

9.2 Defining Classes for Objects


The illustration of class templates and objects can be standardized using Unified Modeling Language
(UML) notation. UML class diagrams

• In a UML diagram, data fields and methods are prepended by


o a plus (+) sign to indicate that they are public
o a minus (-) sign to indicate that they are private

9.4 Constructing Objects Using Constructors


A constructor is a method of a class that initializes an object of the class when it is created.
• It has the same name as the class.
• Constructors have no explicit return type.
A class may be defined without constructors. In this case, a no-arg constructor with an empty body is
implicitly defined in the class. This constructor, called a default constructor, is provided automatically
only if no constructors are explicitly defined in the class.
Example of a simple constructor with no parameters
class MyClass {
int x;

MyClass() { // This is the constructor for MyClass


Page 25 of 25

x = 10;
}
}
It is typically desirable to pass parameters to the constructor to be used when initializing an object. For
example,
class MyClass {
int x;

MyClass(int i) { // This is a constructor for MyClass


// with a parameter passed to it.
x = i;
}
}
It is possible to have multiple constructors for a class, including one without parameters, and ones with
one or more parameters.

9.5 Accessing Objects via Reference Variables


• Declare and create a new object in a single command:
ClassName objectRefVar = new ClassName(optionalParams);
• Address public variables and methods of an object using the dot (.) operator:
objectRefVar.varName
or
objectRefVar.methodName(params)

You might also like