How to implement a Binary Search Algorithm in Java without recursion

<br>

An Iterative implementation of the popular binary search algorithm to find an element in a sorted array.


Hello everyone! I have published a lot of algorithms and data structure articles on my blog, but this one is the first one here. In this article, we’ll examine popular fundamental algorithms for interviews.

Yes, you guessed it right: you need to implement a binary search in Java, and you need to write both iterative and recursive binary search algorithms.

In computer science, a binary search, or half-interval search, is a divide and conquer algorithm that locates the position of an item in a sorted array. Binary searching works by comparing an input value to the middle element of the array.

The comparison determines whether the element equals the input, is less than the input, or is greater than the input.

When the element being compared equals the input, the search stops and typically returns the position of the element.

If the element is not equal to the input, then a comparison is made to determine whether the input is less than or greater than the element.

Depending on the result, the algorithm then starts over again, but only searching the top or a bottom subset of the array’s elements.

If the input is not located within the array, the algorithm will usually output a unique value indicating this like -1 or just throw a RuntimeException in Java like NoValueFoundException.

Binary search algorithms typically halve the number of items to check with each successive iteration, thus locating the given item (or determining its absence) in logarithmic time.

Btw, if you are not familiar with fundamental search and sort algorithms, then you can also join a course like Data Structures and Algorithms: Deep Dive Using Java to learn fundamental algorithms.

If Java is not your choice of language, you can find more recommendations for JavaScript and Python in this list of algorithms courses.

Btw, if you prefer books, I suggest you read a comprehensive algorithm book like Introduction to Algorithms by Thomas H. Cormen.

Here is some sample code which shows the logic of iterative binary search in Java:


Binary Search Implementation in Java

Here is a sample program to implement binary search in Java. The algorithm is implemented recursively. Also, an interesting fact to know about binary search implementation in Java is that Joshua Bloch, author of the famous Effective Java book, wrote the binary search in “java.util.Arrays”.


import java.util.Arrays;
import java.util.Scanner;
/**
 * Java program to implement Binary Search. We have implemented Iterative
* version of Binary Search Algorithm in Java
*
* @author Javin Paul
*/
public class IterativeBinarySearch {
  public static void main(String args[]) {
    int[] list = new int[]{23, 43, 31, 12};
    int number = 12;
    Arrays.sort(list);
    System.out.printf("Binary Search %d in integer array %s %n", number, Arrays.toString(list));
    binarySearch(list, 12);
    System.out.printf("Binary Search %d in integer array %s %n", 43, Arrays.toString(list));
    binarySearch(list, 43);
    list = new int[]{123, 243, 331, 1298};
    number = 331;
    Arrays.sort(list);
    System.out.printf("Binary Search %d in integer array %s %n", number,
    Arrays.toString(list));
    binarySearch(list, 331);
    System.out.printf("Binary Search %d in integer array %s %n",   331, Arrays.toString(list));
    binarySearch(list, 1333);
   // Using Core Java API and Collection framework
   // Precondition to the Arrays.binarySearch
   Arrays.sort(list);
   // Search an element
   int index = Arrays.binarySearch(list, 3);
}
/**
 * Perform a binary Search in Sorted Array in Java
 * @param input
 * @param number
 * @return location of element in array
 */
public static void binarySearch(int[] input, int number) {
int first = 0;
int last = input.length - 1;
int middle = (first + last) / 2;
while (first <= last) {
  if (input[middle] &lt; number) {
  first = middle + 1;
} else if (input[middle] == number) {
System.out.printf(number + " found at location %d %n", middle);
break;
} else {
  last = middle - 1;
}
middle = (first + last) / 2;
}
if (first > last) {
  System.out.println(number + " is not present in the list.\n");
}
}
}
Output
Binary Search 12 in integer array [12, 23, 31, 43]
12 found at location 0
Binary Search 43 in integer array [12, 23, 31, 43]
43 found at location 3
Binary Search 331 in integer array [123, 243, 331, 1298]
331 found at location 2
Binary Search 331 in integer array [123, 243, 331, 1298]
1333 is not present in the list.

That’s all about how to implement binary search using recursion in Java. Along with Linear search, these are two of the essential search algorithms you learn in your computer science class.

The binary search tree data structure takes advantage of this algorithm and arranges data in a hierarchical structure so that you can search any node in O(logN) time.

Though, you must remember that in order to use binary search, you need a sorted list or array, so you also need to consider the cost of sorting when you consider using binary search algorithm in the real world.

 

 Further Learning

 Data Structures and Algorithms: Deep Dive Using Java

 Algorithms and Data Structures — Part 1 and 2 

 Data Structures in Java 9 by Heinz Kabutz

10 Algorithms books for Interviews

10 Data Structure and Algorithm Courses for Interviews

5 Free Courses to Learn Data Structure and Algorithms

Other Data Structure and Algorithms tutorials you may like

  • How to implement Quicksort algorithm in place in Java? (tutorial)
  • How to implement Binary Search Tree in Java? (solution)
  • How to implement Quicksort algorithm without recursion? (tutorial)
  • How to implement Insertion sort algorithm in Java? (tutorial)
  • How to implement Bubble sort algorithm in Java? (tutorial)
  • What is the difference between Comparison and Non-Comparison based sorting algorithm? (answer)
  • How to implement Bucket Sort in Java? (tutorial)
  • How to implement a Binary Search Algorithm without recursion in Java? (tutorial)
  • 50+ Data Structure and Algorithms Courses for Programmers (questions)

Thanks for reading this article. If you like this article then please share with your friends and colleagues. If you have any suggestion or feedback then please drop a comment.

P.S. — If you are serious about improving your Algorithms skills, I think the Data Structures and Algorithms: Deep Dive Using Java is the best one to start with.


By :javinpaul


Bucket Sort in Java with Example - How Algorithm Works

Bucket Sort in Java with Example - How Algorithm Works

Bucket sort works by assigning the input elements to different buckets ... Bucket sort is one of the O(N) sorting algorithm like Radix sort and Counting sort. ...

In recent years, one of the questions I have increasingly seen in programming job interviews is about constant time sorting algorithms like do* you know any O(n) sorting algorithm?* how do they work? When I first encountered this question, I had no idea whether we can sort in constant time because even some of the fastest sorting algorithms like QuickSort or MergeSort takes O(N log N) time for sorting on their average case. After some research, mainly by going through the classic CLRS book and this DS and Algorithms course by Tim Buchalka and Goran Lochert on Udemy, I come to know that there indeed are some constant time or linear time sorting algorithms like bucket sort, counting sort, and radix sort, which can sort an array inO(n) time but they work with only a special set of input.

The idea of bucket sort is quite simple, you distribute the elements of an array into a number of buckets and then sort those individual buckets by a different sorting algorithm or by recursively applying the bucket sorting algorithm.

You might have remembered, how shopkeepers or bank cashiers used to prepare/sort bundles of notes. They usually have a bucket load of cash with different denominations like 5, 10, 20, 50, or 100. They just put all 5 Rs notes into one place, all Rs 10 notes into another place and so on.

This way all notes are sorted in O(n) time because you don't need to sort individual buckets, they are all same notes there.

Anyway, for bucket sort to work at its super fast speed, there are multiple prerequisites. First, the hash function that is used to partition the elements must be very good and must produce ordered hash: if the i < j then hash(i) < hash(j).

If this is not the case then you cannot concatenate individual buckets in O(n) time. Second, the elements to be sorted must be **uniformly distributed. If you still have trouble understanding Bucket sort or want to explore other linear time sorting algorithms, I also suggest you go through the Data Structures and Algorithms: Deep Dive Using Java **course on Udemy. It's fantastic and I suggest every Java programmer go through this to improve their data structure and Algorithmic skills.

Bucket Sort vs Counting Sort

If you keep these prerequisites aside, bucket sort is actually very good considering that counting sort is reasonably equal to its upper bound and counting sort is also super fast.

The particular distinction for bucket sort is that it uses a hash function to partition the keys of the input array, so that multiple keys may hash to the same bucket. Hence each bucket must effectively be a growable list; similar to Radix sort, another O(n) sorting algorithms.

Many programmers get confused between Counting Sort and Bucket sort as they work quite similar, but the most important difference between them is that Bucket sort uses a hash function to distribute keys while Counting sort creates a bucket for each key.

In our example, I have used JDK's Collections.sort() method to sort each bucket. This is to indicate that the bucket sort algorithm does not specify which sorting algorithm should be used to sort individual buckets.

A programmer may choose to recursively use bucket sort on each bucket until the input array is sorted, similar to radix sort. Anyway, whichever sorting method you use to sort individual buckets, the time complexity of bucket sort will still tend towards O(n).

