0% found this document useful (0 votes)
3 views10 pages

Java Notes

The document covers fundamental programming structures in Java, including static methods, the final keyword, and variable declaration. It explains primitive data types, the use of enums, and the importance of initializing variables. Additionally, it discusses string comparison, Unicode handling, and the use of ArrayLists in Java.

Uploaded by

Alex Read
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)
3 views10 pages

Java Notes

The document covers fundamental programming structures in Java, including static methods, the final keyword, and variable declaration. It explains primitive data types, the use of enums, and the importance of initializing variables. Additionally, it discusses string comparison, Unicode handling, and the use of ArrayLists in Java.

Uploaded by

Alex Read
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

Core Java For The Impatient 3rd

Edition
Chapter 1 - Fundamental Programming Structures
A static method is just method that can be called using a class without creating a
object from that class
Static methods should be used when you might want to call a function but not
have a instance of a object

The final keyword is used to indicate that a value or method cannot change
For a variable this is intuitive, for a method this means that subclasses cannot
redefine it

public void myMethod() {


final int localVar = 10;
// localVar = 20; // This would cause a compilation error
- it would but because the reference changes not becasue the
value changes
}

public class ParentClass {


public final void displayMessage() {
[Link]("This is a final method.");
}
}

public class ChildClass extends ParentClass {


// @Override
// public void displayMessage() {
// [Link]("Cannot override this metho
d."); // This would cause a compilation error

Core Java For The Impatient 3rd Edition 1


// }
}

The term instance method describes what you think of as a method ie NOT a
static method but a method that is called from a instance of a class

Because the String datatype is actually not really one of the primitive data types -
then you use a capital letter to declare a String var, unlike a int var

jshell provides a REPL (read evaluate print loop) for learning java and checking out
classes - it is a bit like using the console python interpreter, one thing that is nice
is that is has good autocomplete so you can what methods and classes are
available

jshell> Random generator = new Random()


generator ==> [Link]@1d81eb93

