الثلاثاء، 31 ديسمبر 2019

Java Servlet Session Timeout and Examples

1. Overview


In this tutorial, how to set up and configure a session timeout in a java Servlet based web application.

Configure Session Timeout in the web.xml of a Java Servlet web application, and globally for a Tomcat or Jetty Server.

This can be done in many ways as follows.

A) web.xml
B) Programmatically
C) Tomcat or any server configuration


Java Servlet Session Timeout


الاثنين، 30 ديسمبر 2019

Java 8 Method References With Examples

1. Overview


In this tutorial, We'll learn how to use Method References in Java 8 and where we can use Method References in the programs. To understand this article, you should have a minimal understanding of Lambda Expressions.

Read: Introduction to Lambda Expressions in Java 8

Method References are part of the new Java 8 concept and used to refer to the functional method of Functional Interface. Syntax is ClassName::methodName. Method ref is indicated with "::" - double colon operator. This is a compact and simple form of the lambda expression. If you are using a lambda expression to refer only functional method and not any additional logic then it is best to use method references in these kinds of scenarios.

We'll learn types of method references and their example programs.

Java 8 Method References With Examples


الأحد، 29 ديسمبر 2019

Java 8 Stream mapToInt(ToIntFunction) Method Examples | Convert Stream to IntStream

1. Overview


In this java 8 Streams series, We'll learn today what is Stream API mapToInt() method and when to use this. This method is used to convert the Stream to IntStream. Let us see it's syntax and few examples on mapToInt() method. This is also part of intermediate operations such as map() and filter() methods.

Java 8 Stream mapToInt(ToIntFunction) Method Examples | Convert Stream to IntStream




السبت، 28 ديسمبر 2019

Java List or Traverse All Files in Folder Recursively (Java 8 Files.walk() Example)

1. Overview


In this programming tutorial, we are showing an example program on how to list or traverse all files and folders including subfolders in a directory using the following methods.

A) Using the classic approach
B) Using Java 8 methods

Traverse All Files in Folder Recursively


Java 12 Files mismatch Method Example to Compare two Files

الأربعاء، 25 ديسمبر 2019

What is the need for Default Methods inside Interfaces in Java 8

1. Overview


In this java 8 tutorial series, We'll be learning today why default methods are introduced in java 8 and why default methods are needed?


need for Default Methods inside Interfaces in Java 8

2. Interfaces Before Java 8 


Prior to Java 8, Every method present inside interface is always public and abstract whether we are declaring it or not.

package com.java.w3schools.blog.java.program.to.java8.defaultmethod;

public interface InterfacePriorJava8 {

 int method1();

 int method2();

}


الخميس، 19 ديسمبر 2019

Java Program To Copy(Add) All List Values To A new ArrayList

1. Overview


In this tutorial, We'll be learning how to copy all list values to another new List or ArrayList in Java. Here our context copy means adding all values to a new List. how to copy list values to another list in java or Copy a List to Another List in Java can be done in many ways in java.
And We will keep tracking and show all the possible errors that encounter in our practice programs. Please read the entire article to get a better deeper understanding.

We have already written an article on ArrayList API Methods and its examples.

Java Program To Copy(Add) All List Values To A new ArrayList


We will be showing the example programs using constructor, addAll method, Using Java 8 and Java 10 concepts finally using Collections.copy() method. Hope this article will be interesting for you.

Note: ArrayList is not an Immutable object.

الثلاثاء، 17 ديسمبر 2019

Java Program to Convert Int to String (Best Way)

1. Overview


In this conversion series articles, we will learn today how to convert int to String in java. Previously, I explained converting String to Int in java.

We do not talk much about unnecessary things. Directly jumping into our topic.

int conversion into String can be done using following java builtin methods.

String.valueOf()
Integer.toString()
String.format() 
Using + operator

Java Program to Convert Int to String


الاثنين، 16 ديسمبر 2019

Java 8 Program To Boxed Stream Operations

1. Overview


In this tutorial, We'll learn how to convert primitives to wrapper objects in java 8. Java programs to convert a stream of int, long, double values into Collection using boxed() method.

This boxed() method is present in IntStream, LongStream, and DoubleStream primitive specialization streams.

boxed() method returns a Stream consisting of the elements of this stream, each boxed to a Wrapper.


Java 8 Program To Boxed Stream Operations

الجمعة، 13 ديسمبر 2019

Variables Dynamic Initialization in Java

1. Overview


In this tutorial, We will be discussing variables dynamic initialization topic with example programs in java. Most of the developers do this but do not realize this is said to be dynamic initialization. In the previous tutorial, we discussed in-depth on variables in java.  If you are an experienced developer, continue reading this article. Otherwise, please go through this to get a complete understanding. Accessing Local variables from lambda is quite different and that will cause compile-time errors if you are using variables inside lambda expressions.


If any variable is not assigned with value at compile-time and assigned at run time is called dynamic initialization of a variable. Basically, this is achieved through constructors, setter methods, normal methods and builtin api methods which returns a value or object.

Variables Dynamic Initialization in Java

الخميس، 12 ديسمبر 2019

Java Program To Add All Numbers In A String (Consecutive Digits Considered As One Number)

1. Introduction


In this tutorial, We will learn how to write a java program to add all numbers in a string. Here the ∫. Already shown a program on how to sum all digits in the string (in this case each digit considered as one number. In other words, taking into consideration each individual digit).


Examples of samples:

Exmaple 1:

Input 1: java10program2
Output 1: 12

Exmaple 2:

Input 2: hello100world200
Output 2: 300

Exmaple 3:

Input 3: nodigits
Output 3: 0


Java Program To Add All Numbers In A String

الأربعاء، 11 ديسمبر 2019

Java Program to "Run Length Encoding (RLE)" - String Compression

1. Introduction


In today's article, You will learn What is the "Run Length Encoding" technique which is heavily used in string data compression. This is an experienced java interview question for 4-6 years developers. Earlier days this is used to compress the black and white photos.


Run Length Encoding is abbreviated as "RLE".

Run-length encoding (RLE) is a form of lossless data compression in which runs/flows of data are stored as a single data value and count, rather than as the original run.
Java Program to "Run Length Encoding (RLE)" - String Compression



This works for only sequences in which the same data value occurs in many consecutive data elements.

Examples:

Input: aaabbccccd
Output:a3b2c4d1

Input: xxxyyziiii
Output: x3y2z1i4

Input: kkkkkkiiiiiiuuuuasdfgllll
Output: k6i6u4a1s1d1f1l4

All of the above examples are valid. If the string "aaabba" is invalid because character 'a' is repeated in non-consecutive which is appeared after character 'b'. If the string is invalid then it may produce unexpected results. Please keep in mind this note before implementing it in real-time applications.

الخميس، 5 ديسمبر 2019

Java Program to Send An Email with Plain Text

1. Overview

In this email sending programming series, You will be learning today how to send an email to a specified email address from a default mail address. Content can be anything in the email. Basically, sending emails is a very common feature in the IT industry. After performing a successful case completion or if an error occurred an email should be triggered. And also summarizing the stats for the day and triggering the email at the end of the day. Any scenario is good choice to send an email. It is absolutely based on the need.

Mostly in all banking companies will be running thousands of control-m jobs that need a notification after completion of each job. control-m triggers a shell script or java code and executes all business logic and in the end, it will send the status of the job in the email. If it is not sending the job status to the right person then no action is taken if the job is failed.

Java Program to Send An Email with Plain Text

Java Program to Print or Display Floyd’s Triangle With Example Output

1. Overview


In this programming series tutorial, You'll learn how to create and print Floyd's triangle in java today.  Printing the consecutive numbers in order and right-angled triangle as below is said to be Floyd's Triangle.


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Formula to find the total number of elements in the Floyds triangle is n * (n+1) / 2 where n is the input that how many lines should be printed in the output. The same formula can be used to calculate the sum of n natural numbers also.

Java Program to Print or Display Floyd’s Triangle With Example Output


Refer: Find Sum of N Natural Numbers Using Arthimetic Formulae.

الأربعاء، 4 ديسمبر 2019

Java Program To Convert String to ArrayList Using Arrays.asList()

1. Overview


In this ArrayList articles series, You'll be learning today how to convert a String into an ArrayList using java built-in methods. There are many scenarios in the real-time applications where we need to do transform the string into a list of objects. Typically string should be multiple values separated by a delimiter. For example take a String like "Started,Approved,In Progress,Completed". Here we are seeing the statues in string format and all these statuses are for processing the tickets raised by the users. This is the status flow. We need to now convert this string into a List<String>.


Java Program To Convert String to ArrayList Using Arrays.asList()


Note: String can have integers, double and strings values with a delimiter. The same below shown program works for any type of values present in the input string.

Java Program to Add Two Complex Numbers

1. Overview


In this w3schools programming tutorial, You'll learn a java program to add two complex numbers. Complex number is an A + iB. Every complex equation will have two parts - real and imaginary portions. When adding complex number we need to add separately both real numbers and separately both imaginary numbers.

Here are the two complex number equations.

a1 + ib1, a2 + ib2

(a1,b1) and (a2, b2)

This is also a fresher or 1-2 years of experience java developer interview question.

الثلاثاء، 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

الأربعاء، 30 أكتوبر 2019

Java 13 API - What Are New Features? (JDK 13 Changes)

1. Introduction


In this article, We will learn what are the new features of Java 13 that are added to JDK 13.

Download JDK 13 from the Oracle official website.

Now we are going to learn about the following new changes step by step. Before that, you may have a question that "Is really JDK 13 has major changes?". Because a new java release is expected for every six months. So, Raising this question is common. Answer to this question is "no" changes are very minor. This does not impact the core developers. Except who closely works on CDS, ZGC, Socket API, and switch expressions (It is good to know).

Below is the complete list of changes in JDK 13.



JEP 350: Dynamic CDS Archives
JEP-351: ZGC: Uncommit Unused Memory
JEP-353: Reimplement the Legacy Socket API
JEP-354: Switch Expressions (Preview) (developer feature)
JEP-355: Text Blocks (Preview) (developer feature)

From this list, the first 3 changes can be used directly but the last two are in preview (developer feature). So, We can not use them directly. You will understand how to use the preview functionalities as we go through them each.

الثلاثاء، 29 أكتوبر 2019

Beginners Guide to Spring Email (Spring Boot)

1. Overview


In this article, We'll learn how to send an email using Spring or Spring Boot through step by step procedure. This is absolutely designed for beginners.

In this tutorial, We will see the following as required to send mail in the spring framework with a step by step.


  • Maven dependencies for spring and spring boot.
  • Understanding the common mailing terminologies in spring.
  • Spring and spring boot mailing properties.
  • Sending simple sample spring email examples.
  • Sending emails with an attachment.
  • Construction and sending an email template.
  • How to handle email sending errors.




الأربعاء، 23 أكتوبر 2019

Java Program to Check Leap Year

1. Introduction:


In this program, you'll learn to check if the given year is a leap year or not. This is checked using a if else statement.

A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400.

Java Program to Check Leap Year


الأربعاء، 11 سبتمبر 2019

Complete Guide to Java 8 Lambda Expressions

1. Overview

In this tutorial, We will learn Java 8 new features about Lambda Expressions step by step in-depth.

Lambda word came from lambda calculus which is used to describe computations. We will go through one by one as below topics today.

Definition
Comparing to Older Java Versions
Lambda Syntax
Lambda Valid Examples
Lambda Rules
Where to Use Lambda
Lambda Sorting Example
Invalid Lambda Expressions
Complete Guide to Java 8 Lambda Expressions
We have already shown few examples on Java 8 Examples Programs Before and After Lambda & Streams. Go through this article before continuing further on this tutorial. If you have basic understanding of lambda's then you are good to continue.

السبت، 10 أغسطس 2019

HTML Forms - <form> Tag Examples

1. Overview


In this tutorial, We'll learn about how to use <form> tag and what is the importance of it. We will talk about a few examples where <form> tag usage is appropriate.

The HTML <form> element defines a form that is used to collect user input. Below is the format of the form tag.

<form>
...
...
form inside elements
...
...
</form>

HTML-Forms


<form> tag is used in all registration or log in pages. Because the user provides the data and pushed to the server for persistence.

الثلاثاء، 30 يوليو 2019

HTML - Adding Google Maps to Web Page - API Example

1.Overview


In this tutorial, We'll learn how to add Goole Maps to your website or page.

This is very easy to understand adding Google maps to the web page.

To make maps available on a web page, we must include the google maps API using the below script.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=myMap"></script>

You have to register and get the key from https://cloud.google.com/maps-platform/. Without the key, maps can not be loaded.

الخميس، 11 يوليو 2019

Java 8 - Working with IntSupplier

1. Overview


In this tutorial, We'll learn how to use IntSupplier Functional Interface and part of package java.util.function which has been introduced in java 8.

IntSupplier represents a supplier of int-valued results. This is the int-producing primitive specialization of Supplier.

As we discussed in the previous article on "Working with Supplier Functional Interface", IntSupplier comes under Supplier's category and does not take any argument.

IntSupplier has only one functional method that is getAsInt().

Java 8 - Working with IntSupplier


When we expect an int primitive value rather than Integer wrapper then we should not use directly Supplier FI. Because it does autoboxing and leads to performance issues.

الأربعاء، 10 يوليو 2019

Java 8 Functional Interfaces (FI)

1. Overview

In this tutorial, We'll learn about Functional Interface added to Java 8. Functional Interface is abbreviated as FI.

These Functional Interfaces are used extensively in Lambda Expressions.

Please read article on "A Complete Guide to Lambda Expressions"

If you have a basic understanding of Lambda's that will help in using Functional Interface(FI) properly. But, We will discuss in short about Lambda's.

Java 8 Functional Interfaces (FI)


We will cover the following concepts in this article.


  • Intro to Lambda
  • Lambda Examples
  • Functional Interface Definition
  • @FunctionalInterface annotation
  • Built-in FI's
  • Types of Functional Interfaces with examples


الأربعاء، 3 يوليو 2019

[Fixed] Error: Could not find or load main class

1. Overview


In this tutorial, We'll learn What does "Could not find or load main class" mean?

A common problem that new Java developers experience is that their programs fail to run with the error message: Could not find or load main class.

What does this mean, what causes it, and how should you fix it?

The problem is with this java run command

java  command syntax

We have gathered all these solutions from StackOverflow page and arranged in a simple manner to understand easily.

[Fixed] Error: Could not find or load main class


Please read section 2 and 5 to get a clear understanding. Section 3 tells about all areas where we do mistake usually. But, recommend reading the complete article.

الثلاثاء، 2 يوليو 2019

Java 8: Working with Supplier

1. Overview

In this tutorial, We'll learn about java 8 Supplier Functional Interface.

Supplier is part of package java.util.function. This is introduced in Java 8 as part of Function programming.

Api Reference

Supplier Functional Interface has only one Abstract method.


T get()

Where T -  the type of results supplied by this supplier

Java 8 - Working with Supplier


This method is called as Functional Method.

Supplier does not take any argument but returns a value always. Because of this named as Supplier as supplies everytime something when we call get() method.

Suppliers are very useful when we do not need to supply any value but need to return a value at the same time.

الاثنين، 1 يوليو 2019

Java 8: Accessing Variables from Lambda Expressions

1. Overview

In this tutorial, We'll learn about how to access variables from Lambda Expressions in Java 8.

Before that, We suggest you read the tutorial on Java 8 Lambda Expressions discussed in the previous tutorial.

If you already know about Lambda's, just ignore and continue reading this article.

Can we declare a variable inside Lambda Expression?

Java 8: Accessing Variables from Lambda Expressions


The answer is yes. We can declare variables as many as needed.

What do you think if lambda has a reference to another variable?

Here, We have two scenarios to know.

First, What will happen for local variables in Lambda.

Second, Non-local variables to Lambda.

الاثنين، 17 يونيو 2019

Java 8 Examples Programs Before and After Lambda & Streams

1. Introduction


In this tutorial, We'll learn how to write programs using java 8 coding standards on few examples. Many developers feel learning java 8 concepts may be hard to understand. But once we are good using them then feel reduces error prone code and improves the performance of the application.


Read article on Java 8 Lamda Expression Rules

Examples Programs Before and After Java 8

In this article, We will see the example programs on sorting using Comparator, File names validation, Retrieving only hidden files and filtering list objects based on conditions.

الاثنين، 10 يونيو 2019

Java Type Casting

1. Type Casting Overview


In this tutorial, We'll learn what is Type Casting and how it works in Java.

Type casting is used to convert an object or variable of one type into another.

This is done in two ways.

A) Implicit conversion or type casting
B) Explicit conversion or type casting

Java Type Casting


1.1 Syntax


DataType variableName = (DataType) variableNameToConvert;

The above syntax is to covert one type to another type by specifying the Data Type of Target.


2. Implicit Type Casting


This is also called as Automatic Type Conversion or Widening.

If we assign value of one variable type to another, two types may be compatible or not compatible to each other.

If compatible then conversion will be done automatically. This type of conversion is called Automatic Type Conversion.

DataType1 type_variable_name = another_type_variable_name

This implicit conversion is done in 2 scenario's.

1) If both types are compatible
2) If destination data type is bigger than source data type (Assigning smaller data type to bigger data type)

In java, Numeric primitive data types are converted automatically from smaller to bigger types.

But this is not applicable to the boolean and char types because these two are not compatible to each other.

2.1 Automatic conversion hierarchy


below is the valid conversion's flow in java.

byte --> short --> int --> long --> float --> double

2.2 Example on Primitive Types


Creating a int type variable. Next, assigned int to double without specifying any type casting. This looks working magically to the new java developers.

int number = 10;
double d = number;

The above code does not give compile time error and works perfectly fine. Here, implicit casting has been applied by compiler. So, no issue in this case.

2.3 Example with Inheritance

We will look at another example using inheritance.

Creating A class.

class A {
 public void sayHello() {
  System.out.println("hello developer");
 }
}

Creating class B which extends class A.

class B extends A{
 public void sayBye() {
  System.out.println("Hope you come back to this site soon.");
 }
}

Now, we are going to assign type B to type A as below.


A a = new B();
a.sayHello();

This works well, no doubt in that. Because assigning sub class object to the it's super class reference. All the code is tested against JDK 12.

If we assign type A to B then will get compile time error saying "cannot convert from A to B". The reason behind this is there is no relationship between class A and B.

B b = new A();

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Type mismatch: cannot convert from A to B

2.4 Example on Generics with Wrapper classes


Example demonstration with Wrapper classes using Generics concepts.


Below example, Creating ArrayList instance which accepts any Number implementation classes such as Integer, Double, Float, BigInteger etc.

List numbers = new ArrayList();
numbers.add(new Integer(100));
numbers.add(new Double(100));
numbers.add(new BigInteger("123.5"));

Added Integer, Double and BigInteger objects but did not get any error because compiler does implicit casting for us based on those classes relation with Number class.

3. Explicit Type Casting


This is also called as Narrowing which means reducing the scope of the source type.

In other words, Assigning bigger data type to smaller data type or which are not compatible to each other.

We will see example program on each case with legal and illegal examples.

3.1 Example on primitive types


We will now implement a program to assign float to byte. We will see what will happen and how to eliminate error if anything comes.

float f = 30.087f;
byte b = f;

Output:

When we compile this code then will through compile time error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Type mismatch: cannot convert from float to byte

   
Because float type is getting assigned to byte which is having less capacity. There may be loss of precision of values.

For make above code to work, we should add explicit type casting from float to byte as below.

float f = 30.087f;
byte b = (byte)f;

Print the byte b value.

30

Because of narrowing, it will loose precision of value.

3.2 Example on User defined classes without any relation (Inheritance)


Let us create two classes C and D as below.

class C {
 // some methods
}

class D {
 // some methods
}

Now assign class C type to class D type. There is not relationship between class C and D. So, We must do explicit casting.

C c = new C();
D d = (D)c;

But, still compiler can determine that there no relationship among them. So, Will get compile time error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot cast from C to D

   

3.3 Loss of Precision


Float holds decimal points and double hold very big values as when compared to int. See the below example where casting to int type.

float f1 = 3.14f;
double d1 = 1234567890123456789d;

int i1 = (int)f1;
System.out.println("i1 : "+i1);

int i2 = (int) d1;
System.out.println("i2 : "+i2);


Output:

i1 : 3
i2 : 2147483647

It losts the actual float and double values because int can not hold the decimals. double value is completely changed after casting to int.

So, narrowing casting is not recommended to use unless it significantly effects.

4. Conclusion


We've seen What is type casting in java and how it works in different cases.

Discussed types of casting such as automatic and explicit type casting. Showed exmaple programs using primitive types, Wrapper classes with Generics and Inheritance.

Narrowing casting feature can not hold the actual values if the source type is bigger than the destination type.

All example code snippets shown in this article are available over GitHub.






الاثنين، 3 يونيو 2019

Java String API replaceAll() Method Example

1. String replaceAll() Overview


In this tutorial, We'll learn about Java String API replaceAll() Method with Example (String.replaceAll).

As name "replaceAll" suggests, It replaces each substring of this string that matches the given regular expression with the given replacement. Refer the below syntax, it takes regex which is a regular expression pattern.

This method is a instance method which should be invoked on a string. If this string has a pattern then it replaces all matched pattern's with the second parameter value.

In the previous article,  discussed on String replace() method with examples.

Java String API replaceAll() Method Example


1.1 Syntax


public String replaceAll​(String regex, String replacement)

Java Access Modifiers

1. Overview


In this tutorial, We'll learn about Access Modifiers in Java. Java provides the 4 types of access modifiers for class, constructors, methods and instance variables.

These four access modifiers changes complete accessibility at various levels.

We will explore on each modifier as following.

A. default - No keyword is required
B. private
C. protected
D. public

Java Access Modifiers





This is a very basic in core java programming. If you understand this, you can crack any code in java application.


الجمعة، 31 مايو 2019

Java String API replace() Method Example

1. Java String replace() Overview


In tutorial, We'll learn about Java String replace() method and explanation with examples. replace() method is used to replace a character with another character in a String and this method returns a new string after replacing characters.

In previous tutorial, We've seen How to use Java 11 String API repeat() method.

Java String API replace() Method Example

1.1 Syntax


public String replace​(char oldChar, char newChar)
public String replace​(CharSequence target, CharSequence replacement)

replace() method is available in two variants. First variant takes two char's as input and replace a char by a new char. Where as in second variant, It takes two CharSequence as arguments and replace one CharSequence by new CharSequence.

Here, CharSequence means String, StringBuffer, StringBuilder. Any one of these can be passed as arguments to the second variant of replace().

الأربعاء، 29 مايو 2019

Java 11 String API repeat​() Method Example

1. Java 11 String repeat​() Method Overview


In this tutorial, We'll learn about Java String API repeat​() Method with examples. repeat() method repeat​s the string given n number of times.

repeat() method works as it name suggests.

Java 11 String API repeat​() Method Example

1.1 Syntax

public String repeat​(int count)

This is a public method and can be accessed on string instance directly.

1.2 Parameters

count - number of times to repeat

If we pass count as 3 then string repeats 3 times.

الثلاثاء، 28 مايو 2019

Java String API matches​() Method Example

1. Java String API matches​(String regex) Overview

In this tutorial, We'll learn about Java String API matches​() Method with Example programs. And also will explain how this method works internally.

matches() method tells whether or not this string matches the given regular expression.

In simple words, First regular expression is a pattern which tells string should have only alphabetic's or numbers. This pattern can be anything or specified character set.

If the string fits into the specified regular expression pattern then matches() method returns true. Otherwise returns false.



Java String API matches​() Method Example

Java String API length() Method Example

1. Java String length() Overview

In this tutorial, We'll learn how to find the length of the String using Java String API Length() Method. In other words, Counting the number of characters in String.

Knowing the string length is very important in iterating the string.

Note: All the blank spaces in string are counted as character.

Java String API length() Method Example

Java 11 String API isBlank() Method Example

1. isBlank Method Overview

In this tutorial, We'll learn about new java 11 string isBlank() method and explanation with examples. And also how to check the string is blank or not using isBlank() method.

This method is introduced in Java 11.
Read complete article on What is new in Java 11 String API.

Java 11 String API isBlank() Method Example

Java String intern() Method Example

1. Overview

In this post, We'll learn String intern() method in java with examples and This is part of java.lang package. Intern method is invoked automatically on every string literal creation.

String is immutable that means a new String object will be created for every operation or invoking any method on string object. In another words, Original String content will not be modified.


Java String intern() Method Example



الاثنين، 27 مايو 2019