Chapter 6 - More-Sophisticated Behaviour Flashcards
What is the
**static keyword **
used for
this is used to define class/static variables.
this is a java compiler feature that will automatically box(wrap) and unbox(unwrap) primitive types to/from there wrapper class when the context calls for it (such as adding a primitive type to a collection)
NOTE: we can do this explicitly but java will handle it for us
describe
autoboxing
How do we
call a static method in Java
We can call a static method in Java without creating an instance of the class. Instead, we can simply use the name of the class followed by the name of the method
in 3 points
How do constant declarations differ from field declarations in Java?
these differ in that
1. they include the final keyword before the type and name
2. must be initialized with a value at the point of declaration
3. are usually capitalized by convention.
what is the syntax and params of the String method
split()
Syntax for String method:
split(value)
@param value a character or regex that defines where to separate a string
why might we use a primitive types wrapper class
one reason inludes:
collections may only hold objects, if we tried to place a primitive type into a collection it would not be accepted
in this case we must create an object representing the primitive type using its associated wrapper class
this is the idea that different parts of a system are not strongly connected, and can be changed without affecting each other.
What is
weak or loose coupling
describe the String method
split()
this String method can be used to split a string by a given character or regex. The separated strings are then returned in an array of strings
Syntax for the ArrayList and HashSet method addAll():
Collection1.addAll(collection2)
what is the syntax of the ArrayList and HashSet method
addAll()
this String method will return a new string from the given string but with any leading and trailing whitespace removed
describe the String method
trim()
what is the following also known as
terneray operator
what is the following also known as
conditional operator
syntax:
substring(int beginIndex, int endIndex)
param:
beginIndex the beginning index, inclusive.
endIndex (optional) the ending index, exclusive.
give the syntax and params of the String method
substring()
information includes:
1.The name of the method
2.Purpose of the function or method
3.@param annotation - the name and type and description of a parameter
4.@return annotation - the type and a description of what is returned
name 4 pieces of
information that should be included in the Constructor and method documentation
describe the access modifier
public
this access modifier allows a member (e.g., a field, method, or class) to be accessed from anywhere. (e.g., outside the class it was defined)
Syntax:put(key, value)
@param key- key with which the specified value is to be associated
@param value- value to be associated with the specified key
what is the syntax and params of the HashMap method
put()
What are
class variables
also known as static variables, are variables that only have one copy, no matter how many instances of the class are created.
code:
Int anInt = 22 Integer aWrapper = new Integer(anInt);
write the code that would explicitly wrap a an int using its associated wrapper class
How do we define implementation and interface in a class?
We define the implementation using the private keyword, and the interface using the public keyword.
this class can be imported with the following statement
import java.util.Random;
how do we import the class Random
this is a documentation generator that is included with java
what is
javadoc
describe the
java.lang package
this package is automatically imported into every java program and contains commonly used classes such as
1. wrapper classes - Integer, Boolean, etc
2. String class
3. Math class
this is a method that is not for public use but helps to achieve publicly accessible operations.
It should be declared as private because it is part of the implementation of a class, and is not intended to be used by other classes or users.
What is a
helper method
We can call a static method in Java without creating an instance of the class. Instead, we can simply use the name of the class followed by the name of the method
How do we
call a static method in Java
the wrapper class has the same name as its associated primitive type except
1. we include a capital letter at the beggining
2. int uses wrapper class Integer
3. char uses wrapper class Character
what are the names of the wrapper classes for the primitive types
this String method can be used to split a string by a given character or regex. The separated strings are then returned in an array of strings
describe the String method
split()
in Java these are defined using the modifier keyword final. If any attempt is made to change this, a compile-time error message will occur.
What are
constants in Java
syntax:
booleanCondition ? expressionIfTrue : expressionIfFalse
what is the syntax for the
conditional/ternary operator
What is the
interface in a class?
this is the public information of a class. It includes any data or operation that we would like the class to share with other classes.
What are two
limitations of class methods in Java
these include:
1. Class methods may not access any instance fields defined in the class. They may only access class variables of the same class.
2. A class method may not call an instance method defined in the class. They may only call other class methods of the same class.
describe in 2 points the
conditional/ternary operator
points include:
1. acts as a more consice way of writing an if else statement
2. is the only java operator with three operands
how is
weak or loose coupling
achieved
this is achieved by ensuring that one class does not depend on the implementation of another class, and by allowing the implementation of a class to be changed without breaking other classes that rely on a specific implementation. this is important for writing code that is more flexible and adaptable.
this is a collection whee each entry is made of a key:value pair
describe a
map
describe the Random method
nextInt(intbound)
will return a random number between 0 (inclusive) and the bound (exclusive)
describe the
class method interface
this would be the header of the method and arguably its documentation
this is the process of focusing on the essential aspects of an object and ignoring the details of its implementation. It allows us to use an object without needing to know how it works internally.
What is abstraction?
name 4 pieces of
information that should be included in the Constructor and method documentation
information includes:
1.The name of the method
2.Purpose of the function or method
3.@param annotation - the name and type and description of a parameter
4.@return annotation - the type and a description of what is returned
Can instance methods access both instance and static data in Java
Yes, these can access both instance and static data in Java.
these have access to the instance variables and instance methods of their own instance, as well as to any class variables or class methods that are defined in their class.
what is
javadoc
this is a documentation generator that is included with java
create a
class constant
code example:Private static final int GRAVITY = 3;
describe the HashMap method
keySet()
this HashMap method will return all keys of the hashmap as a set
this is the process of encapsulating or wrapping a primitive type into its associated wrapper class
describe
boxing
this ArrayList and HashSet method allows us to add all the objects from one collection into a new collection
describe the following method of ArrayList and HashSet
addAll()
is a map
an ordered or unordered collection
this is an unordered collection. this means that on access the order that the items are in cannot be guaranteed
describe the String method
trim()
this String method will return a new string from the given string but with any leading and trailing whitespace removed
describe a
set
this is a collectionthat does not allow duplicateelementsto be stored inside of it
how would we read the following statement
HashMap<String, HashSet<String>> animalMap
write out the java statement for the following
“a hash map from keys of type string, to values of type hash set of string”
a limitation of this is that its second and third operands must be expressions and not statements such as “System.out.println()”
what is a limitation of the
conditional/ternary operator
What is the
implementation in a class?
this is the private information of a class. It includes any operation or data that helps in providing the class’s overall objective, and is only accessible within the class.
How do we change the value of static variables in Java, and why is this considered good practice?
To change the value of this in Java, we use dot notation with the class name and the variable name, like this: Employee.employeeCount++;
This style of referencing the static variable using its class name is considered good practice because it helps clarify that the variable belongs to the class, rather than to a specific instance of the class
what is the syntax of the ArrayList and HashSet method
addAll()
Syntax for the ArrayList and HashSet method addAll():
Collection1.addAll(collection2)
this is a class that can represent a primitive type value
describe a
wrapper class
what is the syntax of the
switch statement
syntax:
Switch(expression/variable) { Case “Y”: isValid(); Break; Case “N”: isValid(); Break; Case “M”: isValid(); Break; Default: “please enter Y, N, M” break }
what is the statement to import the
HashMap class
statement:
Import java.util.HashMap;
why must the String method equals() be used when comparing String values
This is because the == operator will compare whether its two operands refer to the same object. The problem is that we can have two different string objects that have the same value but using the == operator would evaluate to false
sometimes though the operator == will work and this is because string objects that are not explicitly created and have already been created are just re referenced.
describe the class Random
by importing this class and creating an instance we can use the instance to generate a stream of pseudorandom numbers
this Integer static method is used to parse a string representation of an integer into an integer value
describe the Integer static method
parseInt()
describe why we might use the HashMap method
**getOrDefault() **
the HashMap method get() would return null if the key did not exist.
If we still wanted to produce a value even if get() returned null, using this we could do so without checking if null was returned
this HashMap method will return all keys of the hashmap as a set
describe the HashMap method
keySet()
this includes Words such as “public” and “private” and define the visibility of a field, constructor, or method.
describe the term
Access modifiers
describe a
hashmap
this is a particular implementation of a map.
it is a parameratized type which requires two type parameters in order to use it
write a
class/static method
code example:
~~~
Public static int getNumberOfDaysThisMonth()
{
…
}
~~~
code example:
~~~
Public static int getNumberOfDaysThisMonth()
{
…
}
~~~
write a
class/static method
write the code that will
Produce and store a random int between 0 and 2 inclusive inside the variable named myRanInt
code:
import java.util.Random; Random ran = new Random(); int myRanInt = ran.nextInt(3);
describe the String method
toUpperCase()
this String method will return the given string but with all characters in lower case
statement:
Import java.util.HashMap;
what is the statement to import the
HashMap class
what is the syntax for the
conditional/ternary operator
syntax:
booleanCondition ? expressionIfTrue : expressionIfFalse
this is a particular implementation of a map.
it is a parameratized type which requires two type parameters in order to use it
describe a
hashmap
points include:
1.allows no duplicate elements
2. is Unordered
3.Is a parameratized type collection
give 4 points regarding a
HashSet
this Allows an element to be accessed only from within the class in which it is defined
describe the term
Private access modifier
Why are there limitations in place for class methods in Java?
These limitations are in place for class variables in Java because class methods and class variables are intended to be used for tasks that are related to the class as a whole, rather than to a specific instance of the class.
Therefore, they do not have access to instance-specific data or behavior, as they are not associated with a specific instance of the class.
This helps maintain the modularity and independence of the class, and promotes encapsulation and information hiding.
this Hashmap method places a new key/value pair in the hashmap.
If the map previously contained a mapping for the key, the old value is replaced.
describe the HashMap method
put()
What are
constants in Java
in Java these are defined using the modifier keyword final. If any attempt is made to change this, a compile-time error message will occur.
also known as static variables, are variables that only have one copy, no matter how many instances of the class are created.
What are
class variables
describe the syntax and param of the String method
equals()
syntax:
equals(ObjectanObject)
param:
anObject a string object to compare this string to
describe
autoboxing
this is a java compiler feature that will automatically box(wrap) and unbox(unwrap) primitive types to/from there wrapper class when the context calls for it (such as adding a primitive type to a collection)
NOTE: we can do this explicitly but java will handle it for us
these are typically used when a value should be the same for all instances of a class.
For example, if you have a class that represents a bank account, you might use a class variable to store the interest rate for all accounts. This ensures that all accounts have the same interest rate, regardless of which instance of the class is used to access it.
When is it
appropriate to use class variables
describe the HashMap method
get()
this HashMap method is used to retrieve values from the hashmap.
Returns the value to which the specified key is mapped, ornullif this map contains no mapping for the key.
code:
for (String aKey : myMap.keySet()) { System.out.println("The key " + aKey \+ " is mapped to the value " + myMap.get(aKey)); }
write the code that will
print out every key/value pair in a HashMap using the following format
the key “HashMapKey” is mapped to the value “HashMapValue”
What is
weak or loose coupling
this is the idea that different parts of a system are not strongly connected, and can be changed without affecting each other.
name 2 scenarios where the following will occur
unboxing
this occurs in the following scenarios:
1.When a wrapper type variable is passed to the parameter of a method that expects a primitive type
2.When a wrapper type is stored in a primitive type variable
this is the public information of a class. It includes any data or operation that we would like the class to share with other classes.
What is the
interface in a class?
what is the syntax and params of the HashMap method
getOrDefault()
Syntax of the HashMap method:
getOrDefault(key, defaultvalue)
Param:
Key - the key of the hashmap collection we would like the value for
Defaultvalue - a default value to return if key does not exist
This is a Paramaterised type collection and is an implementation of a set
describe a
HashSet
What is
modularization
this is the process of breaking a complex system into smaller, more manageable pieces. It allows us to write code that is easier to understand, maintain, and reuse. Together with abstraction, modularization helps us use classes and objects without needing to know the internals of how they work.
give 5 pieces of
information that would be conveyed by a class interface
information includes:
1.The name of the class
2. A general description of the classes purpose
3. A list of the classes constructors and methods
4. The parameters and return types for each constructor and method
5. A description of the purpose of each constructor and method
This is because the == operator will compare whether its two operands refer to the same object. The problem is that we can have two different string objects that have the same value but using the == operator would evaluate to false
sometimes though the operator == will work and this is because string objects that are not explicitly created and have already been created are just re referenced.
why must the String method equals() be used when comparing String values
describe the String method
substring()
this String method will return a specfied substring of the string
what are the names of the wrapper classes for the primitive types
the wrapper class has the same name as its associated primitive type except
1. we include a capital letter at the beggining
2. int uses wrapper class Integer
3. char uses wrapper class Character
describe a
HashSet
This is a Paramaterised type collection and is an implementation of a set
this HashMap method Returns the value to which the specified key is mapped, ora defaultValueif this map contains no mapping for the key.
describe the HashMap method
getOrDefault()
name 2 key differences between
HashSet vs ArrayList
differences include:
1. AHashSetcannot contain duplicate elements, but anArrayListcan.
2. AHashSetis unordered whereas anArrayListis ordered by an index.
this String method will return a specfied substring of the string
describe the String method
substring()
in this case and in regards to maps the the old value associated with that key is overwritten by the new value.
what is the result if we
add a value to a map using a key that already holds a value
this access modifier allows a member (e.g., a field, method, or class) to be accessed from anywhere. (e.g., outside the class it was defined)
describe the access modifier
public
this HashSet method Removes all of the elements from this set. The set will be empty after this call returns
describe the HashSet method
clear()
Syntax for HashSet method:
Contains(element)
@param element element whose presence in this set is to be tested
what is the Syntax and params of the HashSet method
contains()
code example:Private static final int GRAVITY = 3;
create a
class constant
write a
1. declaration
2. initialisation
3. declaration/initialisation
for the following:
a HashSet of String
Declaration:HashSet<String> mySet;
Initialise:mySet = new HashSet<>();
Equivalent:HashSet<String> mySet = new HashSet<>()
this String method will return the given string but with all characters in lower case
describe the String method
toLowerCase()
syntax:
equals(ObjectanObject)
param:
anObject a string object to compare this string to
describe the syntax and param of the String method
equals()
what 2 ways can the following be read as
HashMap<String, String>
this can be read as
1. “a hash map from keys of type string to values of type string”
2. “a map from String to String”
using a conditional/ternary operator
write the code that will print “hello” if a variable named value is equal to 1 else it prints “world”
code:
String toPrint = value == 1 ? "hello" : "world"; System.out.print(toPrint);
this is a java compiler feature that will automatically box(wrap) and unbox(unwrap) primitive types to/from there wrapper class when the context calls for it (such as adding a primitive type to a collection)
NOTE 1: we can do this explicitly but java will handle it for us
NOTE 2: although we do not need to explicitly wrap we do need to ensure that when this occurs the recieving collection or other class is expecting the wrapper class
describe
autoboxing
these should be private because they are mostly a part of the class’s implementation, and declaring them public breaks the principle of information hiding.
Why should fields in a class be private?
what is the syntax and params of the HashMap method
put()
Syntax:put(key, value)
@param key- key with which the specified value is to be associated
@param value- value to be associated with the specified key
information includes:
1.The name of the class
2. A general description of the classes purpose
3. A list of the classes constructors and methods
4. The parameters and return types for each constructor and method
5. A description of the purpose of each constructor and method
give 5 pieces of
information that would be conveyed by a class interface
String objects are immutable meaning they cannot be destroyed
describe what this means if we wanted to change a Strings value
if we wanted to change a strings value then we must create a reference to a new string object either by creating a new variable or overwriting the existing variable
ignore
code:
import java.util.Random; Random ran = new Random(); int myRanInt = ran.nextInt(3);
write the code that will
Produce and store a random int between 0 and 2 inclusive inside the variable named myRanInt
Syntax for the HashSet method:
Add(element)
@param element element to be added to this set
what is the syntax and params of the HashSet method
add()
When is it
appropriate to use class variables
these are typically used when a value should be the same for all instances of a class.
For example, if you have a class that represents a bank account, you might use a class variable to store the interest rate for all accounts. This ensures that all accounts have the same interest rate, regardless of which instance of the class is used to access it.
What is a
helper method
this is a method that is not for public use but helps to achieve publicly accessible operations.
It should be declared as private because it is part of the implementation of a class, and is not intended to be used by other classes or users.
describe
class/static methods
these are conceptually the same as class variables. they belong to the class and will be shared by all instances
this is the private information of a class. It includes any operation or data that helps in providing the class’s overall objective, and is only accessible within the class.
What is the
implementation in a class?
this HashMap method returns a boolean value stating whether a key exists within the hashmap
describe the HashMap method
containsKey()
this occurs in the following scenarios:
1.When a primitive type is passed as a parameter to a method that expects a wrapper type
2.When a primitive type is stored in a wrapper type variable
3.When a primitive type is stored in a collection and expects its wrapper type
name 3 scenarios where the following will occur
autoboxing
describe the
java standard class library
this is a set of packages included as standard with java
each package contains related classes that can be used within a java program
what is the syntax and params of the HashMap method
containsKey()
Syntax:
containsKey(key)
@param key The key whose presence in this map is to be tested
describe the following method of ArrayList and HashSet
addAll()
this ArrayList and HashSet method allows us to add all the objects from one collection into a new collection
write out the java statement for the following
“a hash map from keys of type string, to values of type hash set of string”
how would we read the following statement
HashMap<String, HashSet<String>> animalMap
give 4 points regarding a
HashSet
points include:
1.allows no duplicate elements
2. is Unordered
3.Is a parameratized type collection
describe the String method
equals()
this String method will compare the string value to a given string value. If the values match it will return true
statement:Import java.util.HashSet;
what is the statement to
import the class HashSet
syntax:
startsWith(Stringprefix)
param:
prefix a prefix we would like to know exists at the start of the string
describe the syntax and params of the String method
startsWith()
code:
String toPrint = value == 1 ? "hello" : "world"; System.out.print(toPrint);
using a conditional/ternary operator
write the code that will print “hello” if a variable named value is equal to 1 else it prints “world”
differences include:
1. AHashSetcannot contain duplicate elements, but anArrayListcan.
2. AHashSetis unordered whereas anArrayListis ordered by an index.
name 2 key differences between
HashSet vs ArrayList
why should we maintain the information hiding principle
not being allowed to know
this information hiding principle should be maintained as it means another class will not depend on another classes implementation
this means we are free to change the implemenation without affecting other classes
this is as long as the classes interfcae remains unchanged
this is known as weak or loose coupling
write the code that will
add an int to an ArrayList
code:
ArrayList<Integer> aIntList = new ArrayList<>(); aIntList.add(22)
this is a statement that can be used in place of if…elseif…else where we may have many elseif.
it works by matching a given expression or variable value against a set of different cases
describe the
switch statement
this is a set of packages included as standard with java
each package contains related classes that can be used within a java program
describe the
java standard class library
write the code that will
print out every key/value pair in a HashMap using the following format
the key “HashMapKey” is mapped to the value “HashMapValue”
code:
for (String aKey : myMap.keySet()) { System.out.println("The key " + aKey \+ " is mapped to the value " + myMap.get(aKey)); }
this can be read as
1. “a hash map from keys of type string to values of type string”
2. “a map from String to String”
what 2 ways can the following be read as
HashMap<String, String>
describe the String method
startsWith()
this String method will return true if the given string starts with a given prefix string
these include:
- @version - used to spcify version
- @author - used to specify author
- @param - used to specify parameter information for methods
- @return - used to provide return information for methods
name 4
common javadoc annotations and their purpose
describe the
class implementation
this is any data or methods that enable or aid the interface to work. this is kept hidden in the source code and we usually do not want this information to be public
this is a collectionthat does not allow duplicateelementsto be stored inside of it
describe a
set
by importing this class and creating an instance we can use the instance to generate a stream of pseudorandom numbers
describe the class Random
what is the following also known as
conditional operator
what is the following also known as
terneray operator
describe
boxing
this is the process of encapsulating or wrapping a primitive type into its associated wrapper class
ignore
this is the process of breaking a complex system into smaller, more manageable pieces. It allows us to write code that is easier to understand, maintain, and reuse. Together with abstraction, modularization helps us use classes and objects without needing to know the internals of how they work.
What is
modularization
the HashMap method get() would return null if the key did not exist.
If we still wanted to produce a value even if get() returned null, using this we could do so without checking if null was returned
describe why we might use the HashMap method
**getOrDefault() **
information includes:
1.Class name
2.A description of what a class does and how it can be used
3.@author annotation
4.@version annotation
name 4 pieces of
information that should be included in the class docuentation
this HashSet method returns boolean stating if the given element is in the set
describe the HashSet method
contains()
one reason inludes:
collections may only hold objects, if we tried to place a primitive type into a collection it would not be accepted
in this case we must create an object representing the primitive type using its associated wrapper class
why might we use a primitive types wrapper class
describe the HashSet method
add()
this HashSet method adds an element to the set. If element already exists the set is unchanged
these are conceptually the same as class variables. they belong to the class and will be shared by all instances
describe
class/static methods
this String method will compare the string value to a given string value. If the values match it will return true
describe the String method
equals()
this is any data or methods that enable or aid the interface to work. this is kept hidden in the source code and we usually do not want this information to be public
describe the
class implementation
Yes, these can access both instance and static data in Java.
these have access to the instance variables and instance methods of their own instance, as well as to any class variables or class methods that are defined in their class.
Can instance methods access both instance and static data in Java
What is abstraction?
this is the process of focusing on the essential aspects of an object and ignoring the details of its implementation. It allows us to use an object without needing to know how it works internally.
what is a limitation of the
conditional/ternary operator
a limitation of this is that its second and third operands must be expressions and not statements such as “System.out.println()”
what is the Syntax and params of the HashSet method
contains()
Syntax for HashSet method:
Contains(element)
@param element element whose presence in this set is to be tested
describe the
class interface
this is public information about a class that can be used by programmers to understand what the class does and how it can be used
What is
information hiding
this is a principle that states that the inner workings of a class (implementation) should be hidden from other classes and users. This results in better modularization.
this is an unordered collection. this means that on access the order that the items are in cannot be guaranteed
is a map
an ordered or unordered collection
These limitations are in place for class variables in Java because class methods and class variables are intended to be used for tasks that are related to the class as a whole, rather than to a specific instance of the class.
Therefore, they do not have access to instance-specific data or behavior, as they are not associated with a specific instance of the class.
This helps maintain the modularity and independence of the class, and promotes encapsulation and information hiding.
Why are there limitations in place for class methods in Java?
this String method will return true if the given string starts with a given prefix string
describe the String method
startsWith()
describe the term
Private access modifier
this Allows an element to be accessed only from within the class in which it is defined
We define the implementation using the private keyword, and the interface using the public keyword.
How do we define implementation and interface in a class?
this HashMap method is used to retrieve values from the hashmap.
Returns the value to which the specified key is mapped, ornullif this map contains no mapping for the key.
describe the HashMap method
get()
this is the processs of unwrapping objects back into there associated primtive types
describe
unboxing
declare:HashMap<String, HashSet<String>> animalMap;
initialise:animalMap = new HashMap<>();
place key/value pair in hashmap:animalMap.put("Reptiles", new HashSet<>());
place element in the set that is a value within the hashmap:animalMap.get("repile").add("snake");
declare and initialise the following
“a hash map from keys of type string to values of type hash set of string”
then
1. put the key “reptile” and value “empty set” into the hashmap
2. add the element “snake” into the empty set that is held by the key “reptile”
will return a random number between 0 (inclusive) and the bound (exclusive)
describe the Random method
nextInt(intbound)
in this case and in regards to maps the value null will be returned
what happens if we
use a maps get method to access a key that does not exists
this is used to define class/static variables.
What is the
**static keyword **
used for
syntax of the Integer static method parseInt
parseInt(aString)
aString - a string representing an int that we would like to be parsed into an int
what is the syntax and params of the integer static method
parseInt
describe the HashMap method
put()
this Hashmap method places a new key/value pair in the hashmap.
If the map previously contained a mapping for the key, the old value is replaced.
how does abstraction and modularization maintain the
information hiding principle “not need know”
Abstraction and modularization help maintain this information hiding principle by allowing us to use objects and classes without needing to know the details of their implementation.
what is the syntax and params of the integer static method
parseInt
syntax of the Integer static method parseInt
parseInt(aString)
aString - a string representing an int that we would like to be parsed into an int
what is the statement to
import the class HashSet
statement:Import java.util.HashSet;
describe the Random method
nextInt()
this Random method will return a random number between -2^32 and 2^32
this is achieved by ensuring that one class does not depend on the implementation of another class, and by allowing the implementation of a class to be changed without breaking other classes that rely on a specific implementation. this is important for writing code that is more flexible and adaptable.
how is
weak or loose coupling
achieved
this HashMap method Returns the number of key-value mappings in this map.
describe the HashMap method
size()
Syntax:
containsKey(key)
@param key The key whose presence in this map is to be tested
what is the syntax and params of the HashMap method
containsKey()
this would be the header of the method and arguably its documentation
describe the
class method interface
describe the HashMap method
getOrDefault()
this HashMap method Returns the value to which the specified key is mapped, ora defaultValueif this map contains no mapping for the key.
this occurs in the following scenarios:
1.When a wrapper type variable is passed to the parameter of a method that expects a primitive type
2.When a wrapper type is stored in a primitive type variable
name 2 scenarios where the following will occur
unboxing
how do we import the class Random
this class can be imported with the following statement
import java.util.Random;
describe
autoboxing
this is a java compiler feature that will automatically box(wrap) and unbox(unwrap) primitive types to/from there wrapper class when the context calls for it (such as adding a primitive type to a collection)
NOTE 1: we can do this explicitly but java will handle it for us
NOTE 2: although we do not need to explicitly wrap we do need to ensure that when this occurs the recieving collection or other class is expecting the wrapper class
create an
instance constant
code example:Private final int GRAVITY = 3;
Syntax:
Get(key)
@param key the key whose associated value is to be returned
what is the syntax and params of the HashMap method
get()
describe the HashMap method
size()
this HashMap method Returns the number of key-value mappings in this map.
this package is automatically imported into every java program and contains commonly used classes such as
1. wrapper classes - Integer, Boolean, etc
2. String class
3. Math class
describe the
java.lang package
name 3 scenarios where the following will occur
autoboxing
this occurs in the following scenarios:
1.When a primitive type is passed as a parameter to a method that expects a wrapper type
2.When a primitive type is stored in a wrapper type variable
3.When a primitive type is stored in a collection and expects its wrapper type
name 4
common javadoc annotations and their purpose
these include:
- @version - used to spcify version
- @author - used to specify author
- @param - used to specify parameter information for methods
- @return - used to provide return information for methods
describe the HashSet method
contains()
this HashSet method returns boolean stating if the given element is in the set
name 2 key similarities between
HashSet vs ArrayList
similarities include:
1. Both aHashSetand anArrayListcan grow dynamically.
2. Both aHashSetand anArrayListcan contain only objects.
code example:Private final int GRAVITY = 3;
create an
instance constant
describe
unboxing
this is the processs of unwrapping objects back into there associated primtive types
describe the
switch statement
this is a statement that can be used in place of if…elseif…else where we may have many elseif.
it works by matching a given expression or variable value against a set of different cases
points include:
1. acts as a more consice way of writing an if else statement
2. is the only java operator with three operands
describe in 2 points the
conditional/ternary operator
ignore
what is the result if we
add a value to a map using a key that already holds a value
in this case and in regards to maps the the old value associated with that key is overwritten by the new value.
ignore
Why is it important for a class to maintain full control over its private fields?
this is important because it allows the class to ensure that the fields are not filled with invalid data.
If fields were public, another class could enter data there as it sees fit, which could cause unknown errors.
By maintaining control over the fields, the class can validate the data that is entered and ensure that it is correct. This helps maintain the integrity of the class’s data and behavior.
describe a
map
this is a collection whee each entry is made of a key:value pair
code:
ArrayList<Integer> aIntList = new ArrayList<>(); aIntList.add(22)
write the code that will
add an int to an ArrayList
Syntax of the HashMap method:
getOrDefault(key, defaultvalue)
Param:
Key - the key of the hashmap collection we would like the value for
Defaultvalue - a default value to return if key does not exist
what is the syntax and params of the HashMap method
getOrDefault()
Declaration:HashSet<String> mySet;
Initialise:mySet = new HashSet<>();
Equivalent:HashSet<String> mySet = new HashSet<>()
write a
1. declaration
2. initialisation
3. declaration/initialisation
for the following:
a HashSet of String
give the syntax and params of the String method
substring()
syntax:
substring(int beginIndex, int endIndex)
param:
beginIndex the beginning index, inclusive.
endIndex (optional) the ending index, exclusive.
what is the syntax and params of the HashMap method
get()
Syntax:
Get(key)
@param key the key whose associated value is to be returned
if we wanted to change a strings value then we must create a reference to a new string object either by creating a new variable or overwriting the existing variable
String objects are immutable meaning they cannot be destroyed
describe what this means if we wanted to change a Strings value
this HashSet method adds an element to the set. If element already exists the set is unchanged
describe the HashSet method
add()
these differ in that
1. they include the final keyword before the type and name
2. must be initialized with a value at the point of declaration
3. are usually capitalized by convention.
in 3 points
How do constant declarations differ from field declarations in Java?
The two principles of this are:
1) A programmer should not need to know the internals of a class
2) A user should not be allowed to know the internals of a class.
What are the
two principles of information hiding
describe the HashSet method
clear()
this HashSet method Removes all of the elements from this set. The set will be empty after this call returns
what
information is conveyed by the class method interfcae
information includes:
1.The access modifier
2.The return type
3.The method name
4.The parameters (if any)
information includes:
1.The access modifier
2.The return type
3.The method name
4.The parameters (if any)
what
information is conveyed by the class method interfcae
this Random method will return a random number between -2^32 and 2^32
describe the Random method
nextInt()
this exception may be seen when we try and access a character of a string that is larger than the string itself such as when using the charAt() method.
If we were looking at each character of the string using a loop it is wise to have a check such as
while (i < string.length())
this ensure we cannot access an index larger than the string and avoid such an error at runtime
when might we witness the following exception
StringIndexOutOfBoundsException
describe the term
Access modifiers
this includes Words such as “public” and “private” and define the visibility of a field, constructor, or method.
this String method will return the given string but with all characters in lower case
describe the String method
toUpperCase()
What are the
two principles of information hiding
The two principles of this are:
1) A programmer should not need to know the internals of a class
2) A user should not be allowed to know the internals of a class.
this is important because it allows the class to ensure that the fields are not filled with invalid data.
If fields were public, another class could enter data there as it sees fit, which could cause unknown errors.
By maintaining control over the fields, the class can validate the data that is entered and ensure that it is correct. This helps maintain the integrity of the class’s data and behavior.
Why is it important for a class to maintain full control over its private fields?
when might we witness the following exception
StringIndexOutOfBoundsException
this exception may be seen when we try and access a character of a string that is larger than the string itself such as when using the charAt() method.
If we were looking at each character of the string using a loop it is wise to have a check such as
while (i < string.length())
this ensure we cannot access an index larger than the string and avoid such an error at runtime
Why should fields in a class be private?
these should be private because they are mostly a part of the class’s implementation, and declaring them public breaks the principle of information hiding.
write a
1. declaration
2. initialisation
3. declaration/initialisation
for the following:
a hashmap of key type String to value type String
Declaration:HashMap<String, String> stringsMap;
Initialisation:stringsMap = new HashMap<>();
Equivalent:HashMap<String, String> stringsMap = new HashMap<>();
Abstraction and modularization help maintain this information hiding principle by allowing us to use objects and classes without needing to know the details of their implementation.
how does abstraction and modularization maintain the
information hiding principle “not need know”
what happens if we
use a maps get method to access a key that does not exists
in this case and in regards to maps the value null will be returned
this information hiding principle should be maintained as it means another class will not depend on another classes implementation
this means we are free to change the implemenation without affecting other classes
this is as long as the classes interfcae remains unchanged
this is known as weak or loose coupling
why should we maintain the information hiding principle
not being allowed to know
name 4 pieces of
information that should be included in the class docuentation
information includes:
1.Class name
2.A description of what a class does and how it can be used
3.@author annotation
4.@version annotation
declare and initialise the following
“a hash map from keys of type string to values of type hash set of string”
then
1. put the key “reptile” and value “empty set” into the hashmap
2. add the element “snake” into the empty set that is held by the key “reptile”
declare:HashMap<String, HashSet<String>> animalMap;
initialise:animalMap = new HashMap<>();
place key/value pair in hashmap:animalMap.put("Reptiles", new HashSet<>());
place element in the set that is a value within the hashmap:animalMap.get("repile").add("snake");
Declaration:HashMap<String, String> stringsMap;
Initialisation:stringsMap = new HashMap<>();
Equivalent:HashMap<String, String> stringsMap = new HashMap<>();
write a
1. declaration
2. initialisation
3. declaration/initialisation
for the following:
a hashmap of key type String to value type String
describe the HashMap method
containsKey()
this HashMap method returns a boolean value stating whether a key exists within the hashmap
describe the Integer static method
parseInt()
this Integer static method is used to parse a string representation of an integer into an integer value
describe the syntax and params of the String method
startsWith()
syntax:
startsWith(Stringprefix)
param:
prefix a prefix we would like to know exists at the start of the string
describe a
wrapper class
this is a class that can represent a primitive type value
similarities include:
1. Both aHashSetand anArrayListcan grow dynamically.
2. Both aHashSetand anArrayListcan contain only objects.
name 2 key similarities between
HashSet vs ArrayList
Syntax for String method:
split(value)
@param value a character or regex that defines where to separate a string
what is the syntax and params of the String method
split()
syntax:
Switch(expression/variable) { Case “Y”: isValid(); Break; Case “N”: isValid(); Break; Case “M”: isValid(); Break; Default: “please enter Y, N, M” break }
what is the syntax of the
switch statement
To change the value of this in Java, we use dot notation with the class name and the variable name, like this: Employee.employeeCount++;
This style of referencing the static variable using its class name is considered good practice because it helps clarify that the variable belongs to the class, rather than to a specific instance of the class
How do we change the value of static variables in Java, and why is this considered good practice?
this is a principle that states that the inner workings of a class (implementation) should be hidden from other classes and users. This results in better modularization.
What is
information hiding
write the code that would explicitly wrap a an int using its associated wrapper class
code:
Int anInt = 22 Integer aWrapper = new Integer(anInt);
describe the String method
toLowerCase()
this String method will return the given string but with all characters in lower case
what is the syntax and params of the HashSet method
add()
Syntax for the HashSet method:
Add(element)
@param element element to be added to this set
these include:
1. Class methods may not access any instance fields defined in the class. They may only access class variables of the same class.
2. A class method may not call an instance method defined in the class. They may only call other class methods of the same class.
What are two
limitations of class methods in Java
ignore
this is public information about a class that can be used by programmers to understand what the class does and how it can be used
describe the
class interface