JavaRush/Java Blog/Random EN/Coffee break #134. What to avoid when writing Java code. ...

Coffee break #134. What to avoid when writing Java code. How final, finally and finalize are used in Java

Published in the Random EN group
members

What to Avoid When Writing Java Code

Source: Medium We bring to your attention an article listing common mistakes that developers make when writing Java code. Coffee break #134.  What to avoid when writing Java code.  How final, finally and finalize are used in Java - 1

Using Enum.values

That this was considered a bug took me by surprise since I used Enum.values ​​regularly . The problem here is that Enum.values() is supposed to be an immutable list by specification. To do this, it must return a new instance of the array with the enum values ​​each time it is called.
public enum Fruits {
    APPLE, PEAR, ORANGE, BANANA;

    public static void main(String[] args) {
        System.out.println(Fruits.values());
        System.out.println(Fruits.values());
    }
}
// output
// [Lcom.test.Fruits;@7ad041f3
// [Lcom.test.Fruits;@251a69d7
There are two separate objects in memory here, so it might not seem like it's a big deal. But if you use Fruit.values() when processing a request and you have a high load, then this can lead to memory problems. You can easily fix this by introducing a private static final variable VALUES for caching.

Passing Optional parameters as a method parameter

Consider the following code:
LocalDateTime getCurrentTime(Optional<ZoneId> zoneId) {
    return zoneId.stream()
        .map(LocalDateTime::now)
        .findFirst()
        .orElse(LocalDateTime.now(ZoneId.systemDefault()));
}
We pass the Optional parameter zoneId and, based on its presence, decide whether to give the time in the system time zone or use the specified zone. However, this is not the correct way to work with Optional. We should avoid using them as a parameter and use method overloading instead.
LocalDateTime getCurrentTime(ZoneId zoneId) {
  return LocalDateTime.now(zoneId);
}

LocalDateTime getCurrentTime() {
  return getCurrentTime(ZoneId.systemDefault());
}
The code you see above is much easier to read and debug.

Using StringBuilder

Strings in Java are immutable. This means that once created they are no longer editable. The JVM maintains a string pool and, before creating a new one, calls the String.intern() method , which returns an instance from the string pool corresponding to the value, if one exists. Let's say we want to create a long string by concatenating elements into it.
String longString = new StringBuilder()
  .append("start")
  .append("middle")
  .append("middle")
  .append("middle")
  .append("end")
  .toString();
We were recently told that this was a very bad idea because older versions of Java did the following:
  • in line 1 the string “start” is inserted into the string pool and pointed to by longString
  • line 2 adds the string “startmiddle” to the pool and points to it with longString
  • on line 3 we have “startmiddlemiddle”
  • in line 4 - “startmiddlemiddlemiddle”
  • and finally on line 5 we add “startmiddlemiddlemiddleend” to the pool and point longString to it
All of these rows remain in the pool and are never used, resulting in a large amount of RAM being wasted. To avoid this we can use StringBuilder.
String longString = new StringBuilder()
  .append("start")
  .append("middle")
  .append("middle")
  .append("middle")
  .append("end")
  .toString();
StringBuilder creates only one string when the toString method is called , thereby getting rid of all the intermediate strings that were initially added to the pool. However, after Java 5 this is done automatically by the compiler , so it is better to use string concatenation using “+”.

Using primitive wrappers when they are not needed

Consider the following two fragments:
int sum = 0;
for (int i = 0; i < 1000 * 1000; i++) {
  sum += i;
}
System.out.println(sum);
Integer sum = 0;
for (int i = 0; i < 1000 * 1000; i++) {
  sum += i;
}
System.out.println(sum);
The first example runs six times faster than the second on my computer. The only difference is that we use an Integer wrapper class. The way Integer works is that on line 3, the runtime must convert the sum variable into a primitive integer (automatic unboxing), and after the addition is done, the result is then wrapped into a new Integer class. (automatic packaging). This means we are creating 1 million Integer classes and performing two million packaging operations, which explains the dramatic slowdown. Wrapper classes should only be used when they need to be stored in collections. However, future versions of Java will support collections of primitive types, which will make wrappers obsolete.

How final, finally and finalize are used in Java

Source: Newsshare In this article you will learn where, when and why the Finalize keyword is used, and whether it is worth using it at all in Java. You will also learn the differences between final, finally and finalize.

