Level 41

Old Level 09

Published in the Java Developer group

Knowledge vs. Skills

Old Level 09 - 1College taught us that there is no great difference between theory and practice. Well, surely you understand that’s not the same. But you don’t see the core difference. Yet there is one. Most people put the equality sign between “I know” and “I can”. Do you? How about a few examples?
  1. I know that smoking is bad for me, but I smoke.
  2. I know that fast-food is bad for me, but I eat it.
  3. I know traffic regulations but I can’t drive.
  4. I know jogging is good for me but I don’t jog in the morning.
It often happens that people take “I know” for “I can”. It’s a good example with traffic regulations. If a person knows the regulations and knows, how to drive, does it mean he can drive? Nope. What if he thinks he knows how to drive? So why would he need an instructor – he already knows everything. When you are sure you know everything already you probably won’t learn anything new. And if you’re sure you know how to do everything, you won’t study. A thought like this won’t even cross your mind. And that means you’ll miss all the wonderful opportunities to learn something. Usual college only gives you knowledge; you’ll have to acquire skills on your own. But what do I hear? You’ve had practice besides theory in your college? Ok, if you studied on physics faculty, make a working model of a steam engine with an efficiency of at least 20%. I bet you know how to do it, but you won’t be actually able to do it, am I right? You’re a chemist? Make smokeless powder. You know how, but you can’t, ha? Mathematician, are you? Calculate the trajectory of an artillery shell. Don’t forget to take into account the shape of the shell. Mathematical dots don’t fly in real life. And there are no spherical horses. Old Level 09 - 2Biologist? Isolate penicillin. This mold grows on melons, so you know. You know how – wonderful! Can you do it? Economist? Make a forecast of price grow on oil. Done? And now turn it into $2,000 or $200,000 a year based on your forecast. Have you ever played on FOREX? For real money? Or you just know what it is? International economics? Splendid! Where do I open an offshore company? In Hong-Cong, Ireland or in USA. Why? Even if you know that, which is doubtful, you’ll hardly be able to do it, since you’ve never actually done it. You don’t even have a slightest clue how to do it. Oh, you didn’t study that in college? What right do I have to give you tasks you are unprepared for? ‘Cause these are the tasks of real life. This IS practice, all you’ve studied in the college is: spherical horses, perfect competition – none of it exists in real life. But why have I forgotten to mention marketing specialist? What is the best way to spend my $500 so that as many people as possible know about my lectures? On advertisement? Are you aware that not only classic advertising is already outdated, but also the concept of USP (unique selling proposition), which I am sure you were taught in college as almost unique panacea. Forget you know anything. Ask yourself – what can I do? Useful, I mean? Something people would pay money for? Good money, I mean? So friends, let’s express gratitude to such a wonderful course as CodeGym. Due to it you’ll not only know how to program, but you’ll actually be able to do it. You’ll also be able to get a job and earn good money in a few years. I hope this money will suffice to live nice and cozy. I’ll say it once again, so you remember: it does not matter what you know. The only thing that matters is what useful skills you have, the ones people would be eager to pay you. The sooner you understand this, the better.

You have reached a new level

Level 9

Old Level 09 - 3

1 Risha, Stack trace

Old Level 09 - 4- Hey! Today I’ll tell you what the stack trace is. But first let me explain you what the stack is. - Imagine a stack of papers - assignments for a certain clerk. A new assignment can be put on the top of the stack, and he will take an assignment from the top of a stack. Thus, assignments will be done not on a first-come. Every time the clerk takes the assignment that comes last. Such a structure of collection is called a stack. - In Java, there’s a special collection - Stack. This collection has methods «add an element» and «take(get/take away) an element». As you already know, the last element added will be taken first. - Hum. It’s not difficult, I guess. - Fine. Then let me explain what a stack trace is. - Imagine that in Java function А calls function B, and the latter calls function C, which, in its turn, calls function D. So, to exit function B, you must first exit function C, and to do so you have to exit function D. This is very similar to a stack. - And what is the similarity? - In the stack, to get to a certain assignment, you also have to complete all the assignments put on top. - Well, it's kinda an analogy, but I’m not sure if I understand everything right. - Look here. In Java a stack is a set of elements. It’s like sheets of paper in a stack. To take the third from the top, you must take the second sheet, but before that you have to take the first one. You can always put and take sheets, but you can put them only on the top and take only from the top. The same applies to the function call. Function А calls function B, the latter calls function C. To exit А, you must first exit B, and to do this you have to exit C. - Wait a minute. If I got it right, the whole stack turns out in «only the last sheet that was put on the stack can be taken» and «first, the last called function should exit». Is that so? - Yes. So, the sequence of function calls is the «function call stack», or simply «call stack». The function called last must be terminated first. Let’s look at the example: Old Level 09 - 5- OK. Everything’s clear with the function call, I guess. But what’s this StackTraceElement? - Java virtual machine logs all the function calls. For this purpose it has a special collection - stack. When one function calls another, JVM places a new element StackTraceElement into this stack. When the function ends, the element is deleted from the stack. Thus, this stack always stores up-to-date information about the current state of the «function call stack». - Every StackTraceElement contains information about called method. So you can get the name of this method using the getMethodName. - The example above shows it:
  1. Get the «call stack»:
  2. Iterate the array using the loop for-each. I hope you haven’t forgotten it.
  3. Print method names to System.out.
