CodeGym/Java Blog/Random/Exploring questions and answers from a job interview for ...
Konstantin
Level 36
Odesa

Exploring questions and answers from a job interview for a Java developer position. Part 6

Published in the Random group
members
Hello, World! It is essential for any developer never to stop growing. After all, if you stop, you risk falling out of demand and falling entirely out of the job market. The IT world is constantly evolving and moving forward — you need to move along with it. But at the same time, you can't just always spin in the latest technologies lest you forget the "classics" (classic software development topics). Today I want to continue my discussion of "classic topics" for Java developers. Exploring questions and answers from a job interview for a Java developer position. Part 6 - 1I will point out that my answers are not the final word. They are just my view of the correct answers — you may disagree with some of them. That is just fine, so feel free to share your opinion in the comments. You can find links to the previous parts of the review at the end of the article. Exploring questions and answers from a job interview for a Java developer position. Part 6 - 2

Libraries and standards

52. What is Hibernate? What's the difference between JPA and Hibernate?

To answer this question, I think we first need to understand what JPA is. It is a specification that describes an object-relational mapping of simple Java objects and provides an API for storing, retrieving, and manipulating such objects. That is, relational databases (DBs) are represented as a set of interconnected tables. And JPA is a widely adopted standard that describes how objects can interact with relational databases. As you can see, JPA is something abstract and intangible. It's like the idea itself, the approach. Exploring questions and answers from a job interview for a Java developer position. Part 6 - 3But Hibernate is a specific library that implements JPA paradigms. In order words, you can use this library to work with a relational database through objects that represent data in the database (Entity). This library is said to be very close to JPA ideals. That may be why it became popular. As you can imagine, its popularity justified further development and improvements. Additionally, the widespread use stems from a vast community that has already explored every possible and impossible question related to this tool. Hibernate has been thoroughly studied, and, as it turns out, it is reliable. There's a good reason why even the ideal JPA implementation in Spring generally uses Hibernate under the hood.

53. What is cascading? How is it used in Hibernate?

As I said earlier, communication in Hibernate happens through data objects called entities. These entities represent specific tables in the database, and as you will recall, Java classes can contain references to other classes. These relationships are also reflected in the database. As a rule, they are either foreign keys (for OneToOne, OneToMany, ManyToOne relationships) or intermediate tables (for ManyToMany relationships). When your entity has references to other related entities, annotations are placed above these references to indicate the type of relationship: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany. You can specify the type of cascade for this relationship in the annotations' cascade property. JPA has specific methods for interacting with entities (persist, save, merge ...). Cascade types are used to show how related data should behave; these methods are used on a target entity. So what are the cascading strategies (cascade types)? The JPA standard provides for the use of six cascade types:
  • PERSIST — save operations occur in a cascade (for the save() and persist() methods). In other words, if we save an entity that is associated with other entities, then those entities are also saved in the database (if they are not already there)

  • MERGE — update operations occur in a cascade (for the merge() method)

  • REMOVE — delete operations occur in a cascade (remove() method)

  • ALL — contains three cascading operations all at once — PERSISTMERGEREMOVE

JPA has the concept of a persistent entity — an entity associated with its data in the database and controlled by the current session (connection). If you change it without saving the changes to the database, the entity's data in the database will still be changed.
  • DETACH — related entities are not managed by the session (detach() method). That is, when the related entities' data is changed, the data in the database is not automatically updated — they are converted from persistent to detached (i.e. the entity is not managed by JPA)

  • REFRESH — every time an entity is refreshed with data from the database (refresh() — refreshes detached objects), its related entities are also refreshed. For example, you somehow changed the data taken from the database, and you want to restore the original values. In this case, you will find this operation useful.

