4 Things That are most confusing for Java Developer

Its never been easy to developers to master in Java because some of its concepts are way more confusing & complicated

Himanshu Verma
The Code Monster
8 min readNov 20, 2019

--

Image by Brooke Cagle

Perhaps we all have been using Java since our schools or colleges and we have grown up studying it but there are certain topics in Java which are unclear and confusing till date for beginner as well as senior Java developers. So today, my goal would be to clear out your confusions. At the end of this article, you will learn more about these concepts and also help you to clear all your confusions. We will discuss Anonymous inner classes, Multithreading, Synchronization and Serialization.

1- Usage of Announymous Classes

2- Multithreading

3- Implementation of Synchronization

4- Serialization

Anonymous Class

Java anonymous classes are like local classes or inner classes without a name. We can use java anonymous class to declare and instantiate a class at the same time. You should use them only when you want to use local class only once. An anonymous class cannot have an explicitly declared constructor. Instead, an anonymous constructor is implicitly declared for an anonymous class.

There are two ways to create Anonymous class:

1- By extending class (may be abstract or concrete)

2- By creating an interface

The best way to understand code is to read it first, so let’s take a look at the code.

Anonymous class can be created in the class and method blocks. As you already know Anonymous class can be created either using interface or extending abstract or concrete class, so from the above code i created interface first i.e Football and i implemented this inside the scope of class and main() method. Football can be an abstract as well as normal top level class besides an interface.

Football can be an abstract class, look at the code below.

Anonymous class can not only be abstract, it can also be concrete.

What if our Football class don’t have no-args constructor? Can we access class variables in the anonymous class? Do we need to override all the methods of class in anonymous class?

  1. We can use any constructor while creating anonymous class. Notice the constructor argument is being used too.
  2. Anonymous class extends the top-level class and implements the abstract class or interface. So access modifier rules apply as usual. We are able to access protected variable, if we change it to private then we won’t be able to access it.
  3. Since we are extending the Football class above, we are not required to override all the methods. However if it would have been an interface or abstract class then we have to provide implementation of all the unimplemented methods.
  4. You cannot declare static initializers or member interfaces in an anonymous class.
  5. An anonymous class can have static members provided that they are constant variables.

Use cases of Anonymous classes:

1- Cleaner Project Structure: We usually use anonymous classes when we have to modify on the fly implementation of methods of some classes. In this case, we can avoid adding new *.java files to the project in order to define top-level classes. This is especially true if that top-level class would be used just one time.

2- UI Event Listeners: In applications with a graphical interface, the most common use case of anonymous classes is to create various event listeners. For example, in the following snippet:

we created an instance of an anonymous class that implements interface setOnClickListener. Its onClick method gets triggered when a user clicks the button.

Multithreading

Multithreading in Java is the process of executing multiple threads simultaneously. The thread is the lightweight sub-process, it is also called the smallest unit of processing. The main target of using the multithreading is to maximising the usage of CPU. We use multithreading instead of multiprocessing because threads are lightweight and also share the common memory area than the processes. Multithreading is use to achieve the multi-tasking.

Thread Life Cycle

Image by hubberspot

As you can see from the above image, there are mainly five states of thread life cycle. We will each one of them one by one.

1- New: When we create the instance of thread, it goes in the new state which is first state but thread is still not ready to run.

2- Runnable: When we call the start() method of thread class then state changes from new to runnable which means now our thread is ready to run but when it will start running depends on Java Thread scheduler because scheduler can be busy in executing other threads. Thread scheduler picks one of the threads from the thread pool on the basis of the FIFO i.e First Come First Serve.

3- Blocked: Thread can automatically move to blocked state due to various reasons such as waiting for I/O operations and network connections etc. Also any higher priority thread can make move the currently running thread to the blocked state.

4- Waiting: Thread can enter into the waiting state by calling wait() method. It can go back to runnable state when other thread call the notify() method.

5- Terminated: Thread is terminated when start() method exits.

Why Multithreading?

We use Threads to make Java application faster by doing multiple things at same time. In technical terms, Thread helps you to achieve parallelism in Java program. Since CPU is very fast and nowadays it even contains multiple cores, just one thread is not able to take advantage of all the cores.

