Java code samples with explanations, tips, and best practices that can be accessed on-demand via the code. Carefully curated and prepared by experts.
List<> numbers = List.of();
"A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values" [Java Tutorial].
"A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values" [Java Tutorial].
"A generic type is a generic class or interface that is parameterized over types." [Java Tutorial].
"A generic type is a generic class or interface that is parameterized over types." [Java Tutorial].
Here the numbers 1, 2, and 3 are literal
values
of the primitive type int. Because the method of
expects values inferred to be
of type Integer, the int values will be automatically
converted to values
of type Integer, a process called autoboxing.
Click on the anchor to pin this dialog.
Here the numbers 1, 2, and 3 are literal
values
of the primitive type int. Because the method of
expects values inferred to be
of type Integer, the int values will be automatically
converted to values
of type Integer, a process called autoboxing.
Roll over references to API elements to retrieve a summary of their reference documentation. Click on the element to see the full documentation.
Roll over references to API elements to retrieve a summary of their reference documentation. Click on the element to see the full documentation.
The type parameter of the
List is invoked
with Integer as a parameter. Integer is a wrapper type
for the
int. Wrapper types must be used
with generics because primitive types cannot be used as type
arguments.
Click on the anchor to pin this dialog.
The Integer class wraps a value of the primitive type
int in an object. An object of type Integer
contains a single field whose type is int.
The type parameter of the
List is invoked
with Integer as a parameter. Integer is a wrapper type
for the
int. Wrapper types must be used
with generics because primitive types cannot be used as type
arguments.
Click on the anchor to pin this dialog.
Integer class wraps a value of the
primitive type
int in an object. An object of type Integer
contains a single field whose type is int.
In addition, this class provides several methods for converting
an int to a String and a
String to an
int, as well as other constants and methods useful when
dealing with an int.
This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
Implementation note: The implementations of the "bit twiddling"
methods (such as highestOneBit and
numberOfTrailingZeros) are
based on material from Henry S. Warren, Jr.'s Hacker's
Delight, (Addison Wesley, 2002).
Unlike sets, lists typically allow duplicate elements. More formally,
lists typically allow pairs of elements e1 and e2
such that e1.equals(e2), and they typically allow multiple
null elements if they allow null elements at all. It is not inconceivable
that someone might wish to implement a list that prohibits duplicates, by
throwing runtime exceptions when the user attempts to insert them, but we
expect this usage to be rare.
The List interface places additional stipulations, beyond those
specified in the Collection interface, on the contracts of the
iterator, add, remove,
equals, and
hashCode methods. Declarations for other inherited methods are
also included here for convenience.
The List interface provides four methods for positional
(indexed)
access to list elements. Lists (like Java arrays) are zero based. Note
that these operations may execute in time proportional to the index value
for some implementations (the LinkedList class, for
example). Thus, iterating over the elements in a list is typically
preferable to indexing through it if the caller does not know the
implementation.
The List interface provides a special iterator, called a
ListIterator, that allows element insertion and replacement,
and
bidirectional access in addition to the normal operations that the
Iterator interface provides. A method is provided to obtain a
list iterator that starts at a specified position in the list.
The List interface provides two methods to search for a
specified
object. From a performance standpoint, these methods should be used with
caution. In many implementations they will perform costly linear
searches.
The List interface provides two methods to efficiently insert
and
remove multiple elements at an arbitrary point in the list.
Note: While it is permissible for lists to contain themselves as elements,
extreme caution is advised: the equals and
hashCode
methods are no longer well defined on such a list.
Some list implementations have restrictions on the elements that
they may contain. For example, some implementations prohibit null elements,
and some have restrictions on the types of their elements. Attempting to
add an ineligible element throws an unchecked exception, typically
NullPointerException or ClassCastException.
Attempting
to query the presence of an ineligible element may throw an exception,
or it may simply return false; some implementations will exhibit the former
behavior and some will exhibit the latter. More generally, attempting an
operation on an ineligible element whose completion would not result in
the insertion of an ineligible element into the list may throw an
exception or it may succeed, at the option of the implementation.
Such exceptions are marked as "optional" in the specification for this
interface.
The List.of and
List.copyOf static factory methods
provide a convenient way to create unmodifiable lists. The List
instances created by these methods have the following characteristics:
UnsupportedOperationException to be
thrown.
However, if the contained elements are themselves mutable,
this may cause the List's contents to appear to change.
null elements. Attempts to create them with
null elements result in NullPointerException.
subList views implement the
RandomAccess interface.
This interface is a member of the Java Collections Framework.
E - the List's element typee1 - the first elemente2 - the second elemente3 - the third elementList containing the specified elementsNullPointerException
- if an element is null
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.
The SuppressWarnings annotation interface is applicable
in all declaration contexts, so an @SuppressWarnings
annotation can be used on any element. As a matter of style,
programmers should always use this annotation on the most deeply
nested element where it is effective. For example, if you want to
suppress a warning in a particular method, you should annotate that
method rather than its class.
The set of warnings suppressed in a given element is a union of
the warnings suppressed in all containing elements. For example,
if you annotate a class to suppress one warning and annotate a
method in the class to suppress another, both warnings will be
suppressed in the method. However, note that if a warning is
suppressed in a module-info file, the suppression applies
to elements within the file and not to types contained
within the module. Likewise, if a warning is suppressed in a
package-info file, the suppression applies to elements
within the file and not to types contained within the
package.
Java compilers must recognize all the kinds of warnings defined in the Java Language Specification (JLS section 9.6.4.5) which include:
"unchecked".
"deprecation".
"removal".
"preview".
javac
reference implementation recognizes compilation-related warning
names documented in its --help-lint output.The code samples from the book Introduction to Software Design with Java, 3rd edition.
We are planning to grow our current series and to add additional series.