Sunday, August 29, 2021

10 Most Popular Java Frameworks That You Must Try

In today’s technology-driven world, we all can see how frequently tech advancements are coming into the existence and subsequently how old tools & technologies are becoming obsolete and uncompetitive. But the case is not the same with every single technology as JAVA is one of those few technologies out there that is enjoying a strong position in the tech world for more than 2 decades!

Java Frameworks, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation

As per various standard reports, Java is still among the most popular and demanded programming languages. One of the major reasons behind such immense popularity of Java is that it has a wide range of applications such as in Android Development, Web Applications, Desktop Applications, Scientific Applications, etc. In short, if you’re looking forward to building a career with Java then you can surely go ahead without giving a second thought. However, what you need to know is, to create a worthwhile Java project, you need to know about working with the Java Frameworks.

What is a Java Framework? – A Java Framework is a tool that provides you with pre-written Java code that can be reused for creating an application – it saves a lot of time of yours as in these frameworks you’re not required to code multiple times for a single task. Also, you’re not required to worry about other issues like security issues, making database connections, etc. In simple words, with the help of Java frameworks, there is no need to do coding from scratch while creating a project. There are numerous popular Java frameworks available that you can consider.

Here, in this article, we’ve compiled a list of several most popular and demanded Java frameworks, based on various crucial factors and stats, for the year 2021. So, let’s get started now:

1. Spring


Spring is a lightweight, open-source, and quite popular Java framework that is used by developers to create enterprise-level web applications conveniently and efficiently. You need to know that this modular framework can be used to develop any layer of the project and along with the loosely coupled modules here, dependencies are managed by the framework itself rather than being dependent on the libraries in the code. Spring provides you with a lightweight container and it can be triggered without using an application or web server. Moreover, Spring is compatible with XML configurations and also it is capable of establishing JDBC connections. Various renowned companies like Netflix, Amazon, Microsoft, etc. use Spring for their respective platforms.  

Some of the prominent features of Spring are listed below:

◉ Dependency Injection
◉ Supports Backward Compatibility
◉ Supports both – XML and annotation-based configuration
◉ YAML Support
◉ Better documentation and an active community

2. Hibernate


Hibernate is an ORM (Object-Relational Mapping) Java framework that conveniently maps an object-oriented model to the relational database. In simple words, it makes communication better between Java and relational database management systems. Hibernate can be easily connected with various popular databases like Oracle, MySQL, and others. Also, numerous enriching tools like Hibernate console, Mapping editor, etc. make things a bit more easy for Java developers. Hibernate allows you to do complex data manipulation with minimal or less coding. Moreover, the framework is completely open-source and used by various renowned Companies like Dell, Oracle, IBM, etc. use Hibernate for their respective platforms.  

Some of the prominent features of Hibernate are listed below:

◉ Hibernate Query Language (HQL)
◉ Easy to Customize and Configure
◉ Supports Persistence APIs
◉ Lightweight & High Performance  
◉ Better Scalability

3. Struts


Apache Struts is an open-source Model-View-Controller (MVC) framework that is primarily used to create enterprise-level Java web applications. As of now, Struts has its versions – Struts 1 and Struts 2, among which the latter one is being used more by the developers due to extended functionalities. It is basically designed to inherit and extend the Java Servlet API properties and features to make things easier for the developers. One of the significant features of Struts is that it can be conveniently integrated with other frameworks as well. Various renowned companies like Infosys, Accenture, etc. use the Struts framework in their tech stacks.

Some of the prominent features of Struts are listed below:

◉ Configurable MVC Components
◉ POJO Based Actions
◉ Reduced Development Time & Effort
◉ Supports Creative Themes and Templates  
◉ Better Documentation & Community Support

4. Java Server Faces (JSF)


Java Server Faces (JSF), developed and maintained by Oracle, is another component-based MVC web framework that has reusable UI components to create enriching user interfaces for server-based applications. In this stable framework, there is actually the encapsulation of various client-side technologies such as HTML, CSS & JavaScript. And with the help of drag and drop UI components, developers can handle the frontend part efficiently doing much coding. Moreover, Java Server Faces allows the integration among the back-end code and user interface smoothly and conveniently. Some of the renowned companies that use Java Server Faces (JSF) in their tech stacks are – Insoft, GameDuell, etc.  

Some of the prominent features of JSF are listed below:

◉ Component-based UI Framework
◉ Cross-framework Compatibility
◉ Excellent Tools and Libraries Support
◉ Inbuilt AJAX Support
◉ Templating & Bean Annotations

5. Grails


Another popular Java framework in this list is Grails. Grails is an open-source Java framework that is based on the MVC (Model-View-Controller) design pattern. Though, Grails is actually written in Groovy language – it seamlessly can run on the Java platform and is completely compatible with the syntax of Java. You need to know that Grails is being used in the development of a large number of e-commerce websites available over the web. Furthermore, Grails is comparatively easier to learn, come up with easy documentation, and is strongly recommended to beginners. Various renowned companies like LinkedIn, Greencode, etc. use Grails for their respective platforms.  

Some of the prominent features of Grails are listed below:

◉ Gentle Learning Curve
◉ Seamless Java Integration
◉ Support Various Customized Plugins
◉ Built-in Support for RESTful APIs
◉ Compiled to JVM Bytecode

6. Google Web Toolkit (GWT)


Google Web Toolkit, GWT is an open-source Java framework created by Google. One of the significant features of this framework is that it converts the Java code into JavaScript code. Along with the Java-to-JavaScript Compiler, other major components of the GWT framework are GWT Development Mode, JRE emulation library, and GWT Web UI class library. Other than that, Google Web Toolkit is quite easy to use and comes up with several enriching features like browser history management, unit testing integration, Google APIs support in GWT applications, and many more. Various renowned products of Google including AdSense and AdWords are heavily relying on this GWT framework.

Some of the prominent features of GWT are listed below:

◉ Dynamic and Reusable UI Components
◉ Cross-Browser Compatibility  
◉ Full-featured Java Debugging Support
◉ Highly Developer-friendly
◉ Simple RPC Mechanism

7. Vaadin


Talking about Vaadin, it is basically an open-source platform that is used to develop web applications and consists of the Java web framework along with a set of web components, application starters & tools. Vaadin allows client-server communication in a completely automated manner. As a developer if you’re looking out for a framework that can allow you to focus more on application specifications and core development and the UI part can be effectively handled by the framework itself then Vaadin would be the right choice for you. Some of the popular companies using Vaadin in their tech stacks are – Rockwell Automation, JPMorgan Chase, Dell, etc.

Some of the prominent features of Vaadin are listed below:

◉ Lightweight Framework with Better Documentation
◉ Web Components Integration
◉ Built-in JavaBeans Validation with Annotation
◉ Built-in Spring Framework Support
◉ Data Binding

8. Wicket


Apache Wicket, created by Jonathan Locke, is another component-based Java web framework that is widely used by Java developers. Wicket is primarily known for its POJO model i.e., where each component is Plain Old Java Object. These components include buttons, forms, links, pages, images, behaviors, etc. While working with Wicket, there is no need to learn configuration files. Other than that, Wicket has all real Java objects and is quite secure as well. It would be easier for you to learn Wicket if you’re already familiar with JSP. Meanwhile, the framework is being used by various popular companies like Deloitte, doubleSlash, etc.

Java Frameworks, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation

Some of the prominent features of Wicket are listed below:

◉ Lightweight and Fast Framework
◉ POJO Based Actions
◉ Zero XML Configuration Files
◉ Configurable MVC Components
◉ Theme and Template Support

9. Blade


Going down with the list, here comes another popular Java framework, Blade! It is an extremely lightweight Java framework that is based on Model-View-Controller (MVC) architecture and is widely used to develop web applications. You need to know that the source code here is as minimal as less than 500kb. One of the key features of Blade is Cross-Site Request Forgery (CSRF) and Cross-Site Scripting (XSS) also. The framework allows you to create templates for all the requirements in addition to a master template. Some of the popular companies using Blade in their tech stacks are Stormcatch APIs, Spookies, and a few others.

Some of the prominent features of Blade are listed below:

◉ Lightweight and Modular Framework
◉ Embedded Jetty Server  
◉ Support for Plugin Extensions
◉ Support REST Style Routing Interface
◉ Gentle Learning Curve

10. Play


Last but not least, there is another popular Java Framework, Play. It is a lightweight open-source framework that is used to create web applications using Java and follows the Model-View-Controller (MVC) architectural pattern. Play supports the convention over configuration approach. The framework is highly flexible and makes it easier to create high-performance applications due to the asynchronous processing. Though Play is created in Scala – it is compatible with other programming languages also that are compiled to JVM bytecode like Java. Meanwhile, the framework is being used by various popular companies like Samsung, LinkedIn, and many others in their tech stacks.

Some of the prominent features of Play are listed below:

◉ Integrated Unit Testing
◉ Modular Architecture
◉ Native Scala Support
◉ High-Performance Applications
◉ Hot Code Reloading

So, these are some of the most popular Java frameworks that you can consider in the year 2021 based on your project requirements and preferences. These frameworks will surely make Java development much easier for you!!

Source: geeksforgeeks.org

Friday, August 27, 2021

Difference Between Assembler and Interpreter

Core Java, Oracle Java Tutorial and Materials, Oracle Java Certification, Java Preparation

Assembler vs Interpreter


In general, compiler is a computer program that reads a program written in one language, which is called the source language, and translates it in to another language, which is called the target language. Traditionally, source language is a high level language such as C++ and target language is a low level language such as Assembly language. However, there are compilers that can convert a source program written in Assembly language and convert it to machine code or object code. Assemblers are such tools. On the other hand, Interpreters are tools that execute instructions written in some programming language. Interpreter can either directly execute high level source code or translate them to intermediate code and then interpret it or execute precompiled code.

What is an Assembler?


Assembler is software or a tool that translates Assembly language to machine code. So, an assembler is a type of a compiler and the source code is written in Assembly language. Assembly is a human readable language but it typically has a one to one relationship with the corresponding machine code. Therefore an assembler is said to perform isomorphic (one to one mapping) translation. Advanced assemblers provide additional features that support program development and debugging processes. For example, the type of assemblers called macro assemblers provides a macro facility.

What is an Interpreter?


An interpreter is a computer program or a tool that executes programming instructions. An interpreter may either execute the source code directly or converts the source to an intermediate code and execute it directly or execute precompiled code produced by a compiler (some interpreter systems include a compiler for this task). Languages like Perl, Python, MATLAB and Ruby are examples of programming languages that use an intermediate code. UCSD Pascal interprets a precompiled code. Languages like Java, BASIC and Samlltalk first compile the source to an intermediate code called bytecode and then interpret it.

What is the difference between an Assembler and an Interpreter?


An assembler can be considered a special type of compiler, which only translates Assembly language to machine code. Interpreters are tools that execute instruction written in some language. Interpreter systems may include a compiler to pre-compile code before interpretation, but an interpreter cannot be called a special type of a compiler. Assemblers produce an object code, which might have to be linked using linker programs in order to run on a machine, but most interpreters can complete the execution of a program by themselves. An assembler will typically do a one to one translation, but this is not true for most interpreters. Because Assembly language has a one to one mapping with machine code, an assembler may be used for producing code that runs very efficiently for occasions in which performance is very important (for e.g. graphics engines, embedded systems with limited hardware resources compared to a personal computer like microwaves, washing machines, etc.). On the other hand, interpreters are used when you need high portability. For example, the same Java bytecode can be run on different platforms by using the appropriate interpreter (JVM).