I think there are perhaps greater similarities between radix sort and bucket sort than there are between counting sort and bucket sort. You can also read Introduction to Algorithm by Thomas H. Cormen to learn more about the difference between these two constant time sorting algorithms.

Bucket Sort - FAQ

Now, let's see some of the frequently asked questions about Bucket sort in programming job interviews.

1. Is the bucket sort, a stable algorithm?

Bucket sort is not a stable sorting algorithm. If you remember, A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input array to be sorted. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, or Bubble Sort, etc. In the case of Bucket sort, input sorts themselves by moving into a bucket and their order are not guaranteed to be retained.

2. Is the bucket sort in-place algorithm?

Bucket sort is also not an in-place sorting algorithm because you create buckets which can be array, linked list, or hashtable and they take additional spaces. In the worst of the good cases (sequential values, but no repetition) the additional space needed is as big as the original array.

3. What is the time complexity of Bucket sort?

The time complexity of bucket sort in the O(n) in the best and average case and O(n^2) in the worst case. The creation of bucket will take O(1) time and assume moving elements into bucket will take O(1) time e.g. in the case of hashtable and linked list.

The main step is to sort elements on individual elements. This step also takes O(n) time on average if all numbers are uniformly distributed (please refer CLRS book for more details). The last step to concatenate all bucket will also take O(n) time as there will be n items in all buckets

4. What is the time complexity of Bucket sort in the worst case?

The time complexity of bucket sort is O(n^2) in the worst case i.e. when all elements at allocated to the same bucket. Since individual buckets are sorted using another algorithm, if only a single bucket needs to be sorted, bucket sort will take on the complexity of the inner sorting algorithm. This is why bucket sort is only useful when the input is uniformly distributed in a range. This way they will not end up in the same bucket.

5. What is the space complexity of Bucket sort?

The space complexity of the bucket sort algorithm is O(n) because even in the worst of the good cases (sequential values, but no repetition) the additional space needed is as big as the original array. Please go through Algorithms and Data Structures** ** courses on Pluralsight for more details on complexity analysis of various sorting algorithms in best, average, and worst case.

It's an excellent course but you would need a Plurlasight membership to access this course, which cost around $29 per month or $299 per year. This may seem a bit expensive at first but its well worth because it provides access to more than 5000 online courses on Pluralsight which you can use to learn any latest technology.

I am a Pluralsight member and I also suggest you join it if you can invest that much money in a year for your learning. Anyway, even if you don't have Plurlasight membership, you can still access this course for free by signing up for the 10-day free trial which provides 200 minutes of access to all of their courses.

Java Program to implement Bucket Sort in Java

Problem Statement:

Given an unordered list of integers, rearrange them in the natural order.

Sample Input: {8,5,3,1,9,6,0,7,4,2,5}
Sample Output: {0,1,2,3,4,5,6,7,8,9,5}

Here is our complete Java program to implement bucket sort in Java. This program sorts an integer array using bucket sort algorithm.

Program to implement Bucket sort in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/*
 * Java Program sort an integer array using radix sort algorithm.
 * input: [80, 50, 30, 10, 90, 60, 0, 70, 40, 20, 50]
 * output: [0, 10, 20, 30, 40, 50, 50, 60, 70, 80, 90]
 * 
 * Time Complexity of Solution:
 *     Best Case O(n); Average Case O(n); Worst Case O(n^2).
 * 
 */

public class BuckeSort {

  public static void main(String[] args) {

    System.out.println("Bucket sort in Java");
    int[] input = { 80, 50, 30, 10, 90, 60, 0, 70, 40, 20, 50 };

    System.out.println("integer array before sorting");
    System.out.println(Arrays.toString(input));

    // sorting array using radix Sort Algorithm
    bucketSort(input);

    System.out.println("integer array after sorting using bucket sort algorithm");
    System.out.println(Arrays.toString(input));

  }

  /**
   * 
   * @param input
   */
  public static void bucketSort(int[] input) {
    // get hash codes
    final int[] code = hash(input);
    
    // create and initialize buckets to ArrayList: O(n)
    List[] buckets = new List[code[1]];
    for (int i = 0; i < code[1]; i++) {
      buckets[i] = new ArrayList();
    }
    
    // distribute data into buckets: O(n)
    for (int i : input) {
      buckets[hash(i, code)].add(i);
    }
    
    // sort each bucket O(n)
    for (List bucket : buckets) {
      Collections.sort(bucket);
    }
    
    int ndx = 0;
    // merge the buckets: O(n)
    for (int b = 0; b < buckets.length; b++) {
      for (int v : buckets[b]) {
        input[ndx++] = v;
      }
    }
  }

