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