Friday, March 5, 2021

Exploring Java 8 : Lambda In Java


Welcome to Java4Ninja. Today in this blog we would be learning about Lambda, Functional interfaces and we are going to see a lot of examples about lambda which can tell us with the invention of Lambda how much code has become readable. Lambda is the coolest feature of Java 8.


What are so cool things about Lambda?

  • Till now you have seen passing objects, primitives to the method as a parameter, with lambda coming in the picture, you can pass a function as a parameters
  • functions are treated as the first-class citizen now
  • Your code will become so easy to read and a lot of boilerplate would get removed
  • Lambda is nothing but a shorter way of implementing the functional interface
  • Java 8 bundled with a bunch of handful functional interfaces which is very helpful for building blocks

Let's start exploring Lambda, But before that have look at below classical example; 

class MyThread implements Runnable {
@Override public void run() {
System.out.println("Hello From Thread !");
}
}

public class LambdaExampleOldWay {
public static void main(String args[]) {
Thread t1 = new Thread(new MyThread());
t1.start();
}
}
In the above example, there is a lot of boilerplate code exists. if we are not maintaining a state, we shouldn't be needed to create a class just to declare a function. Now let's have a look at a new way of writing the same code in Lambda.

Solving a problem using Lambda way

public class LambdaExampleOldWay {
public static void main(String args[]) {
Thread t1 = new Thread( () -> {
System.out.println("Hello from Lambda Thread !!");
});
t1.start();
}
}


Simple, Clean, and Stright forward. Easy to understand. No Need for declaring class. you must have understood the syntax for the declaring lambda. Here are the syntax and points about lambda
  • We declare lambda by arrow function -> symbol
  • Before arrow function, we have to specify parameters to the lambda functions
  • Followed by opening and closing curly braces with body specified within it
  • Specifying the data type for parameters is optional
  • Specifying the curly braces and return statement is optional if your lambda is a one-liner statement
  • A semicolon at the end

Another Example of Lambda :

Let's have another example of Lambda for sorting elements in the list

public class LambdaExample {
public static void main(String args[]) {

List<Integer> listOfNumbers = Arrays.asList(10, 15, 30, 35, 22, 12, 9);
listOfNumbers.sort((num1, num2) -> num1.compareTo(num2));
System.out.println(listOfNumbers);

}
}

  • In the above example,  sort accepts an object of the Comparator<T> interface. 
  • We have implemented the compareTo method of Comparator<T> using lambda. 
  • So behind the scene, Lambda is nothing but an anonymous implementation of the function in the interface. 

Parameter and return type identification

Now, the question is how will the lambda come to know the type of parameter, since parameter type declaration is optional and return type are not needed? 

Basically, lambda is nothing but the anonymous method implementation of the interface. In this case of the sort, the method is expecting that passed object is should be implementing the Comparator<? super Integer> interface.  and our lambda is implementing the same thing. our lambda is satisfying the only method in the comparator.
@java.lang.FunctionalInterface
public interface Comparator <T> {
int compare(T t, T t1);
if you compare the format of our lambda, the number of parameters it accepts, the return type of the function is matching with our lambda. Our lambda is creating anonymous objects behind the scene only.


Now the One more question arises. The interface can have multiple abstract methods. Then which one our lambda will pick for matching its arguments?

The answer is that We can create a lambda function only for those interfaces which have only one abstract, unimplemented method in them. Java 8 Call them a Functional Interface. An interface that supports the Functional Style of programming. We would be going to learn more about the functional interface in the next lesson.

Till then stay tuned, and See you all in the Next Lesson
Let me know your comments, suggestion, and question. I would try to resolve it ASAP



Thursday, March 4, 2021

Exploring Java 8 : Whats new in Java 8


Welcome to Java4Ninja. We have started the new Series "Exploring Java 8", Here we would be learning all the things which are making a buzz in the programming world. Since Java 8, java is moving in the direction towards the declarative programming approach from the imperative programming approach. If you are not aware of what is imperative programming and what is declarative programming. it is the way you write code. 


So what you are going to learn in this series?