- An interesting thing, and apparently easy. Thank you, Risha!

2 Diego, Task on stack trace display

- Hey, Amigo! Here’s a little task to display to the screen a stack trace.
1 Each method should return its StackTrace
Write five methods that call each other. Each method should return its StackTrace.
2 StackTrace again
Write five methods that call each other. Each method should return the name of its caller method. You can obtain caller method using StackTrace.
3 The method should return the line number of the code this method was called from
Write five methods that call each other. Each method should return the line number of the code this method was called from. Use the function element.getLineNumber().
4 Stack trace of 10 calls
Write code to get a stack trace of 10 calls.
5 The method should return a result - its stack trace depth
Write a method that displays and returns its stack trace depth. Stack trace depth is the number of its methods (the number of elements in the list).

3 Elly, Errors and Exceptions

- Hey, Amigo! Today we have a very interesting lesson. I’ll tell you about exceptions. Exception is a special mechanism to control errors in the program. Here are some examples of errors that may occur in the program:
  1. The program tries to write a file to the full disk.
  2. The program tries to call a method of a variable that stores the null reference.
  3. The program tries to divide a number by 0.
These actions result in an error. Usually, this leads to the closure of a program – there’s no point to continue executing the code. - Why is that? - Is there any sense to turn the wheel when the car is falling off cliff? - Do you mean the program should end? - Yes. That’s how it was before. Any error led to the termination of a program. - It’s a very smart decision. - Wouldn’t it be better to try to work on? - Yeah. You’ve typed a huge text in MS Word, saved it, it hasn’t been saved, but the program tells you that everything’s OK. And you continue typing. Silly, isn’t it? - Yeah. - Then programmers came up with an interesting move: each function returned the status of its work. 0 meant that the function worked as it was supposed to, any other value – that there was an error: this value was an error code. - But this approach had a disadvantage. After each (!) function call you had to check the code (number) returned by the function. Firstly, it was inconvenient: the error-handling code was rarely executed, but you always had to write it. Secondly, the functions themselves often return different values - what to do with them? - Yeah. That’s what I was going to ask. - Then a bright future came - exceptions and error-handling had appeared. Here’s how it works:
  1. When an error occurs, Java virtual machine creates a special object – an exception – containing all the information about the error. For different errors there are different exceptions.
  2. Then this exception forces the program to interrupt the current function immediately, and the next function, till it exits the main method. After that the program terminates. Java developers call this process «rolls back the call stack».
- But you have said that the program is not going to exit for sure. - That’s right, because there’s a way to catch the exception. Whenever and wherever you need, you can write a special code to catch these exceptions and do something important. - To do this, there’s a special construction try-catch. Look how it works: Old Level 09 - 6- Why «After method1 calling. Never will be shown» won’t be displayed to the screen? - I’m glad you asked about it. In line 25, there is a division by zero. This leads to an error – an exception. Java virtual machine created the object ArithmeticException containing the error information. This object is an exception. - An exception occurred inside the method method1(). This resulted in the immediate termination of the method. It would also lead to the termination of the method main, if there was no try-catch block. - If an exception occurs inside the try block, it will be caught in the catch block. The rest of the code in the block try won’t be executed, the execution of the block catch will start immediately. - I don’t quite understand. - In other words, this code works like this:
  1. If an exception occurs inside the try block, the code in this block is no longer executed, but the execution of the block catch starts.
  2. If no exception occurred, the try block is executed till the end, and catch is never executed.