Where is a finally block used?

The finally block in Java is used to house important parts of code such as cleanup code, closing a file, or closing a connection, for example. The finally block executes regardless of whether an exception is thrown or whether that exception is handled. A finally contains all the important statements whether an exception occurs or not.

How do you finalize a variable in Java?

There are 3 ways to initialize a final Java variable:
  • You can initialize a final variable when it is declared. This approach is the most common.
  • An empty final variable is initialized in an instance-initializer block or constructor.
  • An empty final static variable is initialized inside a static block.

Can we call the finalize method manually in Java?

The finalize() method is not necessary and is not recommended to be called when an object goes out of scope. Because it is not known in advance when (or whether) the finalize() method will be executed . In general, finalize is not the best method to use unless there is a specific need for it. Starting with Java 9 it is deprecated.

When is the finalize method called?

The finalize() method is called to perform cleanup just before garbage collection.

What is the difference between final, finally and finalize?

The main difference between final, finally and finalize is that final is an access modifier, finally is a block in exception handling and finalize is a method of an object class.

Is it possible to override final methods?

No, methods declared final cannot be overridden or hidden.

Can we use try without catch?

Yes, it is possible to have a try block without a catch block by using a final block . As we know, the final block will always be executed even if any exception other than System occurs in the try block.

What are final methods?

Final methods cannot be overridden or hidden by subclasses. They are used to prevent unexpected behavior of a subclass modifying a method that may be critical to the function or consistency of the class.

Can a constructor be final?

Constructors can NEVER be declared final. Your compiler will always throw an error like “final modifier not allowed.” Final when applied to methods means that the method cannot be overridden in a subclass. Constructors are NOT regular methods.

What is the finally keyword used for?

The finally keyword is used to create a block of code following a try block. The finally block is always executed regardless of whether an exception occurs. Using a finally block allows you to run any unwind type statements you want to execute, regardless of what's happening in the protected code.

What's the use of finally?

A finally block in Java is a block used to execute parts of code such as closing a connection and others. The finally block in Java is always executed whether the exception is handled or not. Therefore, it contains all the necessary statements that need to be printed whether an exception occurs or not.

Why is the Finalize method protected?

Why is the finalize() method access modifier protected? Why can't it be public? It is not public because it should not be called by anyone other than the JVM. However, it must be protected so that it can be overridden by subclasses that need to define behavior for it.

Is the finalize method always called in Java?

The finalize method is called when an object is about to be garbage collected. This can happen any time after it becomes eligible for garbage collection. Note that it is entirely possible that the object is never garbage collected (and therefore finalize is never called).

What is the difference between throw and throws?

The throw keyword is used to intentionally throw an exception. The throws keyword is used to declare one or more exceptions, separated by commas. When using throw, only one exception is thrown.

What is the difference between try catch and finally keywords?

These are two different concepts: a catch block is executed only if an exception occurs in the try block. The finally block is always executed after the try(-catch) block, regardless of whether an exception was thrown or not.

Can we use finally without try in Java?

A finally block must be associated with a try block, you cannot use finally without a try block. You must place in this block those statements that must always be executed.

Can we inherit the final method?

Is the final method inherited? Yes, the final method is inherited, but you cannot override it.

Which method cannot be overridden?

We cannot override static methods because method overriding is based on dynamic linking at runtime and static methods are bound using static linking at compile time. Thus, overriding static methods is not possible.

What happens if the final method is overridden?

A final method declared in a parent class cannot be overridden by a child class. If we try to override the last method, the compiler will throw an exception at compile time.

Do the final keyword and the finalize method work the same?

There are no similarities in their functions, except for similar names. The final keyword can be used with a class, method or variable in Java. A final class is not extensible in Java, a final method cannot be overridden, and a final variable cannot be modified.

What is the super keyword in Java?

The super keyword in Java is a reference variable that is used to refer to the immediate object of the parent class. Whenever you instantiate a subclass, an instance of the parent class is created in parallel, which is referenced by the reference variable super. The super keyword can be used to directly call a method of a parent class.

What is the difference between the static and final keywords?

The main difference between the static and final keywords is that the static keyword is used to define a member of a class that can be used independently of any object of that class. The Final keyword is used to declare a constant variable, a method that cannot be overridden, and a class that cannot be inherited.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet