📜 ⬆️ ⬇️

Questions and Tasks for the Russian-language book Thinking in Java (Java Philosophy) by Bruce Ekkel



To the question “Which book to start learning Java?” Is often answered: Thinking in Java by Bruce Ekkel.
But the trouble is that this book (4th edition) does not contain questions and a workshop at the end of each chapter ...

That is what contributes to the most effective language learning!
')
Studying this book, I made small notes about moments that were new or interesting to me. And designed them in the form of short questions. After reading each chapter, I went over this list and invented tasks similar to the code given in the chapter.

Why not share these notes with you?

A list of currently compiled questions.
Questions like “What is the inner class?” Are missing. Such definitions, in my opinion, are clearly formed as the chapter is read and do not require a boring and banal question for reinforcement.

And also there are no questions like “what is a stack? What are the features of his work? " They are basic for many languages ​​and for all programming in general. Therefore, I tried to avoid them.

In general, I tried to formulate questions about various interesting subtleties and nuances that require periodic repetition.

At the end of the questionnaire is a translation made by me of some exercises, tasks, published in the English-language original of the book. The pages on which these exercises are printed are indicated.

You will be pleasantly surprised that the page numbers of the Russian edition have been added to most of the answers to the questions. These pages also contain answers to the formulated questions.


Chapter 10. Inner Classes
Questions:
1. To which fields and methods of the outer class does the inner class have access? How will the answer change if the class is declared static?
2. Write code that creates an object of the inner class. How will this code change if the inner class is declared as static?
3. Give the code that allows you to call the external class method from the internal class method.
4. What is the limitation of the inner class in terms of the implementation of its interfaces?
5. Should the inner class implement the same interface as the outer one?
6. Write the factory implementation code using an anonymous class.

Chapter 11. Object Collections
Questions
1. What is the Collection interface?
Answer
The Collection interface is the root interface that describes the overall functionality of all sequential containers (p. 301).

2. Can containers be used to store primitives?
Answer
Primitives cannot act as container elements. Only references to objects can be placed in the container. However, the Autoboxing mechanism automatically converts the primitive into an object type. Consequently, the programmer can “forget” about the above limitation.
(answer given with MrD )


3. What is the preferred method of adding elements to the ArrayList container:
Arrays.asList or Collections.addAll and why?
Answer
Collections.addAll is preferred because of its greater performance (p. 282).

4. List several methods available when working with an ArrayList.
Answer
“Contains (Object o)” - check the presence of an element in the array.
"IndexOf (Object o)" - get the index of the element.
“SubList (index1, index2)” - copy a part of the elements into a new container.
“ContainsAll (Object [] o)” - check for the presence of elements in the container.

5. What does the remove () method return for a container of type Queue return?
Answer
The Queue.remove () method not only removes the head element of the queue, but also returns its string value.

6. What operations are performed faster when working with LinkedList compared to ArrayList?
Answer
Inserting and deleting items from the middle of the list when using LinkedList is faster (p. 291).

7. What types of containers can be implemented using LinkedList?
Answer
Stack, queue, two-way queue.

8. How does the Set container family differ in the List container family? (thanks to MrD for editing)
Answer
In the Set container family, data can be stored only in one instance (p. 294)

9. Will an exception occur if I try to add an element to the Set that is already present in it?
Answer
Exceptions will not occur.

10. How does a PriorityQueue container differ from a Queue?
Answer
Items in the PriorityQueue can be sorted according to specific rules.

11. What is the Comparator used for PriorityQueue for?
Answer
Comparator allows you to set the rules for sorting elements of PriorityQueue.

12. What do the “Tree” and “Hash”, “LinkedHash” prefixes mean, for example, for the container type Set (TreeSet, HashSet, LinkedHashSet)
Answer
The prefix "Tree" means that the elements of the container are stored in sorted order.
(for example, in alphabetical order or ascending) The prefix “Hash” means that the container implements hashing to speed up the selection. The prefix “LinkedHash” means that the container elements are stored in the order of insertion, and thus provides quick access (p. 309)

13. Does the “Map” container support the Iterable interface?
Answer
The “Map” type container interface Iterable does not support (p. 305) The list of classes that support the Iterable interface:
docs.oracle.com/javase/1.5.0/docs/api/java/lang/Iterable.html

14. Does the foreach syntax work for a “Map” container?
Answer
For a container of type "Map" foreach syntax does not work, because it does not support the interface iterable

15. What is the main advantage of using an iterator to access container elements?
Answer
The iterator can be used for containers of various types (p. 290).

16. What new features are provided by the ListIterator iterator compared to a regular iterator?
Answer
The ListIterator provides sequential access to elements not only from the beginning to the end of the container, but also vice versa (p. 290).


Exercises
11. 1. Create a Fruit class. The class must contain an int weight field, a constructor with initialization of this field, and the printWeight () method, which prints the weight value.
In the main method, add several Fruit objects to the List container. Call printWeight () for each of the objects in the following ways:
A) using the get () method;
B) using an iterator.

