Java Notes
Java Notes
File Names
They file name must be the same as the sole top-level public class within a file with a .java
extension:
publicClassName.java
There may be many top-level classes, as long as only one is public. THIS IS A BAD IDEA TO DO
THOUGH BECAUSE IT IS CONFUSING AND CAN LEAD TO ALL SORTS OF COMPILE ERRORS. It is
better to to use private nested classes or inner classes to accomplish the same thing.
Top-Level Class
Classes not defined within any other block or class
They can only be public or package private
Package
package package.name; must be the first line in the source code. Files in the same package
should have the same package statement. In order to make compilation easy for java, store
source files in directories whose names mirror the package name:
[src, source, etc.]/package/name/myClass.java
and put compiled files in directories that do the same
[bin, out, target, etc]/package/name/myClass.class
$CLASS_PATH is the environmental variable java will use to determine which sub
directory of the current directory to look for to place the compiled class files. If it is not set
it places them where??????????????????????????????????????????
Import
import package.name.* imports all the types in the package
import package.name.Type imports just that type
import static package.name.Type.* allows you to use static methods (i.e. functions) and static
fields (i.e. constants) contained in a type without using the Type.staticMember dot notation. For
example
import static java.lang.Math
allows you to use
cos(PI)
instead of
Math.cos(Math.PI)
Other Modifiers
abstract
method has no body, just a semicolon. It is meant to be implemented in a
subclass
class cannot be instantiated. Is the only kind that can contain abstract methods
final
variables cannot be reassigned a different value
fields cannot be reassigned a different value
method cannot be overridden by a subclass
class cannot be extended
static
variables
method cant access non-static fields
Class Members
consist of fields, methods, and nested classes
Outer class
Are top-level classes so can only be public or package private
Nested class
A class defined within another class. The two types are Static Nested Classes and Inner Classes
Can be private, public, protected, or package private
Inner Class
Use: They are used to logically group related classes whose fields are dependent on each other
Static nested classes DON'T HAVE ACCESS to the members (fields and methods) of the enclosing
class.
They interact with their outer class and other classes just like any other top-level class.
They are accessed using the enclosing class name:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass()
Local classes
local classes are classes defined in a block (a group of zero or more statements betweeen braces).
They can be defined in methods, if clause, for loops etc.
They have access to the members of its enclosing class
They have access to final and effectively final local variables and capture (i.e. like a closure) their
values.
They cannot have any static members except for
constant variables variables type String or a primitive type that is final and initialized
with a compile-time constant expression
Local interfaces are not allowed
example local class:
Anonymous Classes
Are nameless local classes that must implement an interface or extend a class that are
declared and instantiated at the same time
This means they can't declare there own constructor any must use their default construct
(Any fields they have must be initialized with the values you want in the class body).
Even though they must implement an interface or extend a class, they can define extra
methods (but they can only be called inside the class).
functional interface which are interfaces with only one abstract method.
There based on the parameter of the method they are passed to, or the type of the parameter
they are assigned to.
java.util.function defines standard functional interfaces which you should use when you want a
method to accept lambdas or create a variable storing a lambda. For example using the Predicate
interface
Static Block?????????????
Static blocks
Initializer Blocks????????????
Varargs
(Type... parameterName)
allows an arbitray number of input parameters of the SAME type to a method or constructor.
IT STORES THE ARGUMENTS IN AN ARRAY
Abstract Class
public abstract class MyClass {}
a class that cannot be instantiated
They can contain
abstract methods
abstract void draw();
or regular methods
void draw() {}
fields
int max = 100;
int count;
Interface
A special abstract class that allows classes to implement multiple of them do to them only
containing static fields
all methods with a semicolon instead of a body are abstract
all fields are public static final
Implements
public class RectanglePuls implements Relatable {}
Inheritance
class Subclass extends SuperClass {}
subclasses inherit all members (fields, methods, and nested classes) from their superclass, but
not Constructors(as these are not members). THEREFORE you must invoke the superclasses
constructor using super(arguments1, argument2 .. etc):
overrideing if a subclass contains a method with the same signature (name, and parameter types)
and return type then that method will automatically override the superclasses method at
runtime
USE @Override to allow compiler to do runtime checks on method to make sure it matches
the superclass’s method
Generics
type parameter is what you call T in ClassName<T>
parameterized type is what you call the full ClassName<T>
Extras
var allows type inference on the left side
instead of:
Pair<Integer, String> pair = new Pair<Integer, String>(1, "hello");
or
Pair<Integer, String> pair = new Pair<>(1, "hello")
can use:
var pair = new Pair<>(1, "hello")
text block strings are strings preceded by three double quotes """ followed by a new line (which
is ignored in the string), and ending with just three double quotes """ (if you add a new line before
the ending quotes then a new line will be included in the actual string). This preceding new line is
mandatory, thus you can't have single line text block strings. Thus:
becomes:
The compiler takes out all white space to the left of the ending """ so:
will compile to:
but:
will compile to
if you want to control the white space without adding a new line you must use these
methods on the string block
.indent(int spacesToIndentEachLine)
within a text block, escaping characters (e.g. \', \n, \t, \") is not usually required
string interpolation java does not directly support string interpolation yet. Instead use
String::formatted
var s = "x:%d, y%d, z%d".formatted(x, y, z)
try with resources a try statement that declares one or more resources implementing
java.lang.AutoCloseable (which includes all java.io.Closable objects), between
parenthesis. These resources are automatically closed when the the program is finished:
This
allows you to
use these
resources without using a finally block to close them manually
pattern matching for instanceof allows you to specify a binding variable whose scope depends
on the return value of an instance of expression:
POJO (Plain Old Java Object) is a Java object that does not follow any major Java object models,
conventions or frameworks. Therefore it does not have to extend any pre-specified classes,
implement pre-specified interfaces, or contain pre-specified annotations
JavaBean is a serializable POJO (Plain Old Java Object) that has a zero-argument constructor,
and allows access to properties using getter and setter methods following a simple naming
convention.
java.nio new input/output package that has a better api than the old package
jshell command that runs the java shell to run java code in the terminal