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

Monday, July 26, 2021

Difference Between equals and hashCode in Java

Key Difference – equals vs hashCode in Java

The equals is similar to the == operator, which is to test for object identity rather than object equality. The hashCode is a method by which a class implicitly or explicitly break down the data stored in an instance of the class into a single hash value, which is a 32 bit signed integer. The key difference between equals and hashCode in Java is that the equals is used to compare two objects while the hashCode is used in hashing to decide which group an object should be categorized into.

What is equals in Java?

The equals method is used to compare two objects. The default equals method is defined in the object class. That implementation is similar to the == operator. The two object references are equal only if they are pointing to the same object. It is possible to override the equals method.

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career
Figure 01: Java Program with equals

The statement System.out.println(s1.equals(s2)) will give the answer false because s1 and s2 are referring to two different objects. It was similar to the statement, System.out.println(s1 == s2);

The statement System.out.println(s1.equals(s3)) will give the answer true because s1 and s3 are referring to the same object. It was similar to the statement, System.out.println(s1 == s3);

There is no equals method in the Student class. Therefore, the equals in the Object class is called. True is displayed only if the object reference is pointing to the same object.

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career
Figure 02: Java Program with Overridden equals

According to the above program, the equals method is overridden. An object is  passed to the method, and it is type casted to Student. Then, the id values are checked. If the id values are similar, it will return true. If not, it will return false. The ids of s1 and s2 are similar. So, it will print true. The ids of s1 and s3 are also similar, so it will print true.

What is hashCode in Java?


The hashCode is used in hashing to decide to which group an object should be categorized into. A group of objects can share the same hashCode. A correct hashing function can evenly distribute objects into different groups.

A correct hashCode can have properties as follows. Assume that there are two objects as obj1 and obj2. If obj1.equals(obj2) is true, then the obj1.hashCode() is equal to obj2.hashCode(). If obj1.equals(obj2) is false, it is not necessary that obj1.hashCode() is not equal to obj2.hashCode(). The two unequal object might also have the same hashCode.

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career
Figure 03: Student class with equals and hashCode

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Career
Figure 04: Main Program

The Student class contains the equals and hashCode methods. The equals method in the Student class will receive an object. If the object is null, it will return false. If the classes of the objects are not the same, it will return false. The id values are checked in both objects. If they are similar, it will return true. Else it will return false.

In the main program, objects s1 and s2 are created. When calling s1.equals(s2) will give true because the equals method is overridden and it checks the id values of the two objects. Even though they are referring to two objects, the answer is true because the id values of s1 and s2 are the same. As the s1.equals(s2) is true, the hashCode of s1 and s2 should be equal. Printing the hashCode of s1 and s2 gives the same value. The hashCode method can be used with Collections such as HashMap.

What is the Difference Between equals and hashCode in Java?


equals vs hashCode in Java 
equals is a method in Java that acts similar to the == operator, which is to test for object identity rather than object equality.   hashCode is a method by which a class implicitly or explicitly breaks down the data stored in an instance of the class into a single hash value. 
Usage 
The method equals is used to compare two objects.   The method is used in hashing to decide which group an object should be placed into.

Source: differencebetween.com

Friday, July 23, 2021

Difference Between Applets and Servlets

Oracle Java Applets, Oracle Java Servlets, Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Career

Applets vs Servlets

A program written in Java that can be embedded in a HTML page is called an applet. A Java enabled browser can be used to view the web page containing the applet. When the page containing an applet is viewed, the code of the applet is transferred to the user computer and executed on the Java Virtual Machine (JVM) of the browser. A Java program that is used to improve/ extend the functionalities of a server is called a servlet. The server should be accessed by the host applications using the request-response model. In simple terms, a servelt can be seen as an Java applet running on the server.

What is an Applet?

A program written in Java that can be embedded in a HTML page is called an applet. A Java enabled browser can be used to view the web page containing the applet. When the page containing an applet is viewed, the code of the applet is transferred to the user computer and executed on the Java Virtual Machine (JVM) of the browser. Applets allow providing the user with interactive features that might not be possible to provide using only HTML. Since the applet’s code is run on JVM, applets are platform independent (supports Microsoft Windows, UNIX, Mac OS, etc.) and can run in any browser that supports Java. Furthermore, applets are cached by most web browsers. Hence applets could be loaded quickly when returning to a web page. When it comes to security, there are two types of applets called signed applets and unsigned applets. Unsigned applets have some important restrictions like inability to access the local file system. They can only access the applet download site on the web. Signed applets can behave as a standalone application once its signature is verified.

