JAVA Course Notes
JAVA Course Notes
24-07-2023 – RESTART!!!
What is java and what d we need to run it / use it / create programs etc
Look at the following illustration to see the difference between class and objects:
- 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 /
- A java VM (JVM) – An interpreter that can run your java code on any
platform
- Compiler (javac)
- Package name – must be the same as the folder where you storing the
- In our case
- C:\IntroToJava\ch02\examples
- The name of our class file in the package folder must be same as the
- In our case
public class hello { – so our file name within the examples directory
1. So we first write the code – using some sort of editor, following above
rules:
package examples;
{
public static void main(String[] args)
System.out.print("Hello, ");
if (args.length == 0)
System.out.println("World!");
else
System.out.println(args[0] + "!")
It is preferred that you indent / line up your curly braces to make the
You can optionally use the curly braces in the ‘if’ statement as shown
above
the .java package resides. In this case the cho2 folder path is the correct
location
javac examples\Hello.java
The class file is also then found together with the Hello.java code in the
4. Run the program using java command from one folder above the package
program. Also note the ‘/’ instead of backslash. Can also use a dot
java examples.Hello
Since we have some code to deal with ‘args’ being passed in the following can
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
- /lib – contains the java Archive (JAR) files used by the tools – contains
First exercise : Create a new class called myname, compile and run 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:
javap –c <directory where your .class file lives>/name of the class file only
New section:
Using ECLIPSE - ECLIPSE is an INTEGRATED DEVELOPMENT ENVIRONMENT
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
storage location where Eclipse will keep all artefacts / programs / code etc
menu
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
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
The IDE will try to check your code and syntax as you type
When creating a new class you can add the main method by default by just
To execute your program hit the Run button on the menu bar. It will execute
- 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
Specify the source location and the target Eclipse workspace directory
Else just copy the .java source into the workspace target area using Windows
You can also import other java Projects into Eclipse in a similar way by pointing
8 Primitive data types – these are built into the java language
- Byte
- Short
- Long
- Int (default = 0)
- Float
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
To declare a variable :
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
final when used to declare a variable – you cannot change this variable value
afterward
Conventions:
- myName = ‘kani’
syntax
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
If you use the new String method, then java creates a new memory space for
that variable
false
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
If you assign 2 diff string vars with the same value, java optimises by creating
ARRAYS
declaration
When using arrays, you must define the size of the array initially?
String [ ] name = new String[10]; //here we initialise and create the name array
Int odds[] = {1, 2, 3, 4,5}; this inits and creates a new var odds with 5
elements
name[0] = ‘Kani”
name[1] = “Caelen”
name[3] = ‘JACK”
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
String bookinfo[ ] [ ] = {
bookinfo[0][1] = ‘Flanagan’
bookinfo[1][1] = ‘Horstmann’
bookinfo[2][1] = ‘Eckel’
These are defined as classes, as apposed to the 8 Primitive data types (Boolean,
Java comes with many predefined class types of this nature already
Java references objects, like through a pointer concept and are not stored in the
= Assignment operator x = 5;
Arithmetic operators
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
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), !
Logical Operators
x <12 || y > 6
- Both OR/AND use short circuit processing. If the left expression yields a
b=1
n += 50 …so n = n + 50
n *= 10 …so n = n * 10
Conditional operator
Syntax
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;
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
Java will convert automatically, if you’re mixing integer types to the larger int
type
However, if you try to go the opposite way, you will get compile error
System.out.println(myDouble);
System.out.println(myInt);
}
public class Main {
int myInt = 9;
System.out.println(myInt);
System.out.println(myDouble);
CONTROL FLOW
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
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");
}
}
else
// babies and toddlers
System.out.println("Get into movies free.");
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
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
Statement 1 is executed (one time) before the execution of the code block.
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
do something;
step3 – do something
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
String bookinfo[ ] [ ] = {
bookinfo[0][1] = ‘Flanagan’
bookinfo[1][1] = ‘Horstmann’
bookinfo[2][1] = ‘Eckel’
Here are some ways to loop through this matrix. Below we see a nested loop
System.out.println(myNumbers[1][2]);
System.out.println(myNumbers[i][j]);
}
ENHANCED FOR EACH /LOOP SYNTAX to loop through an ARRAY
Syntax
Example
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
int odds[] = { 1, 3, 5, 7, 9 };
String bookInfo[][] = {
{ "Java In a Nutshell", "Flanagan" },
{ "Core Java", "Horstmann" },
{ "Thinking in Java", "Eckel" } };
Use this to cause your for loop to jump to the next iteration
BREAK statement
JAVA ARRAYS
String[] cars;
You must always have a main method. This is used to start you program
Calling methods
Per above example println is a method, and we pass an argument within the ()
}
public static void main(String[] args) {
myMethod();
Above, the method is sqrt, which takes arguments (2,0), and returns a value to
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
public class Main {
return 5 + x;
System.out.println(myMethod(3));
} else {
}
}
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
System.out.println(result);
if (k > 0) {
} else {
return 0;
}
}
- Specify the data type that your method returns e.g. float
- 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
- If the method DOES NOT return a value, then declare its data type as
Usually with a void method, you do not need to put the return
GOSUB
MORE ON METHODS
different parameters / signatures), system will choose the most apt one
SCOPE
In Eclipse, it helps you show where code bolck starts/ends. Eg. Main
P – Polymorphism
I – Inheritance
E – Encapsulation
Features of OOP
- Maintainability
functions
- Abstraction – one doesn’t have to understand the innards of a method /
piece of code
- Objects
Fields / nouns
Methods / verbs
CLASS
instances (objects).
– E.g. Monitor Class – we want all monitors to be 22cms in size. Then all
date
Month
The class FIELDS
Day
year
setDay()
getDay()
getYear()
thedate Date where Date is the datatype
Month – 03
Day = 02
Year = 1967
OBJECT
- 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
Fields
- STATIC
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
Methods
Methods provide the functionality of the object – what the object can do
You can have static (can only access static class fields) / instance methods
An example to demonstrate the differences between static and
public methods:
You will often see Java programs that have either static or public
attributes and methods.
// Public method
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
- Hides fields and actual code, sitting behind your public methods
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
- - controls who has access to your fields / methods inside the class
o Private (-)
Only methods inside the class have access to the data / methods
Classes that inherit this class (sub classes) have access to the data /
methods
foundation
Superclass/baseclass/Generalised class
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
class, it may work to use inheritance from appliance class in this case
Remember:
to a subclass
In this example:
- Employee is the sub class and inherits from / extends the Person class
You can only implement a SINGLE inheritance / only one superclass parent
Lets see an example:
Notes:
- We’ve added 2 more fields ‘title’ and ‘salary’ and a getSalary method
Example:
The below may cause problems though if we start with a Person object and try
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
primitives)
Type casting is when you assign a value of one primitive data type to
another type.
Widening Casting
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting
Example
Here, we have a method with the same name, and same parameters
- 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)
If you have overriding methods in your class / sub class, java decides at run
We talked about this earlier in this training, See where the object started its
life.
Below:
as a Person object
etc)
In a sub class method, you can refer to the superclass using super even if you
Per below example, we refer to the getName() method from the PERSON class
Return super.getName()
You would normally need this when you want to use an overridden method and
- You can also invoke a superclass constructor from your subclass if you
choose this
Above, we invoke the PERSON constructor from the Employee
constructor
- 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 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
With polymorphism:
If you invoke Date.display object – the display() from the Date Object is
executed
TimeStampZone is executed
datatype of dates
BEST PRACTICES
Some conventions
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
Dog spot = new Dog() > here we create a new object of the Dog class assigning
it to variable spot
- We create a new Customer2 object using the new keyword and assign
o cust.firstname = “Jim”;
cust.lastname = “Stewart”;
- by now, the object cust has values stored for firstname / lastname
cust.addAccount(250.0)
- Program execution steps into the addAccount method within
Customer2() class
- 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
CLASS fields
- Fields declared as static are class fields and belong to the class where it
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
Final fields
What is a CONSTRUCTOR?
- Has the same name as the class and lives inside the class you are calling
- You can call one constructor from another by using the this keyword and
Here is an example of the constructor, which basically inits / sets values to your
vars
Example
//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);
}
}
ACCESS MODIFIERS
- You can then use get and set methods to access / set the value or vars
Use Eclipse to insert the get / set methods + constructors if you want
The code is only accessible in the same package. This is used when you
default
don't specify a modifier
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
static Attributes and methods belongs to the class, rather than an object
methods. The method does not have a body, for example abstract
abstract void run();. The body is provided by the subclass (inherited from ). You
%<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 %%.
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 .precision (works usually with floating point numbers) specifies the
maximum number of characters to output.
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);
Using String.format
memory
class
StringBuilder b = new StringBuilder(“Java”): b.append(“ programming”)
exhausted, java will create another mem space of 100, in this example
var.append(“the string”)
strings – this method is slower the StringBuilder, but works the same
Above we can invoke 2 methods on the emp object using the below syntax:
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
However, if your data types / objects reference different objects, you will get
a false result
- 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 (width != other.width)
- return false;
-
- return true;
- }
Use the hashCode() method which returns the same int whenever 2 objects
Java uses the 8 primitive data types AND reference types(objects and all
other types)
- Wrapper classes
Use the autoboxing feature to convert between wrapper object and primitive
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
Example
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
toString()
Example
Use this when you have a var who’s content is a limited set of choices (like a list
of choices)
Switch (mycolourvar) {
Case RED;
Do something …
File/new/enum
enum Level {
LOW,
MEDIUM,
HIGH
}
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
System.out.println(myVar);
GARBAGE COLLECTION
Note:
- The JVM uses garbage collection to reclaim mem that is not used
anymore
ABSTRACT
// 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");
}
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
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
like inherited) by another class with the implements keyword (instead of extends).
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
package examples;
package examples;
interface FirstInterface {
interface SecondInterface {
System.out.println("Some text..");
class Main {
myObj.myMethod();
myObj.myOtherMethod();
If you’re implementing an interface class, then you have to write code for the interface
package examples;
sensor.motionDetected();
System.out.println(sensor);
sensor.timeout();
System.out.println(sensor);
}
}
Java Iterator
Using an Iterator
The iterator() method can be used to get an Iterator for any collection:
// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
ARRAYLIST
The ArrayList class is a resizable array, which can be found in the java.util
package.
Example
import java.util.ArrayList;
System.out.println(cars);
}
}
import java.util.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
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
import java.util.ArrayList;
COLLECTIONS:
You can store items in a collections as type Object
package examples;
package examples;
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 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.
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.
LinkedList Methods
Java Packages & API
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 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 java.util.Scanner;
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;
- 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:
Example
└── root
└── mypack
└── MyPackageClass.java
- 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 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.
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;
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;
If you try to access a private inner class from an outside class, an error occurs:
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;
System.out.println(myInner.y);
}
}
// Outputs 5
You can access attribs and methods of the outclass from the Inner Class
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;
}
}
}
System.out.println(myInner.myInnerMethod());
}
}
// Outputs 10
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:
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
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
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
package examples;
public class CD {
private int id;
private String artist;
private String title;
@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
package examples;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
//import java.util.LinkedHashSet;
cdCollection.add(cd1);
cdCollection.add(cd2);
cdCollection.add(cd3); // add the cd objects
cdCollection.add(cd4);
LIST
Examples:
package examples;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
cdCollection.add(cd1);
cdCollection.add(cd2); // add items to the Arraylist
cdCollection.add(0, cd3); // adding this element at index (0)
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
Uses FIFO
Allows for null elements, but AVOID using nulls, as null is generally
used to indicate an empty list
import java.util.LinkedList;
//
cdCollection.offer(cd2);
cdCollection.offer(cd3);
System.out.println("Using peek():");
System.out.println("Using poll():");
o PriorityQueue
Has the ability to sort elements in the queue – see below example
Example:
import java.util.Queue;
myQueue.offer("C");
myQueue.offer("B");
myQueue.offer("A");
System.out.println(myQueue.poll());
A
B
C
D
MAP
HashMap
LinkedHashMap
TreeMap
Example:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
//import java.util.LinkedHashMap;
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();
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:
The HashMap class has many useful methods. For example, to add items to
it, use the put() method:
Example
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");
Example
capitalCities.clear();
HashMap Size
To find out how many items there are, use the size() method:
Example
capitalCities.size();
Use the keySet() method if you only want the keys, and
Example
// Print keys
for (String i : capitalCities.keySet()) { displays just the keys
System.out.println(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:
// Create a HashMap object called people with string key and integer value
HashMap<String, Integer> people = new HashMap<String, Integer>();
Java HashSet
Example
The HashSet class has many useful methods. For example, to add items to
it, use the add() method:
Example
Example
cars.contains("Mazda");
Remove an Item
Example
cars.remove("Volvo");
Example
cars.clear();
HashSet Size
To find out how many items there are, use the size() method:
Example
cars.size();
Example
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
The try statement allows you to define a block of code to be tested for
errors while it is being executed.
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
If an error occurs, we can use try...catch to catch the error and execute
some code to handle it:
Example
package examples;
import java.text.NumberFormat;
import java.text.ParseException;
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
More on Exceptions
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
Syntax:
The throw statement is used together with an exception type. There are
many exception types available in Java: ArithmeticException,
FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:
Example
package examples;
//constructor
public Person(String n) throws InvalidDataException {
if (n == null || n.equals("")) {
throw new InvalidDataException(); - throw error if name is null
}
name = n;
}
Using Throws
Example
More examples:
package examples;
import java.text.NumberFormat;
import java.text.ParseException;
return num.floatValue();
}
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:
package examples;
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:
Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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
[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
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:
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
// Outputs Match found
Java Threads
Extend Syntax
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
Implement Syntax
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
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
Example
Syntax
Example
Use a lambda expression in the ArrayList's forEach() method to print every
item in the list:
import java.util.ArrayList;
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
import java.util.ArrayList;
import java.util.function.Consumer;
Example
interface StringFunction {
String run(String str);
}
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
Example:
package examples;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
//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 + ".";
}
try {
InputStreamReader conv = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(conv);
package examples;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
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);
}
}
}
}
}
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
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:
To get more information about a file, use any of the File methods:
Example
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
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
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
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
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;
try {
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 {
try {
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
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
try {
pw.println(12);
pw.println('a');
pw.println("A String");
pw.close();
catch (IOException e) {
System.err.println(e.getMessage());
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
try {
buf.close();
catch (IOException e) {
System.err.println(e.getMessage());
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
Book b = new Book("Animal Farm", "George Orwell", 1945, 144); //book object
try {
out.close();
catch (IOException e) {
System.err.println(e.getMessage());
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
Object o = null;
// initialise var for the object to read in as type Object
try {
try {
o = in.readObject(); //
readObject method to read the object from file
catch (ClassNotFoundException e) {
System.err.println(e.getMessage());
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;
String line;
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
import java.io.Serializable;
@Override
public String toString() {
return "\"" + title + "\" by " + author + ", published "
+ yearPublished + ", " + numPages + " pages.";
}
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;
//constructor
custId = id;
name = n;
pout.print("ID: ");
pout.println(custId);
pout.print("Name: ");
pout.print(name);
catch (IOException e) {
System.err.println(e);
doutput.writeInt(custId);
doutput.writeUTF(name);
doutput.close();
catch (IOException e) {
System.err.println(e);
out.writeObject(this);
out.close();
catch (IOException e) {
System.err.println(e);
o.writeText("order.txt");
o.writeBinary("order.dat");
o.writeObj("order.ser");
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
String line;
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
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
Example
Delete a Folder
Example
import java.io.File;
You can easily count the number of words in a string with the following
example using the (split) and length method:
Example
Reverse a String
You can easily reverse a string by characters with the following example
using for loop and string chatAt() method:
Example
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];
}
System.out.println(txt.indexOf("locate"));
Example
int number = 5;
Java has a set of keywords that are reserved words that cannot be used
as variables, methods, classes, or any other identifiers:
abstract inherited from another class). An abstract method can only be used
boolean A data type that can only store true and false values
byte A data type that can store whole numbers from -128 and 127
override)
class
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.
CharSequence or StringBuffer
getBytes() using the named charset, storing the result into byte[]
are replaced
given replacement
given replacement
x
exp(x) Returns the value of E double
x
expm1(x) Returns e -1 double
degrees
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/