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

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