Exploring questions and answers from a job interview for a Java developer position. Part 6 - 4Hibernate supports all of these standard cascading operations and also introduces three of its own:
  • REPLICATE — used when we have more than one data source and we want the data to be synchronized (Hibernate's replicate method). All entities must have identifiers (id) to ensure that they can be created without problems (to ensure that the same entity does not have different ids for different databases)

  • SAVE_UPDATE — cascading save/delete (for Hibernate's saveOrUpdate method)

  • LOCK — the opposite of the DETACHED operation: converts a detached entity back to the persistent state, i.e., the current session will track the entity once again

If no cascade type is selected, then an operation on the entity will not affect other entities associated with it.

54. Can an Entity class be abstract?

According to 2.1 The Entity Class of the JPA specification, "Both abstract and concrete classes can be entities." So, the answer is yes, an abstract class can be an entity and can be marked with the @Entity annotation.

55. What is an entity manager? What is it responsible for?

First of all, I would like to note that EntityManager is a crucial component of JPA. It is used for entities' interaction with the database. In general, methods for the entity's interaction with the database are called on the entity (persist, merge, remove, detach)... But I also note that this component is usually not a singleton for the entire application. It is often lightweight, one is deleted, and a new one is created using the EntityManagerFactory. If we draw a parallel with JDBC, where EntityManagerFactory is analogous to DataSource, then EntityManager is analogous to Connection. Earlier, I mentioned that a persistent entity is an entity that is managed by the current connection. This entity is managed by the EntityManager, which is closely related to the current connection, and the TransactionManager, which is responsible for opening/closing transactions. In the figure below, you can see the entity's life cycle: Exploring questions and answers from a job interview for a Java developer position. Part 6 - 5The EntityManager manages the entity when it is in the Managed stage (when it is persistent, since it has a connection with the EntityManager). That is, it is not new and also not removed. When an entity is new or removed, we can say that it is also detached, because the EntityManager does not manage it. There are different strategies for the EntityManager. You can have a EntityManager singleton for the entire application or create a new one each time for each connection. If you are using Spring, the creation/deletion of EntityManager is managed automatically under the hood (but that doesn't mean that you can't customize it for yourself ^^). I need to mention that one or more EntityManagers form a persistence context. A persistence context is an environment in which instances of entities are synchronized with similar entities in the database (as I said, this only works for persistent entities). If you delve deeper into JPA (which I highly recommend), you will encounter this concept very often.

56. What is the Assert class? Why is it used?

I haven't heard of such a class in JPA, so I will assume that this question refers to a class found in the JUnit library that is used for unit tests. In this library, the Assert class is used to check the results of code execution (here assert means an assertion that you have specific state/data at a specific location in the code). For example, let's say you are testing a method that is supposed to create a cat. You run the method and you get some result:
Cat resultOfTest = createCat();
But you need to make sure it was created correctly, right? So you manually create a specific cat (expectedCat) with exactly the parameters that you expect to see in the cat obtained from the createCat() method. Then you use the Assert class to verify the results:
Assert.assertEquals(resultOfTest, expectedCat);
If the cats are different, then an AssertionError will be thrown, which tells us that we did not get the expected results. The Assert class has many different methods that cover a variety of operations helpful in verifying expected results. Here are a few of them:
  • assertTrue(<boolean>) — the value passed in as an argument is expected to be true

  • assertFalse(<boolean>) — the value passed in as an argument is expected to be false

  • assertNotEquals(<object1>, <object2>) — the objects passed as arguments must be different when compared using equals (false)

  • assertThrows(<ClassNameOfException>.class, <exceptionObject>) — the second argument is expected to be an exception thrown by the first argument (i.e. the second argument is usually a method call that should throw an exception of the required type)

String

57. Describe Java's String class

String is a standard Java class responsible for storing and manipulating string values (sequences of characters). It is an immutable class (I wrote about immutable previously here), i.e., the data of objects of this class cannot be changed after they are created. I would like to note right away that the StringBuilder and StringBuffer classes are essentially identical — the only difference is that one of them is intended for use in a multithreaded environment (StringBuffer). These classes are like String, but differ in that they are mutable. Even after they are created, they let you modify the strings they represent, without creating a new object. Their methods differ from the standard String methods and are designed for string manipulation (there's a reason they call it a builder).

58. What are the ways to create a String object? Where is it created?

The most common way to create a string is to specify the value we want in double quotation marks simply:
String str = "Hello World!";
You can also do it explicitly using new:
String str = new String("Hello World!");
You can also create a string from an array of characters:
char[] charArr = {'H','e','l','l','o',' ', 'W','o','r','l','d','!'};
String str = new String(charArr);
We can do it by calling the toString method on some object:
String str = someObject.toString();
We can do it by calling any other method that returns a string. Example:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine();
You understand that there can be many, many ways to create a string. When a String object is created, it is stored in a string pool, which we will discuss in more detail in one of the questions below.

59. How do you compare two Java strings, and how do you sort them?

Java uses a double equal sign (==) to perform comparisons. If we need to compare simple values like ints, we will use it. But this method is not suitable for comparing full-fledged objects. It will only compare references, i.e. whether the references point to the same object or not. This means that if we compare two objects with the same field values using ==, we will get false. The fields have the same values, but the objects themselves occupy different locations in memory. String objects, despite their deceptive simplicity, are still objects. Comparing them using == is also not appropriate (despite the presence of a string pool). The proper solution is the Object class's standard equals method, which needs to be overridden to work correctly (by default, it uses == for comparisons). The String class overrides it, so we just use its implementation:
String firstStr = "Hello World!";
String secondStr = "Hello World!";
boolean isEquals = firstStr.equals(secondStr);
Exploring questions and answers from a job interview for a Java developer position. Part 6 - 6We've talked about comparisons for equality. Now we'll figure out comparisons for sorting. After all, if we're going to sort something, we need to know what principle we'll be using to sort. To do this, you can use TreeSet, a standard sorted set. This data structure relies on the red-black tree algorithm and sorts the set according to a specified sorting principle. As I said earlier, you need to understand how to sort objects of a certain type. To assign the comparison method for sorting, use comparators. You typically need to implement them for classes you want to sort, but in the case of String, they are already implemented. Accordingly, we simply add our strings to the TreeSet, and it will sort them for us:
TreeSet<String> sortedSet = new TreeSet<>();
sortedSet.add("B");
sortedSet.add("C");
sortedSet.add("A");
sortedSet.forEach(System.out::println);
Console output:
A B C

60. Provide an algorithm for converting a string to characters. Write the corresponding code

As I said earlier, String objects have a lot of different useful methods. One of these is toCharArray. This method converts a string to a character array:
String str = "Hello world";
char[] charArr = str.toCharArray();
Next, we have an array of characters that we can reference by index:
char firstChar = charArr[0]; // H

61. How do you convert a string to a byte array and back? Write the corresponding code

The String class has a getBytes method, which is similar to the toCharArray method and returns the string as a byte array:
String str = "Hello world";
byte[] byteArr = str.getBytes();
byte firstChar = byteArr[6]; // 119
We've come to the logical conclusion of our review today. Thanks for reading!Exploring questions and answers from a job interview for a Java developer position. Part 6 - 7Exploring questions and answers from a job interview for a Java developer position. Part 6 - 8
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet