Programming for Computer Scientists

?

Variables

Numeric data types:

Integer:

byte, short, int, long

Floating point: 

float, double

Other data types:

boolean, char

1 of 21

Type Casting

automatic type conversion: this occurs when one type is converted into a larger compatible type. 

eg. 
int i = 5;
long l = i;

type casting: this occurs when one type is being purposefully converted into another type which is not larger. for numeric variables, type casting will cut the number to the correct size which can often dramatically alter the input number. without clear type casting syntax, java will produce an error.

eg.
long l = 9876543210;
int i = (int) l;

2 of 21

Boolean Logic

AND (&&)

Given two boolean variables, returns true only if both are true

OR ( | | )

Given two boolean variables, returns type if either variable is true

XOR (^)

Given two boolean variables, return true if one and only one is true

NOT (!)

Given one variable, the opposite boolean variable is returned

Lazy operators (&& or | |) mean that if the first statement is false then the second is never executed. For (b && (a++) ==5) a wont be incremented unless b is true.

3 of 21

Operator Precedence

  • Postfix (erpr++, expr--)
  • Unary (++expr --expr)
  • Multiplicative (* %)
  • Additve ( + - )
  • Shift (<< >> >>>)
  • Relational (< > <= >=)
  • Equality (== !=)
  • Strict operators (& | ^)
  • Lazy operators (&& | |)
  • Assignment (= += -= *= /= ...)
4 of 21

Switch statements

switch (variable) {
    case VALUE:
        break;
    case VALUE:
        break;
    default:
}

  • The variable expression must have type long, int, short, byte or char
  • The VALUEs must have the same datatype as the variable expression
  • Switch statements are evaluated from top to bottom
  • Break statements are optional and will terminate the rest of the switch statement
    • Without the break statement, execution starts at the first matched case and continues until the end of the statement
  • The default statement is optional, to be evaluated if no cases match the variable expression
5 of 21

Bounded repetition

If we know:

  • where we start
  • where we end
  • what iterative step to take

Use the FOR Statement

Syntax: 

for (initialisation; booleanExpression; iteration) {

}

Semantics:

  • Execute the initialisation statement
  • Check if booleanExpression evaluates to true
  • If (or when) the booleanExpression evaluates, the loop ends
6 of 21

Unbounded repetition

If we dont know how many times we want code to be repeated, we can use while or do-while statements.

Syntax: 

while (booleanExpression) { //loop body

}

Semantics:

  • This statement is a repeating if
  • If the booleanExpression evaluates the loop, it continues, otherwise the loop ends
  • Make sure something in the loop body alters the booleanExpression

do..while

This ensures the loop runs before the booleanExpression is checked, which means it will always run at least once.

7 of 21

Arrays

Arrays allow lists of monomorphic data to be stored

Declaring arrays: 

  • One dimensional
    • [type] [ ] array = new [type] [size];
      • eg. int [ ] numbers = new int [10];
  • Two dimensional
    • [type] [ ] [ ] array = new [type] [size1] [size2];
      • eg. int [ ] [ ] twoDimArray = new int [10][10];

Using an array:

  • Numerical values are set to zero
  • Boolean values set to false
  • Arrays of objects are set to null
  • An array's index starts at zero and spans to n-1 (where n is the given size)

Arrays have one method- the array.length method which returns the length of the given array. 

8 of 21

Methods

Methods allow us to modularise code to avoid excessive repetition

Main method: 

All methods have a signature that defines the method- it includes the name of the method, the return type, the access privilege and the parameters. 

  • Access privileges- public, private, protected
  • Return type- int, double, String, int[ ]
  • Name
  • List of function parameters

We use the return keyword to return a value from a method. This value must have the same type as the return type expressed in the method signature. If the method has a return type which isnt void, then the method must have a return statement.

Multiple methods can have the same name, as long as there are differences between the signatures of the two methods. Having multiple methods with the same name is called function overloading.

9 of 21

Scope

Variables have scope from the moment theyre declared until the block it was declared within is closed.

When a new function is called, all variables declared before the function is called do not have scope within the function

All variables within the same scope must have unique names

If one variable is needed in multiple methods, we can declare class variables. This is when a variable is declared outside any method but still within the class.

10 of 21

Object Oriented Programming

For object oriented programming, objects are made up of properties and behaviours. The properties of an object store its state while the methods operate on this data.

First create a 'blueprint' of an object- this is called a class and describes how the object will be created.

We define new classes with the class keyword. Public classes must be in their own file (or outside any existing classes). By convention, class names begin with a capital letter.

A constructor method is needed to set up the object. It has no return type and has the same name as the class.

The new keyword- in the creation of an object- reserves enough memory for the object, and calls the class constructor function.

[ObjectType] variableName = new [ObjectType](parameters);

eg. Circle circle = new Circle(5); //creates a circle object with radius 5

11 of 21

Modifiers

What do modifiers do?

  • Allow us to restrict access to an objects properties and behaviours
    • public can be accessed outside the class while private can only be accessed inside the class

Why do we use modifiers?

  • Some data needs to have restricted access
  • It also maintains a good interface between programmers

Why public/private?

  • For a constructor, if we want to create instances of the class from other classes, it needs to be public.
  • Anything which doesnt require external visibility or needs to be secure/not seen by everyday users should be private.
12 of 21

Encapsulation

Making data private, while some methods are public is known as data-hiding. Encapsulation leads to data-hiding.

If code is encapsulated, it forces users to use a class by its external interface rather than having direct access to the data. The class implementation can be done however the programmer desires, while the external functionality is the same.