Source: differencebetween.com

Wednesday, August 25, 2021

DuoDecimal in Java

DuoDecimal in Java, Oracle Java Tutorial and Material, Oracle Java Study Material, Oracle Java Career, Java Preparation

Duodecimal represents a system which is a notation system in which a number having its base as 12 is called a duodecimal number. In java, we can use to find the conversation of duodecimal numbers into respective binary, octal, decimal, hexadecimal number, or any other base numbers. In java, we can use predefined packages or user-defined methods to perform the following conversion.

Let us portray out few sample sets  of duodecimal conversation into other based numbers which are listed below as follows:

The duodecimal number of (15b)12 is converted to the binary number (11010111)2

The duodecimal number of (182)12 is converted to the octal number (362)8

The duodecimal number of (262)12 is converted to the decimal number (362)10

The duodecimal number of(288052)12 is converted to the hexadecimal number (A563E)16

The duodecimal number of (58576a2)12 is converted to the hexatrigesimal number (A563E)32

Procedure: 

There are certain steps required to convert into a duodecimal number which is listed below as follows:

1. Take a hexadecimal number as user input.

2. Create a user-defined function to convert it into a decimal number.

3. Create another user-defined function that will convert a decimal number into a duodecimal number.

4. Print the resultant duodecimal number.

Example:

// Java Program Illustrating DuodecimalNumber via Conversion

// of Hexadecimal Numbers into Duodecimal Numbers

// Importing utility classes

import java.util.*;

// Main class

// Representing equivalent duodecimal No of Hexadecimal No

class Main {

// Method 1

// Returning the decimal number of the given hexadecimal

// number

public static String

convertToDec(String value, int base,

Map<Character, Integer> hexatoDec)

{

int sum = 0;

int pow = 0;

String tempData = value;

// Logic to find equivalent decimal number

for (int i = tempData.length() - 1; i >= 0; i--) {

// charAt() represents element at 'i'th index

int val = tempData.charAt(i) - '0';

if (base == 16

&& hexatoDec.containsKey(

tempData.charAt(i))) {

val = hexatoDec.get(tempData.charAt(i));

}

// Math.pow() calculates x^n

sum += (val) * (Math.pow(base, pow++));

}

return String.valueOf(sum);

}

// Method 2

// Converting decimal number into Duodecimal number and

// return it into main() method.

public static String

convertToDuoDecimal(String value, int base,

Map<Integer, Character> dectoHex,

Map<Character, Integer> hextoDec)

{

String val = value;

int newBase = base;

// Checks whether the base is decimal or not

if (newBase != 10) {

// If the base is not 10, it call the

// convertToDec() method which return the

// corresponding decimal number of the given

// number.

val = convertToDec(value, base, hextoDec);

// After converting the number, new base is

// updated Say be it 10

newBase = 10;

}

// Converting the string number into integer

// using parseInt()

int temp = Integer.parseInt(val);

int rem;

String duoDecimal = "";

// Creating duoDecimalChars[] array for defining the

// characters

char duoDecimalChars[]

= { '0', '1', '2', '3', '4', '5',

'6', '7', '8', '9', 'A', 'B' };

// Logic to find equivalent duodecimal number

while (temp > 0) {

rem = temp % 12;

duoDecimal = duoDecimalChars[rem] + duoDecimal;

temp = temp / 12;

}

return duoDecimal;

}

// Method 3

// Main driver method

public static void main(String[] args)

{

// Createing a variable to store hexadecimal number

String val;

// Custom input in main() for hexadecimal number

val = "3A4C2";

// Creating a hexatoDec and dectoHexa for storing

// values by creating object of Map class Delaring

// object of character and integer type

Map<Character, Integer> hexatoDec = new HashMap<>();

Map<Integer, Character> dectoHex = new HashMap<>();

// Logic to store date into hexatoDec and dectoHexa

// map

for (int i = 0; i < 6; i++) {

dectoHex.put(10 + i, (char)('A' + i));

hexatoDec.put((char)('A' + i), 10 + i);

}

// Call the convertToDuoDecimal() and printing the

// returned value of it.

System.out.println(

"Duodecimal : "

+ convertToDuoDecimal(val, 16, dectoHex,

hexatoDec));

}

}

Output


Duodecimal : B622A

Source: geeksforgeeks.org

Friday, August 20, 2021

Java 8 - Functional Interfaces

Java 8 - Functional Interfaces, Core Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Certification

Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method ‘compareTo’ is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package.

Functional Interface Example

Predicate <T> interface is a functional interface with a method test(Object) to return a Boolean value. This interface signifies that an object is tested to be true or false.

Create the following Java program using any editor of your choice in, say, C:\> JAVA.

Java8Tester.java

import java.util.Arrays;

import java.util.List;

import java.util.function.Predicate;

public class Java8Tester {

   public static void main(String args[]) {

      List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

      // Predicate<Integer> predicate = n -> true

      // n is passed as parameter to test method of Predicate interface

      // test method will always return true no matter what value n has.

      System.out.println("Print all numbers:");

      //pass n as parameter

      eval(list, n->true);

      // Predicate<Integer> predicate1 = n -> n%2 == 0

      // n is passed as parameter to test method of Predicate interface

      // test method will return true if n%2 comes to be zero

      System.out.println("Print even numbers:");

      eval(list, n-> n%2 == 0 );

      // Predicate<Integer> predicate2 = n -> n > 3

      // n is passed as parameter to test method of Predicate interface

      // test method will return true if n is greater than 3.

      System.out.println("Print numbers greater than 3:");

      eval(list, n-> n > 3 );

   }