- Ahem! - Imagine that after each method call we check whether called method terminated by itself or due to exception. If there was an exception, JVM starts to execute the block catch if it’s available, and catches an exception. If there’s no catch block, JVM terminates the current method. Then the same check begins in the method that called current method. - Now I think I got it. - That’s fine. - And what is that Exception inside catch block? - All the exceptions are classes inherited from the class Exception. We can catch any of them by specifying its class in the catch block, or all of them at once by specifying a common parent class Exception. Then, from the variable e (this variable stores the reference of an exception object) you can get all the necessary information about the error. - Great! And what if in my method occur different exceptions, may I handle them in different ways? - You have to. You can do that like this: Old Level 09 - 7- The try block may contain multiple catch blocks, each of which will catch exceptions of its type. - Umph. Well, I kinda got it. Of course, I won’t write something like this myself. However, I won’t get scared if I meet such code.

4 Elly, RuntimeException, throws

Old Level 09 - 8- I decided to bring up another topic today. In Java, all exceptions are divided into two types – controlled/checked and uncontrolled/unchecked. Checked exceptions must be caught, unchecked can be caught but that is not required. - Is it possible to throw exceptions in a code on purpose? - In your code, you can throw exceptions yourself. You can even write your own exceptions. But we’ll deep in this hole later. Now let’s learn how to work with the exceptions thrown by Java virtual machine. - OK. - If exceptions ClassNotFoundException and FileNotFoundException are thrown (appear) in a method, the programmer has to specify them in the signature of a method (method header). Such exceptions are checked. That’s what it usually looks like: Old Level 09 - 9- So, we just write throws and list exceptions separated by commas. Right? Is that so? - Yes. But there’s another interesting thing. In order the example below has been compiled, the method that calls method1() has either to catch these exceptions or throw them forward. If you want to throw checked exception forward you need to specify it in method’s header. - Once again, if in the main method, you want to call a method that has in its header phrase throws FileNotFoundException, … then you have to do one of these two things:
  1. to catch exceptions FileNotFoundException, …
    You’ll have to wrap the code where you call a dangerous method with a try-catch block
  2. not to catch exceptions FileNotFoundException, …
You’ll have to add these exceptions to the throws list of your method main. - Will you give me an example? - Look here: Old Level 09 - 10- This example won’t be compiled, because the method main calls the method method1(), which throws exceptions that must be caught. - In order the example is compiled, you need to add exception handling to the method main. You can do this in two ways: Old Level 09 - 11- And here we catch it using try-catch: Old Level 09 - 12- It’s getting clearer, but very little. - Look into the example below: Old Level 09 - 13- Still there’s an exception – RuntimeException and classes inherited from it. It is not required to catch or throw them. These are unchecked exceptions. These exceptions are considered hard-to-predict, so it’s almost impossible to predict their occurrence. You can do the same things with them, but there’s no need to specify them in throws.

5 Risha, Rolling the call stack, how to do it in exceptions

- I’d like to tell you a little bit more about how exceptions work. The example below explains that: Old Level 09 - 14- I don’t get it. - Ok. I’ll explain what’s going on. - In the example on the left, we call several methods in chain order. In method2() we specifically create and throw an exception (to initiate an error). - The example on the right shows what happens. Look at the method2(). That’s what creation of an exception transforms into: we create an object of RuntimeException type, store it in a special variable exception and immediately exit the method – return. - In method1, after the call of method2 there’s a check, if there is an exception or not; if there’s an exception, then method1 immediately terminates. This check is done implicitly after calling each (!) Java method. - Wow! - Exactly. - In the column on the right in the method main I wrote what happens when an exception is caught by the try-catch block. If there was no exception, code continues executing just as planned. If there was an exception of the type specified in catch, then we handle it. - And what do throw and instanceof mean? - Look at the last line on the left throw new RuntimeException(s). In this way we create and throw an exception. This is just an example. We won’t do it so far. - Using the command «а instanceof B» in the right block we check whether the object a has the type B. That is, whether the object stored in the variable exception, has the type RuntimeException. It’s a logical expression. - Well, it’s getting a little bit clearer.

6 Diego, Exception catch task

