Java Programming

Study Notes by Rahul Prabhudesai

Information

This page is still in progress and new content will be added over time. Estimated completion is unknown, however, new content and/or edits will continue past completion.

Contents


Programming Essentials

Programming Fundamentals

Further Programming

Glossary and References

PROGRAMMING ESSENTIALS

1| Variables and Operators


Naming Rules
Variable, class and method names are called identifiers. These identifies must adhere to the rules for valid names.

  • May contain digits and letters
  • Must start with a letter
  • Cannot contain any symbols other than specified ones
  • May only contain $ (dollar sign) and _ (underscore) symbols
  • Cannot contain any keywords

Constants
Constants are variables that once defined are ‘final’ and value cannot be changed afterwards.

// Example and structure for a constant
final double GST = 0.15;
final <datatype><CONSTANT_NAME>;

Numeric Operators
Numeric operators in Java.

NameMeaningExampleResult
++Increment by 1 (or 1.0)1++2
Decrement by 1 (or 1.0)7.4++6.4
+Add/Sum34 + 135
Subtract34.0 – 0.133.9
*Multiply300 * 309000
/Divide1.0 / 2.00.5
%Remainder20 % 32

Comparison Operators
Operators in Java used to compare two values; also known as relational operators. These operators provide a Boolean result.

NameMeaningExampleResult
<Less Than1 < 4true
>Greater Than55 > 64false
<=Less Than or Equal To4 <= 4true
>=Greater Than or Equal To39 >= 12true
==Equals To (exact)10 == 4false
!=Not Equals To12.9 != 2.7true

Keywords
There are 57 reserved words in Java called ‘Keywords’ which have a predefined meaning in the language. Due to this, these keywords cannot be used as names or any identifiers.

abstractassertbooleanbreakbyte
casecatchcharclasscontinue
defaultdodoubleelseenum
exportsextendsfinalfinallyfloat
forifimplementsimportinstanceof
intinterfacelongmodulenative
newpackageprivateprotectedpublic
requiresreturnshortstaticstrictfp
superswitchsynchronizedthisthrow
throwstransienttryvoidvolatile
whiletruenullfalsevar
constgoto

2| Inputs and Outputs


The String Type
“String” is a predefined class in Java used to represent a string of characters.

// EXAMPLE
String message = "Hello World!";

The “String” type is not a primitive time. It is known as a reference type. Any Java class can be used as a reference type.

String Concatenation
String concatenation is when multiple strings are put together to produce a combined result.

// EXAMPLE
String eg = "Hello " + "World!"; //Result: Hello World!
String pw = "abc " + 123; //Result: abc123

String Conversions
String conversions to Integers or Doubles are necessary when a user input is set as a String and a numeric result is sought. In order to obtain a numeric result, the input String must be converted.

// Convert String to Integer
int year = Integer.parseInt(yearStr);

// Convert String to Double
double salary = Double.parseDouble(salaryStr);

3| Expressions, Operators and Statements


Boolean Type and Operators
A Boolean in Java is a data type with two possibilities, “True” or “False”. This is used in Java to determine the result of a comparison. Boolean expression are called conditions, and to test this, Java uses “if” statements.

// SYNTAX
if (condition) {
  // code block to be executed
}

// EXAMPLE
if (3<5) {
  System.out.println("The result is true.");
}

Not Operator
The Not operator in Java is is a very simple operator which tells the program to return an inverse result to what it would have been.

// SYNTAX
if NOT (condition) {
  // code block to be executed
}

Or Operator
The or operator in Java is represented by the symbol “||” which informs the program to perform an action within a statement if either of the options provide a value of true.

Exclusive Operator
The exclusive operator in Java is represented by the “^” symbol. This means an action will be performed if either one of the options are true, however, not if both options result in true.

Switches in Java
A switch statement is simply another form of choice selection. It alleviates the issue of having unnecessary nested if statements.

// SYNTAX
switch(expression) {
  case (id):
    // code block to be executed
  break;
  case (id):
    // code block to be executed
  break;
  case (id):
    // code block to be executed
  break;
  default:
}

4| Arrays, Loops and Array Lists


The Java programming language makes use of arrays to store multiple values under a single variable to eliminate the need to individually declare separate variables for each value.