   public static void eval(List<Integer> list, Predicate<Integer> predicate) {

      for(Integer n: list) {

         if(predicate.test(n)) {

            System.out.println(n + " ");

         }

      }

   }

}

Here we've passed Predicate interface, which takes a single input and returns Boolean.

Verify the Result

Compile the class using javac compiler as follows −

C:\JAVA>javac Java8Tester.java

Now run the Java8Tester as follows −

C:\JAVA>java Java8Tester

It should produce the following output −

Print all numbers:

1

2

3

4

5

6

7

8

9

Print even numbers:

2

4

6

8

Print numbers greater than 3:

4

5

6

7

8

9

Source: tutorialspoint.com

Wednesday, August 18, 2021

Multithreading in Java

Multithreading in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms : 

1. Extending the Thread class 

2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.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.

// Java code for thread creation by extending

// the Thread class

class MultithreadingDemo extends Thread {

public void run()

{

try {

// Displaying the thread that is running

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");

}

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

}

}

}

// Main Class

public class Multithread {

public static void main(String[] args)

{

int n = 8; // Number of threads

for (int i = 0; i < n; i++) {

MultithreadingDemo object

= new MultithreadingDemo();

object.start();

}

}

}

Output

Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running

Thread creation by implementing the Runnable 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. 

Multithreading in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Learning

// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}

Output

Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running

Thread Class vs Runnable Interface 


1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.

2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.

3. Using runnable will give you an object that can be shared amongst multiple threads. 

Source: geeksforgeeks.org

Monday, August 16, 2021

Abstract Syntax Tree (AST) in Java

Abstract Syntax Tree (AST) in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career

Abstract Syntax Tree is a kind of tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code.

There is numerous importance of AST with application in compilers as abstract syntax trees are data structures widely used in compilers to represent the structure of program code. An AST is usually the result of the syntax analysis phase of a compiler. It often serves as an intermediate representation of the program through several stages that the compiler requires, and has a strong impact on the final output of the compiler.

Let us do discuss the use of AST before proceeding further to the implementation part. AST’s are mainly used in compilers to check code for their accuracy. If the generated tree has errors, the compiler prints an error message. Abstract Syntax Tree (AST) is used because some constructs cannot be represented in context-free grammar, such as implicit typing. They are highly specific to programming languages, but research is underway on universal syntax trees.

Flow Chart:  

id + id * id would have the following syntax tree which is as follows:

Abstract Syntax Tree (AST) in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career

Abstract syntax tree will be as follows:

Abstract Syntax Tree (AST) in Java, Core Java, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career

Implementation:


Here we will be writing custom java source codes corresponding to which we will be providing the AST for the same java source code as in implementation.

Example 1(A) Java source code

Java

// Java Custom Source Code

// Main class
class GFG {

// Main driver method
public static void main(String[] args)
{

// Print statement
System.out.println("Hello World!");
}
}

Example 1(B) AST of above source code

Java

CLASS_DEF -> CLASS_DEF [1:0]
|--MODIFIERS -> MODIFIERS [1:0]
| `--LITERAL_PUBLIC -> public [1:0]
|--LITERAL_CLASS -> class [1:7]
|--IDENT -> GFG [1:13]
`--OBJBLOCK -> OBJBLOCK [1:17]
|--LCURLY -> { [1:17]
|--METHOD_DEF -> METHOD_DEF [2:4]
| |--MODIFIERS -> MODIFIERS [2:4]
| | |--LITERAL_PUBLIC -> public [2:4]
| | `--LITERAL_STATIC -> static [2:11]
| |--TYPE -> TYPE [2:18]
| | `--LITERAL_VOID -> void [2:18]
| |--IDENT -> main [2:23]
| |--LPAREN -> ( [2:27]
| |--PARAMETERS -> PARAMETERS [2:34]
| | `--PARAMETER_DEF -> PARAMETER_DEF [2:34]
| | |--MODIFIERS -> MODIFIERS [2:34]
| | |--TYPE -> TYPE [2:34]
| | | `--ARRAY_DECLARATOR -> [ [2:34]
| | | |--IDENT -> String [2:28]
| | | `--RBRACK -> ] [2:35]
| | `--IDENT -> args [2:37]
| |--RPAREN -> ) [2:41]
| `--SLIST -> { [2:43]
| |--EXPR -> EXPR [3:26]
| | `--METHOD_CALL -> ( [3:26]
| | |--DOT -> . [3:18]
| | | |--DOT -> . [3:14]
| | | | |--IDENT -> System [3:8]
| | | | `--IDENT -> out [3:15]
| | | `--IDENT -> println [3:19]
| | |--ELIST -> ELIST [3:27]
| | | `--EXPR -> EXPR [3:27]
| | | `--STRING_LITERAL -> "Hello World!" [3:27]
| | `--RPAREN -> ) [3:41]
| |--SEMI -> ; [3:42]
| `--RCURLY -> } [4:4]
`--RCURLY -> } [5:0]

Now you must be wondering how to make an AST or how the above code is generated for that geek follow the simple steps as listed in the sequential order. 

◉ Run the Source Code in your local Environment.

checkstyle-8.43-all.jar 

◉ Audit the Program with the help of Checkstyle in your Terminal:

java -jar checkstyle-8.43-all.jar -c /google_checks.xml YourFile.java

◉ After Audit, Run this command in your terminal to get the AST of your preferred  Code: java -jar checkstyle-8.43-all.jar -t YourFile.java

◉ AST is now ready. But wait geeks,

Note: This is not an Updated AST

Remember: To update the AST, we have to do the following two steps

Step 1: We should replace 

">" with "&gt;" and "<" with "&lt;"

Step 2: Remove the code lines

Example 1(C) Updated AST Examples of the above code is as follows:

Java

CLASS_DEF -> CLASS_DEF
|--MODIFIERS -> MODIFIERS
| `--LITERAL_PUBLIC -> public
|--LITERAL_CLASS -> class
|--IDENT -> GFG
`--OBJBLOCK -> OBJBLOCK
|--LCURLY -> {
|--METHOD_DEF -> METHOD_DEF
| |--MODIFIERS -> MODIFIERS
| | |--LITERAL_PUBLIC -> public
| | `--LITERAL_STATIC -> static
| |--TYPE -> TYPE
| | `--LITERAL_VOID -> void
| |--IDENT -> main
| |--LPAREN -> (
| |--PARAMETERS -> PARAMETERS
| | `--PARAMETER_DEF -> PARAMETER_DEF
| | |--MODIFIERS -> MODIFIERS
| | |--TYPE -> TYPE
| | | `--ARRAY_DECLARATOR -> [
| | | |--IDENT -> String
| | | `--RBRACK -> ]
| | `--IDENT -> args
| |--RPAREN -> )
| `--SLIST -> {
| |--EXPR -> EXPR
| | `--METHOD_CALL -> (
| | |--DOT -> .
| | | |--DOT -> .
| | | | |--IDENT -> System
| | | | `--IDENT -> out
| | | `--IDENT -> println
| | |--ELIST -> ELIST
| | | `--EXPR -> EXPR
| | | `--STRING_LITERAL -> "Hello World!"
| | `--RPAREN -> )
| |--SEMI -> ;
| `--RCURLY -> }
`--RCURLY -> }