Answer
// Fruit.java public class Fruit { private int weight = 0; public Fruit(int weight) { this.weight = weight; } public void printWeight() { System.out.println("Weight is: " + weight); } } // Apply.java import java.util.*; public class Apply { public static void main(String[] args) { List<Fruit> fruits = Arrays.asList(new Fruit(10), new Fruit(20)); // a System.out.println("Task a: "); for (Fruit f : fruits) { f.printWeight(); } // b System.out.println("Task b: "); Iterator<Fruit> it = fruits.iterator(); while(it.hasNext()) { it.next().printWeight(); } } } 



11.2. The Fruit class from 11.1 is placed in the map container. Let the name of the owner be specified as the key, the value of the object of the type Fruit. Implement iteration of each Fruit object by key and calling the printWeight () method for the found object: using foreach; using an iterator.

Answer
Thanks quarantino for a compact version of the solution with an iterator.
Fruit class - see task 11.2

 import java.util.*; import java.util.Map.Entry; public class Apply { public static void main(String[] args) { //  HashMap,      Map<String, Fruit> fruit = new HashMap<String, Fruit>(); fruit.put("Bob", new Fruit(10)); fruit.put("Mary", new Fruit(20)); //    foreach System.out.println("With foreach"); for (String key : fruit.keySet()) { fruit.get(key).printWeight(); } //     System.out.println("With iterator"); Iterator<Entry<String, Fruit>> it = fruit.entrySet().iterator(); while (it.hasNext()) { it.next().getValue().printWeight(); } } } 




11.3. Using the Comparator for PriorityQueue, ensure that string variables are sorted by size.

Answer
Note: The example is taken from the Internet.
 // StringComparator.java import java.util.Comparator; public class StringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { if (s1.length() < s2.length()) { return -1; } if(s1.length() > s2.length()) { return 1; } return 0; } } // PriorityQueue.java import java.util.Comparator; import java.util.PriorityQueue; public class PriorityQueueUse { public static void main(String[] args) { Comparator<String> comparator = new StringComparator(); PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator); queue.add("abcde"); queue.add("abc"); queue.add("abcdefghi"); queue.add("a"); //          String System.out.println("Before removing:"); System.out.println(queue); //          String System.out.println(); System.out.println("Look at removing order: "); while (queue.size() != 0) { System.out.println(queue.remove()); } } } 



Translation of exercises from the original book:
11.4. Create a new Gerbil class with an int gerbilNumber field. Let the field be initialized by the constructor. Also create a hop () method that prints Gerbil's number which is hopping is: and the value of the gerbilNumber variable. Place the Gerbil objects in the ArrayList container. Implement the get () method to traverse the list with a call to the hop () method for each of these objects.

11.5. Modify SimpleCollection.java to use the Set method for the variable "c". Modify innerclasses / Sequence.java so that any number of elements can be added there.

11.6. Write a class Generator, which has a list of the names of the characters of your favorite movies (objects of type String). Let each object in this list be returned using the next () method. When the end of the created list is reached, it is necessary to go back to the top of the list.
Use the Generator class to populate containers like ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet. Write a universal method that would output the contents of each of the arrays.

11.7. Modify ListFeatures.java so that it uses objects of type Integers instead of objects of type Pets. Explain the differences in the results of work arising from this modification.

11.8. Repeat exercise 11.7 for ListFeatures.java, but replace Pets with Strings.

11.9. Create a class that generates an initialized array of objects of another class. Using this array, fill the container of type List. Create another container using subList () for the List. Then remove the elements that you extracted using subList () from the container from which you extracted them.

11.10. Humorous exercise on the use of various containers and their methods (designed by yourself)
Suppose we have a list of expenses, initially consisting of 3 elements: “food”, “medicine”, “entertainment”. It is necessary to write these elements into the List container, and their order should not change.

What happened next?
1) We suddenly realized that we had forgotten to add credit costs to the list. It is necessary to place the “taxes” entry between “food” and “medicine” without using record indexes directly.
2) The wife dragged an additional separate list of expenses with entries: "coat", "restaurant". There is nothing to do: add costs to the end of the list (so as not to be deceived).
3) However, the mother-in-law dragged us a couple more points: “theater”, “home decoration” and “medicine”. Maybe you already had one of these items. Just in case, copy the contents of the first container to the new container of Set type and then, without hesitation, add these fad to the end of the list.
4) Without hesitation, we have created an associative dynamic list of expenses map <String, Integer>, where Integer is the planned costs for each of the items of expenses (choose the amounts yourself).
5) We became extremely wealthy and decided to increase the amount of all costs by 30%. Write the method that does it for you.
6) Stop! Enough with us "home decoration!" And, perhaps, on the coat goes too much. Add these items to the new List and pass to the method, which, having considered this sheet, in the Map container will find the corresponding items of expenses and reduce them by ... 80%!
7) Svalim-ka part of the cost of the mother in law. Moreover, we will make her a surprise! We will generate two random numbers that will determine the starting and ending indices, all costs between which will be recorded in a separate List (which later will be slipped by the mother-in-law). Do not forget to update the Map, throwing out the corresponding expenditure items from it.
8) We will write a method that determines what the smallest amount of expenses goes on, we print the name of these expenses and proudly remove this item from the list.
9) However, additional consumables added to us: “food” and “restaurant”, decorated in the form of another array! Check if these items are on our list? And if at least one expense is, then in no case will we add them! If there is nothing of this, then (nothing can be done), we add both of these points at once (as I got hungry!).
10) We are crazy! From the Map list, we will read all the Integer sums we have left, write them into “some” container, which will sort them out ascending, then mix them up with a rage and delete them in the reverse order, furiously applying a special iterator for this.






Chapter 17. Parallel Execution
1. Explain the difference between the start () and run () methods for threads.
Answer
start () is the method that calls to start the stream. The method does not require determination.
Run () is a method that is executed after the start () call. It requires redefinition and contains the code-task for the execution of which the thread was launched.

2. Whether the garbage collector deletes a thread, the link to which is not stored in any variable:
 New Thread(new ThreadTask()).start; 

Answer
Each stream registers itself independently, and the garbage collector does not have the right to delete it (p. 560).

3. How does a daemon thread differ from a regular one?
Answer
After all the main threads have completed, the daemon threads also complete their work. At the same time, it does not matter whether these tasks have completed their tasks or not (p. 568).

4. Let the daemon thread generate a new thread. Is this thread normal or a demon thread?
Answer
Such a method is a daemon thread (since .571).

5. The purpose of the join () method called on the stream.
Answer
The thread.join () method for a thread can be called by another (current) thread. As a result, the current thread pauses its work. The current thread will resume when the thread.join () thread completes its task (p. 576)

6. What are atomic operations in terms of interrupts? Give examples of atomic and non-atomic operations.
Answer
Atomic operations are, as a rule, simple operations that are carried out without the possibility of interruption. That is, it is not possible to obtain an intermediate state of the field.
Examples of atomic operations: assignment, return value.
Examples of non-atomic operations: increment, decrement (p. 579)

7. Why do I need to use the synchronized keyword?
Answer
To prevent conflicts between threads related to access to shared resources (p. 581)

8. Define a mutex.
Answer
Mutex is a deadlock mechanism implemented as follows. The code is placed in a section called a lock section. This code should be passed at a time with only one thread. Another thread during this passage cannot access the blocking section (p. 581).

9. Tell us how you can set access to a shared resource using methods declared as synchronized.
Answer
The shared resource can be placed inside the object. Further, any method that accesses a resource is declared as synchronized. Let some task be performed by a stream inside one of these methods. At the same time, all other threads cannot go into any synchronized method. They will be able to do this only after the first thread does not complete the work with these methods (p. 582).

10. What is a Lock object for?
Answer
The lock object is designed to explicitly manage mutexes. Such an object, explicitly created in a program, allows you to set or release a lock (p. 583).

11. Should the lock () call place a try-catch block?
Answer
To place such a block should. Moreover, it is advisable to add a finally section. In this section, call unlock (). This ensures that the lock is released in the event of an exception.

12. What are the limitations when using synchronized versus Lock?
Answer
Using synchronized cannot get a lock with a bad outcome. It is also impossible to obtain a lock for a certain period of time, after which a refusal may follow (p. 584).


Exercises
1. Implement the Runnable interface in an arbitrary class.
Inside the overridden run () method, type a message. After that, call yield (). Repeat the above two steps three times, then terminate the run () method.
Place a message at the beginning of the constructor stating that the constructor has started. Also place a message stating that the thread has completed. Create several such problems and solve them using multiple threads (p. 826 of the original).
2. In accordance with the form generics / Fibonacci.java, create a task that generates a sequence of n Fibonacci numbers. Moreover, n must be passed to the constructor of this task. Create several such problems and solve them using several threads (p. 804 of the original).
3. Repeat exercises 1 and 2 using different types of executors (p. 804 of the original).
4. Modify exercise 2 so that Callable summarizes all the values ​​of Fibonacci numbers. Make several such problems and print the results of solving these problems (p. 807 of the original).



Questions and exercises will be added periodically, as they are compiled and translated. Each such addition will be written at the end of the article (expand “Updates”) and written in the comments.

I do not guarantee that the chapters will be added sequentially. For example, after the questionnaire for chapter 11, a questionnaire may appear for the 17th.

I suggest you also take part in the preparation of questions and workshops on chapters of the book!
I ask those who wish to take part to write to me in the "dialogue". I will immediately inform you that I will not publish questions and exercises on chapters going to No. 10 (the material has already been studied).

Useful information:
In the English original, Thinking in Java, after paragraphs, exercises are given (Thanks, iflista )
The English book "Annotated Solution Guide for Thinking in Java" provides solutions for these exercises (Thanks, WraithOW ).

References:
Educational material and Java tasks from the Oracle site (eng)
docs.oracle.com/javase/tutorial/java/index.html

Updates
Update 1 (02/15/2014): Revised questions on chapter 11, added answers to questions. Added 3 exercises to Chapter 11 (Thank you, soundie for the idea of ​​borrowing some of them from previous editions)
Update 2 (02/18/2014): Added some questions and exercises to chapter 17. The rest will be published later.

Source: https://habr.com/ru/post/212707/


All Articles