Nothing Special   »   [go: up one dir, main page]

JAVA Course Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 196

Java Course notes – start 31 Oct 2022-10-31

24-07-2023 – RESTART!!!

- Install the JDK – Java Development Kit from Orace

- Setup ENV variables (path , JAVA_HOME)

- Install ECLIPSE / NetBeans / IDEA (IntelliJ)

What is java and what d we need to run it / use it / create programs etc

- It is an OOP – Object oriented programming language

Look at the following illustration to see the difference between class and objects:

So, a class is a template for objects, and an object is an instance of a


class.
When the individual objects are created, they inherit all the variables and
methods from the class.

- You need just a JRE (Java runtime environment) to run JAVA programs

- You need the JSDK (Java Software Dev Kit) –if you need to create /

compile and execute java programs

- A java VM (JVM) – An interpreter that can run your java code on any

platform

- Java API libraries

- Compiler (javac)

Tools (such as java, javac) to execute/compile the java programs

Get the java tutorial doc or refer to https://docs.oracle.com/javase/tutorial/ for

more training / guides / examples etc

Above we have the components described visually

Creating / compiling / executing a java PROGRAM using an editor

Per first example we used notepad


Rules:

- Package name – must be the same as the folder where you storing the

program. So the package name corresponds to a directory name

- In our case

package examples; - so create a folder called examples

In my case, I created the folder in the below path

- C:\IntroToJava\ch02\examples

- The name of our class file in the package folder must be same as the

program class name,

- In our case

