0% found this document useful (0 votes)
2 views92 pages

Java Essentials

The document outlines Java Essentials, detailing the author's career and community involvement, including roles at New Relic and Deutsche Bank, and contributions to the Java community. It covers Java installation, basic programming concepts, data types, arithmetic expressions, decision-making, and object-oriented programming principles. Additionally, it introduces methods, classes, and constructors, emphasizing Java's syntax and structure for effective programming.

Uploaded by

idiotmukul3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views92 pages

Java Essentials

The document outlines Java Essentials, detailing the author's career and community involvement, including roles at New Relic and Deutsche Bank, and contributions to the Java community. It covers Java installation, basic programming concepts, data types, arithmetic expressions, decision-making, and object-oriented programming principles. Additionally, it introduces methods, classes, and constructors, emphasizing Java's syntax and structure for effective programming.

Uploaded by

idiotmukul3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

Java Essentials

About Me - Career
• New Relic, Principal Engineer

• jClarity, Co-founder
• Sold to Microsoft

• Deutsche Bank
• Chief Architect (Listed Derivatives)

• Morgan Stanley
• Google IPO

• Sporting Bet
• Chief Architect
About Me - Community
• Java Champion

• JavaOne Rock Star Speaker

• Java Community Process


Executive Committee

• London Java Community


• Organising Team
• Co-founder, AdoptOpenJDK
Installing Java
• We will use AdoptOpenJDK - Java 11
https://adoptopenjdk.net/

• We will use “OpenJDK 11 (LTS)” and the HotSpot JVM

• Later, we will also use IntelliJ IDEA - Community Edition

• For more on the history of Java - free book:


• “Java: The Legend” (O’Reilly 2015)
https://learning.oreilly.com/library/view/java-the-legend/
9781492048299/cover.html
How Do We Learn?

Creating

Evaluating

Analyzing

Applying

Understanding

Remembering
Why is Programming Different?

Syntax

Language
Platform
theory

Tools
How Do We Learn?

Formal
training

Social
coding

Self study
Java Basics (Reference)
• Variables and Values

• Working with Java’s Maths & Strings

• Flow Control

• Comments
Variables
• All variables must be declared
• before first use
• local variables go out of scope at the end of the enclosing block
• multiple variables can be specified in one declaration

• Two categories of data type int answer = 42, lucky = 7;


• primitive (int, char, boolean, etc.) double betterAnswer = 42.0;
String name = "Adams";
• object references

• Java is a statically typed language


• variables may not change type
Variables and Values – Static Typing
Java Cheat Sheet – Types
• Java’s primitive types
• boolean, byte, short, char, int, long, float, double
• Not objects, used for data values

• All other types are derived from Object

• Java also has interfaces


• These define contracts
• Don’t provide any implementations for their methods
Primitive Data Types
• Java supports several basic data types
• Known as primitive types
• All numeric types are signed
• char is not considered a numeric type

Type Size Example Range


byte 1 byte 123 0173 0x7B -128 .. +127

short 2 bytes 32000 0173 0x5000 -32768 .. +32767

int 4 bytes 70000 010000 0xFFFFFF +- 2147483647

long 8 bytes 1L 0173L 0x7BL +-9223372036854775807

char Unicode: 2 bytes ‘A’ ’\t’ ’\u0065’ \u0000’..’\uFFFF’

float 4 bytes 123.0F 1.23E2F 3.40282347E+38F

double 8 bytes 123.0 1.23E2 1.79769313E+308

boolean 1 byte true false true | false


User Data Types
• Additional types are defined using classes
• Supertype for all objects is java.lang.Object
• Standard language class for strings is java.lang.String

• User-defined types are always classes


• Cannot make new primitive types
Arithmetic Expressions
• Left associative with normal precedence
+1 -1 Unary Plus & minus
A*B B/C D%E Product, Division & Modulo (remainder)
A+B A-B Addition & Subtraction

• JVM calculates using int, long, float or double


