Shared Flashcard Set

Details

Java Cert - OCAJ-SE8 - Chapter 3 - Core Java APIs
Flashcards for Core Java Arrays, Strings, etc
97
Software
Professional
12/23/2017

Additional Software Flashcards

 


 

Cards

Term
What is a String literal?
Definition

Where you assign a String var in the declaration, not with the new keyword, but creating a new object in the stack just using the quotes;

 

String s = "this is a string";

Term
What are the rules for String concatenation?
Definition

1. If both operands are numeric, then the + operation is numeric addition.

2. If either operands is a String, then the + operation is String concatenation.

3. The expression is read left to right.

Term

How would Java concatenation print the following;

 

int three = 3;

String four = "4";

Syste.out.println(1 + 2 + three + four);

Definition

Java would add the ints 1,2, three (3) together first, reading left to right which would be 6. Then it would concatenation the String four.

Lastly it would print out

64.

Term

In Java concatenation, what does the following expression print?

 

String s = "1";

s += "2";

s += 3;

System.out.println(s);

 

Definition

It would print;

 

123

 

+= just means take the previous value, append the new value, and return a new String.

 

For example

s+=3;

Just means

s = s + 3;

Term

Mutable means _____.

Immutable means _____.

Definition

1. Changeable

2. Not Changeable

Term
True or false - Immutable classes in Java are final, and subclasses cannot add mutable behavior.
Definition
True.
Term

What does the following print?

 

String s1 = "1";

String s2 = s1.concat("2");

s2.concat("3");

System.out.println(s2);

Definition
It prints 12.  It does not print the 3 because the concat call on line 3 does not return the result to the s2 reference.
Term
What is the string pool in Java?
Definition
The string pool in Java is a location in the JVM that collects string literals for re-use.  This is also called the intern pool.
Term
Can String objects instantiated with new be added to the string pool in the JVM?
Definition
No, this is only for string literals.
Term
True or false - a Java String is just a sequence of characters and the starting index for a string, is 1.
Definition
False.  Strings are indeed a sequence of characters, however the index for a string starts at 0;
Term

The String method _____ returns the number of characters.

The _____ method returns which character is at the specified index.

The _____ method returns firstIndex of the first time the passed in character occurs in the String.

The _____ method returns a String or sequence of characters for the given starting index and (optional) ending index. If the ending index is not included, it is assumed it will move automatically to the end of the String. This method is the trickiest of the String method because it allows you enter an ending index that adds _____ to the last index in the string, or the total character count in the string. Also the first index cannot be _____ than the end index.

 

 

 

 

Definition

1. Length()

2. CharAt(index)

3. indexOf(String)

4. SubString(beginIndex, endIndex)

5. 1

6. More 

Term
True or false - the String .equals() method checks to see if the reference variables are pointing to the same object location in memory.
Definition
False.  the String .equals() method actually looks to see if the sequence of characters in one String is the same as another String. The == expression checks to see if two Strings are pointing to the same object location in memory.
Term
True or false - the String contains() method is not case-sensitive, meaning you can pass in either lowercase or uppercase chars or strings, and it will find the first instance of characters that occur, regardless of case.
Definition
False.  The String contains() method is case-sensitive, meaning in you pass in lowercase "s", it will not find anything if the String only contains "S".
Term
True or false - The String method replace() finds a String or sequence of chars within a String and replaces it with another String or sequence of characters.  It does not return a new String.
Definition
False.  It does do a find an replace inside a String, but it returns a new String when its done.
Term
In the String method trim(), what characters get trimmed and where in the String do they get trimmed?
Definition
White space chars including empty space " ", \t (tab), \n (new line), and \r (carriage return) characters get removed, ONLY from the beginning of the String and the end of the String.
Term
True or false - In the String trim() method, empty space chars get removed from inside the middle of a String.
Definition
False.
Term
True or false - With Strings, method chaining is allowed, and the resulting String must be returned to an existing or new String reference variable in order to use it in the program.
Definition
True - each time you call a method in the method chain, a new String is created and to capture all of the changes you must make sure to reassign it to a String reference variable.
Term
True or false - The StringBuilder class is immutable.
Definition

False the StringBuilder class is mutable when calling methods on it, the underlying object will reflect the changes made by calling methods on it.

 

StringBuilder sb = new StringBuilder("this is a ");

sb.append("StringBuilder");

 

You do not need to return this to an existing reference var or a new reference var.

Term

For a StringBuilder, lets say you had the following scenario;

 

StringBuilder a = new StringBuilder("a");

StringBuilder b = a.append("b");

 