public class hello { – so our file name within the examples directory

should be hello.java - note it is case sensitive

1. So we first write the code – using some sort of editor, following above

rules:

package examples;

public class hello

{
public static void main(String[] args)

System.out.print("Hello, ");

if (args.length == 0)

System.out.println("World!");

else

System.out.println(args[0] + "!")

{ - indicates the start of a block of code. Then you do not need a ;

A ‘;’ indicates a termination of the statement

It is preferred that you indent / line up your curly braces to make the

code easier to read

You can optionally use the curly braces in the ‘if’ statement as shown

above

2. Compile the code into bytecode using java compiler javac


3. This command is run from the folder one up from the folder where

the .java package resides. In this case the cho2 folder path is the correct

location

javac examples\Hello.java

If compiled ok, we get no errors and a Hello.class file is created

The class file is also then found together with the Hello.java code in the

package folder i.e /examples

4. Run the program using java command from one folder above the package

folder i.e. ch02 in our example


java examples/Hello which is the NAME of the PUBLIC class in our

program. Also note the ‘/’ instead of backslash. Can also use a dot

java examples.Hello

So the class file is then executed by the JVM Virtual machine

The code within the public static void ‘main’ is executed

Since we have some code to deal with ‘args’ being passed in the following can

happen if I pass in an argument e.g. = Kani


What does javac compiler do?

It converts source code into bytecode and creates a .class file. The JVM is then

able to execute that class file, if you choose to run the program

The JSDK (JAVA Software Development Kit) directory structure

- Src.zip – contains the source code for the java libraries

- /bin – contains the compiler and interpreter and other tools

- /lib – contains the java Archive (JAR) files used by the tools – contains

compiled class files


- /jre / /jre/bin, /jre/lib used by the Java Runtime environment

- /include – contains files for the JAVA Native Interface

First exercise : Create a new class called myname, compile and run it

I. created the class within the same Examples directory

II. I named the file myname.java

III. I then compiled it and ran it

 Note the error because I had created a file called myname.java and

within the code I had defined public class as MyName. So consider the

case sensitivity

The code:

To use the javap –c command

javap –c <directory where your .class file lives>/name of the class file only
New section:
Using ECLIPSE - ECLIPSE is an INTEGRATED DEVELOPMENT ENVIRONMENT

(IDE) – kinda like the Visual Studio tool

Get it from the Eclipse website (IDE for developers)

You will need at least the JRE installed before using Eclipse. If you need to do

more than just develop (example debug), advised that you have the full JSDK

installed

When launching Eclipse initially, it asks to define a workspace. This is just a

storage location where Eclipse will keep all artefacts / programs / code etc

C:\Users\kenny.SATSO\eclipse-workspace – In my case this is the workspace

More about Eclipse


- You can customise the perspectives as you like using Windows/Perspective

menu

- To start a new project File/New Java Project/…

- To create a new class – File/New class

So, I ended up with something like the below


Some keyboard shortcuts!!

CTRL-SPACE – invokes methods that you can use instead of typing code – try

typing a few letters of the method, then CTRL-SPACE e.g. sysout, main

CTRL-SHIFT-F – Formats code

CTRL-S – saves and compiles code

CTRL-SHIFT-B – sets a Breakpoint for debugging

F11 – invokes the debug

F6 – Step over to next line in DEBUG mode

e.g. type main CTRL-SPACE and it brings up methods which you can then add

to your code
To compile your code in Eclipse, just save the file

It then creates the .java file (source code) and the .class file in the Eclipse

workspace/bin , workspace/src folders

The IDE will try to check your code and syntax as you type

Here we see errors when saving/compiling at below of screenshot

When creating a new class you can add the main method by default by just

clicking the option

To execute your program hit the Run button on the menu bar. It will execute

whichever class tab is active


- Under Run menu, find Run configuration – Here you can pass in

arguments to your main method` using the ‘arguments’ tab

HOW TO RUN THE DEBUGGER in ECLIPSE?

- Set a breakpoint at the line of code you choose – double click / right click

in the extreme left in the blue bar, at the line of code you want to start

debug or Debug in the Run menu

- Run – it may prompt to change to DEBUG perspective

In DEBUG mode You’ll see something like below


Shows where you are in the code, + values of variables, in this case args

Program stops at the debug breakpoint, in a light green sort of highlight

You can choose to terminate / resume / or step over (f6)


To import other java programs into Eclipse use: File/Import/General_Filesystem

Specify the source location and the target Eclipse workspace directory

Else just copy the .java source into the workspace target area using Windows

Remember to Refresh so the new source appears in Eclipse

You can also import other java Projects into Eclipse in a similar way by pointing

at the parent directory e.g. C:\IntroToJava


You can choose to copy the projects into the Eclipse workspace, or leave them

where they are ‘Copy projects into workspace’ checkbox


JAVA INTRO - DATA TYPES & VARIABLES

8 Primitive data types – these are built into the java language

Four (4) categories

INTEGER – whole numbers

- Byte

- Short

- Long

- Int (default = 0)

Basically defines how much data can be stored as an integer in bytes

FLOATING POINT – Numbers with a fractional component

- Float

- Double (default = 0.0)

We’re talking about level of precision in terms of decimals

CHARACTER – can store any character of the alphabet using the 16bit Unicode

- Char – where you can represent just about any char / letter using 2

bytes

- See Unicode.org

BOOLEAN – true/false type values

Either true or false Values (false is default)


DECLARATIONS

To declare a variable :

int age = <value>

Local variable – must be initialised before use and is available only within the

method

Attribute / field variable – need not be initialised and is usually available to the

class outside of a method, and is available to ALL methods within that class

static int age = 30

final when used to declare a variable – you cannot change this variable value

afterward

COMMENTING OUT CODE / COMMENTS FOR NOTES etc

// - use these to insert comments in your code

/* ----- */ - use this to comment out multiple lines/blocks of code

Conventions:

 Capitalise class names


 Variables and methods – usually start with a lowercase letter

 Use _, letters and numbers for declaring variables

 Variables are case sensitive

- myName = ‘kani’

- MyName = ‘kani’ – MyName is a different variable

You cant used keywords as variables of course

List of keywords below

Assigning Numeric literals

- Append a capital L to the end of your value to specify LONG

long age = 2.4L

- Double can be assigned like this: double xx = 44.56

- Append a capital F to the end of your value to specify FLOAT

float age = 2.5F

Assigning char literals – only allowed to store ONE character

char middleName = ‘k’

java stores this value as a Unicode character code number

e.g. ‘A’ is 65, Z is 90 and so on

*** See Unicode conversion tables for more info


You can also assign char values using the Unicode values like below using the \u

syntax

Or using the decimal value

char letter = 65 - this will store ‘A’ in the variable letter

STRINGS AND STRING COMPARISONS

String name = “Kani” - NOTE this datatype starts with a capital

Use double quotes around the assigned value

To compare values we can use ==

But With strings however, use the below equals method, which evaluates the

content of each string variable regardless of what memory space is being used

== compares the ‘pointers’

String letter1 = “a”

If you use the new String method, then java creates a new memory space for

that variable

String letter2 = “b”

System.out.println(letter1.equalsIgnoreCase(letter2)) – so this should output

false

Note – String has many methods

Use + to concatenate strings


*** google JAVA API DOCS for more details on methods and stuff

String methods are found in the java lang menu blade on the top left

Per above, java creates new memory space for the above method using the New

string method

STRING LITERALS

You can create a String literal : String name = “Kani”


You can also embed special sequence chars into your string literal

If you assign 2 diff string vars with the same value, java optimises by creating

one memory space for both vars

Remember, new String will create a new memory space

String methods also work with string literals

ARRAYS

We define an array using the [ ] chars

You can define it with the datatype or with the variable


You can also define multiple vars in one statement using one datatype

declaration

String name = “Kani”, surname = “Pillay”

String [ ] title, author;

The default value for String datatype = Null

When using arrays, you must define the size of the array initially?

Price = new float[20];

names[1] = new String(“bob james”);

String [ ] name = new String[10]; //here we initialise and create the name array

We can also init an array like below:

Int odds[] = {1, 2, 3, 4,5}; this inits and creates a new var odds with 5

elements

The array cnt starts at zero (0);

name[0] = ‘Kani”

name[1] = “Caelen”

name[3] = ‘JACK”

.length is the attribute to use to get the size of the array

e.g. The above example will display the last element of your array by subtracting

one from the array length. Assuming we can define size using a variable

You can also have an array within an array (array of arrays)


This works like a matrix / or Jbase multivalue

Defining it, will be like below:

2 SQUARE brackets, and then two sets of values in curly braces

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

String bookinfo[ ] [ ] = {

The variable will then become an array/array like below:

bookinfo[0] = ‘Java In a Nutshell’, ‘Flanagan’

bookinfo[0][0] = ‘Java In a Nutshell’

bookinfo[0][1] = ‘Flanagan’

bookinfo[1] = ‘Core Java, ‘Horstmann’

bookinfo[1][0] = ‘Core Java’

bookinfo[1][1] = ‘Horstmann’

bookinfo[2] = ‘Thinking in Java’, ‘Eckel’

bookinfo[2][0] = ‘Thuinking in java’

bookinfo[2][1] = ‘Eckel’

We can access the array values using a for loop

public class Main {


public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}

A String datatype is a Non Primitive data type

These are defined as classes, as apposed to the 8 Primitive data types (Boolean,

char, float, double, byte, int, short, long)

Java comes with many predefined class types of this nature already

A value assocated with a class type = an object

e.g. String name = “Kani” > so here “Kani’ is the object

Objects are created at runtime in ‘heap’ memory

Java references objects, like through a pointer concept and are not stored in the

class type as such

THE DOT OPERATOR


We can use the . operator to invoke methods on a non primitive class’s object

name = “kani pillay”; in this case name is a String datatype

int strLength = name.length() > length is a method on the ‘name’ object

OPERATORS AND EXPRESSIONS

= Assignment operator x = 5;

Max = min = current = 5 > we process this from right to left

Max = (min = (current=5)) > this is equivalent to the above statement

Arithmetic operators

+ -* / this is the usual add, subtract, multiply and divide

Note on divide(/):

If you doing a divide using a float type you get a float answer

If you want a float answer, then one of the variables you are dividing must be

type float

If you divide using integer, you get an integer answer – fractions are dropped
% - Modulus - use this to find the mod of an expression or the remainder of

a division

- Use Unary operator to make a number negative e.g. –balance

Note:

When dealing with type short / byte, java promotes the result as a type int. If

you result isn’t type int, you get a compile error. See example below

Relational Operators

>, >=, <. <=, == (use with primitives, and use the equals method with strings), !

=(not equal to)

The result of an expression using these operators can be stored in a Boolean

boolean trueorfalse = (x >= 5)

Logical Operators

|| - 2 pipe chars – Use this as OR

x <12 || y > 6

&& - 2 ampersand chars – use this as AND

x <12 && y > 6

- Both OR/AND use short circuit processing. If the left expression yields a

result, then it will not evaluate the right expression

! - exclamation mark – use that as NOT – this is like IF !(some expression)


Increment / Decrement operators

++ and -- Can be used only on variables and not literals

b++ or b- - adds or subtracts 1 from the variable

a = ++b here, we use a prefixed notation. a = (b + 1) so a = 1, b=1

a = b++ here we use the postfix notation. first a = b ; then b = b + 1 so a=0,

b=1

Operate – Assign Operators

+= , -=, *=, /=, %=

You can use this operator with a literal or a variable

n += 50 …so n = n + 50

n *= 10 …so n = n * 10

age += years here we’re using variables

Conditional operator

?: also called a ? operator or turnary orperator

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

Op1 ? op2 : op3 > if op1(the condition) is true , then op2 is the result,

otherwise op3
This is typically doing something like an if condition in a single expression / line

char status;

Int age = 16;

status = age >= 18 ? “a” : “m”;

If age >= 18, then status = ‘a’ otherwise status = ‘m’

Example of an if CONDITIION syntax below

if (args.length > 0)
name = args[0];
else
name = "anonymous";

if (args.length > 1)
phone = args[1];
else
phone = "not listed";
System.out.println("Name: " + name + " Phone: " + phone);

OPERATOR PRECEDENCE

Java will process according to its precedence rules. See chart below
If you want to change the order, use parentheses

Implicit Type conversions (type casting)

Java will convert automatically, if you’re mixing integer types to the larger int

type

Example: If you add a short + int = int

However, if you try to go the opposite way, you will get compile error

To get around compiler error from Implicit type conversions:

Use the CAST operator


Per below example, we cast the answer of two float types into an integer

Also the decimals (if any) are lost

public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Explicit casting: double to int

System.out.println(myDouble);

System.out.println(myInt);

}
public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt);

System.out.println(myDouble);

CONTROL FLOW

If / For / While & Compound flows

A STATEMENT is an normal expression followed by ;

X = y; x + y = z; int age;

You can include your code within a block by defining opening/closing { }. These

typically tell you where something starts / ends. Typically, you would use these

for your main method and your class

Also, we typically use { } with Conditional blocks of code

Examples for if/else – remember – use CTRL SPACE with keywords

The final else is optional

if (age < 4 ) {
System.out.println("age is " + age);
}

int age = 16;


if (age < 4) {
System.out.println("age is " + age);
}

or

if (age == 16) {
System.out.println("there is a problem");
}
else {
System.out.println("we are in the else");
}

Using the else if syntax

if (age < 12 && age > 3) {


System.out.println("Order kid's meals.");
System.out.println("Buy child movie ticket.");
}
else if (age >= 12 && age < 16) {
System.out.println("Cannot drive.");
}
else if (age >= 16) {
System.out.println("Can drive and have a job.");
System.out.println("Pay full price for meals.");
System.out.println("Buy adult movie ticket.");

}
else
// babies and toddlers
System.out.println("Get into movies free.");

public class Main {

public static void main(String[] args) {

int time = 22;

if (time < 10) {


System.out.println("Good morning.");

} else if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

Switch statement

Syntax

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This works like the BEGIN CASE syntax

You can then have various ‘case’ statements embedded in the block

WHILE & DO while LOOP constructs

If the test condition is never true, then your loop will never execute

Or

Your loop will execute at least once, then check the test condition

FOR Loops

Syntax

for (statement 1; statement 2; statement 3) {


// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.


Statement 3 is executed (every time) after the code block has been executed.

Note: if you need access to your counter var outside the loop, then you must

declare it outside the loop, else it is only available within the loop block

for (<init your counter> ; <a test condition> ; increment/decrement>)

do something;

step1 – init your counter (if

step2, evaluate test condition

step3 – do something

step4 – increment and repeat from step2

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
LOOPING THROUGH AN ARRAY

odds is the array odds.length method tells us how big the array is

so we can loop through the array using odds.length


You can also have an array within an array (array of arrays)

This works like a matrix / or Jbase multivalue

Defining it, will be like below:

String bookinfo[ ] [ ] = {

The variable will then become an array/array like below:

bookinfo[0] = ‘Java In a Nutshell’, ‘Flanagan’

bookinfo[0][0] = ‘Java In a Nutshell’

bookinfo[0][1] = ‘Flanagan’

bookinfo[1] = ‘Core Java, ‘Horstmann’

bookinfo[1][0] = ‘Core Java’

bookinfo[1][1] = ‘Horstmann’

bookinfo[2] = ‘Thinking in Java’, ‘Eckel’

bookinfo[2][0] = ‘Thuinking in java’

bookinfo[2][1] = ‘Eckel’

Here are some ways to loop through this matrix. Below we see a nested loop

Outer loop works on bookinfo.length

Nested loop works on bookinfo[ i ].length


ARRAY OF AN ARRAY example

 Array indexes start with zero (0)

public class Main {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

System.out.println(myNumbers[1][2]);

LOOPING THOUGH A MULTI DIMENSIONAL ARRAY

…using a nested loop

public class Main {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i) {

for(int j = 0; j < myNumbers[i].length; ++j) {

System.out.println(myNumbers[i][j]);

}
ENHANCED FOR EACH /LOOP SYNTAX to loop through an ARRAY

Syntax

for (type variableName : arrayName) {


// code block to be executed
}

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (String i : cars) {
System.out.println(i);
}

The counter variable must be the same type as the expression / array you are

evaluating. Like below, both the array and counter are type int

You need a : inserted between the counter and the expression

int odds[] = { 1, 3, 5, 7, 9 };

for (int num : odds) {


System.out.println(num);
}

String bookInfo[][] = {
{ "Java In a Nutshell", "Flanagan" },
{ "Core Java", "Horstmann" },
{ "Thinking in Java", "Eckel" } };

for (String[] book : bookInfo) {


for (String s : book) {
System.out.print(s + " ");
}
System.out.println();
}
CONTINUE statement

Use this to cause your for loop to jump to the next iteration

BREAK statement

Use this to break out of your loop altogether

JAVA ARRAYS

String[] cars;

We have now declared a variable that holds an array of strings. To insert


values to it, you can place the values in a comma-separated list, inside
curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};


Using METHODS in JAVA

A method is a set of statements with a name, and is defined within a class

You must always have a main method. This is used to start you program

public static void main(String[] args)

public – means it is accessible from anywhere, to everything

static – main resides in its class, not in objects of its class ?

void – this method doesn’t return any value

main – is the name of the method

String[] <args> - you always pass in an array of strings as argumements,

although you always need to

Calling methods

Per above example println is a method, and we pass an argument within the ()

You use the dot (.) notation to invoke a method

public class Main {

static void myMethod() {

System.out.println("I just got executed!");

}
public static void main(String[] args) {

myMethod();

AND methods can return values

Above, the method is sqrt, which takes arguments (2,0), and returns a value to

be stored in the root variable

public class Main {

static void myMethod(String fname, int age) {

System.out.println(fname + " is " + age);

public static void main(String[] args) {

myMethod("Liam", 5);

myMethod("Jenny", 8);

myMethod("Anja", 31);

}
public class Main {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

System.out.println(myMethod(3));

A METHOD USING THE ‘IF’

public class Main {

// Create a checkAge() method with an integer parameter called age

static void checkAge(int age) { --- the method

// If age is less than 18, print "access denied"

if (age < 18) {

System.out.println("Access denied - You are not old enough!");

// If age is greater than, or equal to, 18, print "access granted"

} else {

System.out.println("Access granted - You are old enough!");

}
}

public static void main(String[] args) {

checkAge(20); // Call the checkAge method and pass along an age of 20

Overloading –we use this term when you have different methods of the same

name, that can take different data types of arguments or different numbers of

arguments

RECURSION

public class Main {

public static void main(String[] args) {

int result = sum(10);

System.out.println(result);

public static int sum(int k) {

if (k > 0) {

return k + sum(k - 1);

} else {

return 0;

}
}

Defining your own method

- Specify the data type that your method returns e.g. float

- A name – use Camelcase e.g. getArea(int x , int y)

- The datatypes and names of the arguments you must pass to the method

return x * y > you can also use an expression with your return

- Use return statement to return a value

- If the method DOES NOT return a value, then declare its data type as

void : example : void getArea(int x, int y)

Usually with a void method, you do not need to put the return

Here’s an example of calling a method within your program – this is like a

GOSUB

getCircum & getVolume are 2 methods

the var PI is a field – it is available to the whole class, as it is defined in the

class area, not the main area


Note:

STATIC keyword – means it belongs to a class. This is why we specify

static float getCircum(x,y), because it lives in the same class SphereMeth

MORE ON METHODS

- METHODS CAN ALSO BE DECLARED AS STATIC

- You can access a static method without needing to create am object of

the class first

You can then call that method on the CLASS


- STATIC methods can only reference static fields

- When calling overloaded methods(methods with the same name and

different parameters / signatures), system will choose the most apt one

that fits your call based on arguments / datatypes of the arguments

Some example next

SCOPE

Refers to Visibility of variables and methods and such in the system

Vars are available to the method only, if used in a method block


Fields (if defined as class level), are available throughout that class

Static vars are available to the whole class

In Eclipse, it helps you show where code bolck starts/ends. Eg. Main

Is marked with that blue line on the left, per below


OOP (Object Oriented Programming)

P – Polymorphism

I – Inheritance

E – Encapsulation

Features of OOP

- Maintainability

- Modularising – breaking large chunks of code into modules / methods /

functions
- Abstraction – one doesn’t have to understand the innards of a method /

piece of code

- Objects

o The state of the object is maintained by a set of variables called

fields. These are usually NOUN type words

o The behaviour of the object is controlled by methods which are

usually VERB like words

o So below, we define a ‘MONITOR’ object

Fields / nouns

Methods / verbs

Understand the difference between

classes and Objects

CLASS

– defines the structure & content of an object (like a house blueprint)

– some of this common content / attributes can be shared amongst all

instances (objects).

– E.g. Monitor Class – we want all monitors to be 22cms in size. Then all

instances/objects of this class will inherit this feature

A description of a group of objects all with similar roles in the system,


which consists of:
– Structural features (attributes) define what objects of the class
"know"
o Represent the state of an object of the class
o Are descriptions of the structural or static features of a class
– Behavioral features (operations) define what objects of the class
"can do"
o Define the way in which objects may interact
o Operations are descriptions of behavioral or dynamic features
of a class

Example of a Class DEFINITION

date
Month
The class FIELDS
Day

year
setDay()

setMonth() The class METHODS

getDay()

getYear()
thedate Date where Date is the datatype
Month – 03

Day = 02

Year = 1967

Above, an example of an object, which is an instance of date class, but


has its own state, by definition of it the values it has set or its state

OBJECT

- is an instance of a class, like a house is an instance of a blueprint

- an object has its own state – based on the variables contained in that

object.
- You can thus have multiple objects in different states, but all are

instances of a specific class

Class FIELDS & METHODS

Fields

- STATIC

Static fields reside in the class

Static fields are shared by all objects of that class

Changing a static field then modifies all the instances/objects of this class

Static fields may exists even without an instance / object being created

- INSTANCE

Instance fields reside in the object, and each object has its own copy of

instance fields

e.g. CurrentDate object will have todays date

XmasDate object will have xmas date stored

Methods

Is a function / procedure that is defined inside a class

Methods provide the functionality of the object – what the object can do

Calling a method on an object means asking the object to do some task

You can have static (can only access static class fields) / instance methods
An example to demonstrate the differences between static and
public methods:

Static vs. Public

You will often see Java programs that have either static or public
attributes and methods.

In the example below, we created a static method, which means that it


can be accessed without creating an object of the class, unlike public,
which can only be accessed by objects:

public class Main {


// Static method

static void myStaticMethod() {


System.out.println("Static methods can be called without creating objects");
}

// Public method

public void myPublicMethod() {


System.out.println("Public methods must be called by creating objects");
}

// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error

Main myObj = new Main(); // Create an object of Main


myObj.myPublicMethod(); // Call the public method on the object
}
}
P – Polymorphism I – Inheritance E – Encapsulation

ENCAPSULATION – what is this?

- Bringing together your fields and methods inside a class

- Hides fields and actual code, sitting behind your public methods

- Guarantees that the data inside in an object is correct / consistently

defined

- Provides a level of abstraction – user of your method need not know the

‘how’ of your method, just the basics of the interface needed to use your

method

- You can change the mechanics of your code inside your method, without

affecting the interface (the callable public methods a user can call) to use

your method

So how do we abstract / keep things away from the wrong hands / eyes /

modification

ACCESS CONTROL modifiers – used to enforce encapsulation

- - controls who has access to your fields / methods inside the class

o Package (discussed later) – shown with ~ sign in uml


o Public (+)

any code anywhere has access to the data / methods

o Private (-)

Only methods inside the class have access to the data / methods

o Protected (pound sign in UML)

Classes that inherit this class (sub classes) have access to the data /

methods

P – Polymorphism I – Inheritance E – Encapsulation

INHERITANCE – what is this?

Allows you to build a new class(datatype), using an existing class as the

foundation

Example: you want to add time information to your Date Class

Superclass/baseclass/Generalised class

sub-class/derived class / specialised class

The arrow pointing up(uml) – indicates

TimeStamp Class is inheriting from Date

We add the new fields with Timestamp class (hour/minute/second etc)

We also override the code implementing the display method in the Timestamp

class in this example. It has the same name / parameters etc, but implements

differently

The original class becomes the superclass, and the new one, the sub-class
All methods / fields etc from Date class become available, together with the

new fields/methods in TimeStamp class

When to use inheritance? Use when it makes sense!

Use the ‘is a kinda’ test

A toaster ‘is a kinda’ appliance > so if you’re wanting to implement a toaster

class, it may work to use inheritance from appliance class in this case

More on INHERITANCE – how to implement inheritance on the classes/sub class

Remember:

Inheritance implies subclass takes on the attributes of the parent/super class,

and we can then add more to the sub class

- Constructors are not inherited from superclass

We use inheritance to largely avoid duplication of functionality / code

Extends – we use the extends keyword to indicate inheritance from a superclass

to a subclass

Syntax: public class Employee extends Person { }

In this example:

- Employee is the sub class and inherits from / extends the Person class

- Person is the superclass

- Final - If declared, means you cannot inherit from this class

You can only implement a SINGLE inheritance / only one superclass parent
Lets see an example:

The superclass = Person

Notes:

- ‘protected’ access modifier – means the var is available to the subclass

and other packages in the same directory

The sub class = Employee


Notes:

- Note the extends keyword

- We’ve added 2 more fields ‘title’ and ‘salary’ and a getSalary method

- The constructor has 5 arguments and a ‘no arg’ constructor


CASTING

- Liksov Substitution Principle (LSP)

- You can substitute a sub class where a super class is required

- Java will ‘upcast’ the sub-class to the superclass by default, meaning

whatever is available to superclass, is available to subclass

e.g. Person p = new Employee()

…where Person is the superclass & Employee is the sub class

We can invoke the isPastRetirement method in the Employee subclass where it

expects a Person object


You can also go the other way i.e. downcast, meaning allow a Person object to

accept an Employee object

Example:

Person p = new Employee() … so p is an Employee object in this case

Employee e = (Employee) p … we are casting Employee type onto Person type

The below may cause problems though if we start with a Person object and try

to cast that as an Employee object

Person p = new Person()

Employee e = Employee() p ….this is likely to cause an exception because

you’re trying to cast from Employee to Person, and objects are misaligned

We can use the instanceof to check whether your object is the correct type

before you try to use casting,. See below!

TYPE CASTING (with

primitives)

Type casting is when you assign a value of one primitive data type to
another type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a


larger type size
byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger type to a
smaller size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller size type


to a larger size type:

public class Main {


public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}

Narrowing Casting

Narrowing casting must be done manually by placing the type in


parentheses in front of the value:

Example

public class Main {


public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
Method Overriding

Here, we have a method with the same name, and same parameters

One method is in the superclass and the other in the subclass

- To implement, the sub class method must have the same name and signature (no

of args)

- The subclass method must not be less accessible than the super class method

@Override – use this to cause java to check whether you are intentionally trying

to override a method. If final, then you cannot override the method (optional)

More about POLYMORPHISM / Dynamic Binding

If you have overriding methods in your class / sub class, java decides at run

time which method to invoke.

We talked about this earlier in this training, See where the object started its

life.

It is usually only applied when we use Inheritance / Mehod Overriding

Below:

Person p = new Employee() so p is actually an Employee() object but stored

as a Person object

p.getname() ; will invoke the Employee().getName method

Using the SUPER keyword

- This relates to modifying access of your vars (private / protected/public

etc)
In a sub class method, you can refer to the superclass using super even if you

vars in the superclass are declared as private

Per below example, we refer to the getName() method from the PERSON class

from within the Employee class

Return super.getName()

You would normally need this when you want to use an overridden method and

then want to rather use the method in the superclass

- You can also invoke a superclass constructor from your subclass if you

choose using super

- It should be the FIRST declaration you make in your constructor if you

choose this
Above, we invoke the PERSON constructor from the Employee

constructor

Super(x,y,z) to deal with lastname, firstname, age – since this is already

being handled in the sperclass (Person)

More on the super usage

The OBJECT class

- Every class in java descends from java.lang.object

- A variable of type Object, can refer to anything!! ?


All of the above are objects

Primitives are not objects

P – Polymorphism I – Inheritance E – Encapsulation

POLYMORPHISM – what is this?

- Usually applies when you use inheritance

- You may have a method in the superclass, that is ‘overidden in the sub

classes. Hence, you can call on that method, depending on the class you

define

- Per below, superclass has a animalSound method, as well as the pig / dog

subclasses

Example

class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound(); - invokes the superclass method
myPig.animalSound(); - invokes the pig class method
myDog.animalSound(); - invokes the dog class method
}
}
Above we added another sub-class – TimeZoneStamp – a new field and also a

display() method, which then overrides the Date display()

With polymorphism:

If you invoke Date.display object – the display() from the Date Object is

executed

If you invoke from TimeStampZone.display object – then the display() from

TimeStampZone is executed

Here’s a good example of the polymorphism


We have the dates [ ] array, which stores objects Date (d), t and tz

So in the loop, the relevant object.display() is invoked, regardless of the

datatype of dates

BEST PRACTICES

- Methods should have fewer parameters

- Fields / methods should usually be declared as private

- Objects should do one thing mostly (high cohesion)

- Objects should rely on other classes as little as possible (low coupling)


More UML Class diagrams

OBJECTS & CLASSES – Implement new object/classes using code

CREATING A NEW CLASS

Some conventions

- Capitalise Class names

- Lowercase for method names

- Camelcase for variables

- A public class has its own java file


Some examples of classes

Note that not every class you create, has to have a main

Usually you will have a main which calls upon other classes / methods

CREATING OBJECTS

Using A CLASS, you can create objects

-an object is often referred to as an instance of a class

Use the NEW keyword to create an instance of an object

Dog spot = new Dog() > here we create a new object of the Dog class assigning

it to variable spot

- System then creates a space in memory for this object, initialises

variables and calls constructors etc


Above, an example of how we use objects

1. We execute from Bank2 class using the main method

- We create a new Customer2 object using the new keyword and assign

this object to the variable cust

Customer2 cust = new Customer2();

- We assign values to the vars initiated in the Customer2 class

Note : I can now use the (.) notation cust.

o cust.firstname = “Jim”;

cust.lastname = “Stewart”;

- by now, the object cust has values stored for firstname / lastname

- addAccount() is a method defined/living in the Customer() class

- We invoke the cust.addAccount method and pass in the value using

cust.addAccount(250.0)
- Program execution steps into the addAccount method within

Customer2() class

- Here we create a new Account2() object in the variable acc

void addAccount(double initialBalance) {


acc = new Account2();

- Here we assign the amount passed into initialBalance to acc.balance and then we
print out stuff.
- For this example, we’re not doing anything with the balance or the arithmetic
being done in the Account2() method

acc.balance = initialBalance;
System.out.println("Account added for " + firstName + " "
+ lastName);

For now, all 3 of the above packages live in the examples directory, so they are

‘aware’ of each other. Later we will see how to use this stuff even if the classes

live in different folders/directories

DIFFERENCE between INSTANCE & CLASS fields

CLASS fields

- Fields declared as static are class fields and belong to the class where it

was defined / declared

- You can reference a class field without even without instantiating an

object of the class

- STATIC fields appear as italics in eclipse

INSTANCE fields

- Every object / copy of class has its own set of variables initiated and

defined
- Any field not declared as static is an instance field

- You cannot refer to an instance field without the object

Final fields

- Most final fields are defined as static

- Once set, they cannot be changed

- By convention, final fields are declared in all uppercase

- E.g. static final int ROUTING_NUMBER = 1234


DEFINING CONSTRUCTORS

What is a CONSTRUCTOR?

- It is called automatically when you create an object using new keyword

- It initialises the fields/vars in the object

- Has the same name as the class and lives inside the class you are calling

- Cannot have a return type

- Must not have VOID as the type

- A constructor looks like a method

- You can call one constructor from another by using the this keyword and

then it must be the first line of code as well

Here is an example of the constructor, which basically inits / sets values to your

vars

If you don’t specify a constructor, java inserts a no arg constructor by default


You can also use Eclipse to generate Constructor using fields menu option
More examples of constructors

Example

public class Main {


int modelYear;
String modelName;

//constructor
public Main(int year, String name) {
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Main myCar = new Main(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}

// Outputs 1969 Mustang

ACCESS MODIFIERS

- Unspecified access control means it is visible to other methods/classes in

the same package directory

More on Public/Private /Default / Protected modes

- You should restrict access to your fields / methods as much as possible

private String accounted

- You can then use get and set methods to access / set the value or vars

Get statement retrieves the value of a var

Set statement assigns a value to the var

Use Eclipse to insert the get / set methods + constructors if you want

We divide modifiers into two groups:

 Access Modifiers - controls the access level


 Non-Access Modifiers - do not control access level, but provides
other functionality
Access Modifiers for CLASSES (AM)

For classes, you can use either public or default:

public The class is accessible by any other class, anywhere

The class is only accessible by classes in the same package.


default
This is used when you don't specify a modifier (default)

Access Modifiers for ATTRIBUTES(fields), METHODS and CONSTRUCTORS you

can use the one of the following:

public The code is accessible for all classes

private The code is only accessible within the declared class

The code is only accessible in the same package. This is used when you
default
don't specify a modifier

The code is accessible to other classes in the same package and


protected
subclasses.

Non-Access Modifiers (NAM)

For classes, you can use either final or abstract

The class cannot be inherited by other classes (You will learn more about
final
inheritance in the Inheritance chapter)

The class cannot be used to create objects (To access an abstract class, it

must be inherited from another class


abstract
For attributes and methods, you can use the one of the following:

final Attributes and methods cannot be overridden/modified

static Attributes and methods belongs to the class, rather than an object

Can only be used in an abstract class, and can only be used on

methods. The method does not have a body, for example abstract

abstract void run();. The body is provided by the subclass (inherited from ). You

will learn more about inheritance and abstraction in the Inheritance

and Abstraction chapters

Attributes and methods are skipped when serializing the object


transient
containing them

ynchronized Methods can only be accessed by one thread at a time

The value of an attribute is not cached thread-locally, and is always


volatile
read from the "main memory"
USING JAVA OBJECTS

- Format strings using System.out.printf()

Use this printf() to format strings

The general syntax for a format specifier is as follows:

%<argument-index$><flags><width><.precision><conversion>

The % and conversion parts are mandatory, all other parts are optional.

There is no space between format specifiers and the % marks the start of
a format specifier inside a format string.
To escape % use %%.

argument-index$ specifies the index of the argument. It has an integer


followed by a $. E.g. 1$ uses the first argument value

The first argument is referred to as 1$, the second as 2$, and so on. We
can refer to the same argument multiple times.

The flags contains a set of characters and specifies the format of the
output. The valid values for flags depend on the data type of the
argument.

The width specifies the minimum number of characters needed to output.

The .precision (works usually with floating point numbers) specifies the
maximum number of characters to output.

For a decimal number, .precision starts with a dot ..

The conversion, a mandatory part, specifies how to format the value.

System.out.printf(format string,list of values)

Example:
LocalDate dob = LocalDate.of(1971, Month.MAY, 16);
System.out.printf(
"%1$tB %1$td, %1$tY is %2$s's birth day. Let's go and celebrate.",
dob, "Mike");
Another example:
import java.util.Calendar;
public class Demo {
public static void main( String args[] ) {
Calendar cal = Calendar.getInstance();
System.out.printf( "%1$tA, %1$tB %1$td, %1$tY
", cal );
System.out.printf( "%1$ta, %1$tb %1$te, %1$ty
", cal );
}
}

Output
Monday, November 26, 2018
MONDAY, NOVEMBER 26, 2018
Mon, Nov 26, 18

Another example:
System.out
.printf("PI to 10 decimal places: %1$.10f%n", Math.PI);

String fs = "The average of %1$d, %2$d, and %3$d is %4$.2f%n";


System.out.printf(fs, 12, 4, 6, ((12 + 4 + 6) / 3.0));

Using String.format

- Using StringBuffer, StringBuilder instead of String

We learned – strings are immutable.

When you reset/re-assign a string value, a new object is created in

memory

To avoid using too much memory, you can use StringBuilder/StringBuffer

class
StringBuilder b = new StringBuilder(“Java”): b.append(“ programming”)

You can convert back to a string type : String s = b.toString()

There are many methods available to StringBuilder (check it out)

You can specify the size (mem) to allocate to StringBuilder. Once

exhausted, java will create another mem space of 100, in this example

StringBuilder var = new StringBuilder(100)

var.append(“the string”)

Use StringBuffer when you have multiple threads making changes to

strings – this method is slower the StringBuilder, but works the same

way, similar methods etc

Note on calling methods:

Above we can invoke 2 methods on the emp object using the below syntax:

System.out.println (emp.getFirstName() . toUpperCase() )

- Using toStrings() to return the object state

Use the toString method in your class to make it return a string object

You can have Eclipse generate a toString method for you inside your class

Example:
- Comparison of objects & object references

You can use == to compare primitive data types

However, if your data types / objects reference different objects, you will get

a false result

Use the equals() method when comparing 2 objects

- Use the this keyword to reference the current (invoking) object

- See example below: This code snippet equals() can also be generated by

Eclipse
- public boolean equals(Object obj) {
- if (this == obj) ;* where the current object and object passed in are equal
and reside in the same memory space
- return true;

- if (obj == null) :* the object passed in is null


- return false;

- if (getClass() != obj.getClass()) :* note - getClass returns the name of your


class
- return false;

- Rectangle other = (Rectangle) obj; ;* we cast the passed in object as a


Rectangle, and compare heights
- if (height != other.height)
- return false;

- if (width != other.width)
- return false;
-
- return true;
- }

More on comparing objects:

Use the hashCode() method which returns the same int whenever 2 objects

are equals() to each other

Example of hashcode() method in your class:

Using wrapper classes for primitive data types

Java uses the 8 primitive data types AND reference types(objects and all

other types)
- Wrapper classes

All the Primitives can have a wrapper class

Use the autoboxing feature to convert between wrapper object and primitive

Double wrapper = 34.5 (Double wrapper = new Double(34.5)

double primitive = wrapper (double primitive = wrapper.doubleValue() )

Wrapper classes provide a way to use primitive data types ( int, boolean,
etc..) as objects.

The table below shows the primitive type and the equivalent wrapper
class:

byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Sometimes you must use wrapper classes, for example when working
with Collection objects, such as ArrayList, where primitive types cannot be
used (the list can only store objects):

Example

ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid

Below, we use wrapper class Integer to store list in Arraylist

ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid

Creating Wrapper Objects

To create a wrapper object, use the wrapper class instead of the


primitive type. To get the value, you can just print the object:

Example

public class Main {


public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}

Since you're now working with objects, you can use certain methods to
get information about the specific object.
For example, the following methods are used to get the value associated
with the corresponding wrapper object: intValue(), byteValue(), shortValue(),
longValue(), floatValue(), doubleValue(), charValue(), booleanValue().

This example however will output the same result as the example above:

Example

public class Main {


public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}

toString()

Another useful method is the toString() method, which is used to convert


wrapper objects to strings.

In the following example, we convert an Integer to a String, and use the


length() method of the String class to output the length of the "string":

Example

public class Main {


public static void main(String[] args) {
Integer myInt = 100; - using wrapper class Integer
String myString = myInt.toString(); save myInt as a string
System.out.println(myString.length()); can now use String methods on the value
}
}
Using ENUM

Use this when you have a var who’s content is a limited set of choices (like a list

of choices)

Public enum Color (RED, GREEN, BLUE)

Color mycolourvar = Color.RED Use the . notation to access the value

Enums can be used in switch statements

Switch (mycolourvar) {

Case RED;

Do something …

- The enum exists as a separate ‘class’

- In the cellphone class, we use the HW and OS enum types

To create a new enum ‘class in Eclipse

File/new/enum

Here is an example of enum


Another example for ENUM

enum Level {
LOW,
MEDIUM,
HIGH
}

public class Main {


public static void main(String[] args) {
Level myVar = Level.MEDIUM;

switch(myVar) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
}
LOOPING THRU AN ENUM

enum Level {

LOW,

MEDIUM,

HIGH

public class Main {

public static void main(String[] args) {

for (Level myVar : Level.values()) { -- use the values() method on enum

System.out.println(myVar);

GARBAGE COLLECTION

Note:

When creating new objects – new memory space is created

How does mem get destroyed?

- The JVM uses garbage collection to reclaim mem that is not used

anymore

the finalise() method

protected void finalise()

- You are notified when garbage collection occurs

- This may occur immediately, or when prof ends or sometimes NEVER


You can also use system.gc() to force a garbage collection – handle with care!

ABSTRACTION (ABSTRACT Classes) & INTERFACES

ABSTRACT

The abstract keyword is a non-access modifier, used for classes and


methods:

 Abstract class: is a restricted class that cannot be used to create


objects (to access it, it must be inherited from another class).

 Abstract method: can only be used in an abstract class, and it does


not have a body. The body is provided by the subclass (inherited
from).

An abstract class can have both abstract and regular methods:

abstract class Animal {


public abstract void animalSound(); >>note the ; at the end of this class definition
public void sleep() {
System.out.println("Zzz");
}

To access the abstract class, it must be inherited from another class

// Abstract class
abstract class Animal {
// Abstract method animalSound (does not have a body)
public abstract void animalSound();

// Regular method
public void sleep() {
System.out.println("Zzz");
}

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep(); - inheritance from the abstract Animal class
}
Abstract

An abstract method belongs to an abstract class, and it does not have a


body. The body is provided by the subclass:

Example

// Code from filename: Main.java


// abstract class
abstract class Main {
public String fname = "John";
public int age = 24;
public abstract void study(); // abstract method
}

// Subclass (inherit from Main)


class Student extends Main {
public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
System.out.println("Studying all day long");
}
}
// End code from filename: Main.java

// Code from filename: Second.java


class Second {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from
Main)
Student myObj = new Student();

System.out.println("Name: " + myObj.fname);


System.out.println("Age: " + myObj.age);
System.out.println("Graduation Year: " + myObj.graduationYear);
myObj.study(); // call abstract method
}
}
INTERFACES

Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related


methods with empty bodies:

// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda

like inherited) by another class with the implements keyword (instead of extends).

The body of the interface method is provided by the "implement" class:

// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}

package examples;

public interface Switchable {


public void turnOn();
public void turnOff();
}

package examples;

public class GasFireplace implements Switchable {


private Status status;

public void turnOn() {


status = Status.ON;
// turn on the gas, ignite the flame
}
public void turnOff() {
status = Status.OFF;
// turn off the gas
}
@Override
public String toString() {
String className = this.getClass().getName();
return "The " + className + " is turned "
+ status.toString().toLowerCase();
}
}

You can also implement multiple interface classes

interface FirstInterface {

public void myMethod(); // interface method


}

interface SecondInterface {

public void myOtherMethod(); // interface method

// DemoClass "implements" FirstInterface and SecondInterface

class DemoClass implements FirstInterface, SecondInterface {

public void myMethod() {

System.out.println("Some text..");

public void myOtherMethod() {

System.out.println("Some other text...");

class Main {

public static void main(String[] args) {

DemoClass myObj = new DemoClass();

myObj.myMethod();

myObj.myOtherMethod();

If you’re implementing an interface class, then you have to write code for the interface

methods in your implementing class


MORE ON INTERFACES & SUBCLASSES & ABSTRACTION

package examples;

public class MotionSensor {


private Switchable[] items; -- sort of an ARRAYLIST definition
private int count = 0;

public MotionSensor(int numItems) {


items = new Switchable[numItems]; -- Constructor
}
public void add(Switchable s) {
if (count < items.length)
items[count++] = s;
// else throw exception
}
public void motionDetected() {
System.out.println("Motion Detected");
for (Switchable item : items) {
if (item != null)
item.turnOn();
}
}
public void timeout() {
// Need to add code to determine if enough time has elapsed
System.out.println("Timeout occurred");
for (Switchable item : items) {
if (item != null)
item.turnOff();
}
}
public String toString() {
StringBuilder builder = new StringBuilder();
for (Switchable item : items) {
if (item != null)
builder.append(item.toString() + "\n");
}
return builder.toString();
}
public static void main(String[] args) {
MotionSensor sensor = new MotionSensor(4);
sensor.add(new FluorescentLamp());
sensor.add(new HalogenLight());
sensor.add(new GasFireplace());
sensor.add(new Fan());
// sensor.add(new Light());

sensor.motionDetected();
System.out.println(sensor);
sensor.timeout();
System.out.println(sensor);
}
}
Java Iterator

An Iterator is an object that can be used to loop through collections, like


ArrayList and HashSet. It is called an "iterator" because "iterating" is the
technical term for looping.

To use an Iterator, you must import it from the java.util package.

Using an Iterator

The iterator() method can be used to get an Iterator for any collection:

// Import the ArrayList class and the Iterator class


import java.util.ArrayList;
import java.util.Iterator;

public class Main {


public static void main(String[] args) {

// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");

// Get the iterator


Iterator<String> it = cars.iterator();

// Print the first item


System.out.println(it.next()); use the next method of the iterator
}

ARRAYLIST

The ArrayList class is a resizable array, which can be found in the java.util
package.

The difference between a built-in array and an ArrayList in Java, is that


the size of an array cannot be modified (if you want to add or remove
elements to/from an array, you have to create a new one). While
elements can be added and removed from an ArrayList whenever you
want.

Create an ArrayList object called cars that will store strings:

import java.util.ArrayList; // import the ArrayList class

ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object

Example

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");

System.out.println(cars);
}
}

Create an ArrayList to store numbers (add elements of type Integer):

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(10);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(25);
for (int i : myNumbers) {
System.out.println(i);
}
}
}

Access an Item IN arraylist

To access an element in the ArrayList, use the get() method and refer to
the index number:

Example

cars.get(0);

Change an Item

To modify an element, use the set() method and refer to the index
number:
Example

cars.set(0, "Opel");

Remove an Item

To remove an element, use the remove() method and refer to the index
number:

Example

cars.remove(0);

To remove all the elements in the ArrayList, use the clear() method:

Example

cars.clear();

ArrayList Size

To find out how many elements an ArrayList have, use the size method:

Example

cars.size();

Sort an ArrayList

Another useful class in the java.util package is the Collections class,


which include the sort() method for sorting lists alphabetically or
numerically:
Example

Sort an ArrayList of Strings:

import java.util.ArrayList;
import java.util.Collections; // Import the Collections class

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars); // Sort cars
for (String i : cars) {
System.out.println(i);
}
}
}

You can also use the Arraylist foreach method

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}

COLLECTIONS:
You can store items in a collections as type Object

package examples;

public class Pair {


private Object first;
private Object second;

public Pair(Object one, Object two) {


first = one;
second = two;
}

public Object getFirstElement() {


return first;
}

public Object getSecondElement() {


return second;
}

public void setFirstElement(Object obj) {


first = obj;
}

public void setSecondElement(Object obj) {


second = obj;
}
}
USING GENERICS – When working with Collections

See Pair. Class – we use a generic type <T>


Then is PairTester, we can create object Pair<Point> points = new Pair<>.
Comparable interface (from the java.lang UTIL)

Uses the compareTo() method

We use this to compare 2 objects

System returns an integer:

(-) value if object is less than

(+) value if object is greater than

0 if objects are equal

package examples;

public class ComparableTester {


public static void main(String[] args) {
Point p1 = new Point(10, 20);
Point p2 = new Point(15, 20);

if (p1.compareTo(p2) < 0) {
System.out.println(p1 + " is less than " + p2);
}
else if (p1.compareTo(p2) > 0) {
System.out.println(p1 + " is greater than " + p2);
}
else {
System.out.println(p1 + " is equal to " + p2);
}
}
}

LinkedList

The LinkedList class is almost identical to the ArrayList:

// Import the LinkedList class


import java.util.LinkedList;

public class Main {


public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}

ArrayList vs. LinkedList

The LinkedList class is a collection which can contain many objects of the same
type, just like the ArrayList.

The LinkedList class has all of the same methods as the ArrayList class because
they both implement the List interface. This means that you can add items,
change items, remove items and clear the list in the same way.

However, while the ArrayList class and the LinkedList class can be used in the
same way, they are built very differently.

How the ArrayList works


The ArrayList class has a regular array inside it. When an element is added, it is
placed into the array. If the array is not big enough, a new, larger array is
created to replace the old one and the old one is removed.

How the LinkedList works

The LinkedList stores its items in "containers." The list has a link to the first
container and each container has a link to the next container in the list. To add
an element to the list, the element is placed into a new container and that
container is linked to one of the other containers in the list.

Use an ArrayList for storing and accessing data, and LinkedList to


manipulate data.

LinkedList Methods
Java Packages & API

A package in Java is used to group related classes. Think of it as a folder


in a file directory. We use packages to avoid name conflicts, and to write
a better maintainable code. Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

Built-in Packages

The Java API is a library of prewritten classes, that are free to use,
included in the Java Development Environment.

The library contains components for managing input, database


programming, and much much more. The complete list can be found at
Oracles website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.

To use a class or a package from the library, you need to use the import
keyword:

IMPORT

Syntax

import package.name.Class; // Import a single class


import package.name.*; // Import the whole package
Example

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the


java.util package.

To import a whole package, end the sentence with an asterisk sign ( *).
The following example will import ALL the classes in the java.util package:

Example

import java.util.*;
CTRL-SHIFT O – allows Eclipse to insert any required import STATEMENTS for you
You can use the static keyword to import java utils
package examples;

import static java.lang.System.out;


import static java.lang.Math.*;

public class StaticImports {


public static void main(String[] args) {
int radius = 5;
double area = PI * pow(radius, 2); >>you can then omit the Math.

out.printf( > you can omit the System


"The area of a circle with radius %1$d is %2$.2f %n",
radius, area);
}
}

- Use the CLASSPATH environment var where applicable so that java can
find your classes – assuming you have your own classes and they may be
in a different location
- Define the path to the foler above where you packages actually live

e.g.
c:\kani\javacode - would be the CLASSPATH
c:\kani\javacode\Manufacture\manu.class - Your package in this case is Manufacture

JAR files
 Contain compiled java classes
 Is like a zip file, and works the same as a zip folder

For JAR files – your CLASSPATH should point directly to where your JAR is located
-

User-defined Packages

To create your own package, you need to understand that Java uses a
file system directory to store them. Just like folders on your computer:

Package names match your directory names

Example
└── root
└── mypack
└── MyPackageClass.java

To create a package, use the package keyword:

- You are allowed to have classes of the same name but must live in
different packages

MyPackageClass.java

package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}

Package names with dots (.)

Package examples.rentalcar.size;
System will create subfolders for each part separated by a dot
Typically, add your company domain name – or come up with a
standard naming structure that works for you

Examples:
Create 2 classes in the animal package (Dog & Cat)
We use the import keyword to import the animal.dog/cat package below
We can then reference the objects as normal
Above, we see example of two classes with same name (cat), used in the
AnimalTest class.

- Import animal.* -- this imports all the animal classes


- zoo.Cat c2 = new zoo.Cat() - explicit use of the cat
class/zoopackage

Java Inner Classes

In Java, it is also possible to nest classes (a class within a class). The


purpose of nested classes is to group classes that belong together, which
makes your code more readable and maintainable.

To access the inner class, create an object of the outer class, and then
create an object of the inner class:

Example
class OuterClass {
int x = 10;

class InnerClass { > nested class


int y = 5;
}
}

public class Main {


public static void main(String[] args) {

OuterClass myOuter = new OuterClass(); > outerclass object created

// create the innerClass object

OuterClass.InnerClass myInner = myOuter.new InnerClass();

System.out.println(myInner.y + myOuter.x);
}
}

// Outputs 15 (5 + 10)

You can declare the inner class as private if you don’t want outside classes
accessing it

Example
class OuterClass {
int x = 10;

private class InnerClass {


int y = 5;
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}

If you try to access a private inner class from an outside class, an error occurs:

Main.java:13: error: OuterClass.InnerClass has private access in OuterClass


OuterClass.InnerClass myInner = myOuter.new InnerClass();

An inner class can also be static, which means that you can access it
without creating an object of the outer class:

Note: just like static attributes and methods, a static inner class does not have
access to members of the outer class.

Example

class OuterClass {
int x = 10;

static class InnerClass {


int y = 5;
}
}

public class Main {


public static void main(String[] args) {

//Create an object of the innerClass without needing to create object of outerClass

OuterClass.InnerClass myInner = new OuterClass.InnerClass();

System.out.println(myInner.y);
}
}

// Outputs 5
You can access attribs and methods of the outclass from the Inner Class

Access Outer Class From Inner Class (nested classes)

One advantage of inner classes, is that they can access attributes and
methods of the outer class:

Example

class OuterClass {
int x = 10;

class InnerClass {
public int myInnerMethod() {
return x;
}
}
}

public class Main {


public static void main(String[] args) {

OuterClass myOuter = new OuterClass(); >Create the outclass Object

OuterClass.InnerClass myInner = myOuter.new InnerClass(); >Create the innerCl;ass


object

System.out.println(myInner.myInnerMethod());
}
}

// Outputs 10

Java User Input


The Scanner class is used to get user input, and it is found in the java.util
package.

To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our
example, we will use the nextLine() method, which is used to read Strings:

import java.util.Scanner; // Import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input as String


System.out.println("Username is: " + userName); // Output user input
}
}

Other methods available on Scanner object

nextBoolean()Reads a boolean value from the user


nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");


// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

Dates – how to access in java


We can import the java.time package to work with the date and time API. The
package includes many date and time classes. For example:

LocalDate Represents a date (year, month, day (yyyy-MM-dd))


Represents a time (hour, minute, second and
LocalTime
nanoseconds (HH-mm-ss-ns))
Represents both a date and a time (yyyy-MM-dd-HH-
LocalDateTime
mm-ss-ns)
DateTimeFormatter Formatter for displaying and parsing date-time objects

Examples - using the now() method from the various classes

import java.time.LocalDate; // import the LocalDate class

public class Main {


public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
}
}
import java.time.LocalTime; // import the LocalTime class

public class Main {


public static void main(String[] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
}
}

import java.time.LocalDateTime; // import the LocalDateTime class

public class Main {


public static void main(String[] args) {
LocalDateTime myObj = LocalDateTime.now();
System.out.println(myObj);
}
}

The output will be:

2023-08-08T08:20:15.307197 > note the T signifies separator between date/time

Formatting Date and Time

The "T" in the example above is used to separate the date from the time.

You can use the DateTimeFormatter class with the ofPattern() method in the
same package to format or parse date-time objects. The following
example will remove both the "T" and nanoseconds from the date-time:

Example

import java.time.LocalDateTime; // Import the LocalDateTime class


import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class
public class Main {
public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now(); > create the object
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy
HH:mm:ss");

String formattedDate = myDateObj.format(myFormatObj);


System.out.println("After formatting: " + formattedDate);
}
}

The output will be:Before Formatting: 2023-08-08T08:20:15.309825


After Formatting: 08-08-2023 08:20:15

The ofPattern() method accepts all sorts of values, if you want to display the
date and time in a different format. For example:

yyyy-MM-dd "1988-09-29"
dd/MM/yyyy "29/09/1988"
dd-MMM-yyyy "29-Sep-1988"
E, MMM dd yyyy "Thu, Sep 29 1988"

More on Collections

- Is an object that contains other objects


- The size of a collection can change
- Some collections may order elements (sort) and others do not
SETS

- Describe a group of unique elements


- SETS implements interfaces such as the below, which inherit SET
methods
o See Hashset,
o TreeSet (sorted list),
o LinkedHashSet (remembers order of elements added)

Example using LinkedHashSet

We have defined a class called CD

Then we create LinkedHashSet containing a bunch of CD objects

package examples;

public class CD {
private int id;
private String artist;
private String title;

public CD(int i, String a, String t) {


id = i;
artist = a;
title = t;
}

@Override
public String toString() {
return "CD [id=" + id + ", artist=" + artist + ", title="
+ title + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((artist == null) ? 0 : artist.hashCode());
result = prime * result + id;
result = prime * result
+ ((title == null) ? 0 : title.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CD other = (CD) obj;
if (artist == null) {
if (other.artist != null)
return false;
}
else if (!artist.equals(other.artist))
return false;
if (id != other.id)
return false;
if (title == null) {
if (other.title != null)
return false;
}
else if (!title.equals(other.title))
return false;
return true;
}

Ensure your class has the equals and hashCode blocks in your class, when using
HashSet

Then we have the SetTest class, with the LinkedHashSet

package examples;

import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
//import java.util.LinkedHashSet;

public class SetTest {


public static void main(String args[]) {
CD cd1 = new CD(1, "The Beatles", "The Beatles 1");
CD cd2 = new CD(2, "Prince", "The Very Best of Prince");
CD cd3 = new CD(3, "Garth Brooks", "The Ultimate Hits");;
CD cd4 = new CD(3, "Garth Brooks", "The Ultimate Hits");;

Set<CD> cdCollection = new HashSet<>();

// you can also use:


HashSet<CD> cdCollection = new HashSet<>();
// Set<CD> cdCollection = new LinkedHashSet<>(); //if we use
LinkedHashSet, we will get the items returned, in the order they were added

cdCollection.add(cd1);
cdCollection.add(cd2);
cdCollection.add(cd3); // add the cd objects
cdCollection.add(cd4);

Iterator<CD> it = cdCollection.iterator(); // create an Iterator object


while (it.hasNext()) // use the Iterator hasNext
method
System.out.println(it.next()); // use the Iterator next
method
}
}

LIST

- Describe an ordered group of elements


- Allows duplicates
- Do NOT need to override equals() and hashcode() methods
- You can use the insertion method, where you can specify what index to
add an element
- Use get(index) to retrieve a specific element from the list
- Implements interfaces like:
o ArrayList – see more in Arraylist section

Examples:

package examples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;

public class ListTest {


public static void main(String args[]) {
CD cd1 = new CD(1, "The Beatles", "The Beatles 1");
CD cd2 = new CD(2, "Prince", "The Very Best of Prince"); //create new CD obj
CD cd3 = new CD(3, "Garth Brooks", "The Ultimate Hits");

List<CD> cdCollection = new ArrayList<>(); // create ArrayLIst object


// List<CD> cdCollection = new LinkedList<CD>();

cdCollection.add(cd1);
cdCollection.add(cd2); // add items to the Arraylist
cdCollection.add(0, cd3); // adding this element at index (0)

for (int i = 0; i < cdCollection.size(); i++) {


System.out.println(cdCollection.get(i)); // for loop going thru the elements
}

// another way to loop through the list


for (CD cd : cdCollection) {
System.out.println(cd); // for each loop
}

// yet another way to loop through the list


Iterator<CD> it = cdCollection.iterator(); // iterator object created
while (it.hasNext()) { // Iterator loop
System.out.println(it.next());
}

o LinkedList
- Double linked – each element is aware / linked to the other per above
- Indexed insertion and gets can be ‘expensive’, as it has to iterate thru the
list either insert or get the correct index – especially for LARGE lists

o Vector

QUEUE

- Describes a group of elements accessed in a FIFO manner(first in first out)


- Use the offer method to add to the queue
- Use the add method also, but raises an Exception if there is an issue
- use the poll method to get the head element(first in the queue) – if list is
empty you get null
- use the remove method to get the first element – if Q is empty you get
an Exception
- use the peek method if you want to just look at the first element – does
not remove the element from the queue. Returns null if Q is empty
- use the element method (similar to peek) – returns exception if the Q is
empty
- Implement the below interfaces for QUEUE
o LinkedList
Implements the queue interface – doubly linked, unbounded list of
elements

Uses FIFO

Allows for null elements, but AVOID using nulls, as null is generally
used to indicate an empty list

Example: - still using the CD class example from above

import java.util.LinkedList;

import java.util.Queue; //use this import util

public class QueueTest {

public static void main(String args[]) {

//create the cd objects

CD cd1 = new CD(1, "The Beatles", "The Beatles 1");

CD cd2 = new CD(2, "Prince", "The Very Best of Prince");

CD cd3 = new CD(3, "Garth Brooks", "The Ultimate Hits");

//

Queue<CD> cdCollection = new LinkedList<CD>();

cdCollection.offer(cd1); //add elements to the queue

cdCollection.offer(cd2);

cdCollection.offer(cd3);
System.out.println("Using peek():");

for (int i = 0; i < cdCollection.size(); i++) {

System.out.println(cdCollection.peek()); //see first element

System.out.println("Using poll():");

// must retrieve the size before the loop, because

// poll() removes elements, reducing the size

int size = cdCollection.size();

for (int i = 0; i < size; i++) {

System.out.println(cdCollection.poll()); //remove item


from list

o PriorityQueue

Has the ability to sort elements in the queue – see below example
Example:

import java.util.PriorityQueue; //use these imports

import java.util.Queue;

public class QueueTest2 {

public static void main(String args[]) {

//create Queue object using PriorityQueue

Queue<String> myQueue = new PriorityQueue<String>();

myQueue.offer("C");

myQueue.offer("D"); // add elements to the queue - random

myQueue.offer("B");

myQueue.offer("A");

// must retrieve the size before the loop, because

// poll() removes elements, reducing the size

int size = myQueue.size();

for (int i = 0; i < size; i++) {

System.out.println(myQueue.poll());

// get elements results in a sorted output

A
B
C
D

MAP

HashMap

- Describes a set of elements as key/value pairs with unique keys


- See HashMap below

- Order of elements is not guaranteed

- Key and value are allowed to be null

- Is fastest of all the MAP interfaces

LinkedHashMap

- Adds ordered iteration to HashMap and keeps the insertion order


- Keyset() method returns set of keys that are in order of insertion

TreeMap

- Implements the SortedMap interface


- Objects are sorted based on the key at time of insertion
- Keyset() returns keys in ascending order

Example:

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;
//import java.util.LinkedHashMap;

public class MapTest {

public static void main(String args[]) {

CD cd1 = new CD(1, "The Beatles", "The Beatles 1");

CD cd2 = new CD(2, "Prince", "The Very Best of Prince");

CD cd3 = new CD(3, "Garth Brooks", "The Ultimate Hits");

Map<String, CD> cdCollection = new HashMap<>();

// Map<String,CD> cdCollection = new LinkedHashMap<>();

//Map<String,CD> cdCollection = new TreeMap<>()  this would output


in sorted order

cdCollection.put("B00004ZAV3", cd1);

cdCollection.put("B00005M989", cd2);

cdCollection.put("B000UVT3OI", cd3);

Set<String> s = cdCollection.keySet();

Iterator<String> it = s.iterator();

while (it.hasNext()) {
String key = it.next();

System.out.print("Key: " + key);

System.out.println(" Value: " + cdCollection.get(key));

Java HashMap

A HashMap store items in "key/value" pairs, and you can access them by
an index of another type (e.g. a String).

One object is used as a key (index) to another object (value). It can store
different types: String keys and Integer values, or the same type, like: String
keys and String values:

To use hashmap, import the HashMap class from java util:

import java.util.HashMap; // import the HashMap class

Add Items to hashmap

The HashMap class has many useful methods. For example, to add items to
it, use the put() method:

Example

// Import the HashMap class


import java.util.HashMap;

public class Main {


public static void main(String[] args) {
// Create a HashMap object called capitalCities and where the key value pair here is
both of String type
HashMap<String, String> capitalCities = new HashMap<String, String>();

// Add keys and values (Country, City)


capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
}
}

Access an Item

To access a value in the HashMap, use the get() method and refer to its
key:

Example

capitalCities.get("England");

Remove an Item

To remove an item, use the remove() method and refer to the key:

Example

capitalCities.remove("England");

To remove all items, use the clear() method:

Example

capitalCities.clear();
HashMap Size

To find out how many items there are, use the size() method:

Example

capitalCities.size();

Loop Through a HashMap

Loop through the items of a HashMap with a for-each loop.

Use the keySet() method if you only want the keys, and

use the values() method if you only want the values:

Example

// Print keys
for (String i : capitalCities.keySet()) { displays just the keys
System.out.println(i);
}

for (String i : capitalCities.values()) { displays only the values


System.out.println(i);
}

// Print keys and values


for (String i : capitalCities.keySet()) { iterates on the key into var i
System.out.println("key: " + i + " value: " + capitalCities.get(i)); gets the value using
the key (i)
}

You can also use other primitive data types in the hashmap aside from string,
just specify the type
Example

Create a HashMap object called people that will store String keys and Integer
values:

// Import the HashMap class


import java.util.HashMap;

public class Main {


public static void main(String[] args) {

// Create a HashMap object called people with string key and integer value
HashMap<String, Integer> people = new HashMap<String, Integer>();

// Add keys and values (Name, Age)


people.put("John", 32);
people.put("Steve", 30);
people.put("Angie", 33);

for (String i : people.keySet()) { iterate on the key of the hashmap into i


System.out.println("key: " + i + " value: " + people.get(i));
}
}
}

Java HashSet

A HashSet is a collection of items where every item is unique, and it is


found in the java.util package:

Example

Create a HashSet object called cars that will store strings:

import java.util.HashSet; // Import the HashSet class


Add Items

The HashSet class has many useful methods. For example, to add items to
it, use the add() method:

Example

// Import the HashSet class


import java.util.HashSet;

public class Main {


public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>(); < create the hashset object
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW"); > although we try to add this value again – it will be not
displayed in the hashset since all items MUST BE UNIQUE
cars.add("Mazda");
System.out.println(cars);
}
}

Check If an Item Exists

To check whether an item exists in a HashSet, use the contains() method:

Example
cars.contains("Mazda");

Remove an Item

To remove an item, use the remove() method:

Example

cars.remove("Volvo");

To remove all items, use the clear() method:

Example

cars.clear();

HashSet Size

To find out how many items there are, use the size() method:

Example

cars.size();

Loop Through a HashSet

Loop through the items of an HashSet with a for-each loop:

Example

for (String i : cars) {


System.out.println(i);
}
You can also use hashset with other primitive values

// Create a HashSet object called numbers


HashSet<Integer> numbers = new HashSet<Integer>();

// Add values to the set


numbers.add(4);
numbers.add(7);
numbers.add(8);

// Show which numbers between 1 and 10 are in the set


for(int i = 1; i <= 10; i++) {
if(numbers.contains(i)) {
System.out.println(i + " was found in the set.");
} else {
System.out.println(i + " was not found in the set.");
}
}

Java Exceptions

When executing Java code, different errors can occur: coding errors
made by the programmer, errors due to wrong input, or other
unforeseeable things.

When an error occurs, Java will normally stop and generate an error
message. The technical term for this is: Java will throw an exception
(throw an error).

Checked exceptions
- the compiler will handle these exceptions usually

Unchecked exceptions
- usually an error (system error like memory or something crazy) OR
run time exceptions

Java try and catch

The try statement allows you to define a block of code to be tested for
errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if


an error occurs in the try block.

- DECLARE that we will throw an exception and let the calling


method deal with it

Method1>method2>main

Depending on what you do, your exception can travel up to the main
class

The try and catch keywords come in pairs: You can have multiple catch
blocks, to deal with various sorts of exceptions

try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
catch(Exception x) {
// Block of code to handle errors
}
catch(Exception y) {
// Block of code to handle errors
}
You may also use syntax like below, to trap multiple EXCEPTIONS, and where

your error / action is the same

catch(Exception | Exception e) { >> separate the exceptions with | symbol


// commonBlock of code to handle errors
}

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {


public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}

The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10


at Main.main(Main.java:4)

If an error occurs, we can use try...catch to catch the error and execute
some code to handle it:

Example

public class Main {


public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");

package examples;

import java.text.NumberFormat;
import java.text.ParseException;

public class ParseTest {


public static void main(String[] args) {
NumberFormat format = NumberFormat.getCurrencyInstance();
String s;
Number num;
s = "$45.67";
// s = "hi mom";

try {
num = format.parse(s); // may generate exception
System.out.println("Float value = " + num.floatValue());
}
catch (ParseException e) {
System.err.println("Invalid string \"" + s + "\"");
}
}
}

Finally

The finally statement lets you execute code, after try...catch, regardless of
the result:

Example

public class Main {


public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}

More on Exceptions

All Exception classes extend from java.lang.Exception, which extends


evenmtually from Throwable class.

Java.text.ParseException > java.lang.Exception > java.lang.Throwable > object

So a lot of methods are inherited down to the Exception class from the
Throwable class, example:

- getMessage()
- printStackTrace()
- toString()

When writing your code around exception, you can do either of 2 things

- use a try/catch block


- throw the exception using throws keyword

Syntax:

Method (x,y) throws exceptionclass1, exceptionclass2 … etc


The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are
many exception types available in Java: ArithmeticException,
FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18


or older, print "Access granted":

1. create an instance of the Exception class –


new ArithmeticException(“your error message”)
2. use the throw keyword to generate the exception

public class Main {


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years
old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}

The output will be:

Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be


at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)

MORE throw examples

package examples;

public class Person {


private String name;

//constructor
public Person(String n) throws InvalidDataException {
if (n == null || n.equals("")) {
throw new InvalidDataException(); - throw error if name is null
}
name = n;
}

public String toString() {


return "Person [name=" + name + "]";
}
}

Using Throws

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18


or older, print "Access granted":

public class Main {

static void checkAge(int age) throws ArithmeticException {


if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years
old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}

More examples:

package examples;

import java.text.NumberFormat;
import java.text.ParseException;

public class ParseDeclare {

public float parseIt(String s) throws ParseException {


NumberFormat format = NumberFormat.getCurrencyInstance();
Number num = format.parse(s); // may generate exception

return num.floatValue();
}

public static void main(String[] args) {


ParseDeclare parser = new ParseDeclare();
String s;
s = "$45.67";
// s = "hi mom";

try {
System.out.println("Float value = " + parser.parseIt(s));
}
catch (ParseException e) {
System.err.println("Invalid string \"" + s + "\"");
}
finally {
System.out.println("Original string was \"" + s + "\"");
}
}
}

throw throws
Used to throw an exception for a Used to indicate what exception
method type may be thrown by a method
Cannot throw multiple exceptions Can declare multiple exceptions
Syntax: Syntax:

 throw is followed by an object  throws is followed by a class


(new type)  and used with the method
 used inside the method signature

Creating your own Exception / custom Exception


- you can do this by creating your own class and extending from the java
Exception class

package examples;

public class InvalidDataException extends Exception {


public String getMessage() {
return "Name must be provided.";
}
}

Java Regular Expressions (REGEX)

What is a Regular Expression?

A regular expression is a sequence of characters that forms a search


pattern. When you search for data in a text, you can use this search
pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated
pattern.

Regular expressions can be used to perform all types of text search and
text replace operations.

Java does not have a built-in Regular Expression class, but we can
import the java.util.regex package to work with regular expressions. The
package includes the following classes:

 Pattern Class - Defines a pattern (to be used in a search)


 Matcher Class - Used to search for the pattern
 PatternSyntaxException Class - Indicates syntax error in a regular
expression pattern

Example

Find out if there are any occurrences of the word "w3schools" in a


sentence:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String[] args) {

Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);

First, the pattern is created using the Pattern.compile() method. The first parameter
indicates which pattern is being searched for and the second parameter has a flag to
indicates that the search should be case-insensitive. The second parameter is optional.

Flags in the compile() method change how the search is performed. Here
are a few of them:
 Pattern.CASE_INSENSITIVE - The case of letters will be ignored when
performing a search.
 Pattern.LITERAL - Special characters in the pattern will not have any

special meaning and will be treated as ordinary characters when


performing a search.
 Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE
flag to also ignore the case of letters outside of the English alphabet

 The first parameter of the Pattern.compile() method is the pattern. It


describes what is being searched for.
 Brackets are used to find a range of characters:

[abc] Find one character from the options between the brackets
[^abc] Find one character NOT between the brackets
[0-9] Find one character from the range 0 to 9

Metacharacters

Metacharacters are characters with a special meaning:

Find a match for any one of the patterns separated by | as in: cat|
|
dog|fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
Find a match at the beginning of a word like this: \bWORD, or at
\b
the end of a word like this: WORD\b
Find the Unicode character specified by the hexadecimal number
\uxxxx
xxxx

Quantifiers
Quantifiers define quantities:

n+ Matches any string that contains at least one n


n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{x} Matches any string that contains a sequence of X n's
n{x,y} Matches any string that contains a sequence of X to Y n's
n{x,} Matches any string that contains a sequence of at least X n's

Matcher matcher = pattern.matcher("Visit W3Schools!");


The matcher() method is used to search for the pattern in a string. It
returns a Matcher object which contains information about the search that
was performed.

boolean matchFound = matcher.find();


The find() method returns true if the pattern was found in the string and
false if it was not found.

if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}

}
// Outputs Match found

Java Threads

Threads allows a program to operate more efficiently by doing multiple


things at the same time.

Threads can be used to perform complicated tasks in the background


without interrupting the main program.
Creating a Thread

There are two ways to create a thread.

1. It can be created by extending the Thread class and overriding its


run() method:

Extend Syntax

public class Main extends Thread {


public void run() {
System.out.println("This code is running in a thread");
}
}

Running Threads

If the class extends the Thread class, the thread can be run by creating an
instance of the class and call its start() method:

Extend Example

public class Main extends Thread {


public static void main(String[] args) {
Main thread = new Main(); -- Create an object of the Main class
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}

2. Another way to create a thread is to implement the Runnable


interface:

Implement Syntax

public class Main implements Runnable {


public void run() {
System.out.println("This code is running in a thread");
}
}

If the class implements the Runnable interface, the thread can be run by
passing an instance of the class to a Thread object's constructor and then
calling the thread's start() method:

Implement Example

public class Main implements Runnable {


public static void main(String[] args) {
Main obj = new Main(); -- Create object of the Main class in obj
Thread thread = new Thread(obj); -- create aan object of Thread using obj
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}

Differences between "extending" and "implementing" Threads

The major difference is that when a class extends the Thread class, you
cannot extend any other class.
By implementing the Runnable interface, it is possible to extend from
another class as well, like: class MyClass extends OtherClass implements Runnable.

Concurrency Problems

Because threads run at the same time as other parts of the program,
there is no way to know in which order the code will run.

When the threads and main program are reading and writing the same
variables, the values are unpredictable. The problems that result from this
are called concurrency problems.

Example

A code example where the value of the variable amount is unpredictable:

public class Main extends Thread {


public static int amount = 0;

public static void main(String[] args) {


Main thread = new Main();
thread.start();
System.out.println(amount);
amount++;
System.out.println(amount);
}

public void run() {


amount++;
}
}

To avoid concurrency problems, it is best to share as few attributes between


threads as possible.
If attributes need to be shared, one possible solution is to use the isAlive()
method of the thread to check whether the thread has finished running before
using any attributes that the thread can change.

Example

Use isAlive() to prevent concurrency problems:

public class Main extends Thread {


public static int amount = 0;

public static void main(String[] args) {


Main thread = new Main();
thread.start();
// Wait for the thread to finish
while(thread.isAlive()) {
System.out.println("Waiting...");
}
// Update amount and print its value
System.out.println("Main: " + amount);
amount++;
System.out.println("Main: " + amount);
}
public void run() {
amount++;
}
}

Java Lambda Expressions

Lambda Expressions were added in Java 8.


A lambda expression is a short block of code which takes in parameters
and returns a value.

Lambda expressions are similar to methods, but they do not need a


name and they can be implemented right in the body of a method.

Syntax

The simplest lambda expression contains a single parameter and an


expression:

parameter -> expression

To use more than one parameter, wrap them in parentheses:

(parameter1, parameter2) -> expression

Expressions are limited. They have to immediately return a value, and


they cannot contain variables, assignments or statements such as if or for.

In order to do more complex operations, a code block can be used with


curly braces. If the lambda expression needs to return a value, then the
code block should have a return statement.

(parameter1, parameter2) -> { code block }

Using Lambda Expressions

Lambda expressions are usually passed as parameters to a function:

Example
Use a lambda expression in the ArrayList's forEach() method to print every
item in the list:

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}

Lambda expressions can be stored in variables if the variable's type is an


interface which has only one method.

The lambda expression should have the same number of parameters and the
same return type as that method.

Java has many of these kinds of interfaces built in, such as the Consumer
interface (found in the java.util package) used by lists.

Example

Use Java's Consumer interface to store a lambda expression in a variable:

import java.util.ArrayList;
import java.util.function.Consumer;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
Consumer<Integer> method = (n) -> { System.out.println(n); };
numbers.forEach( method );
}
}

Example

Create a method which takes a lambda expression as a parameter:

interface StringFunction {
String run(String str);
}

public class Main {


public static void main(String[] args) {
StringFunction exclaim = (s) -> s + "!";
StringFunction ask = (s) -> s + "?";
printFormatted("Hello", exclaim);
printFormatted("Hello", ask);
}
public static void printFormatted(String str, StringFunction format) {
String result = format.run(str);
System.out.println(result);
}
}

Working with Streams – I/O


- Includes working with files
- Socket connections
- Reading / writing database objects
- Serialisation of objects
Most methods in java IO classes use / throws java.io.IOException

Two categories of STREAMS


BYTE stream
- We will typically use classes using Inputstream / Outputstream
- Data is managed in 8 bit byte chunks
- Integers written with outputstreams is written as 4 byte (not readable
text)
- Typically dealing with BINARY data with Streams

CHARACTER stream
- Data is managed as 16bit Unicode characters
- We will typically use reader/writer classes like fileReader / fileWriter
- Int is written as a sequence of chars – readable format

For every input stream - we should have a corresponding READER class


For every output stream – we should have a WRITER class

Converting between BYTE/CHARACTER streams

Example:

package examples;

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class Person {


private String name;
private String favoriteFood;
private int age;

//constructor
public Person(String n, String f, int a) {
name = n;
favoriteFood = f;
age = a;
}
//to string method
@Override
public String toString() {
return name + " is " + age + " and likes " + favoriteFood + ".";
}

public static void main(String[] args) {


String firstName = null;
String food = null;
int age = 0;

try {
InputStreamReader conv = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(conv);

System.out.print("What is your first name? ");


firstName = buf.readLine(); - a method to prompt/read in data
System.out.print("How old are you, " + firstName + "? ");
age = Integer.parseInt(buf.readLine());
System.out.print("And what is your favorite food? ");
food = buf.readLine();
buf.close(); - close the stream / buffer
}
catch (IOException e) {
System.err.println(e.getMessage());
}

Person p = new Person(firstName, food, age);


System.out.println(p);
}
}

Example – reading a file

package examples;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadIt {


public static void main(String[] args) {
BufferedReader bufIn = null;
try {
bufIn = new BufferedReader(new FileReader("input.txt"));

String line;
while ((line = bufIn.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
System.err.println(e);
}
finally {
if (bufIn != null) {
try {
bufIn.close();
}
catch (IOException e) {
System.err.println(e);
}
}
}
}
}

Java File Handling

The File class from the java.io package, allows us to work with files.

To use the File class, create an object of the class, and specify the filename
or directory name:

Example

import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename and create new File Object

The File class has many useful methods for creating and getting information
about files. For example:

canRead() Boolean Tests whether the file is readable or not


canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

Get File Information

To get more information about a file, use any of the File methods:

Example

import java.io.File; // Import the File class

public class GetFileInfo {


public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}

Create a File

To create a file in Java, you can use the createNewFile() method. This
method returns a boolean value: true if the file was successfully created,
and false if the file already exists.
Note that the method is enclosed in a try...catch block. This is necessary
because it throws an IOException if an error occurs (if the file cannot be
created for some reason):

Example

import java.io.File; // Import the File class


import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

The output will be:

File created: filename.txt

To create a file in a specific directory (requires permission), specify the


path of the file and

Use double backslashes to escape the "\" character (for Windows). On Mac
and Linux you can just write the path, like: /Users/name/filename.txt

Example

File myObj = new File("C:\\Users\\MyName\\filename.txt");


Write To a File

In the following example, we use the FileWriter class together with its
write() method to write some text to the file we created in the example
above. Note that when you are done writing to the file, you should close
it with the close() method:

Example

import java.io.FileWriter; // Import the FileWriter class


import java.io.IOException; // Import the IOException class to handle errors

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

The output will be:

Successfully wrote to the file.

Notes:
- Use fileOutputStream/fileInputStream to read/write out binary
files
- Generally good for reading / dealing with byte arrays
- Use fileWriter/fileReader to read/write out text / char files

DataInputStream & dataOutputStream

Used to read/write binary files OR send/receive binary data through a socket

You can convert primitive data types into sequences of bytes

You would typically use these methods / classes together to read/write, and the
order of read/write is also important, else you get unpredictable data

Examples:

package examples;

import java.io.DataInputStream;

import java.io.FileInputStream;

import java.io.IOException;

public class ReadBinary {

public static void main(String[] args) {

try {

FileInputStream fin = new FileInputStream("test.dat"); - file object

DataInputStream din = new DataInputStream(fin); -


System.out.println(din.readInt());

System.out.println(din.readDouble());

System.out.println(din.readBoolean());

System.out.println(din.readChar());

System.out.println(din.readUTF());

din.close();

catch (IOException e) {

System.err.println(e.getMessage());

package examples;

import java.io.DataOutputStream;

import java.io.FileOutputStream;

import java.io.IOException;
public class WriteBinary {

public static void main(String[] args) {

try {

FileOutputStream fout = new FileOutputStream("test.dat");

DataOutputStream dout = new DataOutputStream(fout);

dout.writeInt(12);

dout.writeDouble(12.5);

dout.writeBoolean(false);

dout.writeChar('a');

dout.writeUTF("A String");

dout.close();

catch (IOException e) {

System.err.println(e.getMessage());

}
Using Filewriter & PrintWiter on text files

& FileReader / BufferedReader on text files

Writing data using FileWriter/PrintWriter

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

public class WriteText {

public static void main(String[] args) {

try {

FileWriter fw = new FileWriter("test.txt"); . file object

PrintWriter pw = new PrintWriter(fw); . writer object using fw

pw.println(12);

pw.printf("%1$.2f %n", 12.5);

pw.println(false); --- these lines are actually writing to the


file test.txt

pw.println('a');

pw.println("A String");
pw.close();

catch (IOException e) {

System.err.println(e.getMessage());

Reading data using FileReader/BufferedReader

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class ReadText {

public static void main(String[] args) {

try {

FileReader fr = new FileReader("test.txt"); - file object

BufferedReader buf = new BufferedReader(fr); -buffered reader obj

String line; - declare string line

while ((line = buf.readLine()) != null) { > reads in a line at a time


System.out.println(line);

buf.close();

catch (IOException e) {

System.err.println(e.getMessage());

Reading / Writing OBJECTS

ObjectInputstream & ObjectOutputstream

Write the object

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

public class WriteBook {

public static void main(String[] args) {

Book b = new Book("Animal Farm", "George Orwell", 1945, 144); //book object
try {

FileOutputStream fout = new FileOutputStream("Book.ser"); //FileOutputstream object


for the file

ObjectOutputStream out = new ObjectOutputStream(fout); // ObjectOutputstream


to write the object

out.writeObject(b); // write the object to the file

out.close();

catch (IOException e) {

System.err.println(e.getMessage());

READ the object

import java.io.FileInputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

public class ReadBook {

public static void main(String[] args) {

Object o = null;
// initialise var for the object to read in as type Object

try {

FileInputStream fin = new FileInputStream("Book.ser"); // file object for the file we


want to read
ObjectInputStream in = new ObjectInputStream(fin); // ObjectInputstream
object to read the file

try {

o = in.readObject(); //
readObject method to read the object from file

catch (ClassNotFoundException e) {

System.err.println(e.getMessage());

in.close(); > ALWAYS REMEMBER TO CLOSE THE STREAM!!! TYPICALLY CLOSE

YOUR STREAM IN A FINALLY block

catch (IOException e) {

System.err.println(e.getMessage());

System.out.println(o);

AUTOCLOSE

We can implement the AutoClose feature for our open stream objects

package examples;

import java.io.BufferedReader;

import java.io.FileReader;
import java.io.IOException;

public class ReadIt2 {

public static void main(String[] args) {

try (BufferedReader bufIn =

new BufferedReader(new FileReader("input.txt"))) {

Some syntax diff here where we wrap the TRY block in ( )

Close is then automatically implemented if your class supports AutoClose

String line;

while ((line = bufIn.readLine()) != null) {

System.out.println(line);

catch (IOException e) {

System.err.println(e);

}
In order to write out an object, it must be serialised in the class. See the Book
class below, which we read / write in the above examples

Note – the class has no methods!

See below Book class.

import java.io.Serializable;

public class Book implements Serializable {


private String title;
private String author;
private int yearPublished;
private int numPages;

public Book(String t, String a, int y, int n) {


title = t;
author = a;
yearPublished = y;
numPages = n;
}

@Override
public String toString() {
return "\"" + title + "\" by " + author + ", published "
+ yearPublished + ", " + numPages + " pages.";
}

Examples using various types of writes (binary / object / text)

package solutions;

import java.io.DataOutputStream;

import java.io.FileOutputStream;
import java.io.FileWriter;

import java.io.IOException;

import java.io.ObjectOutputStream;

import java.io.PrintWriter;

import java.io.Serializable;

public class Order implements Serializable {

private int custId;

private String name;

//constructor

public Order(int id, String n) {

custId = id;

name = n;

//method – write text

public void writeText(String fn) {

try (PrintWriter pout =

new PrintWriter(new FileWriter(fn))) {

pout.print("ID: ");

pout.println(custId);

pout.print("Name: ");
pout.print(name);

catch (IOException e) {

System.err.println(e);

//method – write binary

public void writeBinary(String fn) {

try (DataOutputStream doutput =

new DataOutputStream(new FileOutputStream(fn))) {

doutput.writeInt(custId);

doutput.writeUTF(name);

doutput.close();

catch (IOException e) {

System.err.println(e);

//method – write object

public void writeObj(String fn) {

try (ObjectOutputStream out =


new ObjectOutputStream(new FileOutputStream(fn))) {

out.writeObject(this);

out.close();

catch (IOException e) {

System.err.println(e);

public static void main(String[] args) {

//declare the object

Order o = new Order(23, "Bob Dobbs");

//call the methods passing in the filename

o.writeText("order.txt");

o.writeBinary("order.dat");

o.writeObj("order.ser");

Using indexOf – check whether a certain text exists in string

import java.io.BufferedReader;

import java.io.FileReader;
import java.io.IOException;

public class Search {

public static void main(String[] args) {

try (BufferedReader bufin =

new BufferedReader(new FileReader("employee.txt"))) {

String line;

while ((line = bufin.readLine()) != null) {

if (line.indexOf("manager") >= 0) {

// matched

System.out.println(line);

catch (IOException e) {

System.err.println(e);

}
Read a File

we use the Scanner class to read the contents of the text file we created in
the previous chapter:

Example

import java.io.File; // Import the File class


import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt"); --new File object – opens the file
Scanner myReader = new Scanner(myObj); -- new Scanner object
while (myReader.hasNextLine()) { -- check if file has data / next line
String data = myReader.nextLine(); -- read in the next data line
System.out.println(data);
}
myReader.close(); -- close the file
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

The output will be:

Files in Java might be tricky, but it is fun enough!

Note: There are many available classes in the Java API that can be used to read
and write files in Java:
FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter,
FileOutputStream, etc. Which one to use depends on the Java version you're
working with and whether you need to read bytes or characters, and the size of
the file/lines etc.

Delete a File

To delete a file in Java, use the delete() method:

Example

import java.io.File; // Import the File class

public class DeleteFile {


public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}

Delete a Folder

You can also delete a folder. However, it must be empty:

Example

import java.io.File;

public class DeleteFolder {


public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}

Count Number of Words in a String

You can easily count the number of words in a string with the following
example using the (split) and length method:

Example

String words = "One Two Three Four";


int countWords = words.split("\\s").length;
System.out.println(countWords);

Reverse a String

You can easily reverse a string by characters with the following example
using for loop and string chatAt() method:

Example

String originalStr = "Hello";


String reversedStr = "";

for (int i = 0; i < originalStr.length(); i++) {


reversedStr = originalStr.charAt(i) + reversedStr;
}

Calculate the Sum of an Array

Get the sum of array elements:

Example
int[] myArray = {1, 5, 10, 25};
int sum = 0;
int i;

// Loop through the array elements and store the sum in the sum variable
for (i = 0; i < myArray.length; i++) {
sum += myArray[i];
}

Find a string within a string

public class Main {

public static void main(String[] args) {

String txt = "Please locate where 'locate' occurs!";

System.out.println(txt.indexOf("locate"));

Check Whether a Number is Even or Odd

Find out if a number is even or odd:

Example

int number = 5;

// Find out if the number above is even or odd


if (number % 2 == 0) { --using modulus/remainder when diving by 2
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}

Java Reserved Keywords

Java has a set of keywords that are reserved words that cannot be used
as variables, methods, classes, or any other identifiers:

A non-access modifier. Used for classes and methods: An abstract

class cannot be used to create objects (to access it, it must be

abstract inherited from another class). An abstract method can only be used

in an abstract class, and it does not have a body. The body is

provided by the subclass (inherited from)

assert For debugging

boolean A data type that can only store true and false values

break Breaks out of a loop or a switch block

byte A data type that can store whole numbers from -128 and 127

case Marks a block of code in switch statements

catch Catches exceptions generated by try statements


char A data type that is used to store a single character

class Defines a class

continue Continues to the next iteration of a loop

const Defines a constant. Not in use - use final instead

default Specifies the default block of code in a switch statement

do Used together with while to create a do-while loop

A data type that can store whole numbers from 1.7e−308 to


double
1.7e+308

else Used in conditional statements

enum Declares an enumerated (unchangeable) type

exports Exports a package with a module. New in Java 9

Extends a class (indicates that a class is inherited from another


extends
class)

A non-access modifier used for classes, attributes and methods,

final which makes them non-changeable (impossible to inherit or

override)

Used with exceptions, a block of code that will be executed no


finally
matter if there is an exception or not

A data type that can store whole numbers from 3.4e−038 to


float
3.4e+038

for Create a for loop

goto Not in use, and has no function

if Makes a conditional statement


implements Implements an interface

import Used to import a package, class or interface

Checks whether an object is an instance of a specific class or an


instanceof
interface

A data type that can store whole numbers from -2147483648 to


int
2147483647

Used to declare a special type of class that only contains abstract


interface
methods

A data type that can store whole numbers from -


long
9223372036854775808 to 9223372036854775808

module Declares a module. New in Java 9

Specifies that a method is not implemented in the same Java


native
source file (but in another language)

new Creates new objects

package Declares a package

An access modifier used for attributes, methods and constructors,


private
making them only accessible within the declared class

An access modifier used for attributes, methods and constructors,


protected
making them accessible in the same package and subclasses

An access modifier used for classes, attributes, methods and


public
constructors, making them accessible by any other class

requires Specifies required libraries inside a module. New in Java 9

Finished the execution of a method, and can be used to return a


return
value from a method
A data type that can store whole numbers from -32768 to
short
32767

A non-access modifier used for methods and attributes. Static

static methods/attributes can be accessed without creating an object of a

class

strictfp Restrict the precision and rounding of floating point calculations

super Refers to superclass (parent) objects

switch Selects one of many code blocks to be executed

A non-access modifier, which specifies that methods can only be


synchronized
accessed by one thread at a time

this Refers to the current object in a method or constructor

throw Creates a custom error

throws Indicates what exceptions may be thrown by a method

A non-accesss modifier, which specifies that an attribute is not


transient
part of an object's persistent state

try Creates a try...catch statement

var Declares a variable. New in Java 10

void Specifies that a method should not have a return value

Indicates that an attribute is not cached thread-locally, and is


volatile
always read from the "main memory"

while Creates a while loop

Note: true, false, and null are not keywords, but they are literals and
reserved words that cannot be used as identifiers.
Java String Methods

The String class has a set of built-in methods that you can use on strings.

Returns the character at the specified index


charAt() char
(position)

Returns the Unicode of the character at the


codePointAt() int
specified index

Returns the Unicode of the character before the


codePointBefore() int
specified index

Returns the number of Unicode values found in


codePointCount() int
a string.

compareTo() Compares two strings lexicographically int

Compares two strings lexicographically, ignoring


compareToIgnoreCase() int
case differences

concat() Appends a string to the end of another string String

Checks whether a string contains a sequence of


contains() boolean
characters

Checks whether a string contains the exact same

contentEquals() sequence of characters of the specified boolean

CharSequence or StringBuffer

Returns a String that represents the characters


copyValueOf() String
of the character array

endsWith() Checks whether a string ends with the specified boolean


character(s)

Compares two strings. Returns true if the


equals() boolean
strings are equal, and false if not

Compares two strings, ignoring case


equalsIgnoreCase() boolean
considerations

Returns a formatted string using the specified


format() String
locale, format string, and arguments

Encodes this String into a sequence of bytes

getBytes() using the named charset, storing the result into byte[]

a new byte array

Copies characters from a string to an array of


getChars() void
chars

hashCode() Returns the hash code of a string int

Returns the position of the first found


indexOf() int
occurrence of specified characters in a string

Returns the canonical representation for the


intern() String
string object

isEmpty() Checks whether a string is empty or not boolean

Returns the position of the last found occurrence


lastIndexOf() int
of specified characters in a string

length() Returns the length of a specified string int

Searches a string for a match against a regular


matches() boolean
expression, and returns the matches

offsetByCodePoints() Returns the index within this String that is int


offset from the given index by codePointOffset
code points

regionMatches() Tests if two string regions are equal boolean

Searches a string for a specified value, and

replace() returns a new string where the specified values String

are replaced

Replaces the first occurrence of a substring that

replaceFirst() matches the given regular expression with the String

given replacement

Replaces each substring of this string that

replaceAll() matches the given regular expression with the String

given replacement

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with specified ch

Returns a new character sequence that is a


subSequence() CharSequence
subsequence of this sequence

Returns a new string which is the substring of a


substring() String
specified string

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String

Returns the string representation of the specified


valueOf() String
value
Java Math Methods

A list of all Math methods can be found in the table below:

abs(x) Returns the absolute value of x double|float|int|long

acos(x) Returns the arccosine of x, in radians double

asin(x) Returns the arcsine of x, in radians double

Returns the arctangent of x as a numeric


atan(x) double
value between -PI/2 and PI/2 radians

Returns the angle theta from the

atan2(y,x) conversion of rectangular coordinates (x, double

y) to polar coordinates (r, theta).

cbrt(x) Returns the cube root of x double

Returns the value of x rounded up to its


ceil(x) double
nearest integer

Returns the first floating point x with the


copySign(x, y) double
sign of the second floating point y

cos(x) Returns the cosine of x (x is in radians) double

Returns the hyperbolic cosine of a double


cosh(x) double
value

x
exp(x) Returns the value of E double

x
expm1(x) Returns e -1 double

Returns the value of x rounded down to


floor(x) double
its nearest integer

getExponent(x) Returns the unbiased exponent used in x int


2 2
Returns sqrt(x +y ) without intermediate
hypot(x, y) double
overflow or underflow

Computes the remainder operation on x


IEEEremainder(x,
and y as prescribed by the IEEE 754 double
y)
standard

Returns the natural logarithm (base E) of


log(x) double
x

log10(x) Returns the base 10 logarithm of x double

Returns the natural logarithm (base E) of


log1p(x) double
the sum of x and 1

Returns the number with the highest


max(x, y) double|float|int|long
value

Returns the number with the lowest


min(x, y) double|float|int|long
value

Returns the floating point number


nextAfter(x, y) double|float
adjacent to x in the direction of y

Returns the floating point value adjacent


nextUp(x) double|float
to x in the direction of positive infinity

pow(x, y) Returns the value of x to the power of y double

Returns a random number between 0


random() double
and 1

Returns the value of x rounded to its


round(x) int
nearest integer

Returns the double value that is closest to


rint(x) double
x and equal to a mathematical integer
signum(x) Returns the sign of x double

sin(x) Returns the sine of x (x is in radians) double

Returns the hyperbolic sine of a double


sinh(x) double
value

sqrt(x) Returns the square root of x double

tan(x) Returns the tangent of an angle double

Returns the hyperbolic tangent of a


tanh(x) double
double value

Converts an angle measured in radians to

toDegrees(x) an approx. equivalent angle measured in double

degrees

Converts an angle measured in degrees to


toRadians(x) double
an approx. angle measured in radians

Returns the size of the unit of least


ulp(x) double|float
precision (ulp) of x

Note: All Math methods are static.

https://docs.oracle.com/en/java/javase/20/docs/api/

index.html

https://docs.oracle.com/javase/tutorial/

https://docs.oracle.com/javaee/7/tutorial/

You might also like