What is a Servlet?

A Java program that is used to improve/ extend the functionalities of a server is called a servlet. The server should be accessed by the host applications using the request-response model. In simple terms, a servelt can be seen as an Java applet running on the server. Typically servlets are used for storing/ processing data that were submitted using an HTML form and to provide dynamic content in a web page. Furthermore, servlets are used for managing state information. Java servlets are efficient, easier to use and portable compared to other CGI (Common Gateway Interface) technologies.

What is the difference between Applets and Servlets?

A java program that can be embedded in a HTML page and viewed using a Java enabled browser is called an applet, while a Java program that is used to improve/ extend the functionalities of a server is called a servlet. Actually, a servlet can be seen as an applet running on the server. An applet is downloaded in to the client’s machine and run on the client’s browser, whereas a servlet runs on the server and transfers the results back to the client when it is done. When using applets, the entire code of the applet has to be transferred to the client. Therefore it consumes more network bandwidth than servlets, which transfers only the results to the client.

Source: differencebetween.com

Wednesday, July 21, 2021

Difference Between JSP and Servlets

JSP, Servlets, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career

JSP vs Servlets

A Servlet is a server side software component written in Java and runs in a compatible container environment known as a Servelt container (like Apache Tomcat). Servlets are predominantly used in implementing web applications that generate dynamic web pages. They can however generate any other content type like XML, text, images, sound clips, PDF, Excel files programmatically.

A Servlet written to generate some HTML may look like this:

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter w = response.getWriter();

w.write(“<html>”);

w.write(“<body>”);

Date d = new Date();

w.write(d.toString());

w.write(“</body>”);

w.write(“</html>”);

}

}

JSP, Servlets, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career
The code above contains a mixture of HTML and Java source code. Such is not very readable and maintainable. JSP which stands for JavaServer Pages provides a better alternative. For example, the following is a fragment of JSP code that results in identical output:

<%@page import=”java.util.Date”%>

<html>

<body>

<%= new Date().toString() %>

</body>

</html>

Web page authors find JSP easier to write and maintain. JSP files are however translated into Servlets by a Servlet container at the time JSP files are first accessed. However, business logic writers find Servlets to be easier to work with.

A request received by a web application should trigger the execution of some business logic and then generate a resultant web page as the response. In modern day web applications, controlling the overall request processing cycle is mostly handed by Servlets. As the last stage in processing a request, such a Servlet generally hands over the responsibility of generating the dynamic HTML to a JSP.

Monday, July 19, 2021

Set it up

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

In Java, we often have framework support for importing settings from the file system of our application. If we’re lucky, and we often are, these settings can be customized and overridden by system properties or environment variables.

However, there are a couple of situations where this doesn’t quite apply:

◉ Very lightweight applications that use no frameworks

◉ Loading custom settings based on business logic

Though we can shoe-horn heavier frameworks like Spring into the first, or try to force Spring to process properties for us, often we need a lighter solution.

Lightweight Config

I recently wrote and released Lightweight Config, an open source package to solve this with either .yaml or .properties files.

I’ve demonstrated its use in AWS Lambdas in an article on Baeldung.com.

I thought it might be nice to cover a different use case in this article, notably how it might be used to load settings up in a test.

At The Max

I wrote Lightweight Config from the ground up, but I’ve used its predecessors extensively. Originally, it was a test-helper library. Then I created one for loading settings for lambdas.

At full strength, you’d define a .yml file:

hardCoded: true

interpolated: ${SOME_ENV_VAR:-default}

partialInterpolation: Welcome to ${APP_NAME}

database:

   url: ${DB_URL}

   username: ${DB_USER}

   password: ${DB_PASSWORD}

Then a POJO to load the file into:

public class Settings {

    private boolean hardCoded;

    private String interpolated;

    private String partialInterpolation;

    private DatabaseSettings database;

    // getters and setters

}

Then it’s a one liner to load from the yaml into the Settings object – Settings settings = ConfigLoader.loadYmlConfigFromResource("settings.yaml", Settings.class)

There are also some hooks that can be applied to plug in custom tags if necessary.

Reading Per Environment Properties

Let’s flip to an example where we just want some Java .properties loaded into Properties. One might argue that the POJO approach gives us a better API, but let’s say we’re using something that’s already bound to Properties, such as an email client, or DB connection pool.

Here’s a snippet of some settings that relate to dev:

workers=12

sourceEmail=test@mytest.com