Example 2: Representing 1 + 2 can be represented in AST 

Java

+ BinaryExpression
- type: +
- left_value:
LiteralExpr:
value: 1
- right_vaue:
LiteralExpr:
value: 2

Source: geeksforgeeks.org

Friday, August 13, 2021

Four Main Object Oriented Programming Concepts of Java

Object Oriented Programming Concepts of Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Career, Core Java, Oracle Java OOP

Object-oriented programming generally referred to as OOPS is the backbone of java as java being a completely object-oriented language. Java organizes a program around the various objects and well-defined interfaces. There are four pillars been here in OOPS which are listed below. These concepts aim to implement real-world entities in programs.

◉ Abstraction

◉ Encapsulation

◉ Inheritance

◉ Polymorphism

Abstraction is a process of hiding implementation details and exposes only the functionality to the user. In abstraction, we deal with ideas and not events. This means the user will only know “what it does” rather than “how it does”.

There are two ways to achieve abstraction in Java

1. Abstract class (0 to 100%)

2. Interface (100%)

Real-Life Example: A driver will focus on the car functionality (Start/Stop -> Accelerate/ Break), he/she does not bather about how the Accelerate/ brake mechanism works internally. And this is how the abstraction works.

Certain key points should be remembered regarding this pillar of OOPS as follows:

◉ The class should be abstract if a class has one or many abstract methods

◉ An abstract class can have constructors, concrete methods, static method, and final method

◉ Abstract class can’t be instantiated directly with the new operator. It can be possible as shown in pre tag below:

A b = new B();

◉ The child class should override all the abstract methods of parent else the child class should be declared with abstract keyword

Object Oriented Programming Concepts of Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Career, Core Java, Oracle Java OOP

Example:

// Abstract class
public abstract class Car {
public abstract void stop();
}

// Concrete class
public class Honda extends Car {
// Hiding implementation details
@Override public void stop()
{
System.out.println("Honda::Stop");
System.out.println(
"Mechanism to stop the car using break");
}
}

public class Main {
public static void main(String args[])
{
Car obj
= new Honda(); // Car object =>contents of Honda
obj.stop(); // call the method
}
}

Pillar 2: Encapsulation


Encapsulation is the process of wrapping code and data together into a single unit.

Real-Life Example:

A capsule which is mixed of several medicines. The medicines are hidden data to the end user.

In order to achieve encapsulation in java follow certain steps as proposed below:

◉ Declare the variables as private
◉ Declare the setters and getters to set and get the variable values

Note: There are few disadvantages of encapsulation in java as follows:

1. Control Over Data: We can write the logic in the setter method to not store the negative values for an Integer. So by this way we can control the data.
2. Data Hiding: The data members are private so other class can’t access the data members.
3. Easy to test: Unit testing is easy for encapsulated classes

Example:

// AJavaclasswhichisafullyencapsulatedclass.
publicclass Car
{
// privatevariable
privateStringname;
// gettermethodforname
publicStringgetName()
{
returnname;
}
// settermethodforname
publicvoidsetName(Stringname)
{
this.name = name
}
}

// Javaclasstotesttheencapsulatedclass.
public class Test
{
publicstaticvoidmain(String[]args)
{
// creatinginstanceoftheencapsulatedclass
Carcar
= newCar();
// settingvalueinthenamemember
car.setName("Honda");
// gettingvalueofthenamemember
System.out.println(car.getName());
}
}

Pillar 3: Inheritance


Inheritance is the process of one class inheriting properties and methods from another class in Java. Inheritance is used when we have is-a relationship between objects.  Inheritance in Java is implemented using extends keyword.

Real-life Example:

The planet Earth and Mars inherits the super class Solar System and Solar system inherits the Milky Way Galaxy. So Milky Way Galaxy is the top super class for Class Solar System, Earth and Mars.

Let us do discuss the usage of inheritance in java applications with a generic example before proposing the code. So consider an example extending the Exception class to create an application-specific Exception class that contains more information like error codes. For example NullPointerException.

There are 5 different types of inheritance in java as follows:

1. Single Inheritance: Class B inherits Class B using extends keyword

2. Multilevel Inheritance: Class C inherits class B and B inherits class A using extends keyword

3. Hierarchy Inheritance: Class B and C inherits class A in hierarchy order using extends keyword

4. Multiple Inheritance: Class C inherits Class A and B. Here A and B both are superclass and C is only one child class. Java is not supporting Multiple Inheritance, but we can implement using Interfaces.

5. Hybrid Inheritance: Class D inherits class B and class C. Class B and C inherits A. Here same again Class D inherits two superclass, so Java is not supporting Hybrid Inheritance as well.

Example:

// super class
class Car {
// the Car class have one field
public String wheelStatus;
public int noOfWheels;

// the Car class has one constructor
public Car(String wheelStatus, int noOfWheels)
{
this.wheelStatus = wheelStatus;
this.noOfWheels = noOfWheels;
}

// the Car class has three methods
public void applyBrake()
{
wheelStatus = "Stop" System.out.println(
"Stop the car using break");
}

// toString() method to print info of Car
public String toString()
{
return ("No of wheels in car " + noOfWheels + "\n"
+ "status of the wheels " + wheelStatus);
}
}

// sub class
class Honda extends Car {

// the Honda subclass adds one more field
public Boolean alloyWheel;

// the Honda subclass has one constructor
public Honda(String wheelStatus, int noOfWheels,
Boolean alloyWheel)
{
// invoking super-class(Car) constructor
super(wheelStatus, noOfWheels);
alloyWheel = alloyWheel;
}

// the Honda subclass adds one more method
public void setAlloyWheel(Boolean alloyWheel)
{
alloyWheel = alloyWheel;
}

// overriding toString() method of Car to print more
// info
@Override public String toString()
{
return (super.toString() + "\nCar alloy wheel "
+ alloyWheel);
}
}

// driver class
public class Main {
public static void main(String args[])
{

Honda honda = new Honda(3, 100, 25);
System.out.println(honda.toString());
}
}

Pillar 4: Polymorphism in java 


Polymorphism is the ability to perform many things in many ways. The word Polymorphism is from two different Greek words- poly and morphs. “Poly” means many, and “Morphs” means forms. So polymorphism means many forms. The polymorphism can be present in the case of inheritance also. The functions behave differently based on the actual implementation.

Real-life Example:

A delivery person delivers items to the user. If it’s a postman he will deliver the letters. If it’s a food delivery boy he will deliver the foods to the user. Like this polymorphism implemented different ways for the delivery function.

There are two types of polymorphism as listed below:

1. Static or Compile-time Polymorphism
2. Dynamic or Run-time Polymorphism

Static or Compile-time Polymorphism when the compiler is able to determine the actual function, it’s called compile-time polymorphism. Compile-time polymorphism can be achieved by method overloading in java. When different functions in a class have the same name but different signatures, it’s called method overloading. A method signature contains the name and method arguments. So, overloaded methods have different arguments. The arguments might differ in the numbers or the type of arguments.

Example 1: Static Polymorphism

public class Car{
public void speed() {
}
public void speed(String accelerator) {
}
public int speed(String accelerator, int speedUp) {
return carSpeed;
}
}

Dynamic or Run-time Polymorphism occurs when the compiler is not able to determine whether it’s superclass method or sub-class method it’s called run-time polymorphism. The run-time polymorphism is achieved by method overriding. When the superclass method is overridden in the subclass, it’s called method overriding.

Example 2: Dynamic Polymorphism

import java.util.Random;

class DeliveryBoy {

public void deliver() {
System.out.println("Delivering Item");
}

public static void main(String[] args) {
DeliveryBoy deliveryBoy = getDeliveryBoy();
deliveryBoy.deliver();
}

private static DeliveryBoy getDeliveryBoy() {
Random random = new Random();
int number = random.nextInt(5);
return number % 2 == 0 ? new Postman() : new FoodDeliveryBoy();
}
}

class Postman extends DeliveryBoy {
@Override
public void deliver() {
System.out.println("Delivering Letters");
}
}

class FoodDeliveryBoy extends DeliveryBoy {
@Override
public void deliver() {
System.out.println("Delivering Food");
}
}

Output

Delivering Letters

Source: geeksforgeeks.org

Monday, August 9, 2021

Difference Between Implements and Extends

Java Implements, Java Extends, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guides, Java Certification

Implements vs Extends

Implements and Extends are two keywords found in Java programming language that provides a means of transferring added functionality to a new class. Implements keyword is used explicitly for implementing an interface, while Extends keyword is used for inheriting from a (super) class. Please note that the concepts of inheritance and interfaces are present in most of the other object oriented programming languages like C# and VB.NET, but they offer different syntax or keywords for applying those concepts. This article only focuses on Implements and Extends keywords defined in Java.

Extends

Extends keyword is used to implement the concept of inheritance in Java programming language. Inheritance essentially provides code reuse by allowing extending properties and behavior of an existing class by a newly defined class. When a new subclass (or derived class) extends a super class (or parent class) that subclass will inherit all attributes and methods of the super class. The subclass can optionally override the behavior (provide new or extended functionality to methods) inherited from the parent class. A subclass cannot extend multiple super classes in Java. Therefore, you cannot use extends for multiple inheritance. In order to have multiple inheritance, you need to use interfaces as explained below.

Implements

Implements keyword in Java programming language is used for implementing an interface by a class. An interface in Java is an abstract type that is used to specify a contract that should be implemented by classes, which implement that interface. Usually an interface will only contain method signatures and constant declarations. Any interface that implements a particular interface should implement all methods defined in the interface, or should be declared as an abstract class. In Java, the type of an object reference can be defined as an interface type. But that object must either be null or should hold an object of a class, which implements that particular interface. Using Implements keyword in Java, you can implement multiple interfaces to a single class. An Interface cannot implement another interface. However an interface can extend a class.

Difference between Implements and Extends

Although, Implements and Extends are two keywords that provide a mechanism to inherit attributes and behavior to a class in Java programming language, they are used for two different purposes. Implements keyword is used for a class to implement a certain interface, while Extends keyword is used for a subclass to extend from a super class. When a class implements an interface, that class needs to implement all the methods defined in the interface, but when a subclass extends a super class, it may or may not override the methods included in the parent class. Finally, another key difference between Implements and Extends is that, a class can implement multiple interfaces but it can only extend from one super class in Java. In general, usage of Implements (interfaces) is considered more favorable compared to the usage of Extends (inheritance), for several reasons like higher flexibility and the ability to minimize coupling. Therefore in practice, programming to an interface is preferred over extending from base classes.

Source: differencebetween.com

Friday, August 6, 2021

Top 20 Java Multithreading Interview Questions & Answers

Java has been rated number one in TIOBE popular programming developers which are used by over 10 Million developers over 15 billion devices supporting Java. It is used for creating applications for trending technologies like Big Data to household devices like Mobiles and DTH Boxes, it is used everywhere in today’s information age.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Multithreading in Core Java(J2SE) is a very important topic from an interview point of view. It can lead you to become a Java Developer, Java Testing Engineer, Java Architect, Lead Analyst, Java Consultant, and most important a real good java programmer enabling the confidence to dive in J2EE programming that stands for Java to enterprising edition or in layman language making you fit to work in corporate domain workflow directly. Perks wide varied in India for Java developers from 300K to 25000K for as fresher based upon the level of intellect.

So, let’s get started with most asked Java Multithreading Interview Questions with their detailed answers.

Q-1 What is multitasking?

A multitasking operating system is an operating system that gives you the perception of 2 or more tasks/jobs/processes running at the same time. It does this by dividing system resources amongst these tasks/jobs/processes and switching between the tasks/jobs/processes while they are executing over and over again. Usually, the CPU processes only one task at a time but the switching is so fast that it looks like the CPU is executing multiple processes at a time. They can support either preemptive multitasking, where the OS provides time to applications (virtually all modern OS), or cooperative multitasking, where the OS waits for the program to give back control (Windows 3.x, Mac OS 9, and earlier), leading to hangs and crashes. Also known as Timesharing, multitasking is a logical extension of multiprogramming.

Multitasking programming is of two types which are as follows:

1. Process-based Multitasking
2. Thread-based Multitasking

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Note: Performing multiple tasks at one time is referred to as multithreading in java which is of two types namely Process-based multithreading and Thread based multithreading.

Q-2 How can you identify the process?

Any program which is in a working state is referred to as a process. These processes do have threads that are single dispatchable units.

Q-3 How do you see a thread?

In order to see threads status let us take windows as an operating system, it illustrates then we’d have ProcessExplorer where you can see GUI shown below for windows operating systems.

This PC > OS > Users > Oracle Java Certified > Downloads > ProcessExplorer

ProcessExplorer is illustrated below in the windows operating systems

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Note: All of them as listed in the above media are the processes as shown above where at a time many are running in parallel to each other henceforth illustrating multiprocessing in the Jwindows operating system.  

As we have seen threads do reside in a single process so we have to deep dive into a specific process to see them in order to show users how multithreading is going on in the computers at the backend. For example: let us pick a random process from the above media consisting of various processes say it be ‘chrome’. Now we need to right-click over the process and click the properties’ menu.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

From the above media, it is clearly perceived that chrome is a process and after proceeding with the steps to figure out threads running inside the chrome process we go to properties of the process ‘chrome’ below pictorial output will be generated representing threads running in the process chrome.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Note: If we look scroll way from up to down then it will be seeing some colors against a few of those threads. Here green color threads are associated as the newly created threads and red colors associated threads are representing the closed threads.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Note: So for chrome to increase the performance by reducing the response time that is referred to as Thread based multitasking.

Q-4 What is Multithreading and How it is Different from Multitasking?

Multithreading is a specialized form of multitasking. Process-based multitasking refers to executing several tasks simultaneously where each task is a separate independent process is Process-based multitasking. 

Example: Running Java IDE and running TextEdit at the same time. Process-based multitasking is represented by the below pictorial which is as follows:

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Thread-based multitasking refers to executing several tasks simultaneously where each task is a separate independent part of the same program known as a thread. For example, JUnits uses threads to run test cases in parallel. Henceforth, process-based multitasking is a bigger scenario handling process where threads handle the details. It is already discussed to deeper depth already with visual aids.

Q-5 Which Kind of Multitasking is Better and Why?

Thread-based multitasking is better as multitasking of threads requires less overhead as compared to process multitasking because processes are heavyweight in turn requiring their own separate address space in memory while threads being very light-weight processes and share the same address space as cooperatively shared by heavyweight processes.

Switching is a secondary reason as inter-process communication is expensive and limited. Context switching from one process to another is cost hefty whereas inter-thread communication is inexpensive and context switching from one thread to another is lower in cost. 

Note: However java programs make use of process-based multitasking environments, but this feature is not directly under Java’s direct control while multithreading is complete.

Q-6 What is a thread?

Threads are lightweight processes within processes as seen. In java, there are two ways of creating threads namely via Thread class and via Runnable interface.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Q-7 What are the different states of a thread, or what is thread lifecycle?

A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant:

1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Q-8 What is the task of the main thread?

All Java programs have at least one thread, known as the main thread which is created by JVM at the program start when the main() method is invoked with the main thread as depicted from the output perceived from pseudo-code illustration.

Illustration:

System.out.println(“Mayank Solanki”);
Output: Mayank Solanki

