/**
* Copyright (C) 2024 by Martin Robillard. See
* https://codesample.info/about.html
*/
package essentials;
/**
* There are two basic kinds of methods in Java: static methods and instance
* methods. This class shows how the two kinds can achieve the same functionality.
*/
class Point
{
int x;
private int y;
Point(int , int pY)
{
x = pX;
y = pY;
}
/*
* An instance method to move the current point.
*/
void move1(int deltaX, int deltaY)
{
.x += deltaX;
this.y += deltaY;
}
/*
* A static method to move the point argument.
*/
void move2(Point point, int deltaX, int deltaY)
{
deltaX;
point.y += deltaY;
}
/*
* An instance method that returns a new point at a different position
* from the current point.
*/
(int deltaX, int deltaY)
{
return new Point(this.x + deltaX, this.y + deltaY);
}
}
/**
* This class serves as the client code calling various methods.
*/
public class Methods
{
public static void main(String[] args)
{
System.out.println("Absolute value of -5 is " + (-5));
String hello = "Hello";
System.out.println("Length of Hello\" is " + );
Point point = new Point (3,4);
// Moving point with a static method.
Point.move2(, 2, 2);
// Moving point with an equivalent instance method
.move1(2, 2);
// Creating a new, moved point
Point point.copyAndMove(2, 2);
}
}
The fields in this class are private so that code in other classes must access them via methods.
The fields in this class are private so that code in other classes must access them via methods.
This example uses the simple naming convention to prefix parameter names with the letter p
to
avoid a conflict with the field names.
This example uses the simple naming convention to prefix parameter names with the letter p
to
avoid a conflict with the field names.
To include a quote character within a string, it is necessary to escape it by preceding it with a backslash character.
To include a quote character within a string, it is necessary to escape it by preceding it with a backslash character.
In this static method call, point
is an explicit argument, placed in the list of arguments between
parentheses.
In this static method call, point
is an explicit argument, placed in the list of arguments between
parentheses.
In this instance method call, point
is an implicit argument, placed before the
method call.
In this instance method call, point
is an implicit argument, placed before the
method call.
The copyAndMove
method returns a value (a new Point
instance). This instance
is then stored in the other
variable.
The copyAndMove
method returns a value (a new Point
instance). This instance
is then stored in the other
variable.
The declaration of a method includes, at a minimum, a return type
(or the keyword void
if there's nothing to return),
a name (move1
), a list of formal parameters, and a body comprising
the code between curly braces.
This method is an instance method because its signature is not prefixed with
the keyword static
. In addition to the formal parameters, an instance
method has an additional parameter called the implicit parameter, which
is the object upon which the method is called. This parameter is available
through the keyword this
in the body of the method.
The declaration of a method includes, at a minimum, a return type
(or the keyword void
if there's nothing to return),
a name (move1
), a list of formal parameters, and a body comprising
the code between curly braces.
This method is an instance method because its signature is not prefixed with
the keyword static
. In addition to the formal parameters, an instance
method has an additional parameter called the implicit parameter, which
is the object upon which the method is called. This parameter is available
through the keyword this
in the body of the method.
Although the keyword this
is optional, I use it here
to emphasize than an instance method operated on an implicit
parameter (the "current" object), available through the this
keyword.
Although the keyword this
is optional, I use it here
to emphasize than an instance method operated on an implicit
parameter (the "current" object), available through the this
keyword.
A static method is declared like an instance method, but with the keyword
static
placed before the return type. A static method is not associated
with any object, so all the data is needs to access must be provided
through explicit parameters.
In this example, the current object is no longer available through
the this
keyword, so we add it to the list of formal parameters.
A static method is declared like an instance method, but with the keyword
static
placed before the return type. A static method is not associated
with any object, so all the data is needs to access must be provided
through explicit parameters.
In this example, the current object is no longer available through
the this
keyword, so we add it to the list of formal parameters.
When placed before the return type of a method declaration, the static
keyword
specifies that the method is a static method.
When placed before the return type of a method declaration, the static
keyword
specifies that the method is a static method.
This method has a side effect on an explicit parameter. This is normally not a best practice because it can make the code harder to understand. In production code, the instance method would be a better choice.
This method has a side effect on an explicit parameter. This is normally not a best practice because it can make the code harder to understand. In production code, the instance method would be a better choice.
Because this method declaration includes a return type (as opposed to void
),
the body of the method must include at least one return statement.
Because this method declaration includes a return type (as opposed to void
),
the body of the method must include at least one return statement.
To avoid any ambiguity with move
methods that have a side effect on the
input, this method's name makes it clear that the method creates a new
object different from the implicit parameter.
To avoid any ambiguity with move
methods that have a side effect on the
input, this method's name makes it clear that the method creates a new
object different from the implicit parameter.
Math#abs
is an example of a static method from the Java Development Kit (JDK). Notice how there
is no object provided to this method. Math
is just the name of the
class in which the method is located.
Math
contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
int
value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.
Math#abs
is an example of a static method from the Java Development Kit (JDK). Notice how there
is no object provided to this method. Math
is just the name of the
class in which the method is located.
Math
contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
Unlike some of the numeric methods of class StrictMath
, all implementations of the equivalent functions of class Math
are not defined to return the bit-for-bit same results. This relaxation permits better-performing implementations where strict reproducibility is not required.
By default many of the Math
methods simply call the equivalent method in StrictMath
for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math
methods. Such higher-performance implementations still must conform to the specification for Math
.
The quality of implementation specifications concern two properties, accuracy of the returned result and monotonicity of the method. Accuracy of the floating-point Math
methods is measured in terms of ulps, units in the last place. For a given floating-point format, an ulp of a specific real number value is the distance between the two floating-point values bracketing that numerical value. When discussing the accuracy of a method as a whole rather than at a specific argument, the number of ulps cited is for the worst-case error at any argument. If a method always has an error less than 0.5 ulps, the method always returns the floating-point number nearest the exact result; such a method is correctly rounded. A correctly rounded method is generally the best a floating-point approximation can be; however, it is impractical for many floating-point methods to be correctly rounded. Instead, for the Math
class, a larger error bound of 1 or 2 ulps is allowed for certain methods. Informally, with a 1 ulp error bound, when the exact result is a representable number, the exact result should be returned as the computed result; otherwise, either of the two floating-point values which bracket the exact result may be returned. For exact results large in magnitude, one of the endpoints of the bracket may be infinite. Besides accuracy at individual arguments, maintaining proper relations between the method at different arguments is also important. Therefore, most methods with more than 0.5 ulp errors are required to be semi-monotonic: whenever the mathematical function is non-decreasing, so is the floating-point approximation, likewise, whenever the mathematical function is non-increasing, so is the floating-point approximation. Not all approximations that have 1 ulp accuracy will automatically meet the monotonicity requirements.
The platform uses signed two's complement integer arithmetic with int and long primitive types. The developer should choose the primitive type to ensure that arithmetic operations consistently produce correct results, which in some cases means the operations will not overflow the range of values of the computation. The best practice is to choose the primitive type and algorithm to avoid overflow. In cases where the size is int
or long
and overflow errors need to be detected, the methods whose names end with Exact
throw an ArithmeticException
when the results overflow.
sin
, cos
, tan
, asin
, acos
, atan
, exp
, expm1
, log
, log10
, log1p
, sinh
, cosh
, tanh
, hypot
, and pow
. (The sqrt
operation is a required part of IEEE 754 from a different section of the standard.) The special case behavior of the recommended operations generally follows the guidance of the IEEE 754 standard. However, the pow
method defines different behavior for some arguments, as noted in its specification. The IEEE 754 standard defines its operations to be correctly rounded, which is a more stringent quality of implementation condition than required for most of the methods in question that are also included in this class.
int
value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.
Note that if the argument is equal to the value of Integer.MIN_VALUE
, the most negative representable int
value, the result is that same value, which is negative. In contrast, the absExact(int)
method throws an ArithmeticException
for this value.
a
- the argument whose absolute value is to be determined
String#length
is an example of an instance method from the Java Development Kit (JDK).
Notice how we are calling it by using the dot operator on the object stored in the hello
variable. This is the implicit argument to the method. Inside the body of the method,
the object stored in variable hello
becomes the object available through the this
keyword.
String#length
is an example of an instance method from the Java Development Kit (JDK).
Notice how we are calling it by using the dot operator on the object stored in the hello
variable. This is the implicit argument to the method. Inside the body of the method,
the object stored in variable hello
becomes the object available through the this
keyword.
length
in interface CharSequence
System
class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System
class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
System
class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System
class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
Console.charset()
if the Console
exists, stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println
methods in class PrintStream
.
print(String)
and then println()
.
print(String)
and then println()
.
x
- The String
to be printed.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
String
class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.
A String
represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character
class for more information). Index values refer to char
code units, so a supplementary character uses two positions in a String
.
The String
class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator
class provides methods for finer-grain, locale-sensitive String comparison.
javac
compiler may implement the operator with StringBuffer
, StringBuilder
, or java.lang.invoke.StringConcatFactory
depending on the JDK version. The implementation of string conversion is typically through the method toString
, defined by Object
and inherited by all classes in Java.