  • Lambda in Java
  • Functiona Interfaces
  • Method and Constructor Reference
  • Streams API
  • Optionals 
  • New Date/Time API

Few words about Imperative vs Declarative Programming

  • Declarative Programming is style of building the structure and elements of computer programming that express the logic of computiaon without describing its flow. 
  • Many languages that apply this style attempt to minimize or eliminate side effects by describing what the program must accomplish in terms of the problem domain, rather than describe how to accomplish it as a sequence of the programming language primitives.
  • functional programming is sub-paradime of declarative programming
  • Imperative programming is a programming paradigm that uses statements that change a program's state. Imperative programming focuses on describing how a program operates.
  • Procedural programming is a type of imperative programming in which the program is built from one or more procedures (also termed subroutines or functions)


Thats all for the theory, Lets get our hand dirty with the code. See you all in next lessons.

Monday, March 1, 2021

Core Lesson 2 : Data Types in Java


So, In this chapter, we would be learning about the various data types available in java and how to declare them, and how to use them in our java program. It is mostly similar to the C and C++ programming languages. Java is a strongly typed language. Every variable has a type, every expression has a type and java always ensures before store data in the variable, do they match the type of variable we have declared.

How to Declare a variable 


Syntax :

datatype var1 [= init_val], var2 = [init_val], . . . ;

The above syntax shows how to declare a variable in java. You can declare one variable in one line and at the end, you have to specify a semicolon. you can declare more than one variable on a single line separated by a comma. you can also initialize their values while declaring them. Let's have a look at the below program which shows different ways by which we can declare and initialize variables.

public class DataTypeDemo {
public static void main(String args[]) {

int singleLineVariable;
int anotherSingleLineVariable=10;
int multipleVariableOnSameLine1, multipleVariableOnSameLine2;
int multipleVariableOnSameLineWithInitValue1= 10, multipleVariableOnSameLineWithInitValue2= 20;
int dynamicallyInitializedVariable = anotherSingleLineVariable * 20;

}
}


Primitive Types

Primitive type refers to a simple type. they represent a single value at a time. unlike complex objects like structure or class. Although java is a completely object-oriented programming language; the exception is for the primitive type. We do have Wrapper classes for each primitive type we will check that out also going ahead in this blog. the reason for keeping primitive types in java is that speeding up the performance of the program. 

Let's have a look at the different simple types available in java

Numeric Data Type

Integer numbers
  • long (range : –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
  • int (range : –2,147,483,648 to 2,147,483,647)
  • short (range :–32,768 to 32,767)
  • byte (range : –128 to 127)
Integers are nothing but the Whole numbers in mathematical terms. They represent all signed positive to negative numbers as per their data type. Java does not support unsigned integer types as many other programmings do. Let's have a look at the below example for the Integer declaration

class DataTypeDemo {
public static void main(String args[]) {
byte var1 = 10; // Declaring byte variable with initial value of 10
short var2 = 20; // Declaring short variable with initial value of 20
int var3 = 40; // Declaring int variable with initial value of 40
long var4 = 80; // Declaring long variable with initial value of 80
}
}


Java Also supports Octal, Hexa Decimal, and Binary numbers. Let's have a look at the below program to know how we can declare the integer in the different number system

class DifferentNumberSystems {
public static void main(String args[]) {

// octalNumber value can be declare by leading 0 before number
// blow is the declaration of 10 octal number which is 8
int octalNumber = 010;
System.out.println(octalNumber);

// hexaDecimal value can be declare by leading 0x before the number
// below is the declaration of 0x1A hexa number which is 26
int hexaDecimalNumber = 0x1A;
System.out.println(hexaDecimalNumber);

// binaryNumber value can be declare by leading 0b before the number
// below we have declare binary version of 172
int binaryNumber = 0b10101100;
System.out.println(binaryNumber);

}
}

Floating Point numbers
  • double (64 bit)
  • float (32 bit)

Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers. Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05, and 2e+100.

Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to the constant. You can also explicitly specify a double literal by appending a D or d. Doing so is, of course, redundant. The default double type consumes 64 bits of storage, while the smaller float type requires only 32 bits. Let's have a look at below example

public class DataTypeDemo {
public static void main(String args[]) {

// declaring float variable
// Notice f at the end of the number
float var1 = 10.5f;

// declare double variable
double var2 = 3.14;

}
}

Using Separators in the numeric type
  • You must have seen in mathematical books when it comes to defining large number; we use a comma as a separator value
  • This allows the reader to quickly grasp the value of the number by grouping them
  • java allows us to specify separator while you declare the number type values
  • Separator allowed here is underscores character (_)

Let's have a look at the below java example to define a very large number that is easily readable

// Internation format
// one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine
int veryLargeNumber = 123_456_789;

// Indian format
// twelve crore thirty four lakh fifty six thousand and seven hundred and eighty nine
int anotherVeryLargeNumber = 12_34_56_789;

// Value of pi with separator
double fractionalNumber = 3.141_592_653;


Non-Numeric Data Type

Characters
  • In Java, the data type used to store characters is char
  • char in Java is not the same as char in C or C++
  • In C/C++, char is 8 bits wide uses ASCII charset. Instead, Java uses Unicode charset. 
  • Unicode defines a fully international character set that can represent all of the characters found in all human languages. 
  • Unicode required 16 bits. Thus, in Java char is a 16-bit type. 

Let's have a look at the below program that can give you an idea about using characters in java

public class DataTypeDemo {
public static void main(String args[]) {
char firstCharVariable = 'A';
char nextCharVariable = 'B';
char smallCaseLetterVariable = 'h';
}
}

Booleans

  • Java has a primitive type, called boolean, for logical values
  • It can have only one of two possible values, true or false
  • This is the type returned by all relational operators, as in the case of a < b
  • Boolean is mostly used in control execution commands we would be going to learn ahead
  • The values of true and false do not convert into any numerical representation
  • The true literal in Java does not equal 1, nor does the false literal equal 0
Let's have a look at the below example which will demonstrate common usage of boolean

public class DataTypeDemo {
public static void main(String args[]) {

boolean hasVisa = false;
boolean hasJob = true;
boolean isEligibleForVoting = true;

if(isEligibleForVoting) {
System.out.println("Person is eligible for Voting");
}
else {
System.out.println("Person is Not eligible for Voting");
}
}
}

String Data type

String is a Complex data type in java. It is not like the primitive data type. String is a Class in java. String object has a whole bunch of methods available to it. If you have seen the above primitive data type they don't have a method on them which means they are just placeholders to store data on them that can be used for calculation directly. you can not do much on the primitive data type. But String in java is not primitive, you can do a lot of operations on string objects like converting them to lower case, uppercase, concatenate, substring, and so on. We have a separate chapter on String going ahead in this blog.

Let's have a look at the below example of using String data type

public class DataTypeDemo {
public static void main(String args[]) {

String str1 = "Hello this is java program";
String str2 = "This is another line";

String str3 = str1.toUpperCase();

System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}

Important Points to Remember from these lessons

  • We can declare more than 1 variable on the same line of the same data type
  • we can initialize more than 1 variable on the same line of the same data type
  • Java is a strictly typed language. so you cannot assign float to int or float to char
  • We can also initialize number in octal, binary, or hexadecimal format
  • String is not primitive data type. It is a Complex data type in java
  • The primitive variable doesn't have any member function on them
  • Since String is not primitive it has a member function defined inside it


So that All for this Lesson, Let me know if you did not understand anything on this lesson in below comment section, I will try to revert your or I will improve this lesson in this blog.


Till then Good Bye, Happy Coding !!!



Friday, February 26, 2021

Core Lesson 1 : The History and "Hello World" in Java


Java is similar to the C & C++ Language, which is an object originated. most of the functionality of Java is taken from these two languages. Many of Java’s object-oriented features were taken from C++.

The Original motive for Java was not the building computer software or build websites. They wanted to create a language that is platform-independent and could be used for embedded systems in electronic devices, such as TV and remote controls. The problem with C and most other languages were that they are designed to be compiled for a specific architecture. so they need to recompile the program again and again for a different architecture. and many time changes needed in the program to make the execution happen according to the platform. this will turn out to be the platform-dependent code. To overcome this problem they invented java.


Below are the advantage of java 

  • Simple
  • Secure
  • Portable
  • Object-oriented
  • Robust
  • Multithreaded
  • Architecture-neutral
  • High performance


A First Simple Program

Let's take a look at the simple java program below that printout hello world on console

/*
This is Hello World Java Program
Store in the file name HelloWorldJava.java
*/
public class HelloWorldJava {

// Your program execution start from here
public static void main(String args[]) {
System.out.println("Hello World !");
}
}


Compiling the Program

$\> javac HelloWorldJava.java
$\>ll
-rw-r--r-- 1 in-anil.sable 435B Feb 26 21:51 HelloWorldJava.class
-rw-r--r-- 1 in-anil.sable 258B Feb 26 21:50 HelloWorldJava.java


Running the Program

$\> java HelloWorldJava
Hello World !


 A Closer Look at the First Sample Program

/*
This is Hello World Java Program
Store in the file name HelloWorldJava.java
*/

This section in the program represent the Multi Line Comment in the program. these line would be consider as a comments and completely ignore by the Java while compiling the program. We ofter call this as a multi line comment since once can specify many lines withing the pair of /* */


 // Your program execution start from here

This line in the java program represents the Single line Comment. similar to the multiline comment, all the content specified on this line would be ignore by the java while compiling the program. We call it as a single line comment since you can write only 1 line of comment using //. once the line break java treat this as a executable instruction unless new line again start with single line or multi line comment.

Many Developer use the comments to add few details about the method like what is the usage of the method, what kind of parameter we are expecting and what could be the return values. But I personally feel you should avoid adding comments in the program/module unless it is absolutely necessary. I feel your code itself should be so clean that one should not feel the need for comment while reading your code. everything in your program should be self explanatory like name of classes, name of methods and variable name.


public class HelloWorldJava { .... }

The above example uses keyword 'class' to declare the class in java followed by the name of your class. In this example it is 'HelloWorldJava'. You can also see the keyword 'public' which is an access specifier. Dont worry about that now, we would be going to explore all access specifier in java. for now you can just think that this class is Accessiable from other class also. In java programming eveyting like method, variables should be declared inside class only. 


public static void main(String args[]) { .... }

Above line is the declaration on main method. likewise in every other programming language, Application execution start from the main method. This would be the entry point for the the java application. every main method in java should be exactly similar to the above. when we execute the java program, java try to find out the main method in the class, which should be exactly similer to above. talking about the keywords, public is the access specifier which tell the scope of method from which it can get call. since main method is the entry point it should be public so that java can invoke it. We will talk more about the access specifier going ahead in this blog. Static is Non Access specifier, we would talk about this also going ahead in blog, As of now you can think static like, we can Access static things without its object. just by class name. void is return type since this application is not returning anything, we can specify void in its return type


System.out.println("Hello World !");

Result of above line is that whatever is specified in the println("") is getting printed on the terminal. Here System is class inbuilt in java which has out public static variable / data member on which we have println method. System.out by default point out to the output device. in our case it is terminal. There are other data members like System.err, which point out to default error output device and System.in would be default input device, it would be keyboard


An Another Simple Example 

class AnotherSimpleExample {
public static void main(String args[]) {
int firstNumber = 10;
int secondNumber = 15;
int sum = firstNumber + secondNumber;

System.out.println("Sum of numbers is :" + sum);
}
}

Above Example would be little beyond the scope of this lesson, but it will give you the feel of java program. and you can understand how the programs are written in java. By reading each statement you can eaisly understand what this program is doing.


So that All for this Lesson, Let me know if you did not understood anything on this lesson in below comment section, i will try to revert your or i will improve this lesson in this blog.

Till then Good Bye, Happy Coding ! ! !