Common Dev Java Week 1 Java Week 2 Java Week 3 Java Week 4 Java Week 5

The following are the notes to Java Week 1 of the Java Course.


GOOD PRACTICES

edit
  • CamelCase
  • Good naming of variables and methods, be descriptive
  • Use theory from OOP
  • Comment only where applicable
  • Indent your code correctly as per previous examples

INTRODUCTION

edit

Language Types

edit

Statically typed (Compile Time)

edit
  • Manifestly (have to tell the data type e.g. String)
  • Enferred (do not have to tell the data type)

Dynamically typed

edit
  • Runtime (e.g.JavaScript)

Strongly Typed

edit

You can declare something as an int and then use it as a string

Weakly Typed

edit

You can declare something as an int and then use it as a string and vice versa Java is strongly and manifestly typed

Compiled vs Interpreted

edit

Compiled langauges convert the code into binary for the PC to 'understand' it + faster

Interpreted languages use libraries to 'understand' what is written - slower than compiled + you can install a library + independent, doesn't rely on a platform

Java compiles the code into binary (Java byte code) and then the JVM interprets the Java Byte Code

JVM (Java Virtual Machine) is installed on each client (PC, tablet, mobile, etc)

Javac compiles the file, Java runs the file

Data Types

edit

Primitives

edit
  • Primitive just holds the value

examples include long, short, int, double, byte, char, float, boolean no functionality, only used for holding values doubles have problems with rounding numbers (problematic when you want to compare)

Wrappers

edit
  • Wrappers always start with capital letters

same as primitives except Character and Integer

  • wrappers have methods (functionalities)
  • is an object
  • uses far more memory than primitives

Use primitives to hold a value, use wrappers to convert a value

String

edit
  • Strings cannot be changed (immutable)

a new String is created if you try to change it

  • '==' compares the memory address of a String (only for primitives)
  • to compare the contents of wrappers you use .equals() (only for wrappers)

Stringbuilder is faster than Stringbuffer because it is not synchronised both are mutable

Class

edit
  • Thought of as a data type
  • Whenever you use a .method, you will need an object in memory ( CoffeeMachine coffeemachine = new CoffeeMachine() );

Making a Class

edit

The following code is used to make a simple class.

 public class Broker {
   public void setName(String, Name) { 
   }
     public string getName() {
     }
   return name;
 }
  • void has no return (it is the return type)
  • usually a set method will need to have a passing argument

something like a get method will have a ()

SYNTAX

edit
  • A package is like a folder and avoids any duplicate objects being created that belong to Java itself (e.g. Object, Math,...)
  • Packages help to uniquely identify classes, eg - Math is different to com.fdm.model.Math
  • Each '.' represents a new sub folder

Access Modifiers

edit
  • Protected allows any extended classes and the same package to view A
  • Default is visible only in the same package (aka package-private)

Final Modifier

edit
  • A final variable cannot be changed (+44 for UK calling)
  • A final method may not be overridden
  • A final class cannot be extended

Static Modifiers

edit
  • Static variables or methods don't belong to any instance but only to the class

allows accessibility from outside instances

Flow Control

edit

For each

edit
 for (String book : bookList) {
   ...
 }

Ternary Operator

edit

A short hand way of writing if then else statements. ? represents 'then' and : represents 'else'.

 x = (a > b) ? a : b; 

The variable x stores the largest value out of a and b.

Ternary operators are useful for simple if statements where a value is returned for each case. The general syntax is as follows:

 {condition} ? {condition true return value} : {condition false return value};

Instances, Constructors & Casting

edit

Instances

edit

Creating a new instance of a class:

 Calculator calculator = new Calculator();

Constructors

edit
  • have the same name
  • has no return value
  • contructs a new instant in memory
  • there is no return type

Casting

edit
  • can be used for objects as well as primitives
  • forcing an object to be something else without changing the object type
  • handler always returns a double

If it returns a double and you want an integer:

 int number = (int) calculator.handler();

Memory Handling

edit

In java you don't have to deal with freeing the memory due to the garbage collector. When the recycle bin is being used, everything stops

Heap

edit
  • Holds the following information:
    • The object (when an instance is created)
    • Fields (as they are part of the object)
  • There is only one heap per JVM
  • the garbage collector is called using system.gc();

Stack

edit
  • Holds the following information
    • method calls
    • local variables
    • reference to objects
  • there can be many stacks
  • works first in last out
  • memory is not reclaimable unless it goes out of scope (finishes execution that method)
  • recursive calls can cause stack overflow

Reference Type

edit
  • Doesn't contain the value itself, but only references to the value

Value Type

edit
  • Holds the actual value (actual memory that holds the value)
  • e.g. primitives

Pass By Value

edit
  • Java is strictly only pass by value [COMMON INTERVIEW QUESTION]
    • passing a copy of a value/reference, not the original value
    • applies for primitives and for references to objects)

Pass By Reference

edit
  • that you pass in the original reference around
  • passes the original reference around (doesn't create a copy)
  • (C++ uses this)

Garbage Collector

edit
  • Stops the application completely when run ('Stops the World')
  • Reclaims and maintains memory on the Heap
  • Cannot be pre-empted
  • Runs in it's own Thread

Maven

edit
  • Is a build Tool
  • Driven by a central repository
  • Creates the project using a conventional way
  • Encourages convention over configuration
    • Main will include the production classes
    • Test will include the test (JUnit) classes
  • Goals
    • Install (packages the project and puts it in the local repository)
    • Test (runs all the tests at once)
    • Compile
    • Clean (cleans the target folder)

Types of Projects:

  • quickstart (The default one) -> jar (java archive)
  • webapp -> war (web archive)

Group ID:

  • com.fdm

Artifact ID:

  • Project Name

Essential for the Project are the following details in the pom.xml file:

 <groupId>com.fdm</groupId>
 <artifactId>MavenTest</artifactId>
 <version>1.0-SNAPSHOT</version>
 <packaging>jar</packaging>

Dependency Management

edit
  • Compiled: Dependency will be included at compile time and at runtime (won't be included while running the application) - you won't use the dependency when not needed to save memory
  • Provided: Using the dependency of the server when using a different server (the dependency will be provided by the other server)
  • Runtime: Dependency is only used at runtime (when program needs it during execution) and for testing. It is not used during compilation.
  • Test: Dependency only used during testing of project.

Benefits of IDE's and Eclipse

edit
  • Increases speed of delivery
  • Automates configuration
  • Automates project lifecycle
  • Provides early warnings
  • Provides suggestions on how to fix things
  • Automates refactoring

Mockito

edit

Mock Object:

  • An object made to look like another object
  • Not implemented, you have to specify what behaviour to simulate
  • Allows you to simulate the unknown, ie. test parts of programs without all of the project setup

Benefits of Mock Objects:

  • Mock objects use less memory
  • You can test void methods (as you can't assert a void message)
  • Test behaviour rather than data

Mock instance is created as following:

 IceCream icecream = mock(IceCream.Class)
  • The class and the test have to be the real class (mostly)
    • The collaborator can be mock
  • Mock objects cannot be used with static methods

Logging

edit
  • Most commonly used logging is log4j
  • To store certain type of data (error messages) so that they can be retrieved later
  • the log4j logging framework should be used to produce trace and debugging statements

Logging Levels (log4j)

edit
Level Description
FATAL
  • Severe errors that cause premature termination. Expect these to be immediately visible on a status console.
  • e.g. Run out of memory
  • when program can't continue
ERROR
  • Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
  • e.g. file that is needed for a procedure is not available (not very critical)
WARN
  • Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
  • potentially harmful situations
  • similar to error
  • something is wrong but you don't need to take action
INFO
  • Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
  • standard level of logging
  • the usual day-to-day messages
  • e.g. submitted a trade with trade id / user entered calculation
DEBUG
  • Detailed information on the flow through the system. Expect these to be written to logs only.
  • e.g. more details on how exactly the calculation was done (numbers were split up,...
TRACE
  • Most detailed information. Expect these to be written to logs only.
  • extra extra level of logging
  • very rarely used
  • Default Logger: Root


Exceptions

edit
  • Deal with exceptional circumstances
  • Examples include:
    • File Not Found
    • NullPointer
    • Network Connection Lost
  • Alert the user that there is a problem (user can write a code around the exception instead of crashing the program)
  • Errors are irrecoverable (e.g. stackoverflow, out of memory...)
  • Exceptions are problems that can be handled -> recoverable (e.g. outputting it to the log)
  • Runtime exceptions (nullPointerException)don't need to be explicitly thrown
  • Try has to be followed by a catch or finally

There are 2 types of exceptions:

  • Checked Exceptions:
    • Situations outside codes control
    • Developers should only be handling these
  • Unchecked Exceptions
    • Bugs and errors in the code