pdfFolder=/home/test/pdf

Let’s call this file profiles/dev.properties.

Now let’s create a parent file with all the global settings in:

#import profiles/${ENV_NAME}.properties

threadPoolSize=24

versionNumber=${BUILD_VERSION:-Unknown}

adminUser=admin

adminPassword=${ADMIN_PASSWORD}

Let’s call this file app.properties and put it in the same directory as contains the profiles directory mentioned above.

Now we can load both the above files into a Properties object by:

Path appPropertiesPath = PROPERTIES_DIR.resolve("app.properties");

Properties properties = ConfigLoader.loadProperties(appPropertiesPath);

What happens in this case is that the various placeholders are filled in from environment variables (or system properties if you prefer). Included in this is the #import statement, which not only describes how a child file is imported, but allows placeholder interpolation into the path of that file.

So, by setting a different ENV_NAME environment variable, the same loading code could import a different set of per-environment properties into the whole Properties object being loaded.

It’s a simple syntax/approach that’s flexible enough to use for a variety of things.

Source: javacodegeeks.com

Friday, July 16, 2021

Difference Between Abstract Class and Concrete Class

Oracle Java Abstract Class, Oracle Java Concrete Class, Oracle Java Exam Prep, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Material, Oracle Java Guides

Abstract Class vs Concrete Class

Most of the popular modern object oriented programming languages like Java and C# are class based. They achieve the object oriented concepts such as encapsulation, inheritance and polymorphism through the use of classes. Classes are an abstract representation of real world objects. Classes can be either concrete or abstract depending on the level of implementation of their method functionalities. A concrete class completely implements all its methods. An abstract class can be considered as a limited version of a regular (concrete) class, where it may contain partially implemented methods. Typically, concrete classes are referred to as (just) classes.

What is Concrete Class?

The default class is a concrete class. The class keyword is used to define classes (e.g. in Java). And usually they are simply referred to as classes (without the adjective concrete). Concrete classes depict the conceptual representation of real world objects. Classes have properties called attributes. Attributes are implemented as global and instance variables. Methods in the classes represent or define the behavior of these classes. Methods and attributes of classes are called the members of the class. Typically, encapsulation is achieved by making the attributes private, while creating public methods that can be used to access those attributes. An object is the instance of a class. Inheritance allows the user to extend classes (called sub classes) from other classes (called super classes). Polymorphism allows the programmer to substitute an object of a class in place of an object of its super class. Typically, the nouns found in the problem definition directly become classes in the program. And similarly, verbs become methods. Public, private and protected are the typical access modifiers used for classes.

What is Abstract Class?

Abstract classes are declared using Abstract keyword (e.g. in Java,). Typically, Abstract classes, also known as Abstract Base Classes (ABC), cannot be instantiated (an instance of that class cannot be created). So, Abstract classes are only meaningful to have if the programming language supports inheritance (ability to create subclasses from extending a class). Abstract classes usually represent an abstract concept or entity with partial or no implementation. Therefore, Abstract classes act as parent classes from which child classes are derived so that the child class will share the incomplete features of the parent class and functionality can be added to complete them.

Abstract classes may contain Abstract methods. Subclasses extending an abstract class may implement these (inherited) Abstract methods. If the child class implements all such Abstract methods, it becomes a concrete class. But if it does not, the child class also becomes an Abstract class. What all this means is that, when the programmer nominates a class as an Abstract, she is saying that the class will be incomplete and it will have elements that need to be completed by the inheriting subclasses. This is a nice way to create a contract between two programmers, which simplifies tasks in software development. The programmer, who writes code to inherit, needs to follow the method definitions exactly (but of course can have her own implementation).

What is the difference between Abstract Class and Concrete Class?

Abstract classes usually have partial or no implementation. On the other hand, concrete classes always have full implementation of its behavior. Unlike concrete classes, abstract classes cannot be instantiated. Therefore abstract classes have to be extended in order to make them useful. Abstract classes may contain abstract methods, but concrete classes can’t. When an abstract class is extended, all methods (both abstract and concrete) are inherited. The inherited class can implement any or all the methods. If all the abstract methods are not implemented, then that class also becomes an abstract class.

Source: differencebetween.com

Wednesday, July 14, 2021

Difference Between AOP and OOP

AOP vs OOP

AOP (Aspect-oriented programming) and OOP (Object-oriented programming) are two programming paradigms. A programming paradigm is a fundamental style of computer programming. Programming paradigms differ in how each element of the programs is represented and how each step is defined for solving problems. As the name suggests, OOP focuses on representing problems using real-world objects and their behavior, while AOP deals with breaking down the programs in to separate crosscutting concerns.