- Look here! Uncle Diego brought few task on catching for you. Wish you luck. I think you’ll need it. Heh. Old Level 09 - 15- Hey, Amigo! Here are some interesting exception catch tasks.
Catching tasks
1 1. Exception when operating with numbers
Catch the exception that occurs when run the code:
int a = 42 / 0;
Display the exception to the screen, specifying its type
2 2. Exception when operating with strings
Catch the exception that occurs when run the code:
String s = null;
String m = s.toLowerCase();
Display the exception to the screen, specifying its type.
3 3. Exception when operating with arrays
Catch the exception that occurs when run the code:
int[] m = new int[2];
m[8] = 5;
Display the exception to the screen, specifying its type.
4 4. Exception when operating with List collections
Catch the exception that occurs when run the code:
ArrayList<String> list = new ArrayList<String>();
String s = list.get(18);
Display the exception to the screen, specifying its type.
5 5. Exception when operating with Map collections
Catch the exception that occurs when run the code:
HashMap<String, String> map = new HashMap<String, String>(null);
map.put(null, null);
Display the exception to the screen, specifying its type.
- Tip: first write a program, then see what exception occurs and after that change the code and catch that exception.

7 Risha, How multiple catch works

Old Level 09 - 16- Now, some more interesting lectures. I like teaching so much. - I want to tell you how a multiple catch works. Actually it’s very simple: when an exception occurs in the block try, the program execution is transferred to the first catch. - If the type specified in parentheses of the block catch is the same as the type of the exception-object, then the code execution starts inside the {}. Otherwise we go to the next catch. The check is repeated there. - If there are no more catch blocks, but the exception hasn’t been caught, it’s thrown forward, and the current method is interrupted. - I see. That catch will be executed, the type of which matches the type of exception. - Yes, right. Actually, it’s a bit more complicated: The point is that the classes can be inherited from each other. If the class «Cow» is inherited from the class «Animal», the object of the type «Cow» may be stored not only in a variable of the type «Cow», but in a variable of the type «Animal» as well. - So what? - Since all the exceptions are inherited from classes Exception or RuntimeException (which is also inherited from Exception), they all may be caught using commands catch (Exception e) or catch (RuntimeException e). - So what? - This means that, first, you can catch any exception using the command catch(Exception e). Second, the order of the catch blocks does matter. Examples: - ArithmeticException resulting from division by 0 is caught in the second catch. Old Level 09 - 17- In the example below, ArithmeticException is caught in the first catch, because classes of all the exceptions are inherited from Exception. So, Exception catches any exception. Old Level 09 - 18- In the example below, the exception ArithmeticException is not caught, but thrown forward to the calling method. Old Level 09 - 19- Well, it’s getting clearer now. These exceptions are not that easy. - It only seems so. In fact, it’s one of the simplest thing in Java. - I’m in doubt whether to be pleased or upset about it…

8 Diego, Multiple exception catch tasks

- Hey, Amigo! Yesterday I got drunk and over-complicated your tasks, but I hope there are no hard feelings on your part and you will solve all of them? It’s for your own good. Here:
1 1. Exceptions
There’s a method that throws two exceptions inherited from Exception, and the other two inherited from RuntimeException: NullPointerException, ArithmeticException, FileNotFoundException, and URISyntaxException.

You need to catch NullPointerException and FileNotFoundException, but not to catch ArithmeticException and URISyntaxException. How to do it?
2 2. Catching exceptions
There are three exceptions sequentially inherited from Exception:
class Exception1 extends Exception
class Exception2 extends Exception1
class Exception3 extends Exception2
There’s a method, which is described as follows:
public static void method1() throws Exception1, Exception2, Exception3

Write a catch block to catch all the three Exception1, Exception2 and Exception3
3 3. Catching selective exceptions
1. Find out what exceptions are thrown by the method BEAN.methodThrowExceptions.
2. The method processExceptions() should call the method BEAN.methodThrowExceptions and handle exceptions:
2.1. if an exception FileSystemException occurs, then log it by calling the method BEAN.log and throw forward
2.2. if an exception CharConversionException or any other IOException occurs, just log it by calling the method BEAN.log
3. Add the class/type of the exception you are forwarding in 2.1. to the processExceptions() method signature.
4. Handle the remaining exception in the method main() and log it. Use try..catch