Points to remember

  • Better utilization of a single CPU.
  • Better user experience with regards to responsiveness.
  • For reducing response time
  • To serve multiple clients at the same time.

Threads can be created in two ways:

1- By extending Thread class

2- By implementing runnable interface

Creating thread by extending Thread class

We create a class that extends the Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. start() invokes the run() method on the Thread object.

Creating thread by interface.

We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.

Thread Class vs Runnable Interface

  • If we extend Thread class then we can’t extend one more class because Java doesn’t allow multiple inheritance. Multiple inheritance can be achieved by interface in java. So its good practice to use interface instead of Thread class.
  • If we extend Thread class, then it includes some methods such as yield(), interrupt() etc. which might not required in our program and in case of runnable interface, these unnecessary methods are not available.

Synchronization

Synchronization refers to multi-threading. A synchronized block of code can only be executed by one thread at a time. Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of Java object or synchronization of Java class becomes extremely important.

Why Synchronization?

If your code is executing in a multi-threaded environment, you need synchronization for objects, which are shared among multiple threads, to avoid any corruption of state or any kind of unexpected behavior.

Let’s understand the problem before we dive into the concept of synchronization.

Code by Javatpoint

When you run the above code on your system, then you will notice output is very inconsistent, there is no synchronization. Look at the output of the program given below.

Output:

Code by Javatpoint

When you synchronized the printTable() method, now synchronized method not letting enter any other thread to execute the method until currently executing thread doesn’t finish its job. Take a look at the below output its so consistent.

Output:

Similarly you can synchronize Java class and object.

Note: We do not always have to synchronize a whole method. Sometimes it is preferable to synchronize only part of a method. Java synchronized blocks inside methods makes this possible.

Serialization

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. The reverse operation of serialization is called deserialization where byte-stream is converted into an object.

The serialization and deserialization process is platform-independent, it means you can serialize an object in a platform and deserialize in different platform.

For serializing the object, we call the writeObject() method ObjectOutputStream, and for deserialization we call the readObject() method of ObjectInputStream class.

In the image shown below, Java object is converted to Stream of bytes and then it is being stored in the various forms of storage and this process is called serialization. In the right hand part of the image, stream of bytes from memory is being converted to Java object and this process is called de-serialization.

Image by InnovatinM

Why use Serialization

When you create Java class then obviously you may create object of the class but when execution of the program finishes or terminated, then state of the object destroyed. So to overcome this problem java provides us serialization, through which we can store object or persist the state of the object to use this object later either in the same platform or in a different platform since it is platform independent.

Following piece of code demonstrate how it is done.

Output:

Output:

Points to remember
1. If a parent class has implemented Serializable interface then child class doesn’t need to implement it but vice-versa is not true.
2. Only non-static data members are saved via Serialization process.
3. Static data members and transient data members are not saved via Serialization process.So, if you don’t want to save value of a non-static data member then make it transient.
4. Constructor of object is never called when an object is deserialized.
5. Associated objects must be implementing Serializable interface.

Conclusion

1- Firstly we have seen what Anonymous classes are and why we should use it and how.

2- Secondly we discussed about multithreading in java, life cycle of thread and why we should use it.

3- Synchronization allows only single thread to enter into synchronized method or block to access the resources and other thread remains in the queue until current thread is using the resources.

4- Serialization is the process of storing the state of an object so that we can use it later.

I hope you liked reading this article, you can also visit my website where I keep posting article regularly.

Subscribe my mailing list to get the early access of my articles directly in your inbox or follow my own publication on Medium The Code Monster to polish your technical knowledge.

Know your author

Himanshu Verma has graduated from the Dr. APJ Abdul Kalam University, Lucknow (India). He is an Android & IOS Developer and Machine Learning & Data Science Learner, a Financial Advisor, and a Blogger.

--

--

Himanshu Verma
The Code Monster

Visit my website http://thehimanshuverma.com/. Android & IOS Developer | Researcher | ML & Data Science Enthusiastic | Blogger | FA