  /**
   * 
   * @param input
   * @return an array containing hash of input
   */
  private static int[] hash(int[] input) {
    int m = input[0];
    for (int i = 1; i < input.length; i++) {
      if (m < input[i]) {
        m = input[i];
      }
    }
    return new int[] { m, (int) Math.sqrt(input.length) };
  }

  /**
   * 
   * @param i
   * @param code
   * @return
   */
  private static int hash(int i, int[] code) {
    return (int) ((double) i / code[0] * (code[1] - 1));
  }

}


Output
Bucket sort in Java
integer array before sorting
[80, 50, 30, 10, 90, 60, 0, 70, 40, 20, 50]
integer array after sorting using bucket sort algorithm
[0, 10, 20, 30, 40, 50, 50, 60, 70, 80, 90]

Bucket Sort - Important points to remember

Here are some important points about bucket sort you should remember, this is useful from both interview and understanding point of view and Interviewer expects that you know about them when you say that you know bucket sort.

  1. Bucket Sort is also known as bin sort because you create bins or buckets to sort inputs.

  2. Bucket sort is only useful when the input is uniformly distributed over a range like coins, numbers 1 to 100 etc.

  3. You can use a linked list or array as a bucket. The choice of data structure will affect the insertion time e.g. if you use linked list then adding on the head could take O(1) time. You can also use hash tables as buckets.

  4. The bucket sort is one of the rare O(n) sorting algorithm i.e. time complexity of Bucket sort is the liner in best and average case and not NLogN like Quicksort or Mergesort.

  5. Bucket sort is not a stable sorting algorithm because in a stable algorithm if two input is same they retain their place in sorted order and in the bucket it depends upon how you sort the individual bucket. Though, bucket sort can be made stable, known as radix sort, which we'll see in future articles.

  6. You can sort the elements inside individual buckets either by recursively calling the bucket sort or using a separate sorting algorithm like insertion sort, bubble sort, or quicksort.

  7. Is bucket sort an in-place sorting algorithm? No, it's not an in-place sorting algorithm. The whole idea is that input sorts themselves as they are moved to the buckets. In the worst of the good cases (sequential values, but no repetition) the additional space needed is as big as the original array.

  8. The worst case complexity of bucket sort, when all elements will end up in the same bucket is O(n^2) because then it has to be sorted by a different sorting algorithm.

  9. The space complexity of bucket sort is O(n) because even to sort sequential values, without repetition, you need an array as big as the original array.

That's all about bucket sort in Java. It's one of the interesting sorting algorithms which gives you O(n) performance in the best and average case. Bucket sort should only be used when the input is uniformly distributed over a range e.g. numbers up to 1 to 1000.

You should also remember that Bucket sort is not a stable algorithm hence it's not guaranteed that equal keys on input array will retain their places.

It is also not an in-place algorithm, as it will require additional space as big as the original array in the worst case. You can also refer following resources for more details on bucket sort and other O(n) sorting algorithms like Counting sort, Radix sort etc.

Further Learning

Data Structures and Algorithms: Deep Dive Using Java

Algorithms and Data Structures

Practical Data Structures & Algorithms in Java + HW

Introduction to Data Structures & Algorithms in Java

Selenium WebDriver with Java -Basics to Advanced+Frameworks

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or doubt then please let us know and I'll try to find an answer for you.

Efficient one algorithm of these two algorithms

Both of these algorithms are giving same output but the first one takes nearly double time (&gt;.67) compared to second one (.36). How is this possible? Can you tell me the time complexity of both algorithms? If they're the same, why is the time different?

Both of these algorithms are giving same output but the first one takes nearly double time (>.67) compared to second one (.36). How is this possible? Can you tell me the time complexity of both algorithms? If they're the same, why is the time different?

1st algorithm:

 for (int i =0 ;i<n;i++){
        cin>>p[i];
        if(i>0){
            if(p[i-1]>p[i]){
                cout<<p[i]<<" ";
            }
            else{
                cout<<"-1"<<" ";
            }
        }
    }