What is AOP?

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

AOP is a programming paradigm, which deals with breaking down a program in to cohesive areas of functionality (called concerns) that cut across multiple areas, in order to increase modularity. Support for abstractions (such as classes, methods, etc.) to group and encapsulate concerns in to unique entities is provided in many other programming paradigms. But concerns (such as “Logging”) are examples of crosscutting concerns, because every logged part of the system is affected by the strategy used for logging. The main focus of all AOP implementations is to have suitable crosscutting expressions to capture all concerns in a single location.

What is OOP?

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

In OOP, the focus is on thinking about the problem to be solved in terms of real-world elements, and representing the problem in terms of objects and their behavior. Classes depict the abstract representations of real world objects. Classes are like blueprints or templates, which gather similar items or things that can be grouped together. Classes have properties called attributes. Attributes are implemented as global and instance variables. Methods in the classes represent or define the behavior of these classes. Methods and attributes of classes are called the members of the class. An instance of a class is called an object. Therefore, an object is a data structure that closely resembles some real-world object.

There are several important OOP concepts such as Data abstraction, Encapsulation, Polymorphism, Messaging, Modularity and Inheritance. Typically, encapsulation is achieved by making the attributes private, while creating public methods that can be used to access those attributes. Inheritance allows the user to extend classes (called sub classes) from other classes (called super classes). Polymorphism allows the programmer to substitute an object of a class in place of an object of its super class. Typically, the nouns found in the problem definition directly become classes in the program. And similarly, verbs become methods. Some of the most popular OOP languages are Java and C#.

What is the difference between AOP and OOP?

The key difference between OOP and AOP is that the focus of OOP is to break down the programming task in to objects, which encapsulate data and methods, while the focus of AOP is to break down the program in to crosscutting concerns. In fact, AOP is not a competitor for OOP, because it emerged out of OOP paradigm. AOP extends OOP by addressing few of its problems. AOP introduces neat ways to implement crosscutting concerns (which might have been scattered over several places in the corresponding OOP implementation) in a single place. Therefore, AOP makes the program cleaner and more loosely coupled.

Monday, July 12, 2021

Java – How to Convert Java Array to Iterable?

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

A quick guide to convert an array to iterable in java using Stream api with examples programs in two ways.

Read More: 1Z0-808: Java SE 8 Programmer I

1. Overview

In this tutorial, We will learn how to convert java array to iterable in different ways with example programs.

First we will go thorough the basic one how to iterate over the array values. Next, how to convert the array to Iterable using legacy java api and finally using java 8 api for java array iterator.

Bonus section on how to convert string to iterable with a delimiter.

2. Create a iterator over the array using loops

Running a for loop over a array to create iterable logic to get the each value from array based on the index.

package com.oraclejavacertified.arrays.toiterabale;

/**

 * 

 * Array Iterate example using loops

 * 

 */

public class ArrayIterate {

    public static void main(String[] args) {

        // string array

        String[] names = new String[] {"john", "Amal", "Paul"};

        // iterating array over its values.

        for(int index=0; index< names.length ; index++) {

            System.out.println(names[index]);

        }

    }

}

Output:

john

Amal

Paul

3. Convert Java Array to Iterable using legacy java before JDK 8

First we will convert the array to list using Arrays.asList() method. Next, convert list to Iterable in java using list.iterator() method.

Finally, iterate the iterator over the while loop to get the all the values.

Array to Iterable Example:

package com.oraclejavacertified.arrays.toiterabale;

import java.util.Arrays;

import java.util.Iterator;

import java.util.List;

/**

 * 

 * Example to convert Java Array to Iterable before Java 8

 * 

 */

public class JavaArrayToIterableExample {

    public static void main(String[] args) {

        // string array

        String[] names = new String[] {"john", "Amal", "Paul"};

        // string array to list conversion

        List<String> namesList = Arrays.asList(names);

        // List to iterable

        Iterator<String> it = namesList.iterator();

        // printing each value from iterator.

        while(it.hasNext()) {

            System.out.println(it.next());

        }

    }

}

Output:

john

Amal

Paul

4. Convert Java Array to Iterable Using Java 8 Stream

In the above section, we called Arrays.asList() method to convert the array to List. But, now will use another method from java 8 stream api Arrays.stream(array) method which takes input array and returns a Stream of array type.