What would be the value of variables 'a' and 'b' and why?

Definition

The value for both 'a' and 'b' would be "ab".

This is because references 'a' and 'b' are both pointing to the same object, 'a' is the only one with a call to new.

Term
Give examples of 3 ways to create a StringBuilder object.
Definition

StringBuilder sb1 = new StringBuilder();

StringBuilder sb2 = new StringBuilder("a");

StringBuilder sb3 = new StringBuilder(10);

Term
For StringBuilder, what does the size() method refer to?
Definition
Refers to how many characters are currently in the sequence.
Term
For StringBuilder what does capacity refer to?
Definition
Capacity refers to how many characters the sequence can hold.
Term
When you call the append() method on a StringBuilder object, what does it return?
Definition
A reference to the current StringBuilder object.
Term
What are the input params for the StringBuilder insert method, what does it do and what does it return?
Definition

1. Int for the index to insert, String or other type and value to insert

2. It inserts the value in the second param at the given index

3. A reference to the current StringBuilder

 

there is also a 4 parameter method, that takes the insert offset, a char[] or CharSequence, and the begin and end index of the char[] or CharSequence

Term
What are the StringBuilder methods related to delete, what are the input params and what do they return?
Definition

1. Delete and deleteCharAt

2. Delete - int start, int end; deleteCharAt - int index - removes just one char

3. Reference to the current sb.

Term
True or false - the StringBuilder method reverse(), just reverses the sequence of the characters.
Definition
True
Term
Which method of StringBuilder is one of the most important and why?
Definition

1. The toString() method

2. Ultimately we are looking to create a string from StringBuilder, and this method returns it.

Term
What are two key differences between the StringBuilder and StringBuffer classes?
Definition

1. StringBuffer is an older class and was built to be thread-safe.

2. Because it is thread-safe it is slower than StringBuilder

Term

Evaluate the equality of the scenario below and explain it;

 

StringBuilder sb1 = new StringBuilder("Hello World");

StringBuilder sb2 = sb1;

System.out.println(sb1 == sb2);

Definition
This evaluates to True - both StringBuilder references are pointing to the same object.
Term

Evaluate the following String scenarios;

1. String s1 = "Hello World";

String s2 = "Hello World";

==

2. String s1 = new String("Hello Word");

String s2 = "Hello World";

==

3. String s1 = "Hello World";

String s2 = " Hello World".trim();

==

4. String s1 = "Hello World";

String s2 = " Hello World".trim();

S1.equals(s2)

 

Definition

1. Equals - because they are pointing to the String Literal in the String or intern pool.

2. No equals - One is in JVM String pool, one is a new object in the heap.

3. No equals - while both are String literals, one is evaluated on compile time and one is evaluated at runtime, and are pointing to difference objects, because the runtime object was created internally with new.

4. Equals - the String equals() method looks at compares the internal characters in the String to see if they are equal.

Term
Does the StringBuilder class have a .equals() method? What happens if you call .equals() on a StringBuilder object?
Definition

1. Not one that is implemented, so no.

2. It will only return the same referential equality result as ==.

 

Term
Is an Array an ordered list?
Definition
Yes, the order you put in the objects or primitives is the order they will be found by index in the array.
Term
Show three ways to create an array of ints called numbers.
Definition

int[] numbers = new int[3];

int numbers[] = new int[]{1,2,3};

int[] numbers = {1,2,3};

Term
Create an anonymous array of 3 ints called numbers.
Definition
int[] numbers = {1,2,3};
Term
When you declare an array of lets say ints, or anything, is it legal to put either a space after the type, or after the reference variable name? Provide example declarations.
Definition

Yes it is legal to put a space after the type and reference var name.

 

int [] numbers;

int numbers [];

Term

What is the difference between the following code?

 

1. int[] ids, Nums;

2. int ids[], Nums;

Definition

1. Is declaring to two arrys of type int.

2. Is declaring 1 array of ints and one int.

Term
True or false - the .equals() method of an array compares the contents of the arrays.
Definition
False, .equals() for arrays only evaluates referential equality
Term

Identify the different components of the following;

 