2nd algorithm:

for (int i =0 ;i<n;i++){
        cin>>p[i];
}
for (int i =0 ; i&lt;n-1;i++){
   if(p[i]&gt;p[i+1]){
            cout&lt;&lt;p[i]&lt;&lt;" ";
        }
        else{
            cout&lt;&lt;"-1"&lt;&lt;" ";
        } 
}


Java to C# – C# to Java

Java to C# – C# to Java

In this post, we bring you a much needed Rosetta Stone — an explanatory bridge between these two technologies

Originally published by Andy Macdonald at https://medium.com
Java and C# are incredibly similar. Both languages are somewhat derived from C++ and from similar first principles.

Java was developed in 1995 to create a language with a simpler programming model than C++ while still preserving some of the same syntax of the language to facilitate developers transitioning to it.

C# was developed in 2000 by Microsoft as part of its .NET drive in order to develop a language and set of technologies that could address some of the perceived weaknesses of the C++ language. It was also developed with quite heavy “inspiration” from the Java language.

Despite the similarities between the languages and sharing some common ground, transitioning from one technology to the other for a developer well-practised in one technology can be quite tricky.

Innovation happens best when there is collaboration between people of different mindsets — yet users of C# and Java can be somewhat tribalistic.

To that end, I thought it would be useful to put together a sort of guide to help people thinking about or starting to transition between these two technologies. It would also be nice in some way to facilitate a bit more collaboration between these two worlds — hopefully to do my bit to reduce the needless gulf that exists between them.

Some of the similarities right off the bat:

Java is a language that runs in a virtual machine environment (JVM) and runs bytecode that the Java compiler generates.

For C#, the situation is similar. It is a language that runs on the .NET framework and the CLR runtime. It uses a similar intermediary language to Java bytecode called MSIL which gets run via CLR.

Naming and Conventions

Some of the key and most immediately obvious differences in nomenclature, syntax, and conventions are:

  • “Projects” (Java) — “Solutions” (C#)
  • In Java, methods use lowerCamelCase (bar.doAThing()), whilst in C# public methods use PascalCase (bar.DoAThing())
  • In C#, interfaces are always prefixed with an I, as in IUserService<T>, instead of UserService<T>** **in Java
  • In Java, a string is a String** **— in C# a string is a string
  • “POJO” (Java) — “POCO” (C#)
  • Packages (Java) — Namespaces (C#)

Package (Java)

package dev.andymacdonald;

// Code goes here

Namespace (C#)

namespace Dev.AndyMacdonald 
{
  // Code goes here
}

Syntax

**Java has <strong>final</strong> variables — C# has **<strong>readonly</strong>

A key difference here is that Java final variables can be assigned once anywhere in the class, whereas C#’s readonly variables can only be assigned in the constructor.

C# has <strong>out</strong> and <strong>ref</strong> parameters to allow passing arguments by reference — Java doesn’t

It can manipulate objects and variables by reference, but in a method, these arguments are passed by a value. With C#, we can override this behaviour with the out and ref keywords.

Annotations (Java) — attributes (C#)

These are basically equivalent concepts and just differ in actual syntax. Both annotations and attributes can be accessed via each language’s respective Reflection API implementation.

Java annotation:

@PersonallyIdentifiable
private String fullName;

C# attribute:

[PersonallyIdentifiable]
private string fullName;

Getters and setters or Project Lombok (Java) — C# properties

C# really overtakes Java here with its built-in properties* *feature. In the standard JDK, there isn’t an equivalent to this, and instead, in Java, getters and setters must be written for each field requiring an accessor.

These are often just generated by the developer with their IDE as a cheat … still a bit tedious, though.

Java getters and setters:


public class Element 
{
   
  private String symbol;   
  private String name;   
  private int atomicNumber;
  public int getAtomicNumber() 
  {
    return this.atomicNumber;
  }
  public String getSymbol() 
  {
    return this.symbol;
  }
  public String getName() 
  {
    return this.name; 
  }
  public void setAtomicNumber(int atomicNumber) 
  {
    this.atomicNumber = atomicNumber;
  }
  public void setName(String name) 
  {
    this.name = name;
  }
  public void setSymbol(String symbol) 
  {
    this.symbol = symbol;
  }
}

Many Java projects incorporate Project Lombok, which adds getters, setters, equals, and hash code (plus other useful boilerplates) at compile time.

Project Lombok — not part of the standard library:

@Getter @Setter
public class Element 
{
   
  private String symbol;   
  private String name;   
  private int atomicNumber;
}

C# built-in properties feature:

public class Element 
{

  public string Symbol { get; set; }     
  public string Name { get; set; }     
  public int AtomicNumber { get; set; }
}

Loops

Java for each loop:

List<Integer> fibNumbers = Arrays.asList(0, 1, 1, 2, 3, 5, 8, 13);
int count = 0;
for (int element: fibNumbers)
{
    count++;
    System.out.println(String.format("Element #%s: %s", count, element));
}
System.out.println(String.format("Number of elements: %s", count));

C# for each loop:

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

Implementing interfaces/inheritance

Inheritance and implementing interfaces isn’t drastically different between the two languages. Java uses the extends or implements keywords; C# uses C++ syntax (derivation declaration) B : A for defining inheritance.

Defining and implementing an interface with methods in Java:

package dev.andymacdonald;


import java.util.ArrayList;
import java.util.List;

interface Fish
{
   void swim();
}

class Salmon implements Fish
{

   public void swim()
   {
      System.out.println("Salmon.Fish");
   }
}

class Cod implements Fish
{
   public void swim()
   {
      System.out.println("Cod.Swim");
   }
}

public class Program
{
   public static void main()
   {
      List<Fish> fishes = new ArrayList<>();
      fishes.add(new Salmon());
      fishes.add(new Cod());

      for (Fish fish : fishes)
      {
         fish.swim();
      }
   }
}

Defining and implementing an interface with methods in C#:

using System;
using System.Collections.Generic;

namespace Dev.AndyMacdonald 
{
    interface Fish
    {
        void Swim();
    }
    class Salmon : Fish
    {
        public void Swim()
        {
            Console.WriteLine("Salmon.Fish");
        }
    }
    class Cod : Fish
    {
        public void Swim()
        {
            Console.WriteLine("Cod.Swim");
        }
    }
    class Program
    {
        static void Main()
        {
            List<Fish> fishes = new List<Fish>();
            fishes.Add(new Salmon());
            fishes.Add(new Cod());
            foreach (Fish fish in fishes)
            {
                fish.Swim();
            }
        }
    }
}

Pointers

Quite simply, Java just doesn’t do pointers, whereas in C# it is possible to do pointer arithmetic and manipulation.

 unsafe {
  int a = 25;
  int * ptr = &a;
  Console.WriteLine($"Value of pointer is {*ptr}");
}

IDE

Visual Studio

C# developers traditionally and typically use the Visual Studio IDE. This is a situation borne out of the origins of .NET being a closed-source technology. Microsoft developed Visual Studio** **to be a one-stop shop for all things .NET.

Java went down a different route, offering much more developer choice in tooling from the outset. That’s why there’s a much greater range of IDEs for Java development (e.g., IntelliJ, Eclipse, NetBeans). Gradually the landscape for .NET developers has shifted, and more IDEs and developer choice has been offered over the years.

IntelliJ (Java) — Rider (C#)

Users of JetBrains IDEs will find the transition from one IDE to another very smooth if they choose to make a switch to the respective JetBrains IDE in the technology they are targeting. Keyboard shortcuts, IDE layout, and even some plugins are equivalent or comparable — virtually the same IDE.

Dependency Management

Maven (Java) — NuGet and dotnet CLI (C#)

Maven is a tool responsible for dependency management and the life cycle of the building of typically Java and JVM applications. That said, it is pretty flexible, has 1000s of plugins, and can be used to build applications of other languages, such as PHP and JavaScript.

The configurable unit of maven is a pom.xml file that every maven project has. For a project’s submodules, it is possible to have a pom file per submodule which inherits from a parent. Maven uses a remote server or repository of some kind to host and retrieve packages.

Maven pom.xml file (Java):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>dev.andymacdonald</groupId>
    <artifactId>fish-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

At the simplest level, you can test and build a Maven project with the following command:

mvn clean install

And create a package with this:

mvn clean package

And finally, deploy a package like this:

mvn clean deploy

NuGet fulfills a similar, though not identical role in .NET to Maven. NuGet can use a few different configuration files but commonly uses .csproj*. *As with Maven, NuGet uses a server/repository that can host packages.

NuGet .csproj file:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <AssemblyName>MSBuildSample</AssemblyName>
    <OutputPath>Bin\</OutputPath>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="helloworld.cs" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="MyDependency" version="1.0.0" />
  </ItemGroup>  
  <Target Name="Build">
    <MakeDir Directories="$(OutputPath)" Condition="!Exists('$(OutputPath)')" />
    <Csc Sources="@(Compile)" OutputAssembly="$(OutputPath)$(AssemblyName).exe" />
  </Target>
</Project>

NuGet’s primary role is package management, construction, and deployment. Java developers will notice that it doesn’t really have the same concept of build phases as Maven does. Additionally, .NET developers don’t tend to edit their build files manually as Java developers do with pom.xml files, preferring to manipulate them in their IDE instead.

Packages can be built, packaged, and deployed to NuGet with the following nuget commands:

nuget spec
nuget pack {nuspec file}
nuget push {package file} {apikey} -Source {host url}

If you want to run the tests for your .NET application, you can run the following dotnet CLI command:

dotnet test

The dotnet CLI can also be used as a wrapper around nuget commands.

Application Servers

Apache Tomcat (Java) — IIS (ASP.NET)

Tomcat is an open-source web server and servlet container from the Apache Foundation. Though there are many other application servers used widely in Java, it is a pretty common choice for most enterprise-software companies. It works across pretty much every operating system (e.g., Windows, Unix, Linux, and Mac OS).

.NET projects are typically deployed on IIS, a web server that only runs on Windows. While its portability is limited, it’s a pretty popular choice for Windows developers because of its ease of use and simplicity while still offering some advanced configuration options.

… But Wait!

For .NET Core web applications, you can package them to run as standalone web applications — allowing you to run them like this:

dotnet <app_assembly>.dll

In the same way you can run a Java Spring Boot web*** ***application (which has a self-contained Tomcat server):

java -jar <my-application>.jar

And visit your shiny new web app like this:

http://<serveraddress>:<port>

Libraries and Frameworks

Spring Framework (Java) — ASP.NET (C#)

The Spring Framework is a framework and IoC container for Java. In short, the Spring framework is responsible for instantiating objects (beans) and managing the life cycle of these beans in memory.

Create an ApplicationContext* *(similar to the concept of a Startup in ASP.NET). This example uses Spring Boot:

@SpringBootApplication
public class HumanApplication
{
   public static void main(String[] args) 
   {
      SpringApplication.run(HumanApplication.class, args);
   }
}

Create an interface:

public interface Organ<T>
{  
   void function();
}

Implement the Organ<T> interface:

@Component
public class Heart implements Organ<Heart>
{
    public Heart() {}
    public void function() 
    {
        System.out.println("Buh-dump");
    }
}

Constructor injection of Organ dependencies list into a Human service:

@Service
public class Human 
{
    private static final int MAX_SECONDS_OF_LIFE = 3000;
    private List<Organ> organs;
    public Human(List<Organ> organs) 
    {
        this.organs = organs;
    }
    @PostConstruct
    public void live() 
    {
        for (int i = 0; i < MAX_SECONDS_OF_LIFE; i++) 
        {
            organs.forEach(organ -> organ.function());
        }
    }
}

Run the application …

It’s aliiiiiiive:

Buh-dump
Buh-dump
Buh-dump
Buh-dump
...

Spring also ships with a handy suite of modules and packages.

In the core Spring packages, and in the convention-over-configuration extension to the framework, Spring Boot, useful combinations of existing and bespoke technologies are provided for developers wanting access to common libraries to kickstart a project with all that they may need, rather than having to write or track down these utilities themselves:

  • RestTemplate (spring-web — for constructing REST and HTTP requests)
  • JdbcTemplate (spring-data — for constructing JDBC queries and statements)
  • Spring Security (for creating and managing application security models)
  • ObjectMapper (spring-core — useful utility for mapping POJOs from Jackson)
  • etc.

ASP.NET fulfills a similar role in the world of C#, providing IoC functionality, commonly used technologies, and utilities in a single framework. However, ASP.NET generally only provides IoC functionality for web applications, whereas the Spring Framework provides this for any application type.

In terms of dependency inversion, it is possible to do very similar things in ASP.NET as in Spring.

As before, define the needed interface and concrete implementation:

public interface Organ<T>
{  
   void Function();
}
public class Heart : Organ<Heart>
{
    public Heart() {}
    public void Function() 
    {
        Console.WriteLine("Buh-dump");
    }
}

Invoke functions of injected dependencies:

public class Human
{

   private List<IOrgan> _organs;
 
   public Human(List<IOrgan> organs)
   {
      _organs = organs;
      this.Live();
   }
   public void Live()
   {
      organs.ForEach(organ =>
      {
         organ.Function();
      });
   }
}

Define a Startup and register services:

public class Startup  
{    
  public void ConfigureServices(IServiceCollection services)
  {    
    services.AddTransient<IList<IOrgan>>(p => p.GetServices<IOrgan>().ToList());
  }
}

ASP.NET also fulfills the role of providing many useful libraries and utilities to accelerate development of your project.

Streams (Java) — LINQ (C#)

Both Java and C# have mechanisms to simplify the reduction of data sets — Streams and LINQ.

There are some differences and gaps between the two technologies but if you have familiarity with one, you’ll be able to get up and running fairly quickly with the other.

Java Streams:

List<Student> studentList = Arrays.asList( 
    new Student(1, "John", 18, 1),
    new Student(2, "Steve", 21, 1),
);
List<String> studentNames = studentList.stream()
    .filter(s -> s.getAge() > 18)
    .filter(s -> s.getStandardID() > 0)
    .map(s -> s.getName()).collect(Collectors.toList());
studentNames.forEach(name -> System.out.println(name));

LINQ Query (C#):

IList<Student> studentList = new List<Student>() { 
    new Student() { StudentID = 1, StudentName = "John", Age = 18, StandardID = 1 } ,
    new Student() { StudentID = 2, StudentName = "Steve",  Age = 21, StandardID = 1 }
};
var studentNames = studentList.Where(s => s.Age > 18)
                        .Where(st => st.StandardID > 0)
                        .Select(s => s.StudentName);
foreach(var name in studentNames) {   
    Console.WriteLine(name);
}

Apache Commons (Java) — CommonLibrary.NET (C#)

Apache Commons*** ***provides Java developers with a collection of several independently released, useful components and utilities for the purposes of accelerating development.

If you’re in need of a utility to work with ZIP files or a set of utilities for working with mathematical expressions and formulae, then Apache Commons has you covered.

In a similar way, CommonLibrary.NET covers these bases too — there are some key differences in naming of some components and modules, but for the most part, they are pretty much equivalent in their purpose.

That said, unlike Apache Commons, CommonLibrary.NET is quite old and isn’t very commonly used in projects anymore. If you’re after a continuously updated, curated list of libraries for each respective technology, I highly recommend these two lists:

akullpp/awesome-java

quozd/awesome-dotnet

Testing Libraries

JUnit (Java) — NUnit (C#)

Java’s ever-dependable JUnit library has a direct equivalent in C#.

NUnit has almost equivalent functionality to JUnit and is a popular choice for C# developers.

JUnit:

@Test
public void complexNumberTest()
{
    ComplexNumber result = someCalculation();
    Assert.assertEquals("Real", 5.2, result.getRealPart());
    Assert.assertEquals("Imaginary" 3.9, result.getImaginaryPart());
}

NUnit:

[Test]
public void ComplexNumberTest()
{
    ComplexNumber result = SomeCalculation();
    Assert.Multiple(() =>
    {
        Assert.AreEqual(5.2, result.RealPart, "Real");
        Assert.AreEqual(3.9, result.ImaginaryPart, "Imaginary");
    });
}

(Rumour has it NUnit started life as the JUnit source code modified to run in C#.)

Mockito (Java) — Moq (C#)

As with JUnit and NUnit, comparable functionality exists between Java’s Mockito and C#’s Moq library.

Mockito:

Foo mockFoo = mock(Foo.class);
when(mockFoo.doSomething("ping")).thenReturn(true);

Moq:

var mock = new Mock<IFoo>();
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);

That’s It

Thanks for Reading!

I obviously couldn’t fit every difference, similarity, and detail in this article —* *it’s already far too long.

I hope at least I’ve covered enough ground to make you feel confident to make a switch and see how the other half lives.

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Java Tutorial for Absolute Beginners

100+ Java Interview Questions and Answers In 2019

Python vs Java: Understand Object Oriented Programming

Angular 7 + Spring Boot CRUD Example

Build a Simple CRUD App with Spring Boot and Vue.js