Arrays.stream() method provides the arrays to access the stream api and use the power of parallel execution on larger arrays.

But for now, after getting the Stream<String> object then you need to call the iterator() method on stream to convert Stream to iterable.

Do not worry, if you are new to the java 8, the below program is break down into multiple steps. And also provided a single line solution.

import java.util.Arrays;

import java.util.Iterator;

import java.util.stream.Stream;

/**

 * 

 * Example to convert Java Array to Iterable using Java 8 Arrays.stream()

 * 

 */

public class JavaArrayToIterableExampleJava8 {

    public static void main(String[] args) {

        // string array

        String[] names = new String[] {"john", "Amal", "Paul"};

        System.out.println("Multi line solution");

        // Convert string array to Stream<String>

        Stream<String> namesList = Arrays.stream(names);

        // Stream to iterable

        Iterator<String> it = namesList.iterator();

        // printing each value from iterator.

        while(it.hasNext()) {

            System.out.println(it.next());

        }

        // singel line

        System.out.println("\nIn single line");

        Arrays.stream(names).iterator().forEachRemaining(name -> System.out.println(name));

    }

}

Multiline and single line solutions provide the same output. If you are going to use in the realtime project then use it as single line statement as you want to fell like expert and take the advantage of stream power.

Multi line solution

john

Amal

Paul

In single line

john

Amal

Paul

5. Bonus – Convert String to Iterable

Applying iterable on string is quite simple if you have understood the above code correctly. What we need is now to convert the String to String array with space or if the string has any delimiter.

After getting the string array then apply the same logic as java 8 streams as below.

public class JavaStringToIterableExampleJava9 {

    public static void main(String[] args) {

        // string 

        String numbers = "1 2 3 4 5 6";

        // string to string array

        String[] numbersArray = numbers.split(" ");

        System.out.println("Multi line solution");

        // Convert string array to Stream<String>

        Stream<String> numbersList = Arrays.stream(numbersArray);

        // Stream to iterable

        Iterator<String> it = numbersList.iterator();

        // printing each value from iterator.

        while(it.hasNext()) {

            System.out.println(it.next());

        }

        // singel line

        System.out.println("\nIn single line");

        Arrays.stream(numbersArray).iterator().forEachRemaining(name -> System.out.println(name));

    }

}

Output:

Multi line solution

1

2

3

4

5

6

In single line

1

2

3

4

5

6

Source: javacodegeeks.com

Friday, July 9, 2021

Java 8 Streams Filter With Multiple Conditions Examples

Oracle Java, Java 8 Streams, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Learning, Oracle Java Prep, Oracle Java Certification

A quick guide to java 8 streams filtering concept with multiple conditions. This demonstrates how to use filter() in a more advanced way with examples

More Info: 1Z0-809: Java SE 8 Programmer II

1. Overview

In this tutorial, We’ll learn how to utilise stream filter() with several filter conditions (can be more than one condition).

Normally, we apply a single condition to streams using filter() method with lambda and then store the results in Lists or Sets.

However, we’ll learn how to use the filter() method with as many condition filters as we require.

More filters can be applied in a variety of methods, such using the filter() method twice or supplying another predicate to the Predicate.and() method.

In the next sections, we’ll look at examples with single and multiple conditions.

2. Stream.filter() with Single Condition

First, We’ll start by looking at how to apply the single filter condition to java streams.

Predicate is passed as an argument to the filter() method. Each value in the stream is evaluated to this predicate logic.

There are only a few methods in Predicate functional interface, such as and(), or(), or negate(), and isEquals().

package com.oraclejavacertified.java8.streams.filter;

import java.util.List;

import java.util.function.Predicate;

import java.util.stream.Collectors;

import java.util.stream.Stream;

/**

 * Example to filter the steam with single condition.

 * 

 */

public class FilterSingleCondition {

    public static void main(String[] args) {

        System.out.println("Fruites stream : " + getStream().collect(Collectors.toList()));

        // filter 1

        Predicate<String> nofruitWordFilter = name -> !name.contains("fruit");

        List<String> filteredList1 = getStream().filter(nofruitWordFilter).collect(Collectors.toList());

        System.out.println("filteredList 1 : " + filteredList1);

        // filter 1

        Predicate<String> noLetterOFilter = name -> !name.contains("o");

        List<String> noLetterOFilterList = getStream().filter(noLetterOFilter).collect(Collectors.toList());

        System.out.println("noLetterOFilterList : " + noLetterOFilterList);

    }

    // creating the stream of strings.