// SYNTAX
datatype[] identifier = new datatype [arraySize];

// EXAMPLE
String[] cars = new String[4];
int [] grades = new int[5];

Adding Values into an Array

// SYNTAX
datatype[] Name = {value, value, value};

// EXAMPLE
String[] cars = {"Tesla", "Lamborghini", "Porsche", "Ferrari"};
int[] grades = {89, 92, 96, 75, 81};

For Loop
The for loop is a form of repetition. A for loop is useful when the exact number of iterations is known.

// SYNTAX
for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

// EXAMPLE
for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

While and Do While Loops
The while loop is another form of repetition. This will run indefinitely until a condition is met.

// SYNTAX
while (condition) {
  // code block to be executed
}

// EXAMPLE
int i = 0;
while (i < 5) {
  System.out.println(i);
  i++;
}

The do while loop is a variation of the while loop. This code will run at least once regardless of the condition. After the initial iteration, it performs like a standard while loop.

// SYNTAX
do {
  // code block to be executed
}
while (condition);

// EXAMPLE
int i = 0;
do {
  System.out.println(i);
  i++;
}
while (i < 5);

Parallel Arrays
A parallel array is one that contains an identical number of elements and corresponding data.

int[] carIds = {10, 20, 30, 40};
String[] carMakes = {"Audi", "BMW", "Ford", "Holden"};

Array Lists
An ArrayList class can be used to create containers that store lists of objects. This class is dynamically resizable in comparison to the array class.

// SYNTAX
ArrayList<datatype> name = new ArrayList<datatype>();

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

5| Methods and Classes


A method is part of a program in Java that contains a series of statements that perform a task. A class can contain an unlimited number of methods which can be reused.

// SYNTAX
static void methodName() {
  // code block to be executed
}

// EXAMPLE
// Main method
public static void main(String[] args) {
  // code block to be executed
}
// Sample Method
static void myMethod() {
  System.out.println("Hello World!");
}

A class is a general template or blueprint with common variables and methods used by most objects in that class. It is used to create objects and sometimes with the initial values already set. They allow for code reuse, allowing a reduction in redundant code.

// SYNTAX
accessmodifier class classname {
  // code block to be executed
}

// EXAMPLE
public class MyClass {
  int x = 5;

  public static void main(String[] args) {
    MyClass myObj = new MyClass();
    System.out.println(myObj.x);
  }
}

Access Identifiers
In Java, there are a few main access identifiers used to assign the level of access the code will be granted.

ModifierClassPackageSubclassGlobal
Public (+)
Protected (#)
Default/Package (~)
Private (-)

PROGRAMMING FUNDAMENTALS

1| Classes and UML Diagrams


UML Class Diagram
A class diagram in software engineering is a diagram which describes the structure of a system using United Modelling Language (UML). It is comprised of attributes, operations and methods. UML is a collection of symbols and patterns of symbols used for designing a variety of diagrams for designing software.

Class Name – also a file name.DogBook
Attributes (fields) – properties of objects. Implemented as instance variables. Variables and methods are non static; called instance variables and therefore may only be used by instances of the class.-name: String
-breed: String
-age: int
-title: String
-author: String
-year: int
Constructor –
Behavior (methods) – represented as instance methods. Instance variables must have data types and access specifier (-, +) specified.
+bark(): void
+eat(): void
+sit(): void
+Book()
+printDetails(): void

Instance Variables and Methods
Instance variables or methods may be used by instantiating the class.

// SYNTAX
// Creating instances
className instanceName = new Constructor();
// Assign values to instance variables
instanceName.variable = value;
// Use instance methods
instanceName.methodName();

// EXAMPLE
// Creating instances
Dog dog1 = new Dog();
// Assign values to instance variables
dog1.name = "Tez";
// Use instance methods
dog1.bark();

Access Specifier
An access specifier (modifier) defines access levels of methods and variables. This determines what variables, classes and methods will be visible to. The name for this concept is encapsulation.

Problem Domain
Java applications are generally developed as a solution to a problem. Firstly objects responsible for all activities must be selected. A class must also be created which will contain the main method to call other classes.

Domain Diagram
Good object-oriented (OO) programming application design defines main classes and their associations in a domain diagram. Multiplicity of an association must be represented.

2| Constructors and Methods


Null/Default Constructor
All classes must have a constructor otherwise a compiler error will be shown. A null or default constructor can be used to provide initial or default values to instance variables.

// EXAMPLE
public Book() {
  title = “Introduction to Java Programming”;
  author = “Y. Daniel Liang”;
  year = 2016;
}

Constructor with Parameters
Parameters are local variables available only within a constructor which must be assigned to instance variables.

// EXAMPLE
public Book(String t, String a, int y) {
  title = t;
  author = a;
  year = y;
}

Book book2 = new Book("Burial Rites", "Hannah Kent", 2013);

Constructor parameters with the same names as instance variables must be prefaced with this.

// SYNTAX
this.instanceVariable = parameter;

// EXAMPLE
public Book(String title, String author, int year) {
  this.title = title;
  this.author = author;
  this.year = year;
}

Methods
Methods are named blocks of code consisting of statements that perform some task.

The main method contains the access qualifier static and can be run without creating an instance. Instance methods lack the static keyword and require an instance in order to work with instance variables.

Set Methods (Mutator Methods)
A method with a parameter is a mutator or set method and must be public as they set or change the value of a private variable from other classes.

// EXAMPLE
public void setTitle(String title) {
  this.title = title;
}

Get Methods (Accessor Methods)
Accessor or get methods work by providing access to private variables from other classes and like set methods, must also be public. They must contain parameters and contain a return statement to access private instance variables from another class.

// EXAMPLE
public String getTitle() {
  return title;
}
public int getYear() {
  return year;
}

To String Method
The toString() method represents the string method of an object.

// EXAMPLE
public String toString() {
  return "Book ID " + bookID + " "" + title + """ + " written by " + author + " in " + year;
}

// Using the toString() method
public static void main(String[] args) {
  Book book1 = new Book("Good Book", "John", 2019);
  System.out.println(book1.toString());
}

Constructor Overloading
A constructor is described as being overloaded when it has the same name as another constructors, but contains a different list of parameters.

// EXAMPLE
public Book() {
}
public Book(String title, String author, int year) {
  this.title = title;
  this.author = author;
  this.year = year;
}

Constructor Chaining/Reuse
Constructor chaining is when a constructor with the same name is called and parameters used.

// EXAMPLE
public Book(String title, String author) {
  this.title = title;
  this.author = author;
}
public Book(String title, String author, int year) {
  // Note: statement must be the first statement in a constructor
  this(title, author);
  this.year = year;
}

Method Overriding
Methods can be overridden when the body of a method is changed when the name of the method and corresponding parameter list remains identical as in the superclass. A constructor cannot be overridden.

3| Inheritance


All variables and methods which are not private can be inherited by subclasses of a parent class. The protected access specifier allows variables to be accessible only to subclasses.

Inheritance in Java code is represented by the extends keyword. Subclasses can use inherited methods (public methods from superclass) directly.

// SYNTAX
public class SubclassName extends SuperclassName {
  // code to execute goes here
}

// EXAMPLE
public class Truck extends Vehicle {
 // code to execute goes here
}

Constructor Reuse (in a subclass)
Constructors are not inherited by subclasses and therefore must be created. The keyword super can be used to reuse constructors from the superclass.

// EXAMPLE
// Constructor in superclass Vehicle
public Vehicle(String make, String model, int year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
// Constructor reuse in subclass Truck
public Truck(String make, String model, int year, double load) {
  super(make, model, year);
  this.load = load;
}

Default (null) Constructor
A default constructor can be reused by a subclass using constructor reuse in the same way as any other constructor. The keyword super refers to the parent class.

// EXAMPLE
public Truck() {
  super();
}

Overriding To String Method
The toString() method can be overridden to include any extra variables a subclass brings.

public String toString() {
  return super.toString + " " + load;
}

Polymorphism and Dynamic Binding
Polymorphism is the ability of an object to take on many forms. A particularly common use case is when methods contain different instruction sets, but have the same name in both the superclass and subclass.

4| Array of Objects


Arrays are a data store for multiple variables with the same datatype. They have a fixed size and therefore once created, cannot be resized.

// SYNTAX
// Creating array
ClassName[] instanceName = new ClassName[index]
// Add elements to an array
ClassName[index] = new ClassName("value", "value", "value");
// Display array
for(int i = 0; i < instanceName.length; i++) {
  System.out.println(instanceName[i].toString());
}

// EXAMPLE
// Creating array
Car[] cars = new Car[4]
// Add elements to array
cars[0] = new Car("Tesla", "Model X", 2019);
cars[1] = new Car("BMW", "i8", 2018);
cars[2] = new Car("Nissan", "Skyline R34 GT", 2016);
cars[3] = new Car("Nissan", "X-Trail", 2012);
// Display array
for(int i = 0; i < cars.length; i++) {
  System.out.println(cars[i].toString());
}

Elements from an array can use instance variables and methods of the parent class as the array would be an instance of that class.

InstanceOf Operator
The instanceof operator can be used when trying to return only instances of a particular subclass from within the superclass array.

// SYNTAX
if(instanceName instanceof className) {
  // code to execute goes here
}

// EXAMPLE
for(int i = 0; i < count; i++) {
  if(cars[i] instanceof ElectricCars) {
    System.out.println(cars[i]);
  }
}

Methods of Class Array

MethodsDescription
static String toString(int[] a)Returns contents of specified array in a string representation
static void sort(int[] a, int fromIndex, int toIndex)Sorts specified range of array in ascending numerical order
static int binarySearch(int[] a, int key)Searches array until specific defined value is found

5| Array List


Unlike arrays, an array list is dynamic and flexible, therefore can shrink and grow according to the number of objects it contains. Elements are stored in reference to the neighboring element and are not sequential.

Creating an Array List

// SYNTAX
ArrayList<datatype> arrayName = new ArrayList<datatype>();

// EXAMPLE
ArrayList<String> carMakes = new ArrayList<String>();

Add Elements to Array List
Adding to an array list differs to an array as elements cannot be added by defining the index.

// SYNTAX
arrayName.add("value");

// EXAMPLE
carMakes.add("Porsche");

Determine Size of Array
To determine the size of an array, the method size() can be used.

// SYNTAX
int numerOfelements = arrayName.size();

Find Index of Object
To determine the index of an object in an array list, the method indexOf() can be used.

// SYNTAX
dataType index = arrayName.indexOf("value");

// EXAMPLE
int index = carMakes.indexOf("BMW");
System.out.println("Index of BMW is " + index); // returns Index of BMW is 4

Find Object at Index
The method get(index) can be used to find an object at the specified index.

// SYNTAX
dataType arrayName = arrayName.get(index);

// EXAMPLE
String carMake = carMakes.get(4);
System.out.println(carMake + " is at index 4"); //  returns BMW is at index 4

6| Abstract Classes and Interfaces


Abstract classes are like the defining characteristic or type of a group of classes. For example, for the classes “Red”, “Green”, “Blue” and “Purple”, the abstract class would be “Color”. It is beneficial in java as it allows for code reuse.

FURTHER PROGRAMMING

3| Abstract Classes and Interfaces


Mechanisms which can be used to more effectively work with polymorphism.

The abstract modifier
An abstract class cannot be instantiated, but instead is inherited and usually enhanced by subclasses. An abstract class can define constructors to be invoked from subclasses and may contain an abstract method, however, an abstract method cannot be contained in a non-abstract class. Subclasses of abstract superclass much be declared abstract if all abstract methods are not implemented. Despite having a concrete superclass, a subclass may be abstract. An abstract class cannot be instantiated, but used as a data type.

java.lang.Object // sueprclass
GeometricObject // subclass

// Abstract class used as data type
GeometricObject[] geo = new GeometricObect[10];
geo[0] = new Circle(1.0);

Glossary


ArrayList – data structure used to store multiple objects. ArrayList is a flexible (dynamic) collection of objects.

Arrays – Arrays are a data store for multiple variables with the same datatype. Size is fixed and therefore unable to be resized.

Class – A definition of objects of the same kind.

Class – A set or category of things having some property or attribute in common and differentiated from others by kind, type or quality. – (Oxford Dictionary)

Instantiation – Create an instance of.

Methods – Methods are named blocks of code consisting of statements that perform some task.

Polymorphism – the ability for an object to take on multiple forms. Any Java object that can pass more than one IS-A test is considered to be polymorphic.

References