الثلاثاء، 26 نوفمبر 2019

Java program to generate random number using Random.nextInt(), Math.random() and ThreadLocalRandom

1. Overview


In this tutorial, You'll learn how to generate a random number in java. To generate or produce a random number in a specific range, java API has provided several set of classes for this purpose.
We'll be mostly focusing on the following classes and its methods.

.
A) Class Random and method nextInt()
B) Class Math and emthod random()
C) Class ThreadLocalRandom and method nextInt()
.
Java program to generate random number using Random.nextInt(), Math.random() and ThreadLocalRandom



In many scenarios, you might have seen using Math.random() or Random.nextInt() method. The last one is introduced in JDK 1.7 which is for thread-based applications.

الأحد، 24 نوفمبر 2019

Java Program To Find Sum of N Natural Numbers (for Loop, while Loop and Using Arthimetic Formulae)

1. Introduction


In this programming tutorial, You'll learn to a java program to find the sum of n first natural numbers. The positive integers 1, 2, 3, 4, etc. are known as natural numbers and these series must start with digit 1. Here we will show you 4 programs.

.
A) Java program to Sum of first 100 natural numbers using for loop
B) Java program to Sum of first 100 natural numbers using while loop
C) Java program to calculate the sum of n natural numbers which input taken from the user
D) Simple Java program to calculate som of natural numbers using arithmetic formula.
.

Java Program To Find Sum of N Natural Numbers (for Loop, while Loop and Using Arthimetic Formulae)


we have already published in-depth articles on for loop and while loop. Please go through the below articles before seeing the program now.

For Loop in Java
While Loop in Java


السبت، 23 نوفمبر 2019

Java Program to Multiply Two Numbers (Integer, Floating and Double numbers)

1. Overview


In this article, You'll learn to a java program to multiply two numbers. This is a very easy and basic program for freshers and who just started learning java programming language. This program must be part of your assessment in your training. We will show you the two programs first is how to multiply and calculate two integer numbers and in second, will be showing multiplying two floating or double numbers. In both cases, numbers are entered by the user using Scanner.

The formula is using asterisk symbol '*' first_number * second_number.




الجمعة، 22 نوفمبر 2019

Python - TypeError: Object of type 'int64' is not JSON serializable (Works for all data types - Integer, Float, Array, etc)

1. Overview


In this tutorial, You will be learning how to solve the problem in python "TypeError: Object of type 'int64' is not JSON serializable" and "TypeError: (Integer) is not JSON serializable". These two errors come into existence when we working with JSON Serialization. Solutions shown in this article will work for apart from the int or int64 type such as float, array and etc.

Below is the scenario where my friend faced the problem.

Python TypeError Object of type  int64 is not JSON serializable

الثلاثاء، 19 نوفمبر 2019

Java Program To Add All Individual Numbers In A String

1. Overview


In this tutorial, You will learn how to calculate the sum of all numbers present in a string. In most of the interviews or programming HackerRank tests these types of questions will be asked to write a java program to add all numbers in a string.

String may have characters + numbers. But we need to sum only numbers if any numbers are present. If it does not have numbers then print '0'.

java-program-string-add-digits


Examples:

Example 1:

Input: java2program
Output: 2

Example 2:

Input: java234programs56
Output: 20

2 + 3 + 4 + 5 + 6

Example 3:

Input: hello!!world
Output: 0

السبت، 16 نوفمبر 2019

Java Program To Find Unmatched values From Two Lists

1. Overview:

In this tutorial, We'll be learning about a java program how to compare two lists and find out the unmatched contents from those two lists. We will demonstrate the example programs in Java and Python languages.

1.1 Example


Input:

List 1: ["File Name 1", "File Name 2", "File Name 3", "File Name 4", "File Name 5", "File Name 6", "File Name 7", "File Name 8"]
List 2: ["File Name 2", "File Name 4", "File Name 6", "File Name 8"]

Output:

Unmatched values: ["File Name 1", "File Name 3", "File Name 5", "File Name 7]

Find Unmatched values From Two Lists


This example is for Strings. If the list is having custom objects such as objects of Student, Trade or CashFlow. But in our tutorial, We will discuss for Employee objects in the list.

We can use any List implementation classes such as ArrayList, LinkedList, Stack, and Vector. For now, all programs in this post are using ArrayList implementation.

2. Java

We'll write a program to remove the duplicates values from list1 based on list2 and operation seems to be more complex but if we use the java collection API methods then our life will become easy because these methods are being tested by many developers every day.

See in our case need to find the unmatched content against list2 from list1.

2.1 String values


List interface has a method named "removeAll" which takes any collection implementation class (in our example it an ArrayList).

removeAll() method removes from the current list all of its elements that are contained in the specified collection that passed to this method as an argument.

Syntax: See the method signature below.

boolean removeAll(Collection c)

Creating two lists which are having files names in it.

// List 1 contains file names from 1 to 8.
List list1 = new ArrayList<>();
list1.add("File Name 1");
list1.add("File Name 2");
list1.add("File Name 3");
list1.add("File Name 4");
list1.add("File Name 5");
list1.add("File Name 6");
list1.add("File Name 7");
list1.add("File Name 8");

//List 2 contains only even number file names.
List list2 = new ArrayList<>();
list2.add("File Name 2");
list2.add("File Name 4");
list2.add("File Name 6");
list2.add("File Name 8");

Now we are going to delete the file names that are already present in list 2 from list 1.

list1.removeAll(list2);

All the elements that are present in list2 are deleted from list1 which means all even number file names are deleted from list1.

Let us take a look at the contents in list1.

[File Name 1, File Name 3, File Name 5, File Name 7]

Note: If list2 is null then will through NullPointerException.

2.2 Custom Objects

What happens if these two lists are having objects instead of String literals? Custom objects such as Employee, Student, Trade or User objects.

We will demonstrate an example with Employee object for now. The same is applicable for any type of object in the list.

Creating an Employee class with id and name.

public class Employee {

 private int id;
 private String name;

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 // setter and getter methods.
 
 // Overrding toString method.
 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }
}

Creating list1 and list2 with employee objects.

List list1 = new ArrayList<>();
list1.add(new Employee(100, "Jhon"));
list1.add(new Employee(200, "Cena"));
list1.add(new Employee(300, "Rock"));
list1.add(new Employee(400, "Undertaker"));

List list2 = new ArrayList<>();
list2.add(new Employee(100, "Jhon"));
list2.add(new Employee(300, "Rock"));

list1 and list2 have common employee objects for id 100 and 200 with the same name. Now we have to remove these two objects from list1. We know that removeAll method removes objects from list1 comparing with list2 objects. We'll call removeAll method.

list1.removeAll(list2);

Now see the objects in list1 after calling removeAll method.

[Employee [id=100, name=Jhon], Employee [id=200, name=Cena], Employee [id=300, name=Rock], Employee [id=400, name=Undertaker]]


Observe that removeAll method is not removed duplicate objects from list1.
To make this code work, we need to override equals() method in Employee class as below.


@Override
public boolean equals(Object obj) {
 Employee other = (Employee) obj;
 if (id != other.id)
  return false;
 if (name == null) {
  if (other.name != null)
   return false;
 } else if (!name.equals(other.name))
  return false;
 return true;
}


Why we need to override equals method is because removeAll method internally compares the contents invoking equals() method on each object. Here the object is an employee so it calls equals method on employee object.

Take a look at the output of list1 now.

[File Name 1, File Name 3, File Name 5, File Name 7]

We have to notice one point here that the same code had worked in the case of String objects because String class already overridden equals method as below.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String aString = (String)anObject;
        if (coder() == aString.coder()) {
            return isLatin1() ? StringLatin1.equals(value, aString.value)
                              : StringUTF16.equals(value, aString.value);
        }
    }
    return false;
}

All codes are shown are compiled and run successfully in java 12.

3. Python


In Python, finding out the unmatched contents from two lists is very simple in writing a program.

Let us have a look at the following code.

def finder(arr1,arr2):
    eliminated = []

    for x in arr1:
        if x not in arr2:
            eliminated.append(x)
        else:
            pass
    return eliminated

We can sort two lists before for loop as below. I have seen many developers do sorting before comparing the contents. But, actually sorting is not necessary to do.

arr1 = sorted(arr1)
arr2 = sorted(arr2)

4. Conclusion


In this tutorial, We've explored the way to remove the duplicate contents from list 1 against list 2 and finding out the unmatched contents from two lists.

Further discussed comparing two employee lists and finding out unmatched content using removeAll method in Java and Program in Python for the same.

As usual, All examples are shown in this tutorial are available on GitHub.

Java Program to Check Whether a Number is Even Or Odd (3 ways)

1. Introduction


In this tutorial, You will learn how to write a java program to check a given number is even or odd. This can be done by using a mathematic formula or a different approach. Every number in the world must fall under either an even or odd category. Many developers may provide the solution in different ways but finally, they will tell even or not.

java-program-check-even-odd



الثلاثاء، 12 نوفمبر 2019

Java Program To Add Two Numbers (Scanner) For Freshers

1. Overview


In this tutorial, You'll learn writing a java program to add two numbers for freshers or fresh graduates. This program shows how to find the sum of two numbers in a java programming language. This is a very basic when we learn any language first. So, We will see how to do sum for two numbers using '+' symbol directly and next will read the values from user input and do the sum.

Java Program To Add Two Numbers

الأربعاء، 6 نوفمبر 2019

Java ArrayList Real Time Examples

1. Overview


In this tutorial, You'll learn ArrayList with Real-Time examples. If you are new to java programming, you'll get a question "What are the real-life examples of the ArrayList in Java?". Initial days when I was in engineering the second year, my professor was teaching ArrayList in java.

I have learned about it. ArrayList is a dynamic array to store the elements and also it grows the size automatically if it reaching its threshold value. But when we should be using the ArrayList in realtime applications.


Remember, for now, In the software world there is no application deployed in production without ArrayList. Now think about the usage of ArrayList. ArrayList can be used in many more scenarios in realtime.

We will be seeing a few real-time examples of ArrayList in Java.


Java ArrayList Real Time Examples

الجمعة، 1 نوفمبر 2019

How to Read a Large File Efficiently In Java

1. Overview


In this tutorial, You'll learn how to read the file fast in java efficient manner.

Before going to our topic, Every programming developer must be working on some technology such as java, python, c++ or swift. Either developing web applications or mobile applications. All the user operations must be saved in files, databases or in-memory or in image format. But here the challenging part is doing it considering the performance aspect. This is what you are going to see how to read the file in java efficiently.

And also this is a famous interview question for all level java developers. We will see the good and bad ways to read large files.

How to Read a Large File Efficiently In Java