If you caught the exception MyException, which you didn’t want to catch, you can throw it forward using the following code:
catch (MyException e) {
throw e;
4 4. Catching checked exceptions
Handle all the checked exceptions in the method processExceptions().
You need to display to the screen each checked exception that has occurred.
You may use only one block try.
5 5. Catching unchecked exceptions
Handle all the unchecked exceptions in the method processExceptions().
You need to display to the screen a stack trace of each occurred exception using the method printStack().
You may use only one block try.

9 Professor, Lecture on exceptions

- Today we have a super-interesting topic - exceptions. At the time, when young scientists and programmers were deeply excited about this topic… - Sorry, I must go to the lab. Here are lecture notes. I think you’ll figure it out for yourself. Here: Java Exceptions (Oracle Documentation) Exception Handling in Java (Java T point) Java - Exceptions Handling (tutorials point) Basic Java Exception Handling

10 Julio

- Amigo, what do you think of the today’s lesson? Has your positron brain not worked out yet? Diego’s tasks are enough to wear out anyone. Let’s have a beer moment and relax. Are you still standing?

11 Captain Squirrels

- Hello, soldier! - Good morning, sir! - I have some awesome news for you. Here’s a quick check to reinforce your skills. Do it every day, and you’ll enhance your skills real quick. Tasks are specially designed to do in Intellij IDEA.
Additional tasks to do in Intellij Idea
1 1. Division by zero
Create a method public static void divisionByZero(), where you need to divide any number by zero, and display to the screen the result of the division.
Wrap the divisionByZero() method call into a try..catch. Display to the screen the exception stack trace using the method exception.printStackTrace().
2 2. Countdown from 10 to 0
Write a loop to countdown from 10 to 0. Use Thread.sleep(100) to make a delay;
Wrap the sleep call into a try..catch.
3 3. Wrap a method into a try..catch
Read numbers from the keyboard. Write a code for reading numbers from the keyboard into a separate method readData().
Wrap the whole body of this method (the entire code inside readData() method, except for the declaration of the list where the numbers will be stored) into a try..catch.

If the user enters some text instead of entering a number, the method has to catch the exception and display to the screen all numbers entered before.
Display numbers to the screen. Each number should be on a new line. The order of numbers should be just like it was in input.
4 4. Date converter
Read from the keyboard a date in the format «08/18/2013»
Display to the screen that date in the form of «AUG 18, 2013».
Use the objects Date and SimpleDateFormat.
5 5. Vowels and consonants
Write a program that reads line from the keyboard.
The program should display to the screen two strings:
1) the first string should contain vowels
2) the second string should contain consonants and punctuation characters from the entered text.
Separate characters by spaces.

Example input:
Stop look listen
Example output:
o o o i e
s t p l k l s t n
6 6. The tale of the Little Red Riding Hood
1. There are five classes: Red Riding Hood, grandmother, patty, woodcutter, wolf.
2. Each class has two fields of ArrayList type: killed and ate.
3. Necessary objects are already created (hood, grandmother, ...).
4. Create the correct relationship (who ate and killed whom) to get the logic of the «Little Red Riding Hood».
7 7. Move static modifies
Move static modifiers so the code compiles.
8 8. List of arrays of numbers
Create a list whose elements are arrays of numbers. Add to the list five object arrays with length 5, 2, 4, 7, 0, respectively. Fill arrays with any data and display them on the screen.
9 9. Ten cats
Create a class Cat with a field String name.
Create a dictionary Map<String, Cat>, add 10 cats on the model «Name» - «Cat».
Get from the Map a Set of names and display the set to the screen.
- Those tasks were for greens. I added bonus tasks of higher complexity. For top guns only.
Bonus tasks
1 1. Program doesn’t compile and run. Fix it.
Task: The program should read from the keyboard two file names and copy the first file to the location specified by the second name.
2 2. Add new functionality to the program.
Old Task: The program should read from the keyboard two file names and to copy the first file to the location specified by the second name.
New task: The program should read from the keyboard two file names and to copy the first file to the location specified by the second name.

If the file (that is going to be copied) with the specified name doesn’t exist, the program should display to the screen the message «File does not exist» and try to read the file name from the console once again before reading the name of second (destination) file.
3 3. Learning and practicing algorithm.
Read from the keyboard the list of words and numbers. Display to the screen words in ascending order and the numbers in descending order.

Example input:

Example output: