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

Wednesday, August 4, 2021

Different Method Calls in Java

Method Calls in Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career, Oracle Java Study Material

Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes etc, and every class in Java has its own methods, either inherited methods or user-defined methods that are used to define the behavior of the class. In this article, we will discuss different types of methods and ways to call them.

Types of Methods:

1. User-Defined Methods: These are the methods implemented by the user in the particular class to perform a particular operation.

2. Abstract Methods: These are the methods that do not contain the body of the method and implements inside the abstract class.

3. Predefined Methods: These are the methods that are predefined and available in the java library to perform operations, for eg the hashcode() method.

4. static Methods: These are methods that are accessible without any instance of the class. The memory management of these methods is different from ordinary methods.

Method Type 1: User-Defined Methods

User-Defined nonstatic methods can be called or accessed only with the help of an instance of the class.

Syntax:

<ClassName> object=new <ClassName>

object.<MethodName>

Example 

// Java Program to Illustrate User-Defined Methods

// Importing essential input output classes

import java.io.*;

// Class 1

class GFG {

// Method 1

// Method of this class

void hello()

{

// Print statement whenever this method s called

System.out.println("This is the userDefinedMethod");

}

// Method 2

// Main driver method

public static void main(String[] args)

{

// Creating instance of the class

// inside the main() method

GFG ob = new GFG();

// Calling the method of class 1

// inside class 2

ob.hello();

}

}

Output

This is the userDefinedMethod

Method Type 2: Abstract Methods

These are the methods that are declared inside the abstract class without the implementation of the method of a particular signature or without signature. We cannot call it abstract methods. To create the instance of the abstract class ,we have to extend the abstract class. Abstract Methods are used when we have to use the one-way property of the method in different ways. 

Example

// Java Program to Illustrate Abstract Methods

// Class 1
// Helper class acting as Abstract class
abstract class GFGhelp {

// Creating abstract method
abstract void check(String name);
}

// Class 2
// Main class extending to helper class
public class GFG extends GFGhelp {

// main driver method
public static void main(String[] args)
{
// Creating the instance of the class
GFG ob = new GFG();

// Accessing the abstract method
ob.check("GFG");
}

// Extends the abstract method
@Override void check(String name)
{
System.out.println(name);
}
}

Output

GFG

Method Type 3: Predefined Methods

These are the methods that are already implemented in the java library or predefined and inherited by every java class. For example, consider every class in the java inherited object class that has various methods. hashcode() is one of the methods of the object class that is inherited by every class in Java

Example 

// Java Program to Illustrate Predefined Methods

// Main class
public class GFG {

// Main driver method
public static void main(String[] args)
{
// Creating object of the class in
// main() method
GFG ob = new GFG();

// Print the hashcode using
// predefined hashCode() method
System.out.println(ob.hashCode());
}
}

Output

1023892928

Method Type 4: Static methods

Static methods are those methods that there is no need for an instance of the class to access.Basically, these methods are the class methods and every static methods are shared among all the instances equally.
 
Example

// Java Program to Illustrate Static Methods

// Importing input output classes
import java.io.*;

// Main class
class GFG {

// Method 1
// Static method
static void hello()
{

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

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

// calling the Method 1
// Accessing method
hello();
}
}

Hello

Source: geeksforgeeks.org

Tuesday, August 3, 2021

How to Setup Jackson in Java Application?

Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Career, Oracle Java Tutorial and Material, Oracle Java Learning, Core Java

JSON(Javascript Object Notation) is the most popular format for the exchange of data in the world of web applications. The browsers can easily parse json requests and convert them to javascript objects.  The servers parse json requests, process them, and generates a new json response. JSON is self-describing and easy to understand. The process of converting java objects to json is called serialization and the process of converting json to java objects is called deserialization.

Consider a sample illustration below to get to know the file structure of json as shown below:

Illustration:

We have a Student class with attributes like id, name, address, city, hobby. Let’s understand how the corresponding json file looks as follows:

{"id":"S1122","name":"Jane","address":"XYZ Street","city":"Mumbai","hobby":"Badminton, Dancing"}

JSON data is written as a name/value pair where the name is the attribute/property name and value is the value for that attribute.

Now let us do discuss out Jackson JSON library before proceeding to set up Jackson for any java application.

◉ For java applications, it is very difficult to work with Json strings. So in java applications we need a json parser which parses Json files and converts them to java objects.

◉ Jackson is one such  Java Json library used for parsing and generating Json files. It has built in Object Mapper class which parses json files and deserializes it to custom java objects. It helps in generating json from java objects.

◉ Jackson also has a Jackson Json Parser and Jackson Json Generator which parses and generates json one token at a time.

Setup:-

To use Jackson library in our application, we need to add the below dependencies in the pom.xml file of our maven project.

<dependency>

   <groupId>com.fasterxml.jackson.core</groupId>

   <artifactId>jackson-core</artifactId>

   <version>2.9.6</version>

</dependency>

<dependency>

   <groupId>com.fasterxml.jackson.core</groupId>

   <artifactId>jackson-annotations</artifactId>

   <version>2.9.6</version>

</dependency>

<dependency>

   <groupId>com.fasterxml.jackson.core</groupId>

   <artifactId>jackson-databind</artifactId>

   <version>2.9.6</version>

</dependency>

On adding this dependency in pom.xml, the following jar files get added in Maven dependencies folder in eclipse:

◉ jackson-core-2.9.6.jar

◉ jackson-annotations-2.9.6.jar

◉ jackson-databind-2.9.6.jar

Note: If we are not using maven project, then we need to download and add these jar files in our classpath.

Implementation: Let’s understand how the Jackson library parses json files and generates them.

Let’s consider Employee class with attributes like name, id, deptName, salary, rating. We use Jackson library to generate a json file from the Employee object. We update one of its attributes – deptName. We serialize the employee object to a json file and then deserialize it back to an employee object with the updated value for the deptName attribute.

Example 1

// Java Program to Illustrate Setting Up of Jackson by

// parsing Jackson library json files and

// generating the same

// Importing required classes

import java.io.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

{

// Creating an employee object with it's attributes

// set

Employee employee = getEmployee();

ObjectMapper mapper = new ObjectMapper();

// Try blcok to check for exceptions

try {

// Serailizes emp object to a file employee.json

mapper.writeValue(

new File(

"/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/jackson-parsing/src/main/resources/employee.json"),

employee);

// Deserializes emp object in json string format

String empJson

= mapper.writeValueAsString(employee);

System.out.println(

"The employee object in json format:"

+ empJson);

System.out.println(

"Updating the dept of emp object");

// Update deptName attribute of emp object

employee.setDeptName("Devops");

System.out.println(

"Deserializing updated emp json ");

// Reading from updated json and deserializes it

// to emp object

Employee updatedEmp = mapper.readValue(

mapper.writeValueAsString(employee),

Employee.class);

// Print and display the updated employee object

System.out.println("Updated emp object is "

+ updatedEmp.toString());

}

// Catch block to handle exceptions

// Catch block 1

// Handling JsonGenerationException

catch (JsonGenerationException e) {

// Display the exception along with line number

// using printStackTrace() method

e.printStackTrace();

}

// Catch block 2

// Handling JsonmappingException

catch (JsonMappingException e) {

// Display the exception along with line number

// using printStackTrace() method

e.printStackTrace();

}

// Catch block 3

// handling generic I/O exceptions

catch (IOException e) {

// Display the exception along with line number

// using printStackTrace() method

e.printStackTrace();

}

}

// Method 2

// To get the employees

private static Employee getEmployee()

{

// Creating an object of Employee class

Employee emp = new Employee();

emp.setId("E010890");

emp.setName("James");

emp.setDeptName("DBMS");

emp.setRating(5);

emp.setSalary(1000000.00);

// Returning the employee

return emp;

}

}

// Class 2

// Helper class

class Employee {

// Member variables of this class

private String id;

private String name;

private String deptName;

private double salary;

private int rating;

// Member methods of this class

public String getId() { return id; }

public void setId(String id) { this.id = id; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public String getDeptName() { return deptName; }

public void setDeptName(String deptName)

{

// This keyword refers to current instance

this.deptName = deptName;

}

public double getSalary() { return salary; }

public void setSalary(double salary)

{

this.salary = salary;

}

public int getRating() { return rating; }

public void setRating(int rating)

{

this.rating = rating;

}

@Override public String toString()

{

return "Employee [id=" + id + ", name=" + name

+ ", deptName=" + deptName + ", salary="

+ salary + ", rating=" + rating + "]";

}

}

Output:

The employee object in json format:{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}
Updating the dept of emp object
Deserializing updated emp json 
Updated emp object is Employee [id=E010890, name=James, deptName=Devops, salary=1000000.0, rating=5]

In the src/main/resources folder, employee.json is created.

{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}

Now let us move onto the next example where we will be using Jackson to read an object from an InputStream using Object Mapper and deserialize it into a java object.

Note: Here we will be having a file named employee.json in src/main/resources folder

{"id":"E010890","name":"James","deptName":"DBMS","salary":1000000.0,"rating":5}

We will be using ObjectMapper class readValue() method to read a file.

ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = new FileInputStream("file-path"); 
Employee emp = mapper.readValue(inputStream, Employee.class);

Example

// Java Program to Illustrate Setting Up of Jackson by
// Reading an object from an InputStream
// Using Object Mapper & deserializing to object

// Importing required classes
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

// Class 1
// Main class
class GFG {

// Main driver method
public static void main(String[] args)
{
// Creating an object mapper instance
ObjectMapper mapper = new ObjectMapper();

// Try block to check for exceptions
try {

// input stream points to a json file in
// src/main/resources folder
InputStream inputStream = new FileInputStream(
"/home/suchitra/Desktop/suchitra/projects/java-concurrency-examples/jackson-parsing/src/main/resources/employee.json");

// Deserializes from json file to employee
// object
Employee emp = mapper.readValue(inputStream,
Employee.class);
System.out.println(emp.toString());
}

// Catch blocks to handle the exceptions

// Catch block 1
// Handling FileNotFoundException
catch (FileNotFoundException e) {

// Displaying the exception along with line
// number using printStackTrace()
e.printStackTrace();
}

// Catch block 2
catch (JsonParseException e) {

// Displaying the exception along with line
// number using printStackTrace()
e.printStackTrace();
}

// Catch block 3
catch (JsonMappingException e) {
e.printStackTrace();
}

// Catch block 4
catch (IOException e) {
e.printStackTrace();
}
}
}
}

// Class 2
// Helper class
class Employee {

// Member variables of this class
private String id;
private String name;
private String deptName;
private double salary;
private int rating;

// Member methods of this class
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDeptName() { return deptName; }
public void setDeptName(String deptName)
{
// This keyword refers to current object itself
this.deptName = deptName;
}

public double getSalary() { return salary; }

public void setSalary(double salary)
{
this.salary = salary;
}

public int getRating() { return rating; }

public void setRating(int rating)
{
this.rating = rating;
}

@Override public String toString()
{
return "Employee [id=" + id + ", name=" + name
+ ", deptName=" + deptName + ", salary="
+ salary + ", rating=" + rating + "]";
}
}

Output:

Employee [id=E010890, name=James, deptName=DBMS, salary=1000000.0, rating=5]

Source: geeksforgeeks.org

Monday, August 2, 2021

Multi-Language Programming – Java Process Class, JNI and IO

Multi-Language Programming, Java Process Class, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Exam Preparation, Oracle Java Career