• byte and short widened to int
byte b = 1;
b = (byte) (b + 1);

• Use casts to "narrow" or "widen" a numeric value


• cast syntax is: (type)
• may lose range or precision
Logical & Bitwise Expressions
• Logical expressions yield boolean values
• lower precedence than arithmetic operators
• evaluation is lazy, stops when result is known
A == B A != B Logical Equality & inequality
A && B || D Logical AND and OR
!A Logical NOT

• Bitwise operators manipulate bits in int and long


A&B A|B Bitwise AND & OR
~A ^B Bitwise complement and XOR
A<<B B>>C D>>>E Shift left, right, unsigned shift right
Miscellaneous Expressions
• Conditional Expression
cond expression1 ? true_expression : false_expression

int max = (m > n) ? m : n;


System.out.print(n + " row" + ( (n != 1) ? "s" : "" ) );

• Increment & decrement operators


• available in prefix or postfix form

// these affect the value int x=1, y=0;


// of x in the same way y = x++; // x=2, y=1
x = x + 1; y = ++x; // x=3, y=3
x += 1; z = x-- - --y; // z=?
x++; z = x++ + y++; // z=?
++x;
Working with Java’s Maths & Strings
• Static Methods

• Example – java.lang.Math

• String Type

• Simple String Methods


Static Methods
• Java has methods - not functions

• Methods are usually called on objects

• Some methods are declared as static


• similar to functions in other languages
• relate to the class rather than an object
• do not need an object to be created

• Cannot access object methods without instance


• but can call static methods
Example – java.lang.Math
• Static methods still belong to classes
• helps group methods together

• java.lang.Math contains many static methods


• for calculating maths functions
• we don’t need any objects for this

• For example
• sin, cos, tan, exp, log and many, many more
The String Type
• Built-in library class
• Strings are sequences of Unicode characters
• Language provides syntax shortcuts for working with Strings

• String objects are immutable


• Value cannot change

int len = hw.length(); String hw = "Hello ";


int position = hw.indexOf('W'); hw = hw + "World";
String lower = hw.toLower();
if ( hw.equals("Hello World" ) ) ... Hello
+ World

Hello World
Simple String Methods
• String class has many useful methods

• For example
• length() - the length of the string
int len = hw.length();
• indexOf() - find a char in the string int position = hw.indexOf('W');
• lower() - make a lower-cased version String lower = hw.toLower();
if ( hw.equals("Hello World" ) ) ...
• equals() - check if the string has
same characters as another string

• Also some variants


• equalsIgnoreCase()
• upper()
Objects and Strings
• All classes have a toString() method
• returns a String representation

• Generate String using + operator


• Often called implicitly to convert value to String
• System.out.println()

public class Person {


...
public String toString() {
return ( name + ": " + age );
}
...
}

Person bruce = new Person("bruce", 30);


assertEquals( bruce.toString(), "bruce: 30" );
Decision Making
• Basic if statement has the form
if (expression) statement; else statement;

• else clause is optional, and may be another if statement


• statements can be compound block statements

if ( n > 0 ) {
System.out.println( "N is greater than zero” );
}

if ( x == 0 && y == 0 )
System.out.println( "At the origin" );
else if ( x > 0 && y > 0 )
System.out.println( "Top right quadrant" );
else if ( x < 0 && y < 0 )
System.out.println( "Bottom left quadrant" );
else
System.out.println( "Inside Q1 or Q3" );
Multi-way Decisions
• switch statement
• expression may be a number (or enum – see later)

int day = in.get();


switch ( day ) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Sunday";
break;
}
Multi-way Decisions
• switch statement
• expression can be String, but not other types

String today = "Monday";


switch (today) {
case "Monday":
case "Tuesday":
System.out.println("Early week - boo");
break;
case "Wednesday":
case "Thursday":
System.out.println("Getting better...");
break;
case "Friday":
System.out.println("Almost there!");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend :-)");
}
Looping
for ( initialisation; condition; update ) statement; for (String a: args)
System.out.println(a);

for ( ElType el : Collection ) statement; int sum = 0;


for (int low=0, hi=99;
low < hi; low++, --hi)
sum += (low + hi);

while ( condition ) statement; while (sum < 100) {


sum += x++;
}

do statement; while ( condition ); do {


b = System.in.read();
} while (b >= 0);
Additional Loop Control
• Java supports two additional loop control statements
• break is used to terminate a loop
• continue is used to force a loop into the next iteration
• both statements can be given an optional label
Additional Loop Control
• Java supports two additional loop control statements
• break is used to terminate a loop
• continue is used to force a loop into the next iteration
• both statements can be given an optional label

NEXTL:
while ( ( buffer = in.readLine() ) != null ) {
if ( buffer.startsWith("exit") )
break;
if ( buffer.length() == 0 )
continue;
for ( int i=0; i < buffer.length(); i++ ) {
char ch = buffer.charAt(i);
if ( ch == '#' )
continue NEXTL;
... // extra code not shown
} // inner
} // outer (nextline)
Comments
• Comments out the rest of the line
// ...

• Comments out several lines (no nesting)


/* ...
...
... */

• Comment to semi-automate code documentation


• recognised by javadoc standard utility

/** ... */
Introducing OO in Java (Reference)
• Thinking about Data

• Classes and Objects

• null and NullPointerException

• Wrapper Types

• Arrays

• Review
Thinking About Data

House
Last number Street
name <integer> name
<string> <string>
Town/
First city
name <string>
<string>

Date of
birth
<date>
? Post
code
<string>
Methods – Concepts

Method: Full name Method: Current age


First
name + <space> + Last
name
Current
date
– Date of
birth

First name: Bob Current date: 24th May 2015


Last name: Smith Date of birth: 21st May 1976
Full name: Bob Smith Current age: 38 years old
Methods
• All executable code must be contained within methods

Visibility public class Greeting {


Declare class and name it
(who can private String greeting = "";
call method)
private String target = "";
public void setGreeting( String greeting ) {
this.greeting = greeting;
}
public void setTarget( String target ) {
this.target = target;
Return type } No. and types
public String greet( ) { of arguments
return greeting + " " + target;
}
}
Value to return from method,
type must match return type
Method Overloading
• Method names can be overloaded
• formal parameter lists must be different
• return type may be different
• method signature is combination of name and parameter types

public String greet() {


return greeting + " " + target;
}

public String greet(String whoToGreet) {


return greeting + " " + whoToGreet;
}

...
System.out.println(helloWorld.greet());
System.out.println(helloWorld.greet("Everyone"));
...
Java’s Grammar for Method Calls

VERB

mrJones.bill(1500);

NOUN PARAMETER
Bill
of_type: Lawyer
Classes

Class: Person
First
Last
name
name
Full name

Date of
House Current age
birth Street
number
name

Full address
Town/
city Post
code
Classes and Objects

1 4

2 5

3 6
Java References
• Object declarations are references
• they must be associated with an object before use

Person bruce; bruce


Person brian;

brian

• Create objects using the new operator


"bruce"
bruce = new Person("bruce", 30); bruce 30
brian = new Person("brian", 42);

brian "brian"
42
Object Initialisation
• Objects created with new operator public class Person {
private String name;
• Attributes set to default values private int age = 21;

• 0 for numeric/char primitive types public Person ( ) {



• false for boolean }
}
• null for objects

• Class specific initial values are set


A Simple Class

public class Person {

private String name;


private int age; Attributes:
each Person has
public Person(String n, int a) { its own copy of these
name = n;
age = a;
}

public int getAge() {return age;}

public String getName() {return name;}

public void setAge(int a) {age = a;}

}
A Simple Class

public class Person {

private String name;


private int age;

public Person(String n, int a) {


name = n; Constructor:
age = a;
} shows how to make a
Person object
public int getAge() {return age;}

public String getName() {return name;}

public void setAge(int a) {age = a;}

}
A Simple Class

public class Person {

private String name;


private int age;

public Person(String n, int a) {


name = n;
age = a;
}

public int getAge() {return age;}

public String getName() {return name;}


Methods:

public void setAge(int a) {age = a;} describe what each


Person object can do
}
The Constructor
• A pseudo-method to initialise newly created object
• same name as class,
public class Person {
no return type private String name;
private int age = 21;

• May be overloaded public Person(String n) {


name = n;
• correct constructor called }

according to args public Person(String n, int a) {


name = n;
• used with new age = a;
}

• Default "no-arg"
bruce = new Person("bruce");
constructor provided brian = new Person("brian", 42);
john = new Person();
• unless class contains Not allowed!!
other constructors No constructor with
matching signature
The Current Object
• this reference
• Available in constructor and methods
• not static methods ( like main() )

public void addMeToTheList(MemberList theList) {


...
theList.addMember (this);
...
}

public void setAge(int age) {


this.age = age;
}
Working with Objects
• Use the '.' operator to access methods and attributes
• subject to visibility rules defined in class

brian.showDetails(); Not allowed!!


bruce.setAge(31); Person class defines
bruce.age = bruce.age + 1; age attribute as private

• Beware assignment
• assigns reference, not object!!
"bruce"
bruce = brian; bruce 30
bruce.setAge(31);
assertEquals(brian.getAge(), 31);
brian "brian"
X 31
42
Java Programming
• Every piece of code must be contained in a class
• No “free functions”
• Only methods

• Entry point of a program is main() method


• Must be public and static
• Takes an array of strings (the function arguments)
null and NullPointerException
• Java has a special null value

• Used to indicate a “missing object”

• Can’t call methods on null

• There will be a NullPointerException (NPE) if you try


Object references
• Primitive values cannot be altered

• The contents of object references can usually be mutated

• Java always has pass-by-value semantics


• For reference types, what’s passed is a copy of the reference

• See: http://javadude.com/articles/passbyvalue.htm
Wrapper Classes
• Primitive types are not classes Byte Float
• Primitive variables are not objects Short Double
Integer Boolean
• do not need to be instantiated Long Character
• do not have methods associated with them

• Wrappers give primitives object behaviour


• used when primitives cannot be used (eg. in collection classes)
• useful location for relevant methods (numeric, character)
• conversion to and from wrapper objects automatic

int n = Integer.parseInt("123");

while (n < Integer.MAX_VALUE)


n = n + 1;
Autoboxing
• Conversion from primitive type to wrapper is automatic
• Autoboxing

Integer iObj = 10; // Integer iObj = new Integer(10);


int i = iObj // i = iObj.intValue();

• …and back again


• Unboxing
Integer iObj1 = 10;
Integer iObj2 = iObj1 + 1;

• Allows arithmetic on wrapper objects


• etc…
What is a Container?
• A group of elements
• related in some way
• usually objects

• Can be manipulated as a single object


• stored in a variable
• passed as argument to method
• returned as a method result

• Three main families in Java


• arrays
• collections
• “transparent containers” (functional)
Arrays
• The simplest form of container

• Arrays are fixed-size, indexed containers


• elements can be primitive or reference types

• Various syntactic shortcuts int[] values = new int[5];


for handling arrays assertEquals(values.length, 5);

• Arrays are objects


• must be created with new before use
• new operator requires type and number of array elements
• size of an array can be obtained from the length attribute
• array elements are initialised to “zero bits”
• primitives to zero (or equivalent, e.g. false, 0.0), objects to null
Initialising Arrays
• Array elements can be initialised at point of declaration
• size of array determined by number of initialisers
• elements must be of correct type for the array

private static int[] DAYS = {


0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
public int daysInMonth(int month, int year) {
int days = DAYS[month]; // !!!
if ( month == 2 && isLeapYear( year ) )
days++;
return days;
}
Arrays of Objects
• Arrays of objects: elements are initialised to null
• elements must be initialised

public class Person {


private String name;
public Person(String name) {
this.name = name;
}
}

public class Company {


private Person[] staff;
public Company ( String[] people )
{
staff = new Person[people.length];
for (int i=0; i < args.length; i++)
staff[i] = new Person(people[i]);
}
}
Accessing Array Elements
• Array elements are accessed with an int subscript
• subscript ranges from zero to one less than size of the array
• subscript access is bounds checked
• runtime exception thrown if subscript out of range
• ArrayIndexOutOfBoundsException

• Array elements are expression operands


• can be used on left or right hand side of an assignment

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


values[i] = values[i] * 2;
Arrays & Methods
• Arrays can be method parameters or return values
• array references always passed by value (as with all reference types)

int[] values = new int[5];


for (int i=0; i < values.length; i++)
values[i] = i*2;
double[] doubleValues = toDoubles(values);

private double[] toDoubles(int[] values) {


double[] result = new double[values.length];
for (int i=0; i < values.length; i++)
result[i] = (double) values[i];
return result;
}
Review: Object Orientation
• Object orientation focuses on data (state)
• Functionality is associated with the data elements

• Objects have three primary properties


• Attributes (fields)
• Behaviour (methods)
• Identity (reference identity)
Review: Object Orientation
• Objects of a given type belong to a class
• Template for building objects

• Classes may be related by inheritance


• Define one class in terms of another
• Brings many advantages
Review: Building Blocks

Data

Method

Class

Namespace
Java’s Reserved Words
abstract assert boolean break byte case

catch char class const continue default

do double else enum extends false

final finally float for goto if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while


Reserved Words – Primitive Types
abstract assert boolean break byte case

catch char class const continue default

do double else enum extends false

final finally float for goto if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while


Reserved Words – Literals
abstract assert boolean break byte case

catch char class const continue default

do double else enum extends false

final finally float for goto if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while


Reserved Words – Flow Control
abstract assert boolean break byte case

catch char class const continue default

do double else enum extends false

final finally float for goto if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while


Reserved Words – Object Oriented
abstract assert boolean break byte case

catch char class const continue default

do double else enum extends false

final finally float for goto if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while


Reserved Words – Concurrency
abstract assert boolean break byte case

catch char class const continue default

do double else enum extends false

final finally float for goto if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while


Reserved Words – Miscellaneous
abstract assert boolean break byte case

catch char class const continue default

do double else enum extends false

final finally float for goto if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while


New Reserved Words
abstract assert boolean break byte case

catch char class const continue default

do double else enum extends false

final finally float for goto if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while


Tools & the JVM (Reference)
• Command Line Tools

• Introducing the JVM

• Areas of Memory
Command Line Tools
• jshell – Interactive programming environment

• javac – Java source code compiler

• java – Executes Java programs (virtual machine)

• jar – Process and work with Java archives (jars)

• … and many more


Introducing the JVM
JVM
.class
file

javac

Java
source
code

Class file creation Continuous (Just In Time) compilation


Why is Java Different?
• Java consists of
• The Java programming language
• The virtual machine it executes on
• Class libraries and standard interfaces

• Split was originally considered novel


• Now very standard
Java Design Goals
• Comprise a container for application code to run inside

• Provide a secure execution environment as compared to C/C++

• Take memory management out of the hands of developers

• Provide a cross-platform execution environment


Key Aspects of the Java Platform
• Interpreter

• JIT Compiler

• Classloading

• Garbage Collection
Interpreter
• Java environment defined by 2 specifications
• Java language specification
• Java Virtual Machine specification (VMspec)

• Execution of JVM bytecode defined by VMspec

• Interpreter is stack-based

• Aids implementation of strong security model


JIT Compiler
• JIT compilation must maintain correct execution
• Identical semantics to interpreter

• Use profile-guided optimisation


• Highly optimise, including aspects not possible when compiling source
• Potentially complex behaviour

• Only JIT-compiled methods matter for performance

• Benchmarking individual compiled methods is very hard


Classloading
• JVM has classloading time, not just compile & run time

• Somewhat similar to Unix dynamic linking


• Considerably more flexible & powerful

• Rich classloading capabilities key


• To many aspects of Java platform
• Bytecode transformation

• Only way to get new code into a running system

• Provide “pinch point” for Java security model


Garbage Collection
• Automatic reclamation of memory no longer in use
• Key aspect of the platform
• Simplifies programming for most developers

• Outside control of the programmer


• No option for low-level C-style control

• Not defined by the VM or language spec


• Pluggable subsystem
• Has tradeoffs between application concerns
What Does a Modern JVM Look Like?
JVM
.class
file Classloader Method cache

JIT compiler
javac
Interpreter Profiler Emitter

Java
source Code cache
code

Class file creation Continuous (Just In Time) compilation


Areas of Memory At Runtime
• Local Variables
• Private to a method

• Global Shared Heap


• Shared between all Methods and Threads
Areas of Memory At Runtime
• Local Variables
• Private to a method

• Global Shared Heap


• Shared between all Methods and Threads

• (JVM Secret: Read-Only Constant Pool )


• Private to a class

• (JVM Secret: Temporary Evaluation Stack )


• Private to a method
• No registers in the JVM
Objects in the Heap
Stack Heap

Function Y

Function K

Function G

Function A

App entry point

Static and global variables Unreachable heap objects


Local variables Heap objects reachable by roots
Garbage Collection
• Object "lives" as long as something references it
• typically a local variable or an object field

• Space reclaimed for the heap by the garbage collector


• when no external references (GC roots) anchor the object
• “GC cleans up dead objects”

• Compared to C++, much simpler


• no manual cleanup required
• object lifetime much less important to the programmer
Java’s Type System (Reference)
• Inheritance & Access Control

• Interface
Inheritance
• Every Java class has exactly one parent class
• Except java.lang.Object

• Specified in class declaration by the extends keyword

• If a class doesn’t specify a parent


• The parent is taken to be Object

• We say the class inherits from the parent class

• This means that classes form an inheritance hierarchy


• With Object at the top
Inheritance Hierarchy – Biology

living organisms

animals plants

invertibrates vertibrates

fish amphibians reptiles mammals birds

apes felines canines rodents

leopards cats tigers lions cougars


Inheritance Hierarchy – Java SDK

Object

String Class Object[]

String[] List Runnable


Access Control
• Methods and fields have Access Control
• public - anyone can access
• protected - only subclasses or package-mates can access
• <default> - only package-mates can access
• private - only members of the same class can access

• There is also module-level access control


• This is an advanced feature, and out of scope for now
Interfaces
• Interfaces represent only an API
• Provides a description of a type
• Methods that classes which implement that API must supply

• Interface does not usually provide any implementation


• Methods are considered mandatory
• Interfaces must implement these methods

• Some methods may be optional


• Called default methods
• The interface must supply a default implementation
Class Hierarchy

Object

Bear groom() Pet feed()

Furry groom()
Cat purr()
groom()
Example Code
• Let’s look at how we might use these classes, in a simple example:

Bear baloo = new Bear();


Cat tiddles = new Cat("Tiddles");

tiddles.feed();
tiddles.groom();
baloo.groom();

Furry b = baloo;
b.groom();
Example Output
• Here’s the example output:

Tiddles has been fed


Tiddles washes itself.
The bear combs its fur with its claws. Don't get too close.
The bear combs its fur with its claws. Don't get too close.
A Short Java Reading List
• Head First Java - K. Sierra & B. Bates

• Effective Java (3rd Ed) - J. Bloch

• Java in a Nutshell (7th Ed) - B. Evans & D. Flanagan

• Core Java - C. Hortsmann

• Java 8 Lambdas - R. Warburton

• Java - The Legend - B. Evans (free ebook)

• Oracle Java Magazine (free subscription)

You might also like