Why use encapsulation?

  • The boundaries of responsibility are clear
  • The unnecessary detail is hidden
  • The implementation can change without ruining dependant applications

Using getters and setters you get access to the instance variables (private variables within a class). These methods are also known as mutator and accessor methods, and allow the programmer to have more control over the variables- they cant be changed from outside the class.

13 of 21

Static and final

Static

lol nope

You can call static methods anywhere but from a static method you cannot call anything that isnt static.

Calling nonStaticMethod() will not work, but calling object.nonStaticMethod() will

Final

A variable declared final is considered to be constant and can therefore not be changed during the code.

14 of 21

Example of a Class

public class Point { 
    private int x;
    private int y;

    public Point(int x, int y) {...}

    public Point() {...}

    public int getX() {...}

    public int getY() {...}

    public void movePoint(int x, int y) { //move point to x,y }

    public void relocatePoint(int x, int y) { //move point by x,y from its current position }

    public String toString() {...}

    public boolean equals(Point p) {...}
}

15 of 21

Inheritance

Classes can inherit from a parent class

We call the base classes Superclasses and the derived classes Subclasses

The subclass inherits all of the features from its parent class and may have some additional ones of its own.

In class inheritance, method overriding is when a method has the same name as an inherited method, and the method in the subclass will override the method in the superclass.

Using the super keyword means that variables in the superclass can be set despite the fact that they're private variables. Using super to call the superclass constructor must be the first thing you do in a subclass constructor, otherwise the code will produce a compile-time error.

We can also use the super keyword to call methods, and slightly alter their functionality.

The protected modifier is also relevant when it comes to inheritance- subclasses can see protected elements of superclasses, so any inherited classes can see protected variables in the superclasses.

16 of 21

Abstract Classes and Interfaces

Abstract classes are effectively the same as normal classes, with some minor differences

  • They allow us to capture common properties and behaviours at an abstract level
  • They cannot be initialised
  • They cannot contain a mixture of abstract and concrete methods
  • The keyword abstract needs to be used in the class declaration

For abstract methods, a method signature containing the abstract keyword is all that is needed- they dont need to be implemented in the first class they're in. If a class is not abstract and extends an abstract class, all abstract methods must be implemented, otherwise it can still contain abstract methods.

At a very abstract level, interfaces are written. These are defined like a class but instead using the interface keyword. Interfaces can only contain methods and the methods cannot be implemented (but not declared abstract).

Subclasses of interfaces dont extend the interface, they implement it 

eg. public class TestImpl implements Test {...}

17 of 21

Try-catch statment

Syntax
try { 
        //code that may generate an error
} catch (TypeOfExceptionClass e) { 
        //code to handle the exception
} catch (AnotherTypeOfExceptionClass e) { 
        //code to handle this exception
} finally { //code that will always be executed to tidy up the code
}

Semantics
The code in the try block will always be executed, and if an exception is generated the relevant catch block is executed. The ordering of the catch blocks is important- if the exception in the first class block is a superclass of any of the following exceptions, the first one will be executed (none of the others)

Finally
If no exceptions are generated, but the code needs tidying up then a finally block will always be executed to do this.

18 of 21

Exceptions

Errors
An error is a subclass of Throwable that indicates a serious problem that a reasonable application should not try to catch.

Exceptions
The subclasses of Exception are are form of Throwable that indicates certain conditions that a reasonable application may want to catch.

  • Checked Exceptions
    • These must be caught or rethrown
      • Surround the statements in a try-catch block
      • Re-throw the exception using the throws keyword in the method declaration, listing all checked exceptions that may be thrown by the method
    • FileNotFoundException, IOException
  • Unchecked Exceptions
    • Any exception that extends Error or RuntimeException are unchecked
    • They can be caught but dont need to be to allow the file to compile
    • ArrayIndexOutOfBoundsException, NullPointerException
19 of 21

Creating an Exception Class

To create an exception we need to use the throw keyword (not throws)

The throw keyword is used to throw an exception and it must be followed by an object that is an instanceof the Throwable class.

Constructors of exceptions, in most Exception classes there are four constructors:

  • The default constructor with no parameter
  • A constructor which allows us to specify a small error string
  • Two which have space for another Throwable class, such that exceptions can be chained together

Exception methods

  • getMessage()  returns the message string added to the Exception when it was thrown
  • printStackTrace() function prints the chain of evens that cause the generated exception
  • initCause() allows the programmer to set the cause exception after initialisation
  • getCause() can be used to get the next exception in a chained exception
20 of 21

Generics

Generics allow programmers to write 'generic' code that enforces stronger compile-time checks. To make an object generic, when it is declared for the first time, use < > to tell java the type of variables that will be used eg. Stack<String> myStack = new Stack<String>();

Benefits of generics:

  • Stronger type checks at compile-time (turning runtime errors into compile-time ones)
  • Elimination of type casts
  • Implementation of generic algorithms tailored to different types

Generic classes look the same as normal classes, but contain a list of 'generic types' in their class definition. eg. public class MyClass<A,B,C,D,E> { }
The 'type placeholders' are then used to refer to the generic type in the code. Naming convention of these placeholders is a single uppercase letter (E- Element, V- Value, K- Key etc). You cannot use primitive types in generics, so instead the object equivalents are used (Integer instead of int)

Restricting types may also be useful, and this can be done using the extends keyword:
eg. public class Calculator<T extends Number> { } 

21 of 21

Comments

19kaymao

Report

Whats the language?

Similar Computing resources:

See all Computing resources »See all Computer Programming resources »