Multilanguage programming, as the name suggests, involves the use of more than one programming language in a single program. There are a huge number of programming languages out there and it is a common experience that we wished we could use components from other languages as well. Well, at the first go, it may seem to be weird to use more than one language, compile codes in more than one language but at the end of the day, it is very useful.

Before diving into the details and code-based stuff, let us go back in the history of programming languages a bit – the history of Java and the history of operating systems. It was in the 1940s when assembly-level programming languages came into existence. 1951 – the Regional Assembly language came into existence. 1958 – ALGOL; 1959 – COBOL (Common Business Oriented Language) and finally BASIC (Beginners All-purpose Symbolic Instruction Code) in 1964. Finally, we got C in 1972. Python came in 1990 but it only got popular in the current days due to the advent of Data Science and Machine Learning techniques. Java came into existence in 1995. Other languages like Go, Rust, Dark, Kotlin, Swift, Scala, Scratch, etc. are very recent developments. Now, why did I say all these? It may seem irrelevant to the topic of discussion but actually, it is not.

It is agreeable that different programming languages have different capabilities. For example, C and C++ support pointers; Python is good for Data Science and AI-based fields; R is good for Data analytics and mathematical operations. Speaking from my personal experience, BASIC was the first language I used, in like 2011. (I used QBASIC mainly). Though QBASIC is an interpreted language, I later shifted to QB64, which is a modernized version of BASIC and it mostly compiled and generates an EXE file. Apart from these, there are times we have also used machine-executable scripts for achieving certain goals. For example, a bash script to toggle your computer Bluetooth, a bat file to communicate with a connected peripheral, and many more.  

Now, there might be times when you are like, “Gosh! I wish this feature of language X was there in language Y too.” Many a time we all have faced it. But now, with the help of Process class, JNI, and IO in Java, we can access the features of any programming language in Java, provided the same is already installed on the machine, along with the dependencies. For example, we can use the Python OpenCV or the Python text to speech (PyTTSx3) libraries from java. 

Implementation: 

A short program to run a Text to speech engine from Java. It consists of two files namely say be it tt.py of python and GFG.java of java.

Fie 1: tts.py

# Python Demo Program

# System for reading command line arguments

import sys

# Our Text to speech module

import pyttsx3

if __name__ == "__main__":

engine = pyttsx3.init()

# Command line inputs saved in arg

for arg in sys.argv[1:]:

# Speaking the input

engine.say(arg)

engine.runAndWait()

File 2: GFG.java

// Java Program to Run a Text to Speech Engine

// Importing I/O classes
import java.io.*;

// Main class
class GFG
{
// Main driver method
public static void main(String args[])
{
// Custom input string consisting of text to speak
String str= "Hello world";
// Try block to handle the exceptions
try
{
Process ec=Runtime.getRuntime().exec("python tts.py "+str); //Using str as command line argument for the python script
ec.waitFor(); //Waiting for the python script to finish executing
}
catch(Exception excep)
{
excep.printStackTrace();
}
}
}

Output: 

Hello world (spoken)

Okay, now going by the definitions,  

“The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it.” 

Implementation:


It is seen that we can transfer the flow of control from the java application to the python script and after execution of the script is complete, the flow of control is returned. Now, the question is how to transfer data as well, apart from the flow of control only. Here, the I/O classes come into play. 

From the python program, we can just print the data we want to STDOUT. (Using the simple print() function in python.) Now, the instance ec of the Process class has a function called getInputStream(). This returns an InputStream object for the Java program. Now, inputs from the input stream can easily be handled with BufferedReader or Scanner classes. The STDOUT of the Python class is connected to the Input Stream of the Process class Instance.

Example 1: File: tts.py 

# Importing required python classes
import sys
import pyttsx3

if __name__ == "__main__":
engine = pyttsx3.init()

# Iterating over using for loop
for arg in sys.argv[1:]
engine.say(arg)
engine.runAndWait()

# Print to STDOUT of python script
print("Execution from Python completed")

Example 2: File GFG.java

// Importing java I/O classes
import java.io.*;

// Main class
class GFG {

// MAin driver method
public static void main(String args[])
{
// Custom input string
String str = "Hello world";

// Try block to check for exceptions
try {
// Creating object of Processor class for python
// script
Process ec = Runtime.getRuntime().exec(
"python tts.py " + str);

// Taking input from user by
// creating object of BufferedReader class
// as for less salalbilty it is fast

// Connect STDOUT of Python script to
// BufferedReader of Java
BufferedReader br = new BufferedReader(
new InputStreamReader(ec.getInputStream()));

// Initially declaring and initializing empty
// string
String st = " ";

// Read all outputs from python script
while ((st = br.readLine()) != null) {
// Printing them
System.out.println(st);
}

ec.waitFor();
}

// Catch block to handle the exceptions
catch (Exception excep) {

// Print the exception/s along twith line number
// using pprintStacktrace() method
excep.printStackTrace();
}
}
}

Output: 

Hello world (Spoken)
Execution from Python completed

Output explanation:

The output when the Java program is executed is ‘Hello World’ in audio format and ‘Execution from Python completed’ in STDOUT. Now, we may also want to execute some shell commands from the Java program to interact with the system.

Example 3: File GFG.java 

// Java Program to Shut-Down the Computer

// Importing input output classes
import java.io.*;

// Main class
class GFG {

// Main driver method
public static void main(String args[])
{
// Try block to check for exceptions
try {
// Windows machine shutdown
Process ec = Runtime.getRuntime().exec(
"shutdown -s -f -t 0");
ec.waitFor();

// LINUX machine shutdown
ec = Runtime.getRuntime().exec("sudo poweroff");
ec.waitFor();
}

// catch block to handle exceptions
catch (Exception excep) {
// Print and display the exception on the console
// using printStackTrace() method
excep.printStackTrace();
}
}
}

Now, as the heading goes, what is JNI. JNI or Java Native Interface provides an interface ( a .h header file) so that we can include it in our C and C++ programs and call the functions in the C program from our Java program. The functions in the C program are called Native functions, and hence the name. However, going a bit into the JNI, we can define native methods in java looks like in below illustration as shown below.

Illustration:  


native void function(parameters)
{ ... }

The native keyword here signifies that this particular method is to be accessed from an external native code defined in C or C++. On the other hand, for compiling a java program with native methods. We need to use javah for older JDK or javac -h for the latest JDKs. This generates a .h header file that has to be included in the C program with #include preprocessor. Most of us usually use the gcc compiler, and it can be used to compile the C program into a .dll library. 

static {
System.loadLibrary("library.dll");
}

If the C program is compiled into the library.dll file, the same can be imported into the java program like this. The functions defined in the C program by including the .h header generated by javac -h can be directly called native functions.

As we have seen, the Process class can be used to call programs written in other languages, as well as shell scripts. It is quite imperative to say that Process class can also be used to interact with connected hardware as the machine does when there is no proper library in java for the same. Here, we are mainly talking about Serial Communication devices. 

The Process class and using multiple programming languages in a single project can be a lifesaver when the time is very little and appropriate libraries are not available in a single language. For example, we are not very fluent in Python. We are more of a Java programmer. Hence, we mainly write programs in Java, but there are some instances when Python has better libraries. We can easily use the Process class for invoking them.

Note: Be aware of libraries like Jython that might be able to run Python scripts from Java directly, but we are not talking solely about python. Process class can run programs from each and every programming language as long as it is supported on your machine, and you don’t need to learn other libraries to achieve the same. It would be very helpful in projects. Like you want to analyze a huge amount of data you get in your program written in Java. One can simply pass on the data to a program in R or in Python to analyze the data instead of doing the same manually on Java.

Source: geeksforgeeks.org

Friday, July 30, 2021

Interfaces and Polymorphism in Java

Java Interfaces, Java Polymorphism, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Career, Oracle Java Certification, Oracle Java OOPs

Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, interfaces, etc. In this article, we will discuss polymorphism and interface concepts.

Polymorphism is that it has many forms that mean one specific defined form is used in many different ways. The simplest real-life example is let’s suppose we have to store the name of the person and the phone number of the person, but there are many situations when a person has two different phone numbers. We have to save the same phone number under the same name.

Let us interpret it with help . So, in java, the problem can be solved using an object-oriented concept, void insertPhone(String name, int phone). So, this method is used to save the phone number of the particular person. Similarly, we can use the same form but a different signature means different parameters to store the alternative phone number of the person’s void insertPhone(String name, int phone1, int phone2). One method has two different forms and performs different operations. This is an example of polymorphism, which is method overloading.

Types of polymorphism in Java:

1. Run time polymorphism

2. Compile-time polymorphism

Type 1: Run time polymorphism

This type of polymorphism is resolved by the java virtual machine, not by the java compiler. That’s why this type of polymorphism is called run-time polymorphism. Run time polymorphism occurs during method overriding in java.

Example 

// Java Program to Illustrate Run-time polymorphism

// Importing I/O classes

import java.io.*;

// Class 1 (Parent class)

class GFG1 {

//name method

void name() {

System.out.println("This is the GFG1 class");

}

}

// Class 2 (Chile class)

// Main class extending parent class

public class GFG extends GFG1 {

// Method 1

void name() {

// Print statement

System.out.println("This is the GFG class");

}

// Method 2

// Main drive method

public static void main(String[] args) {

// Now creating 2 objects with different references and

// calling the Method 1 over the objects

// Case 1: GFG1 reference and GFG1 is the object

GFG1 ob = new GFG1();

ob.name();

// Case 2: GFG1 reference and GFG is the object

GFG1 ob1 = new GFG();

ob1.name();

}

}

Output

This is the GFG1 class
This is the GFG class

Output explanation: 

In the above example, the same function i.e name is called two times, but in both cases, the output is different. The signatures of these methods are also the same. That’s why compilers cannot be able to identify which should be executed. This is determined only after the object creation and reference of the class, which is performed during run time (Memory management ). That’s why this is run-time polymorphism.

Type 2: Compile-time polymorphism

Method overloading is an example of the compile-time polymorphism method. Overloading means a function having the same name but a different signature. This is compile-time polymorphism because this type of polymorphism is determined during the compilation time because during writing the code we already mention the different types of parameters for the same function name.

Example 

// Java Program to Illustrate Run-time polymorphism

// Importing required classes
import java.io.*;
import java.util.*;

// Class 1
// Helper class
class First {

// Method of this class
// Without any parameter
void check()
{

// Print statement if this method is called
System.out.println("This is the class First");
}
}

// Class 2
// Main class
class Second extends First {

// Method overloading
void check(String name)
{
// Printing the name of the class method having the
// parameter
System.out.println("This is the class " + name);
}

// Method 2
// Main driver method
public static void main(String args[])
{
// Creating object of class 2
Second ob = new Second();
// Calling method over class 2 object
ob.check("Second");

// Creating object of class 1
First ob1 = new First();
ob.check();

// Upcasting
First ob2 = new Second();
ob.check();
}
}

Output

This is the class Second
This is the class First
This is the class First

Java Interfaces, Java Polymorphism, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Career, Oracle Java Certification, Oracle Java OOPs
Interfaces are very similar to classes. They have variables and methods but the interfaces allow only abstract methods(that don’t contain the body of the methods), but what is the difference between the classes and the interfaces? The first advantage is to allow interfaces to implement the multiple inheritances in a particular class. The JAVA language doesn’t support multiple inheritances if we extend multiple classes in the class, but with the help of the interfaces, multiple inheritances are allowed in Java.

Real-life Example

The real-world example of interfaces is that we have multiple classes for different levels of employees working in a particular company and the necessary property of the class is the salary of the employees and this. We must be implemented in every class and. Also, it is different for every employee here. The concept of the interface is used. We simply create an interface containing an abstract salary method and implement it in all the classes and we can easily define different salaries of the employees.

Example

// Java Program to Demonstarte Concept of interfaces

// Interfacce
interface salary {
void insertsalary(int salary);
}

// Class 1
// Implementing the salary in the class
class SDE1 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

// Class 2
// Implementing the salary inside the SDE2 class
class SDE2 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary() { System.out.println(this.salary); }
}

public class GFG {

public static void main(String[] args)
{
SDE1 ob = new SDE1();
// Insert different salaries
ob.insertsalary(100000);
ob.printSalary();
SDE2 ob1 = new SDE2();

ob1.insertsalary(200000);
ob1.printSalary();
}
}

Output

100000
200000

Source: geeksforgeeks.org

Wednesday, July 28, 2021

Difference Between JSF2 and Seam3

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Exam Prep, Core Java

JSF2 vs Seam3

JSF2 and Seam3 are basically two types of application framework that help to create the latest and up-to-date web 2.0 applications. These applications are created by the method of unification and integration of different technologies present, depending upon the application framework you are using. There are some basic differences between these two application frameworks JSF2 and Seam 3.

Seam3 Application Framework

Seam3 application framework is basically a platform, having a set of developing tools and the modules which makes it easier for us to create the Java EE 6 web applications through it. All the developing tools provided in this application framework are basically given by the JBoss Tools and the Seam Forge. The JBoss tools are basically designed to make the developers to write, test and deploy many of the enterprise Java based applications. Similarly, the Seam Forge tools provide the ability to enhance the project’s API and its shell.

Seam is used to create the internet applications in Java by integrating many of the useful technologies, which includes the JavaServer Faces (JSF), Enterprise Java Beans (EJB 3.0), Java Persistence (JPA), Asynchronous JavaScript and XML (AJAX), Business Process Management (BPM). These technologies are combined to give the simple, easier and much more sophisticated tooling experience provided to the developers.

The design of the seam3 has been made by keeping in view the most important aspects of providing the developer with simplicity in creating these web-based applications. It also helps the developers by giving them the opportunities to assemble the entire complex applications by using simple technologies like Plain Old Java Objects (POJOs), componentized UI widgets and some of the XML.

JSF2 Application Framework

The JSF2 is another application platform, created by using the Java Community Process (JCP), which helps to create many of the web application by reusing and assembling the developing components in a page. This JSF2 is quite similar to seam3 in many ways, as both of them are the platforms to create the web-based applications by integrating some special technologies, which are mostly different for both of these frameworks. JSF is basically establish on Model-View-Controller (MVC) design pattern, that is why most of the applications created on it are much easier and simple to handle as compared to other Servlets or Java platforms.

Difference between JSF2 and Seam3:

There is some basic difference between the two application frameworks, despite of many similarities which are:

• Seam3 can execute most of the web-based application, much faster and simpler than the JSF2. This makes the seam the more efficient application framework to work with.

• JSF2 is the simplest application platform available that is why it can run without providing much of the headache to the developer, but the Seam3 is basically a complex application framework which needs the proper setting of its Embedded JBoss tools, before working with it.

• Seam3 is much better to use with the low-level integration tests, so that one can stay away of the complexity it can cause with high level java based application for the web.

Difference between JSF2 and Seam3:

There is some basic difference between the two application frameworks, despite of many similarities which are:

• Seam3 can execute most of the web-based application, much faster and simpler than the JSF2. This makes the seam the more efficient application framework to work with.

• JSF2 is the simplest application platform available that is why it can run without providing much of the headache to the developer, but the Seam3 is basically a complex application framework which needs the proper setting of its Embedded JBoss tools, before working with it.

• Seam3 is much better to use with the low-level integration tests, so that one can stay away of the complexity it can cause with high level java based application for the web.

Source: differencebetween.com