[Ljava.lang.String;@ 160bc7c0

Definition

1. [L means that the object is an array

2. Java.lang.String; means it is an array of Strings

3. @ 160bc7c0 is the hascode for the array

Term
What is a class and method that will print an array of stuff elegantly?
Definition
java.util.Arrays.toString(array)
Term
True or False - an array allocates storage space for the objects in the array.
Definition
False. It allocates space for a reference to where the objects are actually stored.
Term

What are the values of the following?

 

1. String[] stars;

2. String[] stars2 = new String[2];

 

Definition

1. Stars refers to null.

2. Stars2 refers to a String array that has to two references to null.

Term

What does the following print and why?

String wary [] = new String[8];

System.out.println(wary.length);

Definition
It will print 8 - length does not care what is in the array, just how many slots have been allocated.
Term

When looping through an array, should you ever have <= in the comparison statement? Why or why not?

 

i.e.

int[] numbers = new int[10];

for(int i = 0; i<= numbers.length;++i){

 

}

 

Definition
No.  If you have equal, that assumes that you can access an element in the array that is the same as the length, but since array indeces are zero (0) based, this will generate and ArrayIndexOutOfBounds exception.
Term
What is the easiest way to sort an array?
Definition
java.util.Arrays.sort(array)
Term

If you sort the following array, what will be the result?

String[] Nums = {"10", "90", "100"};

Definition
it will sort to "10", "100", "90". Sorting strings does alphabetical order, 1 is before 9, numbers sort before letters, uppercase sorts before lowercase.
Term

What has to happen with array before you execute a search on it? How do you execute a search for a value in an array? What happens when the value is not found?

 

i.e.

int[] Nums = {1,2,3,6,8};

what value is returned when we search for 9?

Definition

1. You need to sort it (java.util.Arrays.sort(nums)) or the results will be unpredictable.

2. Java.util.Arrays.binarySearch(Nums, value)

3. You find the index where the value should be, negate it and add -1 to that value

4. So the index should be 5, we negate it to -5 and add -1 which is -6.

Term

True or false - When using a multi-dimensional array, you can initialize an arrays first dimension, and then define the size of each array component after in a separate statement.

 

int[][] numarys = new int[4][];

numarys[0] = new int[4];

numarys[1] = new int[2]; 

Definition
True
Term
What is the difference between the size of an array and the size of an ArrayList?
Definition
you cannot change the size of an array, but an ArrayList can add elements and change the size on the fly.
Term
Using Generics show how to create an ArrayList of Strings called strings, using at least two different ways.
Definition

ArrayList<String> strings = new ArrayList<String>();

ArrayList<String> strings = new ArrayList<>();

Term
What are 3 different ways to initialize an ArrayList?
Definition

ArrayList list1= new ArrayList();

ArrayList list2 = new ArrayList(3);

ArrayList list3 = new ArrayList(list2);

Term
True or false - ArrayList does not implement toString(), and will not elegantly print the contents of an array.
Definition
False, ArrayList does implement toString() and prints out the contents nicely.
Term
What are the overloaded methods for add() in an ArrayList?
Definition

boolean add(Object) (primitives can be autoboxed) always returns true

void add(int index, E element) E stands for whatever class. You want to put in the ArrayList

Term
True or false - The ArrayList remove() method has one signature that takes the index of the item to removed and returns true Boolean, or false if it can't be found or removed.
Definition
False, you can also pass in an object to be removed.
Term
Can you add duplicate objects to an ArrayList?
Definition
Yes
Term
True or false - with an ArrayList, if you execute the remove(int i) method with an index, and that index is not found, it just returns false.
Definition
False, it generates an ArrayIndexOutOfBoundsException.
Term
What happens if you call the remove(index) method on an ArrayList and the index is not found? Is this the same behavoir as calling remove(E type)?
Definition
It generates an ArrayIndexOutOfBoundsException. Remove(index) generates exception when index is not found, where remove(E type) returns false when not found.
Term
What happens when there are duplicates (Objects, Strings, etc) in an ArrayList, and you call remove on the value, not the index?
Definition
It will not remove the first instance it finds, not all instances.
Term
What is the signature of the set() method in an ArrayList? What happens if you try to set a value on an index that does not exist?
Definition

E set(index i, E type)

It will generate an error

Term
An ArrayList uses the method _____ to see if the list has any values, and uses the method _____ to see how many values are in the list.
Definition

1. IsEmpty()

2. Size()

Term
What happens when you call the clear() method on an ArrayList()?
Definition
It clears out all values from the ArrayList, and sets the size to zero.  It is not null because you can still call the size method on it.
Term
When contains() method is called on an ArrayList, does the ArrayList utilize the objects equals method?
Definition
Yes, so for an ArrayList of Strings it will compare the contents of the strings. However for other objects that do not implement .equals(), it will only look at the == referential integrity of the internal objects.
Term
What are the requirements for 2 ArrayLists to be equal when the .equals() method is called?
Definition
Must have the same type of objects with the same values, in the same order.
Term
What are the methods to convert strings to primitives?
Definition

Boolean.parseBoolean("TrUe");

Short.parseShort("0");

Byte.parseByte("1");

Integer.parseInteger("2");

Long.parseLong("3");

Float.parseFloat("4");

Double.parseDouble("4.0");

Character does not have a parse method 

Term
What are the methods for converting strings to Wrapper type objects?
Definition

Booealn.valueOf("True");

...Double.valueOf("4.89");

 

All wrapper types have valueOf methods, except Character.

Term
In an ArrayList, what happens when you add an item as null value, and then try to call .get() on that value?
Definition
When the Autoboxing tries to convert the null to the type of object on the ArrayList, it will fail with a NullPointerException.
Term
What are two ways you can convert an ArrayList to an array?
Definition

List<String> l = new ArrayList<>();

1. String[] ary1 = l.toArray();

2. String [] ary2 = l.toArray(new String[0]);

Term

Explain the concept of an array backed list?

What happens when you try to remove an element from the List?

Definition

1. When you want to convert from an array to a list, you exectute;

String[] oldAry = new String[4];

List newList = Arrays.asList(oldAry);

When you do this you have created an fixed-size, array backed list - when you make a change to one, the other will be affected as well.

2. Because an array cannot change its size on the fly, meaning it cannot add or remove elements, the list cannot change either.

Term
In the Arrays class, what parameter does the asList() method take, and what can you do when you call this method?
Definition

The asLIst() method takes a Varargs param Arrays.asList("one", "two", "three");

This is handy for testing and creating a list on one line.

Term
How do you sort a List?
Definition
You use Collections.sort(List l)
Term
How do you create time, date, datetime objects in Java 8, and what does the default value look like when printed?
Definition

LocalDate ld = LocalDate.now();

LocalTime lt = LocalTime.now();

LocalDateTime ldt = LocalDateTime.now();

 

2015-01-02

T12:35:34.401

2015-01-02T12:35:34.401

Term
What is another way to create a LocalDateTime object?
Definition

LocalDate ld1 = LocalDate.of(2015, Month.JANUARY, 7);

LocalTime lt1 = LocalTime.of(11, 36, 59, 200);

LocalDateTime ldt1 = LocalDateTime.of(ld1, lt1);

 

OR

 

LocalDateTime ldt2 = LocalDateTime.of(2015, Month.JANUARY, 7, 11, 36, 59, 201);

Term
True or False - LocalDate, LocalTime, LocalDateTime objects have public constructors.
Definition
False, none of these objects have public constructors, they all have private constructors, and force implementer to use the static methods .of()
Term
True or false - the LocalDate, LocalTime, and LocalDateTime classes are Mutable.
Definition
False, all these classes, like the String class are immutable, and you must assign the resulting value to an object.
Term
What are the public methods used to change the date and time objects in Java 8?
Definition

.plusDays(int),

.plusYears(int),

.plusMonths(int),

.plusMinutes(int),

.plusHours(int),

.plusSeconds(int),

and the minus versions of these methods

REMEMBER YOU MUST ASSIGN THE VALUE BACK TO AN OBJECT REFERENCE

 

Term
Can you use method chaining with new Java 8 date time objects?
Definition
Yes, but the values will only show as chained and updated if you assign the result back to a reference variable.
Term

True or false - you can use object methods from LocalDate and LocalTime on their respective objects. In other words, it is legal to call a method like plusDays() on a LocalTime object, and minusSeconds() on a LocalDate object, and it will compile.

i.e.

LocalTime lt1 = LocalTime.now();

lt1 = lt1.plusDays(1);

Definition

False, you can only use the related methods to the fields that are associated with that object.

i.e.

LocalTime lt1 = LocalTime.now();

lt1 = lt1.plusMinutes(1);

Term
What are the 5 ways to create a period class?
Definition

Period months = Period.ofMonths(4);

Period years = Period.ofYears(3);

Period days = Period.ofDays(5);

Period weeks = Period.ofWeeks(6);

Period yearAndAWeek = Period.of(1, 0, 7);

Term
What params are in the Period.of() method?
Definition
Years months and days
Term

True or false - method chaining is legal for Period class;

Period p = Period.ofMonths(2).ofDays(6);

Definition
False - method chaining is not legal for Period class.
Term

True or false - you can mix date and time Period info among LocalDate and LocalTime classes.

 

Period months = Period.ofMonths(3);

LocalTime time = LocalTime.now();

time.plus(months);

Definition
False - you cannot mix date and time Period info among the LocalDate and LocalTime objects, because Period object only works with LocalDate, and LocalDateTime, NOT LocalTime.
Term
How do you add Period objects to LocalTime and LocalDate and LocalDateTime objects?
Definition
Use the plus method.
Term
How do you convert a LocalDate or LocalTime object to String?
Definition

Use the built-in format method by passing in the DateTimeFormatter type.

 

LocalTime time = LocalTime.now();

String tStr = time.format(DateTimeFormatter.ISO_LOCAL_TIME);

 

Or ISO_LOCAL_DATE, Or ISO_LOCAL_DATE_TIME

Term
Provide an example of the output of formatting LocalDate, etc objects with DateTimeFormatter.ISO_LOCAL_*.
Definition

DateTimeFormatter.ISO_LOCAL_DATE = "2012-01-01"

DateTimeFormatter.ISO_LOCAL_TIME = "11:35:46.890"

DateTimeFormatter.ISO_LOCAL_DATE_TIME = "2012-01-01T11:35:46.890"

 

 

Term
True or false - the .format() method exists on the LocalDate, etc objects, as well as the DateTimeFormatter Object.
Definition

True - for example;

LocalDate ld = LocalDate.now(2013, Month.JANUARY, 29);

String dateStr = ld.format(DateTimeFormatter.ISO_LOCAL_DATE);

 

AND

 

DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);

String dateStr2 = dtf.format(ld);


 

Term
For a DateTimeFormatter object, what does the FormatStyle.SHORT format look like for a date, time, and datetime?
Definition

1. 01/01/2012

2. 11:12 AM

3. 01/01/2012 11:12 AM

Term
For a DateTimeFormatter object, what does the FormatStyle.MEDIUM format look like for a date, time, and datetime?
Definition

1. Jan 20, 2013

2. 11:12:45 AM

3. Jan 20, 2013 11:12:45 AM

Term

Provide an example of the DateTimeFormatter.ofPattern() method.

 

Definition

LocalDateTime dateTimeNow = LocalDateTime.now();

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM, yyyy, dd");

 

String dateTimeStr = dtf.format(dateTimeNow);

 

 

Term
How do you convert a String to a LocalDate or LocalTime object?
Definition

Use the parse() method on the objects.

LocalDate date = LocalDate.parse("01-01-2012");

OR

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM dd yyyy");

date = LocalDate.parse("01-01-2013", dtf);

Term
What happens if the String method indexOf("s") can't find the string its looking for?
Definition
It returns -1.
Term
True or false - after you declare an array, without initializing it, you can 1) then on the next line initialize it with an anonymous array initializer ({"1", "2", "3"};) or 2) Also with the new keyword (new String[]{"1", "2", "3"};).
Definition
False - while you can use the new keyword to initialize the array after declaration, you cannot use the anonymous array initializer after the array is first declared.
Term
True or false - StringBuilder and StringBuffer have the same methods, but the difference is that StringBuilder is not thread safe (methods do not have the synchronized keyword) and it is faster.
Definition
True
Term

