Test 1 Flashcards
Java Structure
public class myProgram { variable_type variable_name; public static void main(String[] args){ // variable declaration // IO statements // if- statements // loops // method calls } //end of main }// end of class
Packages
▪ A package creates a namespace for a set of classes.
▪ With packages, it is possible to have different classes/methods with the same name
in different packages.
▪ A package can contain a subpackage that should be accessed by
name_of_the_package.name_of_the_subpackage
▪ Java.lang, java.io
Variable
A variable is a name that refers to a value
It’s a placeholder to store a value
To store, assignment operator is used.
To declare a variable, its data type should be given.
Data Types
Specifies the size of storage in which you store data, a set of acceptable values and operations. 33 Name Size (bit) Value Range Defined operators byte 8 (-128) – (127) + , -, * , / short 16 (-32,768) – (32,767) + , -, * , / int 32 (-2 31 ) - (231 -1) + , -, * , / long 64 (-2 63 ) – (263 -1) + , -, * , / float 32 + , -, * , / double 64 + , -, * , / boolean 1 True/ false (0 or 1) &&, ||, ! char 16 unicode 0-65535 , >=, ==, !=
Memory Diagram/Model– Primitive Variable
• Memory is like a set of lockers. • A locker has a number • Lockers accommodate items with different sizes. • Memory is different from lockers • All memory spaces are the same size int height = 165; double weight = 58.5; char initial = 'D'; boolean found = true;
A Chain of Function Call
Function A (….){ A_stmt1; B(…); A_stmt2; }
Function B (….){ B_stmt1 ; C(…); B_stmt2; }
Function C (….){ C_stmt1; D(…); C_stmt2; }
Function D (….){ D_stmt; }
Variables Types
Java cares about the type. Java is a strongly typed language.
▪ Variables must have a type to indicate the size of the container (i.e. memory space)
that it requires.
▪ A primitive data type is the one, whose size is fixed.
▪ Non-primitive data types are flexible in size.
▪ Can you give an example when data types with flexible size come handy?
Non-primitives
There are a lot of non-primitive built-in data types that you are familiar with ▪ String, Math, Scanner, ArrayList, Vector, StringBuilder, StringBuffer ▪ Non-primitive data types are also called reference types. ▪ Why do you think is the rational behind this naming? 4 Fixed Memory Spaces = Program Stack growable Memory Spaces = Garbage Collectible Heap 100 3000 public static void main (String[] args) { double grade = 98.5; String name = "Marzieh";
Non-primitive data types
▪ Reference types have zero or more states.
▪ Their states are presented by their instance
variables (AKA fields, attributes)
▪ There are zero or more behaviours
associated with them.
▪ Behaviours are presented by functions.
▪ In object-oriented programming, functions are
called methods.
▪ Example: Self-driving cars
Classes
A bundle of instance variables and methods is called a class. • A class is a data type.
Objects
A variable defined using a class (non-primitive/ reference type) is called an
object.
• An object is an instance of a class.
• To make an object ‘new’ operator is used followed by the name of the class.
• To get access to the objects’ property (i.e. fields & methods), dot ‘.’ operator is
used.
• With one class (reference type), you can define as many objects as you require.
Just like primitive variables, when you define an object you tell java to reserve a
space in memory for the object
The keyword to order the reservation is ‘new’.
• In which part of the memory, the space is reserved?
▪ Creating an object is a 3 steps process:
▪ Declaration: Student john
▪ Space reservation: new Student();
▪ Address Assignment: Student john = new Student();
11
Stack
GCH
int noOfStudents = 1;
Student john = new Student();
Arrays are non-primitive data type
Just like other reference types, arrays need to
request for a memory space.
▪ Example: initialize the courseTaken array in class
student.
A class is a blueprints for objects
A class represent a data type by which you can define a variable. ▪ The variable that you define using a class, is called an object. ▪ This variable holds a reference to the actual object. ▪ You define one class (i.e. Student) by which you can define as many objects as you need (i.e. all the students who enrolled in EECS2030) ▪ Up to now, you used built-in classes (e.g. String, Math, Scanner, etc) to define an object, but from now on you can create your own classes. ▪ It’s good to know: For simplicity in the memory diagram presented in this course both GCH and Stack grow down when a variable is added. In reality, however, stack grows down, and heap grows up.
Constructors
A special method with no return value. ▪ It is not a void. ▪ It is the same name as the class. ▪ It is used to initialize the instance variables. ▪ Does it make sense now as to why you use the name of the class after ‘new’? ▪ new Student(); ▪ When I didn’t have any constructor for Student, I didn’t get any error for new Student(); why? ▪ This type of the constructor, in which you initialize the attributes to the default values, is called default constructor.
To combine the object creation and instance variable initialization, a constructor can accept parameters.
this
‘this’ is a keyword that refers to the instance variables of the current object.
public Student (char initial, int studentId, int [] courseTaken, int enrolmentYear) { this.initial = initial; this.studentId = studentId; this.enrolmentYear = enrolmentYear; this.courseTaken = new int [courseTaken.length]; For (int i= 0; i < courseTaken.length; i++) this.courseTaken[i] = courseTaken[i]; }
Overloaded Constructors
▪ To give the user of the class the flexibility on creating an object, multiple version of the constructors can be defined. ▪ These constructors are different in the number or types of the arguments that they accept. ▪ They are called overloaded constructors.
Constructor Chaining & Overloaded constructors
To avoid duplicate code, constructors are chained.
▪ To chain the constructors, this()is used.
▪ this() can have zero or more parameters, depending on which constructor is
called.
Copy constructors
It is possible to clone an object.
▪ This type of constructors are called copy constructors.
▪ The input parameter is an object of the same type.
Garbage Collection Mechanism
Objects are stored in the heap. ▪ If an object is no longer needed, the memory space that is allocated to them should be released. ▪ This is a process that is performed by Garbage Collection in Java.
Encapsulation
The first object-oriented principle.
▪ Data encapsulation refers to hiding the internal states
of an object
▪ an implementer controls the clients’ access to the instance
variables.
▪ The first step is to make the instance variables
inaccessible to the clients.
▪ This is done by choosing right access modifiers.
Access Modifiers
To define an access level for
a variable, method or
constructors access
modifiers are used.
Access modifiers
Access Modifier 1 within class 2 within package 3 outside package by subclass only 4 outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y
Accessors and Mutators (AKA getters & Setters)
When data is encapsulated, the only way by which you can get access to the data is
via the object methods.
▪ Mutators (setters): updates the value of the instance variable.
▪ You can check the validity of the value that you assign to the instance variable.
How to recognize which instance variable should be private?
There is no correct answer as to what instance variables should be public. It is
application specific.
▪ Rule of thumb: if you are not sure how sensitive a data is, make the variable invisible
and provide the access by mutator and accessor methods.
Static Variable
▪ The memory space for bookNo should be shared amongst all the objects (i.e.
instances).
▪ Independent of the objects that you define
▪ This is done by defining it as static variable.
▪ AKA class variables
▪ They are normally used as a counter of the objects created.
▪ The static variable only is initialised when the class is first loaded.
▪ If you do not initialize the static variable, it will get the default value.
▪ Primitive integers → 0
▪ Primitive floating point → 0.0
▪ boolean → false
▪ Object reference → null
▪ Static variables can be accessed in two ways.
Static Variables: Access
▪ Access to a static variable can be done in two ways
Book.obj or javaBook.obj
static final
constant
Static methods function the same on all the instances
of a classes
▪ sqrt(a), pow(a,b), min(a, b)
▪ They can be called independent of any object that is
created by the class.
▪ You can call static methods in two ways.
▪ you can find plenty of static methods in
java.lang.Math
Static Method & Variables
Static methods cannot use non-static instance
variables.
▪ Because static methods run without any knowledge of
existence of any instance variables.
▪ Static methods cannot use non-static methods too.
▪ Because a non-static method may have used a nonstatic instance variable.
▪ It should make sense now as to why you had to define
all the methods as a static method prior to learning
classes & objects.
Static Factory Method
Another application for static methods. • It is a static method • It creates an object of the class in which the static method is defined. • It returns a reference to the object that it’s created. • Normally the name is not the same as the name of the class (and therefore its constructor). • getInstance() is a popular name for static factory methods. • Does the name “static factory” make sense now?
Static Factory Method: Another example
▪ A class to define users’ display preferences. ▪ Each user, can only create one object of the class ▪ To change the preference, mutators can be used. ▪ i.e. no object should be created.
Examples of Static Factory in Java
Wrapper classes:
▪ Float.valueOf(f) : where f is a float
▪ Integer.valueOf(i): where i is an int
▪ Boolean.valueOf(b): where b is Boolean
▪ etc. etc. etc.
▪ java.util.Arrays.copyOf(int[] originalArray, int newLength): useful when you want to
extend the length of the current array.
▪ java.util.Calendar.getInstance(): creates an object of Calendar using the default time
zone.
▪ java.util.Currency.getInstance(str): creates an object of Currency for the given
currency code.
toString()
A magic method that can be called for any kind of object that you create.
▪ It’s going to stay mysterious until you learn about inheritance ☺
▪ It returns the address in which the object is stored if you don’t define it in the class.
▪ When you print the name of the object, toString() is called.
▪ You can make your own version of this method by giving it a meaningful
functionality.
▪ public String toSting() {}
Class Invariants
Recall:
▪ Design by contract: a contract between the implementers and the clients.
▪ If the clients guarantee the preconditions, implementers guarantee the postconditions
▪ Invariants is another component of design by contact.
▪ It refers to a statement that is true during the certain point of executing a program.
▪ e.g. for (int i = 0; i < 10; i++) {//loop invarient is true here}
▪ Generally, an invarient is a certain property that is assumed to be ture on the entry
of a method and guarenteed to be true on the exit of the method.
▪ Invarients are used for program correctness.
Immutability
The value of the instance variable at the exit of the methods should remain the same as its value at the entry of the methods. It means its value should remain unchanged (immutable).
one of the DBC components is pre-condition.
What if the pre-condition is not met?
▪ Your program should stop running?
▪ A message is generated referring to the problem(error) encountered.
▪ Question: out of 3 types of error that you know, which one is this error?
▪ This is done by throwing an exception.
▪ An exception is an error that happens during program execution (i.e. run-time error)
▪ It may/may not cause the program to terminate abnormally.
▪ There are two types of exceptions: checked and unchecked.
▪ Will talk about which exceptions are checked and which unchecked later!
Try… Catch statement
To handle checked statement, you must use try… catch statement. ▪ This statement can be used for unchecked exception too. [optional] try{ // the risky code that may produce a run time error goes here. } catch (Exception e){ // a proper error message or any other statement that should be run in case exception happens, goes here }
Testing “Exception Handling” by Junit
Recall: Things that you already know that should be tested:
▪ A representative test case from every category of expected input.
▪ The boundary cases
▪ Question: what test cases should be written for this algorithm?
▪ Now, you need to add (at least) one test case to check the exceptions