    private static Stream<String> getStream() {

        Stream<String> fruitesStream = Stream.of("mango", "grapes", "apple", "papaya", "jack fruit", "dragon fruit");

        return fruitesStream;

    }

}

Output:

Fruites stream : [mango, grapes, apple, papaya, jack fruit, dragon fruit]

filteredList 1 : [mango, grapes, apple, papaya]

noLetterOFilterList : [grapes, apple, papaya, jack fruit]

In the preceding example, we generated two predicate filters but only applied one of them to the stream at a time.

And it has generated two distinct outputs, which you should carefully examine.

3. Stream.filter() – Java 8 Stream Filter Multiple Parameters or Conditions

In the previous section, we have seen how to create a filter in java for stream

Next, we’ll attempt two different approaches of applying many conditions to a stream.

3.1 Invoking the filter() method on the stream multiple times

Take a look at the results after using the filter() method twice with different predicates criteria.

package com.oraclejavacertified.java8.streams.filter;

import java.util.List;

import java.util.function.Predicate;

import java.util.stream.Collectors;

import java.util.stream.Stream;

/**

 * Example to filter the steam with multiple conditions.

 * 

 */

public class FilterMultipleCondition {

    public static void main(String[] args) {

        System.out.println("Fruites stream : " + getStream().collect(Collectors.toList()));

        // filter 1

        Predicate<String> nofruitWordFilter = name -> !name.contains("fruit");

        // filter 2

        Predicate<String> noLetterOFilter = name -> !name.contains("o");

        // to remove the fruites with word "fruit" and with letter "o".

        List<String> result = getStream().filter(nofruitWordFilter)

                .filter(noLetterOFilter)

                .collect(Collectors.toList());

        // printing the final result

        System.out.println("Final result : " + result);

    }

    // creating the stream of strings.

    private static Stream<String> getStream() {

        Stream<String> fruitesStream = Stream.of("mango", "grapes", "apple", "papaya", "jack fruit", "dragon fruit");

        return fruitesStream;

    }

}

Output:

Fruites stream : [mango, grapes, apple, papaya, jack fruit, dragon fruit]

Final result : [grapes, apple, papaya]

3.2 Invoking Predicate.and() method with two conditions

Let’s utilise the method firstPredicate.and(secondPredicate) now. Pass the second predicate as a parameter to the and() function on the first predicate.

This signifies that the first predicate receives each instance from the stream. If the first predicate returns true, the second predicate receives the same value.

Finally, the result of filter() method will be satisfied by first and second predicate’s.

You can also use p1.and(p2.and(p3) to call with multiple predicates.

List<String> andPredicateResult = getStream().filter(nofruitWordFilter
        .and(noLetterOFilter))
        .collect(Collectors.toList());
 
System.out.println("andPredicateResult : "+andPredicateResult);

Output:

andPredicateResult : [grapes, apple, papaya]

When you call the filter() method several times and the predicate.and() method, the results are the same. However, it is recommended that you use the predicate and() method as needed.

this is similar to the grouping the multiple conditions into the single conditions as single predicate to filter() method.

You can use predicate or() or isEquals() methods with the multiple predicate conditions.

Source: javacodegeeks.com

Wednesday, July 7, 2021

Java 8 – Converting a List to String with Examples

Oracle Java 8, Oracle Java Certification, Oracle Java Guides, Oracle Java Career, Oracle Java Preparation

A quick guide to convert List to String in java using different methods and apache commons api with examples.

1. Overview

In this tutorial, we will learn how to convert List to String in java with example programs.

This conversion is done with the simple steps with java api methods.

First, we will understand how to make List to String using toString() method.

Next, Collection to String with comma separator or custom delimiter using Java 8 Streams Collectors api and String.join() method.

Finally, learn with famous library apache commands StringUtils.join() method.

For all the examples, input list must be a type of String as List<String> otherwise we need to convert the non string to String. Example, List is type of Double then need to convert then double to string first.

2. List to String Using Standard toString() method

List.toString() is the simplest one but it adds the square brackets at the start and end with each string is separated with comma separator.

The drawback is that we can not replace the comma with another separator and can not remove the square brackets.

package com.oraclejavacertified.convert.list2string;

import java.util.Arrays;

import java.util.List;

/**

 * Example to convert List to string using toString() method.

 *

 */

public class ListToStringUsingToStringExample {

    public static void main(String[] args) { 

    // creating a list with strings.

    List<String> list = Arrays.asList("One",

                      "Two",

                      "Three",

                      "Four",

                      "Five");

    // converting List<String> to String using toString() method

    String stringFromList = list.toString();

    // priting the string

    System.out.println("String : "+stringFromList);     

    }

}

Output:

String : [One, Two, Three, Four, Five]

3. List to String Using Java 8 String.join() Method

The above program works before java 8 and after. But, java 8 String is added with a special method String.join() to convert the collection to a string with a given delimiter.

The below example is with the pipe and tilde separators in the string.

import java.util.Arrays;

import java.util.List;

/**

 * Example to convert List to string using String.join() method.

 * 

 */

public class ListToStringUsingString_JoinExample {

    public static void main(String[] args) {

    // creating a list with strings.

    List<String> list = Arrays.asList("One",

                      "Two",

                      "Three",

                      "Four",

                      "Five");

    // converting List<String> to String using toString() method

    String stringFromList = String.join("~", list);

    // priting the string

    System.out.println("String with tilde delimiter: "+stringFromList);

    // delimiting with pipe | symbol.

    String stringPipe = String.join("|", list);

    // printing

    System.out.println("String with pipe delimiter : "+stringPipe);

    }

}

Output:

String with tilde delimiter: One~Two~Three~Four~Five

String with pipe delimiter : One|Two|Three|Four|Five

4. List to String Using Java 8 Collectors.joining() Method

Collectors.join() method is from java 8 stream api. Collctors.joining() method takes delimiter, prefix and suffix as arguments. This method converts list to string with the given delimiter, prefix and suffix.

Look at the below examples on joining() method with different delimiters. But, String.join() method does not provide the prefix and suffix options.

If you need a custom delimiter, prefix and suffix then go with these. If you do not want the prefix and suffix then provide empty string to not to add any before and after the result string.

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

/**

 * Example to convert List to string using Collectors.joining() method.

 * 

 */

public class ListToStringUsingString_JoinExample {

    public static void main(String[] args) {

    // creating a list with strings.

    List<String> list = Arrays.asList("One",

                      "Two",

                      "Three",

                      "Four",

                      "Five");

    // using java 8 Collectors.joining with delimiter, prefix and suffix

    String joiningString = list.stream().collect(Collectors.joining("-", "{", "}"));

    // printing

    System.out.println("Collectors.joining string : "+joiningString);

    String joiningString3 = list.stream().collect(Collectors.joining("@", "", ""));

    // printing

    System.out.println("Collectors.joining string with @ separator : "+joiningString3);

    }

}

Output:

Collectors.joining string : {One-Two-Three-Four-Five}

Collectors.joining string with @ separator : One@Two@Three@Four@Five

5. List to String Using Apache Commons StringUtils.join() method

Finally way is using external library from apache commons package. This library has a method

StringUtils.join() which takes the list and delimiter similar to the String.join() method.

import org.apache.commons.lang3.StringUtils;

/**

 * Example to convert List to string using apache commons stringutils.join() method.

 * 

 */

public class ListToStringUsingStringUtils_JoinExample {

    public static void main(String[] args) {   

    // creating a list with strings.

    List<String> list = Arrays.asList("One",

                      "Two",

                      "Three",

                      "Four",

                      "Five");

    // using java 8 Collectors.joining with delimiter, prefix and suffix

    String joiningString = StringUtils.join(list, "^"); 

    // printing

    System.out.println("StringUtils.join string with ^ delimiter : "+joiningString);

    String joiningString3 = StringUtils.join(list, "$");

    // printing

    System.out.println("StringUtils.join string with @ separator : "+joiningString3);

    }

}

Output:

StringUtils.join string with ^ delimiter : One^Two^Three^Four^Five

StringUtils.join string with @ separator : One$Two$Three$Four$Five

Source: javacodegeeks.com    

Monday, July 5, 2021

Hibernate in Java- Overview

Hibernate in Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Career

Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.

Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from 95% of common data persistence related programming tasks.

Hibernate sits between traditional Java objects and database server to handle all the works in persisting those objects based on the appropriate O/R mechanisms and patterns.

Hibernate in Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Career

Hibernate Advantages


◉ Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code.

◉ Provides simple APIs for storing and retrieving Java objects directly to and from the database.

◉ If there is change in the database or in any table, then you need to change the XML file properties only.

◉ Abstracts away the unfamiliar SQL types and provides a way to work around familiar Java Objects.

◉ Hibernate does not require an application server to operate.

◉ Manipulates Complex associations of objects of your database.

◉ Minimizes database access with smart fetching strategies.

◉ Provides simple querying of data.

Supported Databases


Hibernate supports almost all the major RDBMS. Following is a list of few of the database engines supported by Hibernate −

◉ HSQL Database Engine

◉ DB2/NT

◉ MySQL

◉ PostgreSQL

◉ FrontBase

◉ Oracle

◉ Microsoft SQL Server Database

◉ Sybase SQL Server

◉ Informix Dynamic Server

Supported Technologies


Hibernate supports a variety of other technologies, including −

◉ XDoclet Spring

◉ J2EE

◉ Eclipse plug-ins

◉ Maven

Source: tutorialspoint.com

Friday, July 2, 2021

Java vs JavaScript

Java is an object-oriented, general purpose programming language (though it is not entirely object-oriented as it contains primitive types). Java codes are platform-independent, meaning java codes can run on any platform which is supporting Java. There is no need for re-compilation of code. Java has become one of the most used languages for client-server applications. Java code are converted to bytecode which runs on the Java Virtual Machine (JVM) irrespective of the computer architecture.

Read More: 1Z0-819: Oracle Java SE 11 Developer

Java was initially developed by James Gosling. He developed it at Sun Microsystems which got later acquired by Oracle. Java was first released in 1995. The latest versions in use are java 11 and Java 12.

Java vs JavaScript, Oracle Java, Oracle JavaScript, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Tutorial and Material

Features of Java


The main reason why Java came into existence was that the previously used C++ was a bit cumbersome and not very feasible for client-server applications.

Following are the features of Java:

◉ It is an object-oriented programming language which makes writing code easy.

◉ Memory allocation takes place at run-time that is why a java program can be compiled even without the main function.

◉ It is platform independent, which is one of the most significant features of Java. The Java codes are not compiled directly, they are first converted to a bytecode which can be run on any platform which has JVM.

◉ Java is an interpreted language which means that the Java code compiles and runs simultaneously.

◉ Java is widely distributed due to its platform independent nature.

What is JavaScript?


JavaScript is a scripting language. It is a high level object-oriented scripting language which is used to give instructions in run-time environment. It is interpreted language i.e. it is not compiled step by step rather than instructions are interpreted line by line. This makes JavaScript very dynamic. JavaScript is used in both client-side and server-side of web applications.

JavaScript along with the use of CSS and HTML makes websites responsive. JavaScript engines are embedded in many host services, including web servers and databases.

Java vs JavaScript, Oracle Java, Oracle JavaScript, Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Tutorial and Material

Features of JavaScript


◉ JavaScript is a versatile scripting language used in both server-side as well as client-side technologies.

◉ It forms basis to many web frameworks like Node.JS, Angular.JS, and React.JS etc.

◉ It is light-weighted as it can be embedded within HTML of website.

◉ It has event based approach to concurrency.

◉ JavaScript is a case-sensitive language that means, if it has two members with same name but different case, then they will be considered different and also there is a special schema for declaring variable names.

◉ It follows the object oriented paradigm.

Java vs. JavaScript


For a new programmer, both Java and JavaScript would probably look same but both of them are poles apart. Even though they share many common attributes like object-oriented paradigm, libraries and frameworks, still they are quite different when we talk in the context of their use cases.

Following are few differences between Java and JavaScript which would help you to draw a margin between the two:-

Java JavaScript 
Java is strongly typed and has strict rules. Also, the variable type has to be declared before initializing the variable.   JavaScript is weakly typed and does not have strict rules. There is no need to declare the type of variable during initialization.
Java is an object-oriented programming language.   JavaScript is an object-oriented scripting language.
Java programs are platform-independent. They can run on any device having Java Virtual Machine.   JavaScript code run only on web browsers as they were developed to run only on web browsers.
Java objects are class-based which means you have got to make a class in order to make a program.   JavaScript objects are prototype-based. 
Java files have a ".java" extension. These files are converted to bytecode which are executed by JVM.   JavaScript files have extension ".js". These are not compiled instead they are interpreted by the JavaScript interpreter which is present in every browser. 
Java is a standalone language which means it does not require any other thing to be embedded in.   JavaScript is contained in web pages and is embedded in HTML content. 
Java programs require a large amount of memory.   JavaScript is memory optimized and therefore is used in web pages. 
When facing concurrency, then Java uses a thread-based approach to solve it.   JavaScript uses an event-based approach to tackle concurrency. 
Java is vividly used for Android application development   JavaScript is vividly used for web development. 

Source: javatpoint.com