True or false = when instantiating an array like;

String[] strAry = new String[]{"1", "2"};

it is also legal to instantiate by moving the brackets on the right before String and after new.

Definition
False - must be new String[]
Term
True or false - for String, capacity and length are redundant properties.
Definition
True, because String is immutable. Length and capacity will be the same.
Term

True or false - when using the diamond operator as a generic declaration element, you have the option to only include it on the left side of the declaration.

 

i.e.

List<Integer> l = new ArrayList();

Definition
True
Term
True or false - ArrayList has a method subList(index x, index y) that returns the elements between those indices.  Also, if the index numbers are the same it returns an empty list.
Definition

True

List l = new ArrayList();

List l2 = new ArrayList();

l.add("hello");

l2.add("goodbye");

List l3 = l2.subList(0, 1); // this is the proper way to get a sublist

l.add(l3);

List l4 = l2.subList(0,0); // this returns an empty list.

Term

True or false - you can initialize an array by using the array size and an anonymous array on the right side of the declaration.

String[] sA = new String[1] {"aaa"};

Definition
False - you cannot use size on the right side when you also use an anonymous array declaration.
Term

True or false - String builder does not have a 4 parameter insert method that inserts a portion of a charsequence into the designated offset char;

i.e.

public StringBuilder insert(int dstOffset, CharSeqence s, int start, int end)

Definition
False - StringBuilder DOES have a 4 parameter insert method, that takes a portion of the passed in char sequence and inserts it at the designated offset char of the original StringBuilder.
Supporting users have an ad free experience!