System.out.println(Thread.getname().currentthread()); 
Output: main

Q-9 What are Different Types of threads in Java? 

There are two types of threads in java as follows:

◉ User thread
◉ Daemon thread 

User threads are created by java developers for example Main thread. All threads are created inside the main() method are by default non-daemon thread because the ‘main’ thread is non-daemon. Daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection, etc. They do not prevent daemon threads from exiting when all user threads finish their execution. JVM terminates itself when all non-daemon threads finish their execution. JVM does not care whether a thread is running or not, if JVM finds a running daemon thread it terminates the thread and after that shutdown itself.

Q-10 How to Create a User thread?

As discussed earlier when the JVM starts it creates a main thread over which the program is run unless an additional thread is not created by the user. The first thing “Main” thread looks for ‘public static void main(String [] args)’ method to invoke it as it acts as an entry point to the program. All other threads created in main acts as child threads of the “Main” thread. 

User thread can be implemented in two ways listed below:

1. Using Thread class by extending java.lang.Thread class.
2. Using Runnable Interface by implementing it.

Q-11 How to set the name of the thread?

We can name a thread by using a method been already up there known as setName() replacing default naming which was ‘Thread-0’, ‘Thread-1’, and so on.

thread_class_object.setName("Name_thread_here");

Q-12 What is thread priority?

Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10. 

◉ The default priority is set to 5 as excepted.
◉ Minimum priority is set to 0.
◉ Maximum priority is set to 10.

Here 3 constants are defined in it namely as follows:

1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY

Q-13 How deadlock plays a important role in multithreading?

If we do incorporate threads in operating systems one can perceive that the process scheduling algorithms in operating systems are strongly deep-down working on the same concept incorporating thread in Gantt charts. A few of the most popular are listed below which wraps up all of them and are used practically in software development.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

◉ First In First Out
◉ Last In First Out
◉ Round Robin Scheduling

Now one Imagine the concept of Deadlock in operating systems with threads by now how the switching is getting computed over internally if one only has an overview of them. 

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Q-14 Why output is not ordered? 

Scheduling of threads involves two boundary scheduling,

◉ Scheduling of user-level threads (ULT) to kernel-level threads (KLT) via lightweight process (LWP) by the application developer.

◉ Scheduling of kernel-level threads by the system scheduler to perform different unique os functions.

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

If multiple threads are waiting to execute then thread execution is decided by “ThreadScheduler” which is a part of JVM hence its vendor dependent resulting in unexpected execution of output order.

Note

◉ In multithreading, the guarantee of order is very less where we can predict possible outputs but not exactly one.
◉ Also, note that synchronization when incorporated with multithreading does affect our desired output simply by using the keyword ‘synchronized’.

It is as illustrated in the below illustration which is as follows:

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Q-15 What is Daemon Thread in Java and explain their properties? 

Daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection. It does possess certain specific properties as listed below:

◉ They can not prevent the JVM from exiting when all the user threads finish their execution.

◉ JVM terminates itself when all user threads finish their execution

◉ If JVM finds a running daemon thread, it terminates the thread and after that shutdown itself. JVM does not care whether the Daemon thread is running or not.

◉ It is an utmost low priority thread

Note: The main difference between user thread and daemon thread is that JVM does not wait for daemon thread  before exiting while it do waits for the user thread.

Q-16 How to Make User Thread to Daemon Thread?

It is carried out with the help of two methods listed in ‘Thread class’ known as setDaemon() and isDaemon(). First, the setDaemon() method converts user thread to daemon thread and vice-versa. This method can only be called before starting the thread using start() method else is called after starting the thread wit will throw IllegalThreadStateException After this, isDaemon() method is used which returns a boolean true if the thread is daemon else returns false if it is a non-daemon thread.  

Q-17 What are the tasks of the start() method?

The primary task of the start() method is to register the thread with the thread scheduler, so one can tell what child thread should perform, when, and how it will be scheduled that is handled by the thread scheduler. The secondary task is to call the corresponding run() method got the threads.

Q-18 What is the difference between the start() and run() method?

First, both methods are operated in general over the thread. So if we do use threadT1.start() then this method will look for the run() method to create a new thread. While in case of theadT1.run() method will be executed just likely the normal method by the “Main” thread without the creation of any new thread.

Note: If we do replace start() method with run() method then the entire program is carried by ‘main’ thread.

Q-19 Can we Overload run() method? What if we do not override the run() method? 

Java Multithreading Interview Questions & Answers, Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Career, Java Guides

Yes, it is possible to overload run() by passing parameters to it and also keeping a check over to comment down @override from the run() method. 

It should be as good as a thread wherein thread we do not have any arguments, so practice to overload is to comment on the call out for overloaded run() method. Now, so we need to acknowledge the same whether the output is the same or not if we have not overloaded it. 

If we have overloaded the run() method, then we will observe that output is always the main method as can be perceived from the stack call from the aboe image. It is because if we debug the code as provided in the link below we see as soon as the start() method is called again, run() is called because we have not overridden the run() method. 

The compiler will simply execute the run() method of the Thread class, keeping a check that the run() method of the Thread class must have an empty implementation. Hence, it results out in no output corresponding to the thread. As we have discussed above already, if we try to do so, then the Thread class run() method will be called and we will never get our desired output.

Note: Oracle Java Certified initially we are requesting to create a thread for us and later the same thread is doing nothing for us which we have created. So it becomes completely meaningless to us by writing unwanted operations to our code fragments. Hence, it becomes useless not to override the run() method. 

Q-20 Can we Override the start() method?

Even if we override the start() method in the custom class then no initializations will be carried on by the Thread class for us. The run() method is also not called and even a new thread is also not created.

Source: geeksforgeeks.org