jshell> generator.
doubles( equals( getClass() h
ashCode() ints( isDeprecated() lo
ngs(
nextBoolean() nextBytes( nextDouble( n
extExponential() nextFloat( nextGaussian( ne
xtInt(
nextLong( notify() notifyAll() s
etSeed( toString() wait(
jshell> generator.

There are 8 primitive types

Core Java For The Impatient 3rd Edition 2


Storage
Type Range (inclusive)
requirement
byte 1 byte –128 to 127
short 2 bytes –32,768 to 32,767
–2,147,483,648 to 2,147,483,647 (just over 2
int 4 bytes
billion)
–9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,775,807

Approximately ±3.40282347E+38F (6–7 significant


float 4 bytes
decimal digits)
Approximately ±1.79769313486231570E+308 (15
double 8 bytes
significant decimal digits)
char

boolean - boolean has no relation to 1/0 for true/false unlike other languages

The only other thing is that is now rare to use the float data type - you should
nearly always use the double data type

When declaring variables you can either declare the type of the variable or use
the var keyword, you should only use the var keyword when the type is
completely obvious

var generator = new Random();

Random generator = new Random();

The term identifier is used to describe the name you have given to a variable or
method ect

Core Java For The Impatient 3rd Edition 3


even public methods use camelCase with a lowercase starting letter. Classes only
use the capitalised first letter CamelCase

Before you do anything with a variable it must be initialized - see below as to what
I mean - this is an easy pitfall

int count;
count++; // Error—uses an uninitialized variable

int count;
if (total == 0) {
count = 0;
} else {
count++; // Error—count might not be initialized
}

Inside methods it is best to declare variables as late as possible that is right


before they are used

as already mentioned the final keyword is used for final values - for variables a
final variable is of course a constant (see below) - constants should be capitalized
and use underscores

public class Calendar {


public static final int DAYS_PER_WEEK = 7;
...
}

final int DAYS_PER_WEEK = 7;

Core Java For The Impatient 3rd Edition 4


enums can be declared both inside and outside of a class - example for enum
outside of class:

enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY, SUNDAY };

// calling it
Weekday startDay = [Link];

Integer division by 0 can lead to a exception, similiary float division by 0 leads to a


nast NaN / infinite float value

Also if you divide two integers then integer division will be used - discarding any
remainder

When an operator combines operands of different number types, the numbers are
automatically converted to a common type before they are combined. - usually
the conversion is intuaitve - for example dividing a int and a double - both
numbers will be converted to doubles. Java converts so that there is no loss of
information

Java has a ternary operator:


time < 12 ? "am" : "pm"

Core Java For The Impatient 3rd Edition 5


Because strings are not a primtive data type you cannot compare them using a ==
operator, this will only return true if the two strings are the same object

instead you should use the .equals() operation, the only time you might want to do
this is check i the string is null - you should always call . equals on the string
because that way you wont get any errors trying to call a method on a null pointer

[Link]("World") // dont do location == "World"

// this acceptable though


if (middleName == null) ...

// always put the string before the equals


if ("World".equals(location)) ...

Unicode details - code points and code units


When unicode was first introduced it used 16bit unicode points - Java used this
and was revolutionary - however when the next version of unicode was
introduced (requiring 21 bits) Java had to deal with this which is a bit of a pain.
Each valid unicode value is called a code point (a code point in the most recent
version of unicode is 21 bits) -
Java uses a variable-length encoding, called UTF-16, that represents all “classic”
Unicode characters with a single 16-bit value and the ones beyond U+FFFF as
pairs of 16-bit values taken from a special region of the code space called
“surrogate characters.” In this encoding, the letter A is represented by
one char value, written as \u0041 , and 𝕆 is the pair of char values \ud835\udd46 .

Core Java For The Impatient 3rd Edition 6


So if for whatever reason you need to see the code point for a value then this is ok
only if the unicode characters are inside the range of the ones that use only one
code unit.
char ch = [Link](i);

else you need to use something like this:


int codePoint = [Link]([Link](0, i));

you have triple strings in java

there is a weird thing called a fall through switch statement where if the 1st case
works the switch statemnt keeps going unless it hits a yield or break

public class FallThroughExample {


public static void main(String[] args) {
int day = 3;

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
// No break statement here, so execution will
fall through to the next case
case 4:
[Link]("Thursday");
// No break statement here, so execution will
fall through to the next case
case 5:
[Link]("Friday");
yield 5

Core Java For The Impatient 3rd Edition 7


case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day");
break;
}
}
}
// will print wednesday, thursday, friday

// yield returns a value and this version of a switch statmen


t uses
// different synatx (not arrows) to that of a
// normal one

in loops it is usally best convetnion to not use breaks or continue

arrays are fixed size but you can use ArrayList which is [Link] and provides a
resizeable array

there is a slighty nicer syntax for decalring array lists as seen in the final example

ArrayList<String> friends = new ArrayList<String>();


var friends = new ArrayList<String>();
ArrayList<String> friends = new ArrayList<>();

Core Java For The Impatient 3rd Edition 8


you cannot use primitive types when declaring an array list - however java
provides wrapper classes that just use a capital letter

var numbers = new ArrayList<Integer>(); // new ArrayList<int>(); would give an error


[Link](42);
int first = [Link](0);

there is some synatic sugar to make for loops a big nicer when you just want th
element:

int sum = 0;
for (int n : numbers) {
sum += n;
}

The collection class provides stuff to fuck with a array list

[Link](numbers, 0); // int[] array


[Link](friends, ""); // ArrayList<String>

[Link](names);
[Link](friends);

for some reason if you just put all your code in one class with the static main
method (and add other methods to that class, then all those methods but be static
as well) - to be clear the class with the main method entrance point must have all
its methods be static

Core Java For The Impatient 3rd Edition 9


a function can accept a variable no of paramaters

public static double max(double first, double... rest) {


double result = first;
for (double v : rest) result = [Link](v, result);
return result;
}

Core Java For The Impatient 3rd Edition 10

You might also like