Java Field Notes
Java Field Notes
The interpreter calls this main() subroutine, and the statements that it contains are
executed.
The word “public” in the first line of main() means that this routine can be called from
outside the program. This is essential because the main() routine is called by the Java
interpreter, which is something external to the program itself.
A program is defined by a public class that takes the form:
<optional-package-declaration>
<optional-imports>
Types of Variables
1. Instance Variables (Non-Static Variables) objects store their individual states in "non-
static fields", that is, fields declared without the static keyword. Non-static fields are
also known as instance variables because their values are unique to each instance of a
class (to each object, in other words); the currentSpeed of one bicycle is independent
from the currentSpeed of another.
2. Class Variables (Static Fields) A class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in existence,
regardless of how many times the class has been instantiated. A field defining the
number of gears for a particular kind of bicycle could be marked as static since
conceptually the same number of gears will apply to all instances. The code static int
numGears = 6; would create such a static field. Additionally, the keyword final
could be added to indicate that the number of gears will never change.
3. Local Variables Similar to how an object stores its state in fields, a method will often
store its temporary state in local variables. The syntax for declaring a local variable is
similar to declaring a field (for example, int count = 0; ). There is no special keyword
designating a variable as local; that determination comes entirely from the location in
which the variable is declared — which is between the opening and closing braces of a
method. As such, local variables are only visible to the methods in which they are
declared; they are not accessible from the rest of the class. TL;DR: Local variables are
variables defined in the local scope of methods.
4. Parameters Similar to other languages, the argument taking variables of methods and
class constructors. The important thing to remember is that parameters are always
classified as "variables" not "fields".
A type's fields, methods, and nested types are collectively called its members.
Naming
Variable names are case-sensitive. Convention is to start with a letter.
Subsequent characters may be letters, digits, dollar signs, or underscore characters.
Convention is to use Pascal case or UpperCamelCase.
int gear = 1;
A variable's data type determines the values it may contain, plus the operations that may
be performed on it.
Java has 8 primitive types.
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.
The eight primitive data types supported by the Java programming language are:
byte : The byte data type is an 8-bit signed two's complement integer. It has a
minimum value of -128 and a maximum value of 127 (inclusive). The byte data type
can be useful for saving memory in large arrays, where the memory savings actually
matters.
short : The short data type is a 16-bit signed two's complement integer. It has a
minimum value of -32,768 and a maximum value of 32,767 (inclusive).
int : By default, the int data type is a 32-bit signed two's complement integer, which
has a minimum value of -231 and a maximum value of 231-1.
long : The long data type is a 64-bit two's complement integer. The signed long has a
minimum value of -263 and a maximum value of 263-1.
float : The float data type is a single-precision 32-bit IEEE 754 floating point. As with
the recommendations for byte and short , use a float (instead of double ) if one
needs to save memory in large arrays of floating point numbers. This data type should
never be used for precise values, such as currency. For that, one will need to use the
java.math.BigDecimal class instead.
double : The double data type is a double-precision 64-bit IEEE 754 floating point. For
decimal values, this data type is generally the default choice. As mentioned above, this
data type should never be used for precise values, such as currency.
boolean : The boolean data type has only two possible values: true and false . Use
this data type for simple flags that track true/false conditions. This data type represents
one bit of information, but its "size" isn't something that's precisely defined.
char : The char data type is a single 16-bit Unicode character. It has a minimum value
of \u0000 (or 0) and a maximum value of \uffff (or 65,535 inclusive).
In Java SE 8 and later, int data type can be used to represent an unsigned 32-bit
integer, which has a minimum value of 0 and a maximum value of 232-1. Use the
Integer class to use int data type as an unsigned integer. Same with, long data
type.
Java supports for character strings via the java.lang.String class. Enclosing
character string within double quotes will automatically create a new String object; for
example:
String objects are immutable, which means that once created, their values cannot
be changed.
The String class is not technically a primitive data type.
Local variables are slightly different; the compiler never assigns a default value to an
uninitialized local variable
Literals
A literal is the source code representation of a fixed value; literals are represented directly in
the code without requiring computation. It is possible to assign a literal to a variable of a
primitive type. TL;DR: RHS values are known as literals.
Example,
// OK (decimal literal)
int x1 = 5_2;
// Invalid: cannot put underscores
// At the end of a literal
int x2 = 52_;
// OK (decimal literal)
int x3 = 5_______2;
Variables in Programs
A variable can be used in a program only if it has first been declared .
A variable declaration statement is used to declare one or more variables and to give
them names. When the computer executes a variable declaration, it sets aside memory
for the variable and associates the variable’s name with that memory.
Variable declaration syntax,
<type-name> <variable-name>;
The <variable-name-or-names> can be a single variable name or a list of variable
names separated by commas.
Good programming style is to declare only one variable in a declaration statement,
unless the variables are closely related in some way.
Example,
int numberOfStudents;
String name;
double x, y;
boolean isFinished;
char firstInitial, middleInitial, lastInitial;
Local variables: Variables declared inside a subroutine are called local variables for that
subroutine. They exist only inside the subroutine, while it is running, and are completely
inaccessible from outside.
Subroutines in Java
A subroutine is designed to perform some task. To get that task performed in a program,
one can “call” the subroutine using a subroutine call statement.
Every subroutine is contained either in a class or in an object.
One of the purposes of a class is to group together some variables and subroutines,
which are contained in that class. These variables and subroutines are called static
members of the class.
When a class contains a static variable or subroutine, the name of the class is part of the
full name of the variable or subroutine. For example, the standard class named System
contains a subroutine named exit .
System.exit(0)
Calling System.exit will terminate the program and shut down the Java Virtual
Machine.
Now, any subroutine performs some specific task, but for some subroutines, the task is
to compute or retrieve some data value. Subroutines of this type are called functions.
A function always returns a value.
Finally, subroutines in Java are often referred to as methods. Generally, the term
“method” means a subroutine that is contained in a class or in an object. Since this is
true of every subroutine in Java, every subroutine in Java is a method. The same is not
true for other programming languages.
Enumerated Types
This large collection of types is not sufficient to cover all the possible situations that a
programmer might have to deal with. So, an essential part of Java, just like almost any
other programming language, is the ability to create new types. Enum helps with that.
Technically, enum is a class.
An enum is a type that has a fixed list of possible values, which is specified when the
enum is created.
Definition of enum,
Example,
An enum value is a constant; that is, it represents a fixed value that cannot be changed.
The possible values of an enum type are usually referred to as enum constants.
Since enum is technically a class, the enum values are technically objects. As objects,
they can contain subroutines. One of the subroutines in every enum value is named
ordinal() - it returns the ordinal number of the value in the list of values of the enum.
System.out.println(vacation.ordinal())
// 1
Operations on String
The String class defines a lot of functions. Assume that s1 and s2 are variables of type
String :
One can also use the plus operator, +, to concatenate two strings.
Text Blocks
Java 17 defines a new kind of string literal that makes it easier to represent multi-line strings.
A text block starts with a string of three double-quote characters, followed by optional white
space and then a new line. The white space and newline are not part of the string constant
that is represented by the text block. The text block is terminated by another string of three
double-quote characters.
Arrays
An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is
fixed.
Each item in an array is called an element, and each element is accessed by its
numerical index.
Example,
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
Multi-Dimensional Array As an array can hold any reference, and since an array is itself
a reference, one can easily create arrays of arrays.
Array of arrays are also known as a multidimensional array. One can declare them by
using two or more sets of brackets, such as String[][] names.
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}
One can use the built-in length property defined on any array to determine the size of
this array.
System.out.println(anArray.length);
Copying Arrays The System class has an arraycopy() method that one can use to
efficiently copy data from one array into another:
The two Object arguments specify the array to copy from and the array to copy to. The
three int arguments specify the starting position in the source array, the starting
position in the destination array, and the number of array elements to copy.
, Java SE provides several methods for performing array manipulations (common tasks,
sch as copying, sorting and searching arrays) in the java.util.Arrays class.
For instance, copying of array can be used with method of the java.util.Arrays
class, as one can see in the ArrayCopyOfDemo example. The difference is that using the
java.util.Arrays method does not require one to create the destination array before
calling the method, because the destination array is returned by the method:
class ArrayCopyOfDemo {
public static void main(String[] args) {
String[] copyFrom = {
"Affogato", "Americano", "Cappuccino", "Corretto",
"Cortado",
"Doppio", "Espresso", "Frappucino", "Freddo", "Lungo",
"Macchiato",
"Marocchino", "Ristretto" };
Searching an array for a specific value to get the index at which it is placed (the
binarySearch() method).
Comparing two arrays to determine if they are equal or not (the equals() method).
Filling an array to place a specific value at each index (the fill() method).
Sorting an array into ascending order. This can be done either sequentially, using the
sort() method, or concurrently, using the parallelSort() method introduced in Java
SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential
array sorting.
Creating a stream that uses an array as its source (the stream() method). For
example, the following statement prints the contents of the copyTo array in the same
way as in the previous example:
java.util.Arrays.stream(copyTo)
.map(coffee -> coffee + "")
.forEach(System.out::print);
Converting an array to a string. The toString() method converts each element of the
array to a string, separates them with commas, then surrounds them with brackets. For
example, the following statement converts the copyTo array to a string and prints it:
System.out.println(java.util.Arrays.toString(copyTo));
// [Cappuccino, Corretto, Cortado, Doppio, Espresso, Frappucino,
Freddo]
Restrictions on var ,
Operators
Operators Precedence
postfix expr++ expr--
multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR \|
logical OR \|
ternary ? :
result--;
// result is now 0
System.out.println(result);
result++;
// result is now 1
System.out.println(result);
result = -result;
// result is now -1
System.out.println(result);
Prefix/Postfix Demo,
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
Type Comparison,
The instanceof operator compares an object to a specified type. One can use it to test if
an object is an instance of a class, an instance of a subclass, or an instance of a class that
implements a particular interface.
Example,
The following program, InstanceofDemo , defines a parent class (named Parent ), a simple
interface (named MyInterface ), and a child class (named Child ) that inherits from the
parent and implements the interface.
class InstanceofDemo {
public static void main(String[] args) {
class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}
with output,
Control Flow
Same as C/C++, with the addition of, yield statement.
The yield statement exits from the current switch expression it is in. A yield statement
is always followed by an expression that must produce a value. This expression must not be
void . The value of this expression is the value produced by the enclosing switch
expression.
Example,
class Test {
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Switch Statements
A switch statement takes a selector variable as an argument and uses the value of this
variable to choose the path that will be executed.
The following primitive types cannot be used for the type of the selector variable:
boolean , long , float , and double .
Example,
int quarter = ...; // any value
All statements after the matching case label are executed in sequence, regardless of
the expression of subsequent case labels, until a break statement is encountered.
The default section handles all values that are not explicitly handled by one of the
case sections.
In Java SE 7 and later, one can use a String object in the switch statement's
expression.
The selector variable of a switch statement can be an object, and this object can be
null.
switch Expressions
Several things have motivated this new syntax.
1. The default control flow behaviour between switch labels is to fall through. This syntax is
error-prone and leads to bugs in applications.
2. The switch block is treated as one block. This may be an impediment in the case
where one need to define a variable only in one particular case .
3. The switch statement is a statement. In the examples of the previous sections, a
variable is given a value in each case . Making it an expression could lead to better and
more readable code.
Example, from,
to,
The syntax of switch label is now case L -> . Only the code to the right of the label is
executed if the label is matched. This code may be a single expression, a block, or a throw
statement. Because this code is one block, we can define variables in it that are local to this
particular block.
When using block, return does not work,
Traditionally, the return keyword is used to denote the value produced by a block of
code. Unfortunately this syntax leads to ambiguity in the case of the switch statement.
The block of code executed in the case where quarter is equal to 0 needs to return a
value. It uses the return keyword to denote this value. If one take a close look at this
code, one see that there are two return statements: one in the case block, and
another one in the method block. This is where the ambiguity lies: one may be wondering
what is the semantics of the first return . Does it mean that the program exits the
method with this value? Or does it leave the switch statement? Such ambiguities lead
to poor readability and error-prone code.
A new syntax has been created to solve this ambiguity: the yield statement.
So far, switch statements do not accept null selector values. If one try to switch on
a null value one will get a NullPointerException .
Input/Output
Basic Output and Formatted Output
The most basic output function is System.out.print(x) , where x can be a value or
expression of any type. If the parameter, x , is not already a string, it is converted to a
value of type String , and the string is then output to the destination called standard
output.
System.out.println(x) outputs the same text as System.out.print , but it follows
that text by a line feed ( \n ), which means that any subsequent output will be on the
next line.
The function System.out.printf can be used to produce formatted output (like
C/C++).
System.out.printf takes one or more parameters.
The first parameter is a String that specifies the format of the output.
This parameter is called the format string . The remaining parameters specify
the values that are to be output.
System.out.printf("%1.2f", amount);
// Eg output, 5.28
Every format specifier begins with a percent sign (%) and ends with a letter,
possibly with some extra formatting information in between. The letter specifies the
type of output that is to be produced. For example, in %d and %12d , the “d”
specifies that an integer is to be written.
A format specifier such as %15.8e specifies an output in exponential form, with the
“8” telling how many digits to use after the decimal point. If one use “g” instead of
“e”, the output will be in exponential form for very small values and very large
values and in floating-point form for other values. In %1.8g , the 8 gives the total
number of digits in the answer, including both the digits before the decimal point
and the digits after the decimal point.
The “s” stands for “string,” and it can be used for values of type String. It can also
be used for values of other types; in that case the value is converted into a String
value in the usual way
To include an actual percent sign in the output, use the format specifier %% in the
format string.
Use %n to output a line feed.
Can also use a backslash, \ , as usual in strings to output special characters such
as tabs and double quote characters.
For numeric output, the format specifier can include a comma (“,”), which will cause
the digits of the number to be separated into groups, to make it easier to read big
numbers.
System.out.printf("%,d",x);
// 1,000,000,000 (in the United States)