Java 8: Lambda Expression


Java 8 introduced lambda expression to move toward functional programming. A lambda expression is an anonymous function that doesn’t have a name and doesn’t belong to any class.

Where to use the Lambda Expression

A lambda expression can only be used where the type they are matched against is a single abstract method(SAM) interface or functional interface.

To use a lambda expression, you can either create your own functional interface or use the predefined functional interface provided by Java.

Example of a pre-defined interface: Runnable, callable, ActionListener, etc.

Pre Java 8: Use anonymous inner classes.
Post-Java 8: Now use lambda expression instead of anonymous inner classes.

Points to remember

  • Lambda expression is also known as a closure that allows us to treat functionality as a method arguments (passing functions around) or treat code as data.
  • Lambda expression concept was first introduced in the LISP programming language.
  • Lambda expression is used to provide an implementation of a functional interface or Single Method Interface.
  • Lambda expression treated as a function so the compiler does not create .class file.
  • Lambda expression doesn’t need to define a method again for implementation.
  • Lambda expression benefit is less coding.

Java Lambda expression Syntax

To create a lambda expression, On the left side of the symbol lambda operator(->) specify input parameters (if there are any), and on the right side place the expression or block of statements.


 (parameter_list) -> {function_body}

For example, the lambda expression (x, y) -> x + y specifies that lambda expression takes two arguments x and y and returns the sum of these.

Note:

  • Optional type declaration: No need to declare the data type of a parameter. The compiler can inference the data type from the value of the parameter.
  • The optional parenthesis around parameter: No needs to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces: For a single line of the statement, No need to use curly braces in the expression body.
  • Optional return keyword: The compiler automatically returns the value if the body has a single expression statement to return the value. Curly braces are required to indicate that expression statement returns a value.

Here is some Lamda expression example according to a number of arguments.

No Argument Syntax


()->{
//write some statemnet here
}

One Argument Syntax


(arg1)->{
//write some statemnet here
}

Two Argument Syntax


(arg1,arg2)->{
//write some statemnet here
}

Method vs Lambda Expression in Java

A function (or method) in Java has four main parts:
1. Name
2. Parameter list
3. Body
4. return type.

A lambda expression has these main parts:
Lambda expression only has a parameter list and body.
1. No name – Lambda expression is an anonymous function that doesn’t have a name.
2. Parameter list
3. Body – This is the main part of the function where implementation is written.
4. No return type – Don’t need to write a return statement explicitly. The compiler is able to infer the return type by checking the code.

Example 1: Lambda Expression with a predefined functional interface

In this thread, execution example consider both ways legacy and lambda expression to implement the run method and start threads.

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

// Implementing Runnable using anonymous class (legacy way)
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("Thread name : " + Thread.currentThread().getName());
}
};
Thread thread1 = new Thread(runnable1);

// Implementing Runnable using Lambda expression because Runnable having
// only one abstarct method run()
Runnable runnable2 = () -> {
System.out.println("Thread name : " + Thread.currentThread().getName());
};
Thread thread2 = new Thread(runnable2);

// Start Threads
thread1.start();
thread2.start();
}
}

Example 2: lambda Expression with your own functional interface

In this example, define the functional interface “YourFunctionalInterface” definition by the lambda expression for arguments (a,b). When we call the functional interface method with the argument (120,100) then it will make reference to the given definition of FunctionalInterface and return the result as 220.

@FunctionalInterface
interface YourFunctionalInterface
{
 public int addValues(int a, int b);
}

public class CalculateClass {

   public static void main(String args[]) {
        // lambda expression
    YourFunctionalInterface sum = (a, b) -> a + b;
        System.out.println("Result: "+sum.addValues(120, 100));
    }
}

Output


Result: 220

Example 3: Lambda Expression with no arguments

@FunctionalInterface
interface MyFunctionalInterface {
//abstarct method with no argument
public String sayWelcome();
}
public class LambdaExpressionExample {
public static void main(String args[]) {
//No argument lambda expression
MyFunctionalInterface msg = () -> {
return "Welcome to Facing Issues on IT !!";
};
System.out.println(msg.sayWelcome());
}
}

Output


Welcome to Facing Issues on IT !!

Example 4: Lambda Expression for Collection Iteration

import java.util.*;
public class LambdaExpressionLoopExample{
public static void main(String[] args) {
List list=new ArrayList();
list.add("Saurabh");
list.add("Gaurav");
list.add("Bharti");
list.add("Herry");
list.add("Henry");
list.forEach(
// lambda expression for list iteration
(names)->System.out.println(names)
);
}
}

Output


Saurabh
Gaurav
Bharti
Herry
Henry

Note:

  1. As you can see from these examples lambda expression used less code.
  2. Lambda expression is backward compatible so we can enhance our existing API when migrating to Java 8.

References

Java 8: Optional for handling NULL


Java 8 introduces a new class called java.util.Optional to overcome the headache of NullPointerException. Optional class is a type of container of optional single value that either contains a value or doesn’t (it is then said to be “empty”).

The optional class having lots of methods to deal with different cases:

Create Optional Object

Create Optional Object : Empty


Optional optionalObj=Optional.empty();

Create Optional Object: Non-Null
Optional.of() method throw NullPointerException if passing object reference is null.


YourClass yourObj=new YourClass();
Optional optionalObj=Optional.of(yourObj);

Create Optional Object: Allowed Null
Optional.ofNullable() method allowed null reference in Optional object container.


YourClass yourObj=null;
Optional optionalObj=Optional.ofNullable(yourObj);

Check Optional Object for value present

Optional.isPresent() method return boolean true/false based on any value present in Optional container.


if(optionalObj.isPresent())
{
//do something
}

Optional Object for value

if Optional.isPresent() method return true then we get value from Optional object by get() method. If value is not exist in Optional object and trying to call get() method then throw exception as NoSuchElementException


if(optionalObj.isPresent())
{
YourClass yourObj=optionalObj.get();
}

Set Optional Object default value and actions

We can use Optional.orElse() method which provide default value if Optional object is empty.


YourClass yourObj=optionalObj.orElse(new YourClass("defaut"));
</pre We can use Optional.orElseThrow() method which instread of returning default value if Optional empty , throw an exception:

YourClass yourObj = optionalObj.orElseThrow(IllegalStateException::new);

Example 1

In this example, covered all the above case.


import java.util.Optional;
public class OptionalExamples {

	public static void main(String args[]) {
		OptionalExamples java8Tester = new OptionalExamples();
	      Integer value1 = null;
	      Integer value2 = new Integer(25);

	      //Optional.ofNullable - allows passed parameter to be null.
	      Optional<Integer> firstParam = Optional.ofNullable(value1);

	      //Optional.of - throws NullPointerException if passed parameter is null
	      Optional<Integer> secondParam = Optional.of(value2);
	      System.out.println(java8Tester.sum(firstParam,secondParam));
	   }

	   public Integer sum(Optional<Integer> a, Optional<Integer> b) {
	      //Optional.isPresent - checks the value is present or not

	      System.out.println("First parameter is present: " + a.isPresent());
	      System.out.println("Second parameter is present: " + b.isPresent());

	      //Optional.orElse - returns the value if present otherwise returns
	      //the default value passed.
	      Integer value1 = a.orElse(new Integer(0));

	      //Optional.get - gets the value, value should be present
	      Integer value2 = b.get();
	      return value1 + value2;
	   }

}

Output


First parameter is present: false
Second parameter is present: true
25

Example 2

public class OptionalExaple2

	public static void main(String[] args) {
		Optional<String> completeName = Optional.ofNullable(null);
		// The isPresent() method returns true if this instance of Optional has
		// non-null value and false otherwise.
		System.out.println("Complete Name is set? " + completeName.isPresent());
		// The orElseGet() method provides the fallback mechanism in case
		// Optional has null value by accepting the function to generate the
		// default one.
		System.out.println("Complete Name: " + completeName.orElseGet(() -> "[Unknown]"));
		// The map() method transforms the current Optional’s value and returns
		// the new Optional instance.
		System.out.println(completeName.map(s -> "Hey " + s + "!").orElse("Hey Unknown!"));

		Optional<String> firstName = Optional.of("Saurabh");
		System.out.println("First Name is set? " + firstName.isPresent());
		// The orElse() method is similar to orElseGet() but instead of function
		// it accepts the default value.
		System.out.println("First Name: " + firstName.orElseGet(() -> "[Unknown]"));
		System.out.println(firstName.map(s -> "Hey " + s + "!").orElse("Hey Unnknown!"));
		System.out.println();

	}

}

Output


Complete Name is set? false
Complete Name: [Unknown]
Hey Unknown!
First Name is set? true
First Name: Saurabh
Hey Saurabh!

References

 

Java 8: Base64 Encoding and Decoding


In Java 8 added new class Base64 for encryption and decryption. It supports three types encoding and decoding:

  • Simple
  • URL
  • MIME

Note: Passing a null argument to a method of this class will cause a NullPointerException to be thrown.

Simple

Uses “The Base64 Alphabets” lying in A-Za-z0-9+/ for encoding and decoding. The encoder does not add any line feed/line separate character in output and decoder rejects all characters out of the Base 64 alphabet.

Example: Simple Encoding and Decoding

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64s {

	public static void main(String[] args) {
    final String text = "Facing Issues On IT in Java 8!";

        final String encoded = Base64.getEncoder().encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
        System.out.println("After Encoding:"+ encoded );

        final String decoded = new String(Base64.getDecoder().decode( encoded ),StandardCharsets.UTF_8 );
        System.out.println("After Decoding:"+ decoded );
	}
}

Output


After Encoding:RmFjaW5nIElzc3VlcyBPbiBJVCBpbiBKYXZhIDgh
After Decoding:Facing Issues On IT in Java 8!

URL

Uses “URL and Filename safe Base64 Alphabet” lying in A-Za-z0-9+_ for encoding and decoding. The encoder does not add any line feed/line separater character in output and decoder rejects all characters out of the Base 64 alphabet.

Example: URL Encoding and Decoding

import java.util.Base64;

public class Base64URLExample {

	public static void main(String[] args) {
		String originalUrl = "https://www.google.co.in/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java";
		String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
		System.out.println("After Encoding:"+ encodedUrl );

		byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl);
		String decodedUrl = new String(decodedBytes);
		System.out.println("After Decoding:"+ decodedUrl );
	}

}

Output


After Encoding:aHR0cHM6Ly93d3cuZ29vZ2xlLmNvLmluLz9nZmVfcmQ9Y3ImZWk9ZHpiRlYmZ3dzX3JkPXNzbCNxPWphdmE=
After Decoding:https://www.google.co.in/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java

MIME

Uses “The Base64 Alphabet” lying in lying in A-Za-z0-9+/ for encoding and decoding. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return ‘\r’ followed immediately by a linefeed ‘\n’ as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.

Example: MIME Encoding and Decoding

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;

public class Base64Mime {

	public static void main(String[] args) {

		try {
			StringBuilder stringBuilder = new StringBuilder();
			// Lets generate some mime input to encode
			for (int i = 0; i < 10; ++i) {
				stringBuilder.append(UUID.randomUUID().toString());
			}

			byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
			String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
			System.out.println("Base64 Encoded String (MIME) :" + mimeEncodedString);

			byte[] decodedBytes = Base64.getMimeDecoder().decode(mimeEncodedString);
			String decodedMime = new String(decodedBytes);
			System.out.println("Base64 Decoded String (MIME) :" + decodedMime);

		} catch (UnsupportedEncodingException e) {
			System.out.println("Error :" + e.getMessage());
		}
	}

}

Output


Base64 Encoded String (MIME) :YWY1MWRkMDAtNjg0MC00MDE4LTk5YWYtMDE4NTFhYmZkYzA3M2Q0MjU1YjMtNDFiOS00ZmZmLTky
NjktYzc5YjU2Mzg4OGMyM2IzZTAyN2QtNzhkMC00YzRiLTg3MzgtZWFiMmI3OTdlNmVlMzdmYzQ3
ZDItYmI2Zi00NmVjLThlYTQtOWUwYWJlODA0M2IwN2I1NzIxNjUtNzJjZC00ODhmLWJkMWUtOWVl
NGI3YTc5M2NmZjczMjU1MDItMzIyNC00Mjc1LWI2MjQtNTcxZTU3ZmZkZjVhNTdiMmM4NTgtMzFi
Yi00ZjNlLWI5MWYtZWJkNjc5ODlkOTA2NDQ4MDZiZDQtOWM4Zi00NjJlLWI1ZWUtODZiNWM0MTJm
MmVjM2JmMjFjMDAtNjUwYi00ZjE0LWI5ZTUtOTY2YjE2NjUzMWQxMGJhYTIzMTAtOTFmMy00OGYz
LTg1ZTgtZmU3OTEyMjNhODc3
Base64 Decoded String (MIME) :af51dd00-6840-4018-99af-01851abfdc073d4255b3-41b9-4fff-9269-c79b563888c23b3e027d-78d0-4c4b-8738-eab2b797e6ee37fc47d2-bb6f-46ec-8ea4-9e0abe8043b07b572165-72cd-488f-bd1e-9ee4b7a793cff7325502-3224-4275-b624-571e57ffdf5a57b2c858-31bb-4f3e-b91f-ebd67989d90644806bd4-9c8f-462e-b5ee-86b5c412f2ec3bf21c00-650b-4f14-b9e5-966b166531d10baa2310-91f3-48f3-85e8-fe791223a877

References

Java 8: Arrays Parallel Processing


Java 8 added lots of new methods to allow parallel processing for arrays. The most frequently used one is parallelSort() which may speed up the arrays sorting on multicore machines.

Java 8 new methods for Arrays

  • Arrays.parallelSetAll(): Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
  • Arrays.parallelSort(): Sorts the specified array into ascending numerical order.
  • Arrays.parallelPrefix(): Cumulates, in parallel, each element of the given array in place, using the supplied function.

Example: Arrays Parallel Processing

In this example uses method parallelSetAll() to fill up arrays with 25000 random values.
After that, the apply parallelSort() on these arrays values. Here you can see the output of the initial 10 values before and after sorting.

public class ParallelArrays {

	public static void main(String[] args) {
		    long[] arrayOfLong = new long [ 25000 ];
            //Fill long array with random numbers parallelly
	        Arrays.parallelSetAll( arrayOfLong,index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
			//Print initial 10 values of array
            System.out.println("Before Sorting:Print initial 10 values of array");
	        Arrays.stream( arrayOfLong ).limit( 10 ).forEach(i -> System.out.print( i + " " ) );
	        System.out.println();
			//Parallel Sort Array Values
	        Arrays.parallelSort( arrayOfLong );
			//Print initial 10 values of array
			System.out.println("After Sorting:Print initial 10 values of array");
	        Arrays.stream( arrayOfLong ).limit( 10 ).forEach(i -> System.out.print( i + " " ) );
	        System.out.println();
	}

}

Output


Before Sorting:Print initial 10 values of array
164965 546280 269106 800751 338598 862392 358814 206345 611726 788465 
After Sorting: Print initial 10 values of array
4 13 87 93 94 145 203 281 319 397

References

Java 8 : Nashorn JavaScript Engine


Java 8 introduced a new Nashorn Javascript Engine to replace existing Rhino. Nashorn Javascript engine provides 2 to 10 times better performance and it directly compiles the code in memory and passes the bytecode to JVM. Nashorn JavaScript Engine enhanced version of javax.script.ScriptEngine and follows the same set of rules, permitting for Java and JavaScript interoperability.

Points to remember

  • Use jjs command to run Javascript through Nashhorn Engine.
  • The class name for the Nashorn Javascript engine is jdk.nashorn.api.scripting.NashornScriptEngine.

Exmaple: Nashorn JavaScript Engine

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class NashornEngineTest {

	public static void main(String[] args) {
		try {
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("JavaScript");

			System.out.println(engine.getClass().getName());
			System.out.println("Result:"
					+ engine.eval("function increment() { return 1; }; increment() + 1;"));
		} catch (ScriptException ex) {
			ex.printStackTrace();
		}

	}

}

Output


jdk.nashorn.api.scripting.NashornScriptEngine
Result:2.0

References

Java 8:Named Parameters in Reflection


With Java 8 reflection API added method to get parameters name of the method. For that, you need to make some compile-time configuration as pass the compiler flag: javac -parameters.

In this example, you will difference in reflection API output with and without named parameter configuration.

Example: Named Parameter Reflection API

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class NamedParameterExample {

	public static void main(String[] args) throws Exception {

		for(Method method :NamedParameterExample.class.getDeclaredMethods()) {
			System.out.println("\nMethod :"+method.getName()+" Parameters are :");
			for (final Parameter parameter : method.getParameters()) {
				System.out.println("Parameter: " + parameter.getName());
			}
		}
	}

	public static void printValues()
	{
		//Some statement here
	}

	public static int addOperation(int A, int b)
	{
		return A+b;
	}

	public static int substractionOperation(int param1 , int param2)
	{
		return param1-param2;
	}
}

Output: Without Configuration for the named parameter


Method :main Parameters are :
Parameter: arg0

Method :printValues Parameters are :

Method :addOperation Parameters are :
Parameter: arg0
Parameter: arg1

Method :substractionOperation Parameters are :
Parameter: arg0
Parameter: arg1

Output: With Configuration for the named parameter



Method :main Parameters are :
Parameter: args

Method :printValues Parameters are :

Method :addOperation Parameters are :
Parameter: A
Parameter: b

Method :substractionOperation Parameters are :
Parameter: param1
Parameter: param2

Eclipse Configuration for Named Parameter

Go to Window Tab -> Preferences -> Compiler -> Select Checkbox for “Store Information about method parameters (usable via reflection)”.
As shown in the below screen.

Java 8 named parameter eclipse setting

Console Configuration for Named Parameter

On time on compile with javac pass additional configuration as javac -parameters “class name”.

Maven Configuration for Named Parameter

On section of the maven-compiler-plugin:


<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId> 
  <version>3.1</version>
  <configuration> 
       <compilerArgument>-parameters</compilerArgument>
       <source>1.8</source> 
       <target>1.8</target> 
  </configuration>
</plugin>

Java 8: Reflection API to get Repeatable Annotation Detail


Java 8, introduced some new reflection APIs to retrieve annotation related information from different elements types like classes, interfaces, method, type, etc.

Reflection API provides new method getAnnotionByType() to return array of repeating annotations type.

Pre-requisite: Java: Annotations

In previous post Java 8: Repeatable Annotations you have learned about the creation and implementation of repeatable annotation. Let’s take one more example of repeatable annotation and see how to get annotation detail by Java reflection APIs.

Example: Retrieve Annotation Detail by Reflection API

As repeating annotations should themselves annotated with @Repeatable(Filetrs.class) annotation. Here Filters is just a holder of Filter’s annotations. The filterable interface defined Filter annotation two times with different values.

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class RepeatingAnnotations {
	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	public @interface Filters {
		Filter[] value();
	}

	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	@Repeatable(Filters.class)
	public @interface Filter {
		String value();
	};

	@Filter("filter1")
	@Filter("filter2")
	public interface Filterable {
	}

	public static void main(String[] args) {

	    /**
		*Here reflection API Class.getAnnotationsByType() returns
		*array of applied annotations
		*/
		for (Filter filter : Filterable.class
				.getAnnotationsByType(Filter.class)) {
			System.out.println(filter.value());
		}
	}

}

Output


filter1
filter2

Java 8: Repeatable Annotations


In Java 8 introduced repeatable annotation so that same annotation can be used multiple time on the same declaration and type use. For example, create a custom annotation to implement as repeatable annotation.

Pre-Requisite : Java: Annotations Tutorial

See also: Java 8: Reflection API to get Repeatable Annotation Detail

Create Custom Repeatable Annotation

import java.lang.annotation.Repeatable;
@Repeatable(Schedules.class)
public @interface Schedule {
String dayOfMonth() default "first";
String dayOfWeek() default "Mon";
int hour() default 2;
}

Create an array of repeatable annotation


package com.common.annotations;
public @interface Schedules {
Schedule[] value();
}

Use of repeatable annotation


package com.common.annotations;
import java.util.Date;
public class RepeatableAnnotationExample {
    public static void main(String[] args) {

    } 

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour=23)
   public void doPeriodicCleanup() {
     System.out.println("Clean up started at :"+new Date());
   }
}

Java 8: StringJoiner Class


In java 8, introduced a new class StringJoiner to join more than one strings with the specified delimiter. This class also provides prefix and suffix to the final delimited String. We can also set default text value if no values added for string joined.

Constructors

  • StringJoiner(CharSequence delimiter): Constructs a StringJoiner with a delimiter, with no prefix or suffix.
  • StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): Constructs a StringJoiner with delimiter on values and add prefix and suffix on the final value.

Example 1: StringJoiner with delimiter (:)

Here in this example defined StringJoiner with a delimiter (:) to separate values, use StringJoiner.setEmptyValue() method to default value if not data added. Use StringJoiner.add() method to add values on StringJoiner.

import java.util.StringJoiner;

public class StringJoinerExample {

	public static void main(String[] args) {
		// Passing Hyphen(:) as delimiter
        StringJoiner myFriends = new StringJoiner(":");
        myFriends.setEmptyValue("No Friends Found");
        System.out.println("Friends Detail : When no data added");
        System.out.println(myFriends);
        // Joining multiple strings by using add() method
        myFriends.add("Saurabh");
        myFriends.add("Gaurav");
        myFriends.add("Raghav");
        myFriends.add("Shailesh");
        myFriends.add("Ankur");                 

        System.out.println("Friends Detail : After data added");
        // Displaying the output String with delimiter :
        System.out.println(myFriends);
	}

}

Output


Friends Detail : When no data added
No Friends Found
Friends Detail : After data added
Saurabh:Gaurav:Raghav:Shailesh:Ankur

Example 2: StringJoiner with a delimiter (:), prefix, and suffix

In this example, defined StringJoiner with a delimiter for values, prefix, and suffix for final delimited String.

import java.util.StringJoiner;

public class StringJoinerPrefixSuffixExample {

	public static void main(String[] args) {
		// Passing colon (:) as delimiter , prefix ({) and suffix (})
        StringJoiner myFriends = new StringJoiner(":","{","}"); 

        myFriends.setEmptyValue("No Friends Found");
        System.out.println("Friends Detail : When no data added");
        System.out.println("Friends Detail :"+myFriends);
        // Joining multiple strings by using add() method
        myFriends.add("Saurabh");
        myFriends.add("Gaurav");
        myFriends.add("Raghav");
        myFriends.add("Shailesh");
        myFriends.add("Ankur");
        System.out.println("Friends Detail : After data added");
        // Displaying the output String with delimiter :
        System.out.println(myFriends);
	}

}

Output


Friends Detail : When no data added
Friends Detail :No Friends Found
Friends Detail : After data added
{Saurabh:Gaurav:Raghav:Shailesh:Ankur}

Example 3: Merge StringJoiner 1 with a delimiter (:), StringJoiner 2 with a delimiter (,)

We can use StringJoiner.merge() method to merge the values of two StringJoiner. Here also use StringJoiner.length() method which returns the length of the final delimited String.

import java.util.StringJoiner;

public class StringJoinerMergeExample {

	public static void main(String[] args) {
	   // Passing Hyphen(:) as delimiter
        StringJoiner myFriends = new StringJoiner(":");
        // Joining multiple strings by using add() method
        myFriends.add("Saurabh");
        myFriends.add("Gaurav");
        myFriends.add("Raghav");
        myFriends.add("Shailesh");
        myFriends.add("Ankur");                 

        System.out.println("Friends Detail 1: After data added");
        // Displaying the output String with delimiter :
        System.out.println(myFriends); 

     // Passing Hyphen(:) as delimiter
        StringJoiner myFriends1 = new StringJoiner(",");
        // Joining multiple strings by using add() method
        myFriends1.add("Saurabh1");
        myFriends1.add("Gaurav1");
        myFriends1.add("Raghav1");
        myFriends1.add("Shailesh1");
        myFriends1.add("Ankur1");                 

        System.out.println("Friends Detail 2: After data added");
        // Displaying the output String with delimiter :
        System.out.println(myFriends1); 

        //Merge StringJoiner
        myFriends1.merge(myFriends);
        System.out.println("Result after merge Friends Detail 1 & 2:");
        System.out.println(myFriends1);

        //Length of String Joiner
        System.out.println(myFriends1.length());

	}

}

Output


Friends Detail 1: After data added
Saurabh:Gaurav:Raghav:Shailesh:Ankur
Friends Detail 2: After data added
Saurabh1,Gaurav1,Raghav1,Shailesh1,Ankur1
Result after merge Friends Detail 1 & 2:
Saurabh1,Gaurav1,Raghav1,Shailesh1,Ankur1,Saurabh:Gaurav:Raghav:Shailesh:Ankur
78

References

Java 8: Functional Interface


“An interface having exactly one abstract method is called Function Interface. Along with one abstract method can have any number of default and static methods.”

Points to Remember

  • This is also called as Single Abstract Method Interfaces or SAM Interfaces.
  • The default method having implementation is not considered as an abstract method.
  • An interface declares an abstract method overriding one of the public methods of java.lang.Object is not considered as an abstract method because any implementation of the interface will have an implementation from java.lang.Object or elsewhere.
  • If you declare an interface with @FunctionalInterface then the annotated interface must satisfy the requirements of a functional interface, if not match requirement will get the compile-time issue.

Note: Compiler will treat an interface as a functional interface if fulfilling conditions of Functional interface regardless of whether or not declared with @FunctionalInterface annotation.

Where to use Functional Interface

  • Functional Interface uses to represent Lambda Expressions.

Create your own functional interface

We can create our own Functional Interface by using @FunctionalInterface or Define interface having only one abstract method.

@FunctionalInterface
interface YourFunctionalInterface
{
 public int addValues(int a, int b);
}

Use of Functional Interface

We can use our own functional interface as above or predefined interface also such as Runnable, ActionListener, Comparator, etc. all these having a single abstract method.

Example: Use your own functional interface

In this example, define the functional interface “YourFunctionalInterface” definition by the lambda expression for arguments (a,b). When we call the functional interface method with the argument (120,100)  then it will make reference to the given definition of FunctionalInterface and return the result as 220.

public class CalculateClass {

   public static void main(String args[]) {
        // lambda expression
    YourFunctionalInterface sum = (a, b) -> a + b;
        System.out.println("Result: "+sum.addValues(120, 100));
    }
}

Output


Result: 220

Example: Use a predefined functional interface

In this thread, execution example consider both ways legacy and lambda expression to implement the run method and start threads.

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

// Implementing Runnable using anonymous class (legacy way)
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("Thread name : " + Thread.currentThread().getName());
}
};
Thread thread1 = new Thread(runnable1);

// Implementing Runnable using Lambda expression because Runnable having
// only one abstarct method run()
Runnable runnable2 = () -> {
System.out.println("Thread name : " + Thread.currentThread().getName());
};
Thread thread2 = new Thread(runnable2);

// Start Threads
thread1.start();
thread2.start();
}
}

References

Java : Data Types


Java is a strictly-typed programming language. It means all variable names must be declared with Data Type before its use. Each variable with Data Type specifies allowed values and size allocated to it.

Java allowed two types of data types:

  1. Primitive data types: These are the most basic data type in Java, used to the building blocks of manipulation. These 8 are the primitive data types: boolean, char, byte, short, int, long, float and double.
  2. Non-primitive data types: The non-primitive data types are predefined or user-defined Classes, Interfaces, and Arrays.

Except for primitive type all other data type variables are non-primitive type.

See Also: Java : Primitive Types size and default value

Java Data Types

 

Java : Program Execution


Java is a high level programming language. To run a java program (.java file) first need to compile by javac compiler that convert java code to byte code (.class file). Machine language for JVM is byte code that is same for all type JVM machines (i.e OS). After running java command, JVM executes the byte code gennerated by compiler and produce output.

For Example : Byte code generated on windows machine can be run on Mac or Linux OS and vice versa.

Java program exceution

JVM makes java portable (write once, run anywhere) and platform independent. Because each operating system has different JVM, however the machine language is byte code output they produce after execution of byte code is same across all operating systems.

See Also: JDK, JRE, JIT,SDK, JVM Introduction

 

JDK, JRE, JIT,SDK, JVM Introduction


JDK (Java  Development Kit)

JDK (Java Development Kit) is a superset of JRE (Java Runtime Environment), it contains everything that JRE has along with development tools such as compiler, debugger, etc.

JDK Java development Kit
Java Development Kit

See Also: Java: Program Execution

JRE (Java Runtime Environment)

JRE (Java Runtime Environment) provides the environment in which the JVM (Java Virtual Machine) runs. JRE contains JVM, class libraries, and other files excluding development tools such as compiler and debugger.

It means, you can run the code in JRE but you can’t develop and compile the code in JRE.

JDK and JRE Formulae

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) runs the program by using class, libraries, and files provided by JRE. JVM able to run a program written in Java and other languages also that are compiled to Java byte code. For Example Jython, Jruby, Closure, Apache, Groovy, Kotlin, etc.

JVM Architecture

Now discussed terminology used for JVM.

Class Loader

The class loader reads the .class file and saves the byte code in the method area.

Method Area

Method area holds class level information of .class file. JVM jave only one method area which is shared among all the classes.

Heap

Heap is a JVM memory part where objects are allocated. JVM creates an object for each .class Class file.

Stack

The stack is  JVM memory part but unlike Heap, it is used for storing temporary variables i.e method parameters.

PC Registers

PC Registers use to keeps the track of which instruction has been executed and which one is going to be executed. Because instructions are executed by threads, each thread has a separate PC register.

JIT Compiler

The JIT also called a Just-In-Time compiler. It used when a method is called. The JIT compiles the bytecode of that called method into native machine code. When a method has been compiled in native machine code, the JVM calls the compiled code of that method directly instead of interpreting it.

Native Method Stack

A native method used to access the runtime data areas of the virtual machine.

Native Method interface

It enables java code to call or be called by native applications wiritten in C or C++. Native applications are programs in low-level language that is specific to the hardware and OS of a system.

Garbage collection

Garbage Collection use for automatic memory management by JVM. It destroys unreferenced objects from Heap so that allocates more memory for new objects.

JDK Architecture & API’s Details

In this figure, you will get an idea of how these libraries and API’s are distributed on different levels.

JDK APIs Architecture

Difference between API and Methods

API (Application Programming Interface) interfaces that the rest of the world sees and can use. A Method can be part of the public interface or not. But an API executes a set of methods.

In java, APIs provide through the interface which is really a set of public methods. An API has contract like tells about method signatures and return type.

For Example List API’s provide different method signature and expected result as return type so that you can use according to your convenience.

Difference between JDK and SDK

JDK(Java Development Kit) is an extended subset of a SDK (Software Development Kit).

  • JDK includes tools for developing, debugging and monitoring of Java Program. It mainly responsible for the writing and running of Java programs.
  • SDK is composed of extra software related to a Web application or mobile application etc. such as Application Server, Documentation, Debuggers, Code Samples, Tutorials, GlassFish server, MySQL and IDE Netbeans.

Now, Oracle strongly suggests using the term JDK to refer to the Java SE Development Kit. The Java EE SDK is now available with or without the JDK, by which they specifically mean the Java SE 7 JDK.

See Also: Java Versions History

 

Java: final Vs finally Vs finalize


Here is a list of key differences between final, finally and finalize:

final

  • final is keyword
  • final is use with class, method, and variables
  • A final class can not be instantiated.
  • A final method can not be overridden.
  • A final variable can not be re-assigned.

final Example

A final variable can not be re-assigned.

final variable example
Final Variable can be reassigned

A final class can not be subclassed.

Final Class Example
Final class can not be subclassed

A final method can not be overridden.

Final method Example
final method can not be overloaded

finally

  • finally is keyword
  • finally block is used in exception handling that follows try block.
  • finally block of code always executes, whether an exception occurred or not. It’s used to run clean-type resources.
  • After java 7+ by using try-resources with files make finally as optional.

finally Example

In this example, you will see finally block executes, whether an exception occurred or not.

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

      try{
         int a = 20;
         int b = 0;
         int result = a/b;
      }catch(Exception e){
         System.out.println("Exception occured: "+ e.getMessage());
      }
      finally{
         System.out.println("Finally Exceuted.");
      }
   }
}

Output


Exception occured: / by zero
Finally Executed.

finalize

  • finalize is an object class method
  • finalize() method is called just before the object is destroyed or garbage collected.
  • finalize() method is used to clean up object resources before destroy.
  • If finalize() method call Explicitly, then it will be executed just like a normal method but the object won’t be deleted/destroyed.

See Also: Java: Garbage Collection Finalize() Method Example And Uses

finalize Example

In this example first calling finalize() method manually by test object which will behave as a normal method. For checking how Garbage collector call finalize() method setting test as null make object as unreferenced to make eligible for garbage collection. Here calling System.gc() to request JVM to call the garbage collector method. Now it’s up to JVM to call Garbage Collector or not. Usually, JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.

public class FinalizeMethodTest {

    public static void main(String[] args) {
        FinalizeMethodTest test=new FinalizeMethodTest();
        //manually calling finalize method is call like normal method
        test.finalize();

        //unreferenced object to make eligible for garbage collector
        test=null;

        //Requesting JVM to call Garbage Collector method
        System.gc();

        System.out.println("Main Method Completed !!");
    }
    @Override
     public void finalize()
        {
            System.out.println("finalize method overriden");
        }
}

Output


finalize method overriden
Main Method Completed !!
finalize method overriden

Here finalize() method calls two times one for manually another by garbage collector for cleaning up this test object.

 

Java: do-while loop


The Java do-while loop is a control flow statement, used to iterate a part of the program several times. this loop is preferred when the number of iteration is not fixed and you must have to execute the loop at least once.

In the do-while loop, statements inside will be executed at least once because the condition is checked after the loop body.

See Also: Java: Types of Looping Statements

Syntax:


do{  
//code to be executed  
}while(condition); 

Flow chart of do-while loop

do while loop flow chart

Example: Prints Even numbers between 1 to 20.

The same example writes in for and while loop also in a different way.

public class DoWhileLoopExample {
    public static void main(String[] args) {
    int i=1;
    System.out.println("Even numbers between 1 to 20:");
    do{
      if(i%2==0)
      {
      // If modulus of number after devision 2 is 0 then even number
      System.out.println(i);
       }
      i++;
      while(i<=20);
}
}

Output:


Even nmbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Infinitive do-while Loop

If you pass true or condition satisfied always as true in the do-while loop, it will be execute infinitive times.

Syntax:


do{  
//code to be executed  
}while(true);

Example: do-while infinite loop

public class DoWhileInfiniteLoopExample {
public static void main(String[] args) {
    do{
        System.out.println("FacingissuesOnIT");
    }while(true);
}
}

Output:


FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
.................
..............
............

ctrl+c

Note: Use press ctrl+c to exit from the program otherwise that will continue the print “FacingIssuesOnIT” statement.

Java: while loop


The Java while loop is a control flow statement, used to iterate a part of the program several times. It preferred when the number of iteration is not fixed.

See Also: Java: Types of Looping Statements

Syntax:


while(condition){  
//code to be executed  
}

Flow chart for while loop

while loop flow chart

Example: Print even numbers between 1 to 20.

This is the same example written in for loop also in the previous post.

class WhileLoopExample {
public static void main(String[] args) {
   System.out.println("Even Numbers between 1 to 20 :");
   int i=1;
   while(i<=20){
     // If modulus of number after devision 2 is 0 then even number
     if (i % 2 == 0) {
            System.out.println(i);
       }
      i++;
     }
   }
}

Output:


Even Numbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Infinitive While Loop

If you pass true or condition satisfied always as true in the while loop, it will be execute infinitive times.

Syntax:


while(true){  
//code to be executed  
}  

Example: while infinite loop

public class WhileExample2 {
public static void main(String[] args) {
    while(true){
        System.out.println("FacingIssuesOnIT”);
    }
}
}

Output:


FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
.................
..............
............

ctrl+c

Note: Use press ctrl+c to exit from the program otherwise that will continue the print “FacingIssuesOnIT” statement.

Java : for loop


The for loop in Java is a control flow statement used to iterate a part of the program several times. It’s most preferred when the number of the iteration is fixed.

In for loop are used in three ways :

  1. Simple For Loop
  2. Enhanced For Loop or For-each
  3. Labeled For Loop

Java Simple For Loop

In java, simple for loop is the same as C/C++. It consists of four parts:

Syntax


for(initialization;condition;increment/decrement){  
// code to be executed 
}
  • Initialization (Optional): It is the initialization condition which is executed once when the loop starts. We can initialize the variable or use an already initialized variable.
  • Condition (Optional): It is executed each time to test the condition of the loop. It return boolean values true or false but continues execution depend on until the condition is true.
  • Statement: The statement inside the loop is executed each time until the second condition is false.
  • Increment/Decrement (Optional): It increments or decrements the intialization variable value.

For Loop Flow Chart

for loop flow chart

Example:

Program to print even numbers between 1 to 20

public class SimpleForLoopExample {

	public static void main(String[] args) {
		System.out.println("Even Numbers between 1 to 20 :");
		for (int i = 1; i <= 20; i++) {
			// If modulus of number after devision 2 is 0 then even number
			if (i % 2 == 0) {
				System.out.println(i);
			}
		}
	}
}

Output


Even Numbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Nested For Loop

If we have a loop inside a loop that is called as nested loop. For each iteration of outer loop inner loop executes completely.

Example:
Print table for 1 to 10

public class NestedForLoop {

	public static void main(String[] args) {
     for(int i=1;i<=10;i++)
     {
    	 for(int j=1;j<=10;j++)
    	 {
    		System.out.printf("%-3d",(i*j)) ;
    	 }
    	 System.out.println();
     }

	}
}

Output:


1  2  3  4  5  6  7  8  9  10 
2  4  6  8  10 12 14 16 18 20 
3  6  9  12 15 18 21 24 27 30 
4  8  12 16 20 24 28 32 36 40 
5  10 15 20 25 30 35 40 45 50 
6  12 18 24 30 36 42 48 54 60 
7  14 21 28 35 42 49 56 63 70 
8  16 24 32 40 48 56 64 72 80 
9  18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100

Java for-each Loop (Java 5+)

The for-each loop is used to traverse object type like array or collection. Java for-each loop is easier than simple for loop because not required to increase or decrese indexes for accessing collections values.

Java for-each loop works on elements basis not index and returns element one by one in the defined variable.

Syntax:


for(Type var:array){  
//code to be executed  
}

Example:

public class ForEachLoopExample {
public static void main(String[] args) {
    //Declaring an array
    int numArr[]={10,20,30,40,50};
    //Print array by using for-each loop
    for(int i:numArr){
        System.out.println(i);
    }
}
}

Output

10
20
30
40
50

Java Labeled For Loop

By using labeled for loop can define a name of loop by using label before the for loop. It’s useful when nested for loop need to break/continue specific for loop.

Usually, break and continue keywords breaks/continues the innermost for loop only.

Syntax:


labelname:  
for(initialization;condition;incr/decr){  
//code to be executed  
}  

Example:

public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+” “+j);
}
}
}
}
Output:

1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the default behavior of any loop.

public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+” “+j);
}
}
}
}
Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax:

for(;;){
//code to be executed
}
Example:

//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println(“infinitive loop”);
}
}
}
Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.

Java: Program execution from Command Line and Eclipse with Arguments.


In the previous post First Java “Hello World” Program, you got some basic understanding for starting a Java Program. In this post, you will learn about to execute a Java Program from Eclipse and Commandline. Here consider both the case by passing with and without arguments to the main method().

Points to Remember

These are some points that need keep in mind while passing arguments from the eclipse or command line.

  • When you need to pass more than one argument. These values separated by spaces.
  • If passing an argument String value having space make sure to pass in the double quote (” “). For Example: “Saurabh Gupta”.
  • Always check for the length of  main() method argument otherwise you may get ArrayIndexOutOfBoundException if trying to access index beyond passed arguments.

Execute Java Program from Eclipse without Arguments

When your program not required any argument to pass in main() methods follow these steps to execute a program.

For Example :

public class TestProgram {

	public static void main(String[] args) {
		System.out.println("Hello World ! ");
	}
}

Output


Hellow World !
  • Step 1: Go to the Java Class file  “TestProgram”.java.
  • Step 2: Right-click on the file select option as  “Run As” -> “Java Application”.
  • Step 3: You will see the output in the console tab.

Execute Java Program from Eclipse with Arguments

When your program required arguments to pass in the main() method follow these steps to execute a program.

For Example:

In this program, main() method required three arguments to print for “First Name “, “Last Name ” and “Full Name”.

public class TestProgram {

	public static void main(String[] args) {
		System.out.println("Hello World ! ");

		System.out.println("Number of argument passed :"+args.length);
		//Check for number of argument passed from command line
		if (args != null && args.length == 3) {
			System.out.println("First Name :" + args[0]);
			System.out.println("Last Name :" + args[1]);
			System.out.println("Full Name :" + args[2]);
		}
	}
}

Output


Hello World ! 
Number of argument passed :3
First Name :Saurabh
Last Name :Gupta
Full Name :Saurabh Gupta
  • Step 1: Go to the Java Class file  “TestProgram”.java.
  • Step 2: Right-click on the file select option as  “Run As” -> “Run Configuration”.
  • Step 3: You will get pop up, Go to the “Arguments” tab pass arguments in the “Program Arguments” section as mentioned in the below screen for this example.
  • Step 4: Click on the Run Button.
  • Step 3: You will see the output in the console tab.

Eclipse Arguments Passing to java program

ss

ss

Java Program run from command line.jpg

 

 

ss

java program run commandline with argument

First Java “Hello World” Program


First Java “Hello World” Program

Here is the first Java program “Hello World” program for basic understanding about the Java Syntax and execution of a program.

public class HelloWorldFirstProgram {
    public static void main(String[] args) {
	    // Prints the string to the console.
        System.out.println("Hello World!");
    }
}

Output


Hello World !

See Also :

Explanation about each keyword

public: The keyword public is access modifier that denotes a method can be called from code in other classes, or that a class may be used by classes outside the class hierarchy.

static: The keyword static with method main() indicate a static method, which is associated with only class and not with the specific instance of the class. That can be called by class name.

void: The keyword void indicates that the main method does not return any value to the caller.
main method: The main method is a java launcher method, that is used to call by JVM to pass control to the program for execution.

See Also :

System.out.println

System.out.println is one of the most frequent statements used by java programmers for debugging purpose and prints logs in the console.

  • The System is the class defined public
  • Out is the public static object of System class of type PrintStream.
  • println() is a method of PrintSteam class as String.

See Also: Java: System.out Vs System.in Vs System.err classes and methods.

 

Java: System.out Vs System.in Vs System.err classes and methods.


The java.lang.System class, having three static members (in, out and err) that pre-initialize at JVM startup that’s what no need to initialize. These classes also known as Stream classes.

Out of these System.out is most frequent use by programmers to write output on the console.

System Stream Classes

Here is a list of System Stream classes objects:

  • System.in
  • System.out
  • System.err

System.in

System.in is an InputStream type object which is typically connected to the keyboard input of console programs.

Note: It’s generally used often, Mainly used by beginner-level programmers to insert input from the keyboard. Because when you consider for application-level data is commonly passed to program by:

  • Command-line arguments
  • Configuration files
  • Application GUI

See Also:

System.out

System.out is a PrintStream type used to outputs the data to the console.

Note: It’s the most frequent used Stream object to print out of the program and for debugging about the flow and values.

System.err

System.err is a PrintStream type mainly used to output an error texts to console.

Note: Some of IDE like eclipse show System.err output in the console in red color so that you can easily see error messages.

Example for System .in, System.out and System.err

In this example, you will see, How to insert value to a program by the keyboard by System.in. Output to console by System.out and for any error print by System.err.

System in out and Err Example
Example System.in, System.out and System.err

Output

System in out err result

Exchanging System Streams

By default System Stream class is to console, but we can also change System Streams by programmatical configuration for each type so that InputStream for System.in or OutputStream for System.out or System.err will read and write to the new stream.

  • System.setIn() : This method use to change input stream.
  • System.setOut() : This method use to change output stream.
  • System.setErr() : This method use to change error output stream.

See Also:

System.out Stream Change

In the below example, out will be got to the given file instead of default OutputStream as Console.

OutputStream output = new FileOutputStream("c:\\output\\FacingIssuesOnIT_logs.txt");
PrintStream printOut = new PrintStream(output);

//This method will change output stream.
System.setOut(printOut);

Java : Types of Statements


A java method body is a series of one or more statements. In a java programming language, a statement is a basic unit of execution which follows the syntax of the language and includes one or more clauses.

Note: All statements except blocks terminated by a semicolon(;).

Type of Java Statements

Java supports three different types of statements:

Blocks

A block is a series of zero or more statements between a matching set of open and close curly braces.  For example :

  • The bodies of methods and switch statements are blocks.
  • The bodies of if, for, while, and do-while statements may also be blocks.
  • You can also simply create a new block inside another block by enclosing code within curly braces. A block contained within another block is itself a statement of the outer block.
  • Blocks that contain no statements are called an empty block.

Example of Statements

At the high level below are some examples of statements. You can get more detail about each type of statement in the corresponding link.

Java Block and Types of Statements
Java Block and Types of Statements

References

 

Java : Control Flow Statements


Statements in java source code generally executed from top to bottom, in the order they appear. However, with control-flow statements, that order can be interrupted to implement decision making, branching or looping so that the Java program can run particular blocks of code based on certain conditions. Control flow statements categorize as below:

See Also: Type of Statements in Java

Java : Looping Statements


Programming language loops are control flow statements used when need to execute a set of instructions repeatedly when some conditions become true. There are three types of loops in java.

for loop

The for loop is used to iterates a part of the programs multiple times. It’s most preferred to use when the number of iteration is fixed.

For Detail Information follow: Java: for loop

Syntax


for(initialization;condition;increment/decrement){  
// code to be executed 
}

Example

//for loop
for(int i=1; i<=15; i++){
System.out.println(i);
}

The syntax for infinitive loop

for(;;){
//code to be executed
}

while loop

The while loop is used to executes a part of the programs repeatedly on the basis of given boolean condition. It’s most preferred when the number of the iteration is not fixed.

For Detail Information follow: Java: while loop

Syntax


while(condition){  
//code to be executed 
}

Example

//while loop
int i=1;
while(i<=10){
System.out.println(i);
i++;
}

The syntax for infinitive loop

while(true){
//code to be executed
}

do-while loop

The do-while loop is used to executes a part of the programs at least once and the further execution depends upon the given boolean condition. It’s preferred when the number of iteration is not fixed and you must have to execute the loop at least once.

For Detail Information follow: Java: do-while loop

Syntax

     
do{  
//code to be executed  
}while(condition); 

Example

//do-while loop
int i=1;
do{
System.out.println(i);
i++;
}while(i<=15);

The syntax for infinitive loop

do{
//code to be executed
}while(true);

Setup Java/JDK and Eclipse On Window & Linux


Before creating the Java project, the first thing is to check to JDK installed or not in your machine.

How to check Java version in your machine?

Window

  • Go to search
  • Type cmd and enter or search for Command prompt
  • You will see a black screen for the command prompt as below.
  • Type java -version to get detail about it.

Linux

  • On the current screen type command as java -version to get detail about it.

Java Version Check.jpg

The above screen is for the case when java is installed on your screen. If JDK/JRE is not installed on your machine then you will get a message like “Java is not recognized as an internal-external command.”

How to setup Java from Initial?

If JDK/JRE is not set up in your machine then follow below steps:

Download JDK from this siteDownload JDK Latest Version

Windows

  • After downloading click on the .exe file to install
  • Follow all steps as the next button and continue as long as a process not complete.
  • Default download location for Java will be  “C:\Program Files\Java\jdkVerXYZ”

Java JDK Directory

To access Java from command prompts or IDE need to configure environment variables as JAVA_HOME and Path. The value of JAVA_HOME would be home directory path where JDK installed and Path would be (JAVA_HOME/bin)

Follow these steps to configure the environment variables

  • Go to Computer ->right click-> Properties -> Advance System Settings->System Variable
  • or Go to search type ENV and click on enter.
  • Enter that value of JAVA_HOME as below
Java_Home
Set JAVA_HOME

 

 

 

 

  • Set the Path by appending at last as below %JAVA_HOME%/bin;

Java Path Settings

  • Follow the above steps to check Java versions.

Linux 

  • Download JDK and untar it.
  • Go to your home directory/ sudo directory and set JAVA_HOME and Path in .bashrc file as below:

export JAVA_HOME=/opt/app/<installation directory>/jdk1.8.0_66

          export Path=%JAVA_HOME%/bin:$Path

  •   Save .bashrc file
  •  Now run java -version  to check configuration is successful.

Configure Eclipse IDE

Download Eclipse: Download Eclipse Latest Version

  • Click on the installable of Eclipse IDE.
  • Continue the installation by next click.
  • Select the path of JDK as installed.
  • Select the workspace location for your projects.

Now you are ready to create new projects in Eclipse IDE.

See Also :

Java: How to generate Java doc by command line and Eclipse IDE?


In the previous post, you learn about the type of comments supported by Java. Now in this post will explain the ways to generate Java documentation of project by both ways:

  1. Java Doc by Eclipse
  2. Java Doc from Commandline

Now we will continue with the same previous comments file example to generate java documents by both ways:

Java Comments Type

Java Doc generation from Eclipse

Follow the below steps to generate Java API documentation:

  • Go to Project tab
  • Select the option “Generate Javadoc”
  • Follow steps in the screen as below:
  • Click on Next button
  • Click on Next button again
  • Finally, click on Finish button

java Doc generation in eclipse 1.jpg

In your console logs will see a link like as below to java doc of file.

D:\Saurabh Gupta\Workspace-learning\JavaExamples\doc\com\common\statements\CalculatorTest.html

Open this file you will see java doc comments on class and method level of this file as highlighted:

Java doc generation eclipse 2

Java Doc generation from Command-line

To generate Java doc from command-line you can use the below command.  It will generate Java doc file in your user directory (default) on below location:

C:/Users/username/CalculatorTest.html


javadoc you_java_file_path

You can use javadoc command as below.

Java doc generation from commnad line

Here are some of the scenarios to generate java doc:

Java doc on a specific location from the package

You can use below command to generate Javadoc for all files with the package from the projects folder:

Syntax:


C:\myprojects> javadoc -d [path to javadoc destination directory] [package name]

Example:


C:\myprojects> javadoc -d C:\javadoc\test com.fiot.test

Java doc generation execution from some other location

You can use the below command when you need to generate java docs and want to run the script from a different location.

Syntax:


C:\> javadoc -d [path to javadoc destination directory] -sourcepath [path to package directory] [package name]

Example:


C:\> javadoc -d C:\javadoc\test -sourcepath C:\myprojects com.fiot.test

Java doc generation for selected files

You can use the below command when you need to generate Javadoc for specific files then you can mentioned files path separated by spaces (or use an asterisk(*) for a wild card).

Syntax:


C:\> javadoc -d [path to javadoc destination directory] 

Example:


C:\> javadoc -d C:\javadoc\test C:\projects\com\test\file1.java

If you need to generate Javadoc from the same folder use wildcard(*) and mentioned in the given example.

Example:


E:\MyJavaFileFolder> javadoc *.java

References

https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html

Java Script : Debugging


In JavaScript debugging can be performed in two ways:

  1. Generating Alerts
  2. Printing in Console

Generating Alerts

By generating alerts in javascript you can check what values are getting the pass, which method is getting executed etc . on the page popup.


var a= 5;

alert(a);

alert("Hello world !!");

When you load you page you will get alert like this:
Java script debug alert

Note : After you testing complete you have to remove these alert statment otherwise duw to lots of alerts, end user will frustrate and that would be bad experience to user.

Printing in Console

For printing console logs help to analyse the execution of statement and values so that how flow got executed.

Syntax :


console.log(statement or text or variable);

Example


  

console.log("Hello World !"); 


For checking debug logs of your page: Press Cntr + F12 function key to you open browser screen then go to console as in below screen.

Java script debug

Java : Types of Comments


Java comments are used to provide information or description about the class, statements, variable and method for future reference so that easy to understand code for future enhancement. Java comments statements don’t compile. It also helps to hide unused code.

Types of Java Comments

Java supports 3 types of comments statments:

  1. Single Line Comment
  2. Multi line Comment
  3. Documentation Comment
Java Comments Type
Java : Types of Comments

Single Line Comment

Single line comment statement is use to comment single line.


//Single line commnet statement

Multi Line Comment

Multi line comment statement is use to comment multiple line.


/*Multi line 
 *commnet statement
 */

Documentation Comment

The documentation comment statement is used to create documentation of APIs. To generate documentation of API, you need to use the Javadoc tool.


/**
 *Multi line 
 *Java doc
 *commnet statement
 */
 

See Also: How to generate Java doc by command line and Eclipse IDE

Comments Type Example

In this Calculator example all types of comments.

 /**
 * This is a calculator class to perform
 * mathematical operations
 * @author saurabh.gupta1
 *
 */
public class CalculatorTest {

public static void main(String[] args) {

CalculatorTest calculator=new CalculatorTest();
//Calling add method to get sum of
int sum=calculator.add(10, 20);

/*
* This is System method to
* debug logs statement in console
*/
System.out.println("Sum of A =10 and B=20 is "+sum);
}
/**
* This method add passing values
* and return sum
* @param a
* @param b
* @return
*/
public int add(int a, int b)
{
return a+b;
}
}
 

Output


 Sum of A =10 and B=20 is 30
 

 

Java : Object Creation Way


In java objects can be created by five ways as follows:

  1. Object Creation by new
  2. Object Creation by reflection Class.newInstance() method.
  3. Object Creation by clone() method
  4. Object creation by the Annonymous Object.
  5. Object Creation by  Deserialization

Object Creation Way Example

Here is a complete example after considering all ways for object creations:

ackage objects;

import java.io.Serializable;

//Cloneable and Serializable is marker interface
public class Calculation implements Cloneable, Serializable{
	public int x=5;
	void fact(int n) {
		int fact = 1;
		for (int i = 1; i <= n; i++) {
			fact = fact * i;
		}
		System.out.println("factorial is " + fact);
	}
	public Object clone()throws CloneNotSupportedException{
		return super.clone();
		} 

}

package objects;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectCreationWay {

	public static void main(String[] args) {
		System.out.println("Object Creation by New");
		// Object Creation by using New
		Calculation cal = new Calculation();
		cal.fact(3);

		System.out.println("\nObject Creation by Reflection");
		// Object creation by newInstance method by reflection
		try {
			Class calculationClass = Class
					.forName("objects.Calculation");
			Calculation calc = (Calculation) calculationClass.newInstance();
			calc.fact(5);
		} catch (ClassNotFoundException |IllegalAccessException |InstantiationException ex) {
			ex.printStackTrace();
			//Multiple exception in single catch example in java  7
		} 

		System.out.println("\nObject Creation by Clone");
		/**
		 * Object creation by clone
		 */
		try {
			System.out.println(cal.x);
			Calculation cal2 = (Calculation) cal.clone();
			System.out.println(cal2.x);
			cal.x=10;
			//No change on clone object
			System.out.println(cal2.x);
		} catch (CloneNotSupportedException ex) {
			ex.printStackTrace();
		}

		System.out.println("\nObject Creation by Annonymous");
		/**
		 * Annonymous simply means nameless.An object that have no reference is
		 * known as annonymous object. If you have to use an object only once,
		 * annonymous object is a good approach.
		 */
		// calling method with annonymous object
		new Calculation().fact(5);

		System.out.println("\nObject Creation by  Deserialization");
		//By using deserialization of serialize object

		searializeObject(); //method to serialization of calculation object

		//By deserialization create object of Calculation Object

		Calculation c=deserializationOfObject();
		c.fact(5);

	}
	//serialize from java object to Object Stream
	public static void searializeObject()
	{
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(
					"calculator.ser");

			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

			Calculation c= new Calculation();
			c.x=12;
			//serialization of object
			objectOutputStream.writeObject(c);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	//deserialization of objectStream to Java object
	public static Calculation deserializationOfObject()
	{

			Calculation c = null;

			try {
				FileInputStream fileInputStream = new FileInputStream("calculator.ser");

				ObjectInputStream objectInputStream = new ObjectInputStream(
						fileInputStream);

				c = (Calculation) objectInputStream.readObject();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {

				e.printStackTrace();
			}

			return c;
	}

}

Output


Object Creation by New
factorial is 6

Object Creation by Reflection
factorial is 120

Object Creation by Clone
5
5
5

Object Creation by Annonymous
factorial is 120

Object Creation by  Deserialization
factorial is 120

Java : Unary Operators


The Unary Arithmetic Operators are used to increasing or decreasing the value of an operand by adding 1 to the variable, whereas the decrement operator decreases a value.

These two operators have two forms: Postfix and  Prefix to increment or decrement in appropriate variables. These two operators can be placed before or after variables. It’s called a prefix is placed before variable and called as postfix if placed after the variable.

Syntax:


//Postfix
val=a++; //Store the  value of "a" in val then increments.
val=a--; //Store the  value of "a" in val then decrements.

//Prefix
val=++a; //First increment in value of "a" then store in val.
val=--a; //First decrement in value of "a" then store in val.

See Also :

Unary Operator Example


public class UnaryOperatorTest {
public static void main(String[] args) {
int r = 8;
System.out.println("r=: " + r++);
System.out.println("r=: " + r);

int x = 7;
System.out.println("x=: " + x--);
System.out.println("x=: " + x);

int y = 9;
System.out.println("y=: " + ++y);

int p = 5;
System.out.println("p=: " + --p);
}
}

Output


r=: 8
r=: 9

x=:7
x=:6

y=:10

p=:4

Java : Type of Operators


Java supports the following categories of operators as follows:

    1. Arithmetic Operators
    2. Assignment Operators
    3. Unary Operators
    4. Relational Operators
    5. Bitwise Shift and Logical Operators
    6. Ternary Operator
    7. instanceof Operator

See Also: Precedence of Operators in Expression Solutions

 

Java : Bitwise Logical Operators


Java supports several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. These Bitwise operator works on bits and performs the bit-by-bit operation.

For Example: Assume if a = 60 and b = 13; now in the binary format they will define follows:


a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

See Also :

Here is a complete list of bitwise operators:

Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>> Shift right assignment
>>>= Shift right zero-fill assignment
<<= Shift left assignment

Bitwise Logical Operators:

Here is a table of the result after performing a bitwise operator on values A  and B.

A B A | B A & B A ^ B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0

Bitwise Operator Example

public class BitwiseOperatorTest {

	public static void main(String[] args) {
		//Bitwise And
	 System.out.println(9 & 7);

	 //Bitwise or
	 System.out.println(19 | 7);

	 //Bitwise XOR
	 System.out.println(9 ^ 7);

	 //left Shift
	 System.out.println(9 << 7);

	 //Bitwise complement(~), Inverts ones and zeros in a number

	 int i = 1;
	    System.out.println(i);

	    int j = ~i + 1;
	    System.out.println(j);

	    i = ~j + 1;
	    System.out.println(i);

	    //Example Bitwise demonstration
	    String binary[] = {
	    	      "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
	    	      "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
		    	    };
    int a = 3; // 0 + 2 + 1 or 0011 in binary
    int b = 6; // 4 + 2 + 0 or 0110 in binary
    int c = a | b;
    int d = a & b;
    int e = a ^ b;
    int f = (~a & b) | (a & ~b);
    int g = ~a & 0x0f;

    System.out.println("        a = " + binary[a]);
    System.out.println("        b = " + binary[b]);
    System.out.println("      a|b = " + binary[c]);
    System.out.println("      a&b = " + binary[d]);
    System.out.println("      a^b = " + binary[e]);
    System.out.println("~a&b|a&~b = " + binary[f]);
    System.out.println("       ~a = " + binary[g]);
	}
}

Output


1
23
14
1152
1
-1
1
        a = 0011
        b = 0110
      a|b = 0111
      a&b = 0010
      a^b = 0101
~a&b|a&~b = 0101
       ~a = 1100

Java : Arithmetic operators


The Arithmetic operators are used to perform arithmetic operations on numeric values of type int, float, double, short and byte. Assignment operators are also considered as arithmetic operators.

Here is the complete list of arithmetic operators:

Operator Result
+ Addition
Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Decrement

An assignment statement has three elements:

  1. The variable to store the result,
  2. The assignment operator: =,
  3. An arithmetic expression

For Example, Here the assignment operator will add value 5 on the previous value of a.


int a=1;
a+=5;

See Also :

Arithmetic Operators Example

public class ArithmaticOperatorTest {

	public static void main(String[] args) {
		ArithmaticOperatorTest test=new ArithmaticOperatorTest();
		test.testArithmaticOperatorWithIntegers();
		test.testArithmaticOperatorWithFloat();
		test.testModulusOperator();
                test.testAssignmentOperators();
	}
	public void testArithmaticOperatorWithIntegers()
	{
		// arithmetic using integers
	     System.out.println("Integer Arithmetic Operations");
	     int a = 2 + 2;
	     int b = a * 3;
	     int c = b / 5;
	     int d = c - a;
	     int e = -d;
	     System.out.println("a = " + a);
	     System.out.println("b = " + b);
	     System.out.println("c = " + c);
	     System.out.println("d = " + d);
	     System.out.println("e = " + e);
	}

	public void testArithmaticOperatorWithFloat()
	{
		 int a=2;
		// arithmetic using doubles
	     System.out.println("\nFloating Point Arithmetic Operations");
	     double da = 2 + 2;
	     double db = da * 3;
	     double dc = db / 5;
	     double dd = dc - a;
	     double de = -dd;
	     System.out.println("da = " + da);
	     System.out.println("db = " + db);
	     System.out.println("dc = " + dc);
	     System.out.println("dd = " + dd);
	     System.out.println("de = " + de);
	}

	public void testModulusOperator()
	{
		 //Modulus :Modulus operator %: obtain the remainder after a division
		 System.out.println("\nModulus Arithmetic Operator");
	     int a = 5 % 2;
	     int b = 13 % 3;
	     int c = 8 % -3;

	     System.out.println(a);
	     System.out.println(b);
	     System.out.println(c);
	}

     public void testAssignmentOperator()
{ 			

System.out.println("Assignment Operators");
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);

}
}

Output


Integer Arithmetic Operations
a = 4
b = 12
c = 2
d = -2
e = 2

Floating Point Arithmetic Operations
da = 4.0
db = 12.0
dc = 2.4
dd = 0.3999999999999999
de = -0.3999999999999999

Modulus Arithmetic Operator
1
1
2
Assignment Operators
5
8
43
7

Java : Instanceof Operator


The instanceof keyword can be used to test if an object is of a specified type. To check with InstanceOf follow below Syntax:

if (objectRef instanceof type)

Points to Remember

  • Applying instanceof on a null reference variable returns false because null values do not have any reference.
  • Applying instance to check subclass ‘is a’ type of its superclass will return true.

See Also :

instanceof Operator Example

In this example, you will learn about to use of instanceof operator to check the type of predefined classes as well as user-defined classes.

Here the parent is superclass and ChildA and ChildB are subclasses of the parent class.


public class Parent {

}

public class ChildA extends Parent{
	public ChildA() {
	    super();
	  }
<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>}

public class ChildB extends Parent{
	public ChildB() {
	    super();
	  }
}

Here you will see, how to apply instanceof and check the type before performing any operation with objects.

import java.util.ArrayList;
import java.util.Vector;

public class InstanceOfOperatorTest {

	public static void main(String[] args) {
		String str="Saurabh";

		//To check of String class
		if(str instanceof java.lang.String)
		{
			System.out.println("It's String class");
		}

		String strNull=null;
		//to check with null value always retunn false because null values not have any reference.
		if(strNull instanceof java.lang.String)
		{
			System.out.println("It's String class");
		}

		//To check parent and Child text
		Parent p=new Parent();
		ChildA a=new ChildA();
		ChildB b=new ChildB();
		Parent pA=new ChildA();
		Parent pB=new ChildB();

	   if(p instanceof Parent)
		   System.out.println("It's Parent Class");

	   if(a instanceof ChildA)
		   System.out.println("It's ChildA Class");

	   if(b instanceof ChildB)
		   System.out.println("It's ChildB Class");

	   if(pA instanceof Parent)
		   System.out.println("ChildA is type of Parent Class");

	   if(pB instanceof Parent)
		   System.out.println("ChildB is type of Parent Class");

	   //This statement will not execute because not possible case.
	   if(p instanceof ChildA)
		   System.out.println("Parent is type of ChildA Class");

	   //To check object of Collections
	   Object object = new Vector();
	    if (object instanceof Vector)
	      System.out.println("Object was an instance of the class java.util.Vector");
	    else if (object instanceof ArrayList)
	      System.out.println("Object was an instance of the class java.util.ArrayList");
	    else
	      System.out.println("Object was an instance of the " + object.getClass());

	}

}

Output


It's String class
It's Parent Class
It's ChildA Class
It's ChildB Class
ChildA is type of Parent Class
ChildB is type of Parent Class
Object was an instance of the class java.util.Vector

Java : Boolean Logical Operators


The Boolean logical operators operate only with Boolean Operands (true or false) where combine results of expressions will be boolean after performing two or more boolean logical operators.

Here is a complete list of Boolean Logical Operators:

Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else

Table to the effect of each operator

Here is a list of results when combining boolean operators’ operands values.

A B A | B A & B A ^ B !A
False False False False False True
True False True False True False
False True True False True True
True True True True False False

See Also :

Boolean Logical Operators Example

public class BooleanLogicalOperatorTest {

		    public static void main(String args[])
		    {

		        boolean a = false;
		        boolean b = true;

		        boolean c = a | b;
		        boolean d = a & b;
		        boolean e = a ^ b;
		        boolean f = (!a & b) | (a & !b);
		        boolean g = !a;

		        System.out.println("            a = " + a);
		        System.out.println("            b = " + b);
		        System.out.println("          a|b = " + c);
		        System.out.println("          a&b = " + d);
		        System.out.println("          a^b = " + e);
		        System.out.println("(!a&b)|(a&!b) = " + f);
		        System.out.println("           !a = " + g);

	

Output



            a = false
            b = true
          a|b = true
          a&b = false
          a^b = true
(!a&b)|(a&!b) = true
           !a = truecode>

Java : Relational Operators


Relational operators also called as comparison operators used to check the relation between two operands and return the result as a boolean value.

For Example:

x < y (x is less than y) this expression will return the result as true if x is less than y, otherwise false.

See Also :

Here is a complete list of relational operators:

Relational Operators Description
> greater than
>= greater than or equal to
== equal to
!= not equal to
<= less than or equal to
< less than

Relation Operator Example

import java.util.Random;

public class RelationalOperatorTest {

	public static void main(String[] args) {
		Random rand = new Random();
	    int i = rand.nextInt(200);
	    int j = rand.nextInt(200);
	    System.out.println("i = " + i);
	    System.out.println("j = " + j);
	    System.out.println("i > j is " + (i > j));
	    System.out.println("i = j));
	    System.out.println("i <= j is " + (i <= j));
	    System.out.println("i == j is " + (i == j));
	    System.out.println("i != j is " + (i != j));

	    System.out.println("(i < 10) && (j < 10) is " + ((i < 10) && (j < 10)));
	    System.out.println("(i < 10) || (j < 10) is " + ((i < 10) || (j < 10)));

	}

}

Output


i = 185
j = 170
i > j is true
i = j is true
i <= j is false
i == j is false
i != j is true
(i < 10) && (j < 10) is false
(i < 10) || (j < 10) is false

Java : if-else-if Statement


The if-else-if statement is the decision-making statement, Use If the if-statement conditional statement execution result is false then control will reach to check conditions for an else-if statement. If the result is true, block associated with else-if statement will execute otherwise control will reach to else block. We can add multiple else-if statements consecutively.

Syntax:

if(test_expression)
{
   //execute your code
}
else if(test_expression n)
{
   //execute your code
}
else
{
   //execute your code
}

Note :
An if-else-if statement else is an optional clause. Below is the format without the else clause:

if (test-expression)
{
statement
}
else if (test-expression)
{
statement
}

See Also :

if-else-if Statement Example

public class IfStatementTest{

   public static void main(String args[]){
      int a=20;

      if(a>0){
         System.out.println("a is positive number");
      }
	  if(a<0){
         System.out.println("a is negative number");
      }
	  else{
         System.out.println("a is zero");
      }
}

Output


a is positive number

Note :
The if-else-if statement can be a simple statement terminated by a semicolon or a block enclosed in curly braces.
For Example, the Below code is equivalent to the same as the above example and returns the same result.

public class IfElseIf{

   public static void main(String args[]){
      int a=20;

      if(a>0)
         System.out.println("a is positive number");
      else if(a<0)
         System.out.println("a is negative number or zero");
      else
         System.out.println("a is zero");

}

Recommendation :

  • For a better understanding of code always use curly braces ({}) with if, if-else-if or if-else statements.
  • It always creates confusion when more than one statement is in code.

Java: if-else Statement


The if-else statement is the decision-making statement, Use with conditional expression execution result is true then only the block associated with if statement will execute otherwise control will reach to else block.

Syntax:

if(test_expression)
{
   //execute your code
}
else
{
   //execute your code
}

Note :
In if-else statement else is an optional clause. Below is the format without the else clause:

if (test-expression)
{
statement
}

See Also :

if-else Statement Example

public class IfElseStatementTest{

   public static void main(String args[]){
      int a=20;

      if(a>0){
         System.out.println("a is positive number");
      }
	  else{
         System.out.println("a is negative number or zero");
      }
}

Output


a is positive number

Note :
The if-else statement can be a simple statement terminated by a semicolon or a block enclosed in curly braces.
For Example: Below code is equivalent to same as above example and return same result.

public class IfStatementTest{

   public static void main(String args[]){
      int a=20;

      if(a>0)
         System.out.println("a is positive number");
      else
         System.out.println("a is negative number or zero");

}

Recommendation :

  • For better understanding of code always use curly braces ({}) with if , if-else-if or if-else statements.
  • It always create confusion when more than one statement are in code.

 

Java: Switch Case Statement


The switch statement is a decision-making statement, also called a multi-way branch statement. It provides an easy way to jump execution to different parts of code based on the case value match with expression. This expression result allowed type as byte, short, char, and int primitive data types.

Note: After java 7+, it also allowed to work with enumerated types ( Enums in java), the String class and Wrapper classes.

Points to remember about Switch-Case statements

  • The value data type for a case must be the same data type as the variable in the switch.
  • The value for a case must be a constant or a literal.
    The value for the case, Variables are not allowed.
  • Duplicate case values are not allowed.
  • The break statement (optional) is used inside the switch to terminate a statement sequence.
  • If break statment is omitted, execution will continue on into the next case.
  • The default statement (optional) can appear anywhere inside the switch block. In case, if it is placed not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement.

See Also :

Syntax:

switch(variable)
{
case 1:
   //execute your code
break;

case n:
   //execute your code
break;

default:
   //execute your code
break;
}

Note:

  • The switch statement is fast when compared with the case of multiple else if because it directly jumps to match condition.

Switch-Case Example

ublic class SwitchCaseTest {

	public static void main(String[] args){
		        int month = 5;
		        String monthString; 

		        // switch statement with int data type
		        switch (month) {
		        case 1:
		        	monthString = "January";
		            break;
		        case 2:
		        	monthString = "February";
		            break;
		        case 3:
		        	monthString = "March";
		            break;
		        case 4:
		        	monthString = "April";
		            break;
		        case 5:
		        	monthString = "May";
		            break;
		        case 6:
		        	monthString = "June";
		            break;
		        case 7:
		        	monthString = "July";
		            break;
		        case 8:
		        	monthString = "August";
		            break;
		        case 9:
		        	monthString = "September";
		            break;
		        case 10:
		        	monthString = "October";
		            break;
		        case 11:
		        	monthString = "November";
		            break;
		        case 12:
		        	monthString = "December";
		            break;
		        default:
		        	monthString = "Invalid Month";
		            break;
		        }
		        System.out.println("Selected Month "+month+" is "+monthString);
		    }
		}

Output


Selected Month 5 is May

 

Java : if Statement


The if-statement is a decision-making statement, used to control the program flow based on some conditional statements. If the execution result of the statement is true then only the block associated with if-statement will execute otherwise skipped. This if-statement is the simplest way to modify the control execution flow of the program.
Syntax:

if(test_expression)
{
    statement 1;
    statement 2;
    ...
}

See Also :

if Statement Example

public class IfStatementTest{

   public static void main(String args[]){
      int a=20;

      if(a>0){
         System.out.println("a is positive number");
      }

	  if(a<0){
         System.out.println("a is negative number");
      }
}

Output


a is positive number

Note :
The if statement can be a simple statement terminated by a semicolon or a block enclosed in curly braces.
For Example, the Below code is equivalent to the same as the above example and return the same result.

public class IfStatementTest{

   public static void main(String args[]){
      int a=20;

      if(a>0)
         System.out.println("a is positive number");

	  if(a<0)
         System.out.println("a is negative number");

}

Recommendation :

  • For better undesirability of code always use curly braces ({}) with if, if-else-if or if-else statements.
  • It always creates confusion when more than one statement is in code.

Java : Decision Making Statements


All the program statements in java executed sequentially in the order in which they appear. This order of execution can change when there is used jumping statements or the repetition of certain statements or any decision making statements.

These are some decision making statements:

Below is the syntax for each decision making statements. For more in-depth knowledge follow the link corresponding to it.

See Also :

if statement

If the statement is used to control the program flow based on some conditional statements. If the execution result of the statement is true then only the block associated with if-statement will execute otherwise skipped. This if-statement is the simplest way to modify the control execution flow of the program.
Syntax:

if(test_expression)
{
    statement 1;
    statement 2;
    ...
}

See Also: if statement in detail with example

if-else statement

If this conditional expression execution result is true then only the block associated with if statement will execute otherwise control will reach to else block.

Syntax:

if(test_expression)
{
   //execute your code
}
else
{
   //execute your code
}

See Also: if-else statement in detail with example

else-if Statement

If the if-statement conditional statement execution result is false then control will reach to check conditions for an else-if statement. If the result is true, block associated with if-else statement will execute otherwise control will reach to else block.

Syntax:

if(test_expression)
{
   //execute your code
}
else if(test_expression n)
{
   //execute your code
}
else
{
   //execute your code
}

See Also: else-if statement in detail with example

Switch Statement

The switch statement is used when there are multiple possibilities of if blocks. When there is a chance to implement multiple if-else-if statements better go with a switch statement.

Syntax:

switch(variable)
{
case 1:
   //execute your code
break;

case n:
   //execute your code
break;

default:
   //execute your code
break;
}

See Also: switch statement in detail with example

Note:

  • After the end of each block for the case it is necessary to insert a break statement because if you do not use the break statement, all consecutive blocks of codes will get executed after matching the case block.
  • The switch statement is fast when compared with the case of multiple else if because it directly jumps to match condition.

Reachability of Statements


In decision making statements, must write in such a way so that at least for one exception condition java program must be reachable. There must be at least one exception path of execution that will “reach” to statement.

For Example
This code will not compile because ++count is unreachable.

class TestExample {
	public static void main(String[] args) {
	int count = 0;
	//This won't compile because reachability rule not with while
	//statments inside block for false
	while (false) {
		++count;
		}
	}
}

The exception to the reachability rule apply with the if statement.
The following code does compile:

class TestExample {
	public static void main(String[] args) {
	// This compiles fine.
	int count = 0;
	if (false)
	{
	++count;
	}
}
}

Note: If statement is special so that can be used for conditional compilation. In above code would compile file , but the if (false) { ++Count; } code would not appear in the class file.

Java : Ternary/Conditional Operator


The Ternary Operator also knew as Conditional Operator. If this logical expression result is true then only block or statements of expression1 will execute otherwise control will reach to expression2.

Ternary operator is equivalent to if-else statement If this logical expression execution result is true then only the block associated with if statement will execute otherwise control will reach to else block.

Ternary Operator or conditional Operator

Note: Ternary operators use when need to reduce the number of line of code for better readability.

See Also :

Ternary Operator Example

In this example, the ternary operator uses to decide the category of a person based on age. another example is to decide odd or even number.

public class TernaryOperatorTest {

	public static void main(String[] args) {
		//age test
		int age =25;

		String ageCategory=age<18? "Minor" : "Adult";
		System.out.println("Category for Age :" + age +" is"+ ageCategory );

		//Odd even test
		int number=50;
		boolean isEven= number%2==0 ? true: false;

		System.out.println("Number :" + 50 +" is even "+ isEven );
	}

}

Output


Category for Age :25 isAdult
Number :50 is even true

Java : Assignment Operators


Assignment Operator also called as op= operators and it’s used to reduce the expression size.

Following is the list of complete op= operators



+=
-=
*=
/=
%=
<>=
>>>=
&=
|=
^= 

See Also :

For Example : count +=2 has the will return the same result as expression statement : count = count + 2 ;

public class TestClass {

  public static void main(String[] arg) {
    int count1 = 5 , count2 = 5;

	//Calculation with assignment operator
    count1 += 2;
    System.out.println(count1);
    //equivalent matematical operation
    count2 = count2 + 2;
    System.out.println(count2);
  }
}

Output


7
7

Java : Operators Precedence in Expression


In an expression statement, precedence decides the order of operations performed based on operator use. Following is the list all operators in Java and it’s having precedence and execution direct of operators.

“Operators with higher precedence are executed before those of lower precedence.”

Precedence Operator Description Association
1 ++,– Postincrement, Postdecrement R -> L
2 ++,–+,- ~ ! Pre-increment, Predecrement Unary plus, unary minus Bitwise complement Boolean NOT R -> L
3 new
(Type)
Create Object
Typecast
R -> L
4 *,/,% Multiplication, division, remainder L -> R
5 +-
+
Addition, subtraction
String Concatenation
L -> R
6 <>, >>> Left shift, right shift, unsigned right shift L -> R
7 <, , >=instanceof Type Comparison L -> R
8 ==, !=
==, !=
Value equality and inequality
Reference equality and inequality
L -> R
9 &
&
Boolean AND
Bitwise AND
L -> R
10 ^
^
Boolean XOR
Bitwise XOR
L -> R
11 |
|
Boolean OR
Bitwise OR
L -> R
12 && Conditional AND L -> R
13 || Conditional OR L -> R
14 ?: Conditional Ternary Operator L -> R
15 =,+=,-=,*=,/ =,%=,&=,^=, |=,<> =,>>>= Assignment Operators R -> L

See Also :

Valid Variations of main() in Java


Main method is launcher method acts as an entry point for the JVM to start execution of a program. JVM always looks the main() method signature to launch the program. Below are different variation of main() method that are valid in Java.

  1. Default Prototype: This most  preferred way to write main() method in Java
    class TestClass
    {
        public static void main(String[] args)
        {
            System.out.println("Main Method");
        }
    }
    

    Meaning of the main Syntax:

    • main(): This is launcher method configured in the JVM to initiate execution of a program.
    • String[]: These are parameters passed as command line arguments.
    • public: This keyword is access modifier to define scope of a method. For JVM can execute the method from anywhere.
    • static: This keyword is Non access modifier use to show part of a class.Here use with Main method so that called by JVM without any object.
    • void: The main method doesn’t return anything. void keyword use to as part of method signature if there is no return type.
  2. Order of Modifiers: We can swap position of modifiers (static and public) in main method.
    class TestClass
    {
        static public void main(String[] args)
        {
            System.out.println("Main Method");
        }
    }
    
  3. Variants of String Array Arguments: We can place square brackets at different positions or use varargs (…) for arguments in main method.
             Arguments Array Declaration (Way 1):

    class TestClass
    {
        public static void main(String[] args)
        {
            System.out.println("Main Method");
        }
    }
    

    Arguments Array Declaration (Way 2):

    class TestClass
    {
    	public static void main(String args[])
    	{
    		System.out.println("Main Method");
    	}
    }
    

    Arguments with Variants:

    class TestClass
    {
    	public static void main(String...args)
    	{
    		System.out.println("Main Method");
    	}
    }
    
  4. Final Modifier to static main method: We can make main() as final.
    class Testclass
    {
        public final static void main(String[] args)
        {
            System.out.println("Main Method");
        }
    }
    
  5. Final Modifier String argument: We can make String args[] as final.
    class TestClass
    {
        public static void main(final String[] args)
        {
            System.out.println("Main Method");
        }
    }
    
  6. synchronized keyword to static main method:
    class TestClass
    {
        public synchronized static void main(String[] args)
        {
            System.out.println("Main Method");
        }
    }
    
  7. strictfp keyword to static main method: strictfp used to restrict floating point calculations.
    class TestClass
    {
        public strictfp static void main(String[] args)
        {
            System.out.println("Main Method");
        }
    }
    
  8. Combined all  above keyword to static main method:
    class TestClass
    {
        final static synchronized strictfp static void main(String[] args)
        {
            System.out.println("Main Method");
        }
    }
    

Inheritance of main() method

In inheritance JVM Executes the main() without any errors.

class Parent
{
    public static void main(String[] args)
    {
        System.out.println("Main Method Parent");
    }
} 

class Child extends Parent
{ 

}

or

class Parent
{
    public static void main(String[] args)
    {
        System.out.println("Main Method Parent");
    }
}
class Child extends Parent
{
    public static void main(String[] args)
    {
        System.out.println("Main Method Child");
    }
}

In both the cases, Parent.class and Child.class files generated by Java compiler javac. When we execute any of the two .class, JVM will execute without any error as Child class hide parent class method when override.

Method Overloading with main()

Java allow the main method overloading but the program doesn’t execute the overloaded main method when we run your program. Program execution start for one method only which is following one of any above allowed main() method signatures.

import java.io.*;
public class Test { 

	// Normal main()
	public static void main(String[] args) {
		System.out.println("Hello Facing Issues on IT? (from main)");
		Test.main("Facing Issues on IT");
	} 

	// Overloaded main methods
	public static void main(String arg1) {
		System.out.println("Hello, " + arg1);
		Test.main("Dear ","Facing Issues on IT");
	}
	public static void main(String arg1, String arg2) {
		System.out.println("Hello , " + arg1 + ", " + arg2);
	}
}

Output


Hello Facing Issues on IT? (from main)
Hello  Facing Issues on IT
Hello Dear Facing Issues on IT

Mathematical Programming Test


Here are some most common formulae based mathematical programs. These programming test is basically for checking the mathematical knowledge and Java operator precedence to implement these formulae.

  1. Program to calculate the area of rectangle
    Input: Width = 10; Height = 5
    Output:
    Area of Rectangle = Width * Height
    = 10 * 5
    = 50
  2. Program to calculate the volume of sphere
    Input:Radius = 48; Pie = 3.14
    Output:
    Volume = (4.0/3.0) * pie * (radius * radius * radius);
    = (4.0/3.0) * 3.14 * 48 * 48 * 48
    = 463433.132812
  3. Program find the area of the pentagon
    Input:s = 13; a = 5;
    Output:
    Area of Pentagon = (5.0/2.0) * s * a
    = (5.0/2.0) * 13 * 5
    = 162.5
  4. Program to find the area of parallelogram
    Input:base = 4; height = 18;
    Output:
    Area of Parallelogram = base * height;
    = 4 * 18
    = 72
  5. Program to find the area of square
    Input:a = 13
    Output:
    Area of Square = a2
    = 132
    = 169
  6. Program to find the surface area of sphere
    Input:Radius = 37, Pie = 3.14
    Output:
    Volume = 4 * pie * (radius * radius);
    = 4 * 3.14 * 37 * 37
    = 17210.285714
  7. Program to find the volume of cone
    Input:Radius = 38, Height = 35, Pie = 3.14
    Output:
    Volume = pie * radius * radius * height/3;
    = 3.14 * 38 * 38 * 35/3
    = 48766.666667
  8. Program to find the volume of the cube
    Input:side = 4
    Output:
    Volume of cube = side3
    = 43
    = 64
  9. Program to find the volume of cylinder
    Input:radius (r) = 38 , height (h) = 35
    Output:
    Volume of the cylinder = pie * radius2 * height
    = 3.14 * 38* 38 * 35
    = 146300.000000
  10. Program to calculate the CGPA percentage
    CGPA percentage is = (float)(9.5 * (CGPA));
    Input:
    CGPA = (Grades in all Subjects) / (Total Number of Subjects).
    English = 9.1;
    Hindi = 8.5;
    Maths = 9.5;
    Science =9.6;
    SocialStudy = 8.6;
    CGPA = (9.1+8.5+9.5+9.6+8.6)/(5.0);
    Output:CGPA percentage is = 86.070000
  11. Program to convert Celsius into Fahrenheit
    Temperature in Fahrenheit = ((celsius * 9) / 5) + 32
    Input:celsius= 12
    Output:Temperature in Fahrenheit = 53.6
  12. Program to convert days into years
    Input:days= 799;
    Output:
    Number of years = days / 365;
    = 799 / 365
    = 2
  13. Program to convert Fahrenheit into Celsius
    Temperature in Celsius = ((Fahrenheit-32)*5)/9
    Input:Fahrenheit = 54
    Output:Temperature in Celsius= ((54-32)*5)/9 = 12.22222
  14. Program to find the area of an equilateral triangle
    Input:side (a) = 5
    Output:
    Area of Equilateral Triangle = ( 1.73 * a * a) / 4
    = ( 1.73 * 5 * 5) / 4
    = 10.81250
  15. Program to find the area of a triangle
    Input:b = 5; h = 12
    Output:Area of Triangle = (b * h) / 2
    = (5 * 12) / 2
    = 30.0
  16. Program to find the area of the right angle triangle
    Input:b = 5; h = 8
    Output:Area of Triangle = (b * h) / 2
    = (5 * 8) / 2
    = 20.0
  17. Program to find the perimeter of the rectangle
    Input:a = c = 5
    b = d = 4
    Output:Perimeter of Rectangle = 2 * ( a + b);
    = 2 * (5 + 4)
    = 18.00000
  18. Program to find the simple interest
    Simple Interest = (P × R × T) / 100
    Input:P = 34000, R = 30,T = 5
    where P = Principal Amount, R = Rate per Annum, T = Time (years)
    Output: Simple Interest = 51000.000
  19. Program to find the surface area of a cube
    Surface Area Of Cube = 6 ( a * a )
    Input:b = 5, h = 5
    a (side) = length = breadth = height
    Output:Surface Area Of Cube = 6 * 5 * 5=150.00000
  20. Program to find the surface area of sphere
    Input:l= 2, w = 3, h = 5;
    where l = length, w = width and h = height.
    Output:
    Surface Area OfCuboid = 2 * (l * w+ w * h + h * l)
    = 2 * (2 * 3 + 3 * 5 + 5 * 2)
    = 62.00000
  21. Program to find the surface area of the cylinder
    Surface Area of Cylinder = 2 Π (r + h)
    Input:r = 2.0, h = 5.0
    Output:
    Surface Area of Cylinder = 2 Π (r + h)
    Here, r = radius, h = height, and Π ( pie ) = 3.14
    = 2 * 3.14 * ( 2.0 + 5.0)
    = 44.00000
  22. Write a Java program to compute the area of a hexagon.
    Area of a hexagon = (6 * s^2)/(4*tan(π/6))
    where s is the length of a side
    Input: Input the length of a side of the hexagon: 6
    Output: The area of the hexagon is: 93.53074360871938
  23. Write a Java program to compute the area of a polygon.
    Area of a polygon = (n*s^2)/(4*tan(π/n))
    where n is n-sided polygon and s is the length of a side
    Input:
    Input the number of sides on the polygon: 7
    Input the length of one of the sides: 6
    Output: The area is: 130.82084798405722
  24. Write a Java program to compute the distance between two points on the surface of earth.
    Distance between the two points [ (x1,y1) & (x2,y2)]
    d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 – y2))
    Radius of the earth r = 6371.01 Kilometers
    Input:
    Input the latitude of coordinate 1: 25
    Input the longitude of coordinate 1: 35
    Input the latitude of coordinate 2: 35.5
    Input the longitude of coordinate 2: 25.5
    Output: The distance between those points is: 1480.0848451069087 km

 

Frequently Asked Algorithms & Java Programs


Below are most frequently asked algorithms and programs in interview to test interviewee programming and logical skill. These question can be asked with fresher and any senior level programmers to check hands on with the code or not.

  1. Write a program to print alphabet using java loop
    Output:
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  2. Write a program to check odd or even number.
    Input:  5
    Output: Odd Number
  3. Write a program to convert Fahrenheit to Celsius.
    Input: 50
    Output: 10.0
  4. Write a java program to print fibonacci series without using recursion and using recursion.
    Input: 12
    Output: 0 1 1 2 3 5 8 13 21 34 55 89 144
  5. Write a java program to check prime number.
    Input: 42
    Output: Not prime number
    Input: 13
    Output: Prime number
  6. Write a java program to check palindrome number.
    Input: 349
    Output: Not palindrome number
    Input: 1234321
    Output: Palindrome number
  7. Write a java program to print factorial of a number.
    Input: 4
    Output: 24
    Input: 5
    Output: 120
  8. Write a java program to check Armstrong number.
    Input: 153
    Output: Armstrong number
    Input: 22
    Output: Not Armstrong number
  9. Write a program to swap numbers without using third variable.
    Input: 20 30
    Output: 30 20
  10. Write a program to reverse of number.
    Input:    123456
    Output: 654321
  11. Write a program to find largest of three numbers.
    Input: 10 30 40
    Output: 40
  12. Write a program to print Floyd triangle.
    Input: 7
    Output:

    1
    2 3
    4 5 6
    7 8 9 10
    11 12 13 14 15
    16 17 18 19 20 21
    22 23 24 25 26 27 28

Sorting Program

  1. Write a java program to sort an array elements using bubble sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  2. Write a java program to sort an array elements using selection sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  3. Write a java program to sort an array elements using insertion sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  4. Write a java program to sort an array elements using quick sort algorithm.
    Input:    12 24 45 56 10 9 49 30 5 15
    Output: 5 9 10 12 15 24 30 45 49 56
  5. Write a java program to sort an array elements using heap sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  6. Write a java program to sort an array elements using merge sort algorithm.
    Input:    12 24 45 56 10 9 49 30 5 15
    Output: 5 9 10 12 15 24 30 45 49 56
  7. Write a java program to sort an array elements using shell sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  8. Write a java program to sort an array elements using radix sort algorithm.
    Input:   170 45 75 90 2 802 2 66
    Output: 2 2 45 66 75 90 170 802
  9. Write a java program to sort an array elements using bucket sort algorithm.
    Input:   0.23 0.67 0.32 0.25 0.88 0.45 0.86 0.16 0.59 0.38 0.19 0.43 0.02
    Output: 0.02 0.16 0.19 0.23 0.25 0.32 0.38 0.43 0.45 0.59 0.67 0.86 0.88
  10. Write a java program to sort an array elements using counting sort algorithm.
    Input:    2 6 3 2 8 4 8 1 5 3 1 4 0
    Output: 0 1 1 2 2 3 3 4 4  5 6 8 8

Java Searching Programs

  1. Write a java program to perform linear search in java.
  2. Write a java program to perform binary search in java.

Fibonacci Series Java Program


“A fibonacci series is sequence of numbers, where each number is sum of the two preceding two numbers, Series initial two values are 1 , 1″

For Example : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144………

Fibonacci Series Program

Here is program to get Fibonacci series number on particular position and print series up to that point. In this program using recursion to generate Fibonacci numbers, Here put base condition to terminate recursion as when number reach to 1 or 2  and for rest of the case work recursively for current number and previous one and then add it.

import java.util.HashMap;
import java.util.Map;

public class FibonacciSeriesExample {

	private static Map series = new HashMap();

	public static void main(String[] args) {

		// Get the 12th fibonacci number from series
		System.out.println("Fibonacci 12 the position element :" + fibonacci(12));

		System.out.println("Print Complete Fibonacci Series :");
		printFibonacci(series);
	}

	public static int fibonacci(int fibIndex) {

		// set base element of fibonacci series
		if (fibIndex == 1 || fibIndex == 2) {
			series.put(1, 1);
			series.put(2, 1);
		}

		// execute fibonacci recursively until fibIndex reach to 1
		if (series.containsKey(fibIndex)) {
			return series.get(fibIndex);
		} else {
			int answer = fibonacci(fibIndex - 1) + fibonacci(fibIndex - 2);
			series.put(fibIndex, answer);
			return answer;
		}
	}

	public static void printFibonacci(Map series) {

		for (Map.Entry entry : series.entrySet()) {
			System.out.println(entry.getValue());
		}
	}
}

Output


Fabonnici 12 the position element :144
Print Complete Fabonni Series :
1
1
2
3
5
8
13
21
34
55
89
144

Java Versions History


Here is a list of all versions of Java and features introduced with each release.

JDK Alpha and Beta

The Java Alpha and Beta version was released in 1995 but they have highly unstable APIs. The supplied Java web browser was named WebRunner.

JDK 1.0

Java’s first stable version 1.0.2 was released on January 23, 1996. Its code name was Oak and called as java 1.

JDK 1.1

JDK 1.1 version was released on February 19, 1997. It was having some additional features as :

  • The concept of Inner Class
  • JavaBeans
  • JDBC
  • RMI
  • The AWT event model was totally reshaped.
  • Reflection(which supported Introspection only, the modification was not possible at runtime).
  • JIT (Just In Time) compiler added on Microsoft Windows platforms to produced for JavaSoft by Symantec
  • Internationalization and Unicode support originating from Taligent.

J2SE 1.2

JDK 1.2 version was released on December 8, 1998, called codename Playground. It was a very big release and replaced JDK to recognize the base platform from J2EE and J2ME. It was having so many additional features as

  • strictfp keyword
  • Java plug-in
  • Java IDL, an IDL implementation for CORBA interoperability
  • Collections framework
  • Core classes added some new Swing graphical API.
  • Sun’s JVM was added with a JIT compiler for the first time to enhance performance.

J2SE 1.3

JDK 1.3 version was released on May 8, 2000, called codename Kestrel. It was having so many additional features as

  • HotSpot JVM included.
  • RMI was updated to support optional compatibility with CORBA.
  • JNDI (Java Naming and Directory Interface).
  • Java Platform Debugger Architecture (JPDA) included.
  • JavaSound.
  • Synthetic proxy classes.

J2SE 1.4

JDK 1.4 version was released on February 6, 2002, called codename Merlin. It was first Java Platform which was released under the Java community process and having so many additional features as

  • Improved libraries.
  • Perl regular expressions included.
  • Provided exception chaining (It allows an exception to encapsulate original lower-level exception).
  • IPv6 support (Internet Protocol version 6).
  • Logging API (Specified in JSR 47.)
  • The image I/O API for reading and writing images in formats like JPEG and PNG.
  • XML parser and XSLT processor integrated.
  • Security and cryptography extensions (JCE, JSSE, JAAS) integrated.

J2SE 5.0

J2SE 1.5 version was released on September 30, 2004, called as codename Tiger also called as Java 5.0. It was having so many additional features as

  • It provided compile-time type safety for collections by using generics and eliminates the need for most typecasts.
  • Used Metadata or annotations.
  • Autoboxing/unboxing.
  • Enumerations.
  • Enhanced for each loop.
  • Improved semantics of execution for multi-threaded Java programs.
    Static imports.
  • There were also some improvements in standard libraries:
  • Automatic stub generation for RMI objects.
  • Swing: It provided a skinny look and feel.
  • The concurrency utilities in package java.util.concurrent.
  • Scanner class added for parsing data from various input streams and buffers.
  • Java 5 was the last release of Java which officially supported the older versions Microsoft Windows 9x line i.e (Windows 95, Windows 98, Windows ME) and window Vista
  • Apple Mac OS X 10.5 by default having java version 5 installed.

Java SE 6

Java SE version was released on December 11, 2006, called as codename Mustang also called as Java SE 6. It was having so many additional features as

  • Dropped the support for older Win9x versions.
  • Scripting Language Support.
  • Generic API for tight integration with scripting languages.
  • Improved Web Service support.
  • JDBC 4.0 support.
  • Now invoke Java Compiler by using Java Compiler API programmatically.

Java SE 7

Java SE version was released on July 28, 2011, called codename Dolphin also called as Java SE 7. It was having so many additional features as

  • JVM support for dynamic languages.
  • Compressed 64-bits pointer.
  • Strings added in the switch.
  • Automatic resource management in try-statement.
  • Underscores allowed in numeric literals.
  • Binary integer literals.
  • Improved type interface for creating a generic instance. (also called diamond operator )
  • Improved caching and throwing. (catch multiple exceptions and rethrow with improved type checking)
  • Provided Java Deployment rulesets.

Java SE 8

Java SE version was released on March 18, 2014, called codename Spider. It was having so many additional features as

  • Language-level support for Lambda expressions.
  • Allowed developers to embed JavaScript code within applications.
  • Annotation of Java Types.
  • Provided Date and Time API.
  • Repeating Annotations.
  • Launching of JavaFX applications.
  • Removal of permanent generation.
  • Java SE 8 was not supported in Windows XP but after JDK 8 update version 25, we can install and run it under Windows XP.

Java SE 9

Java SE version was released on September 21, 2017, developed by Oracle. It was having so many additional features as

  • Java 9 would include better support for better native code integration,multi-gigabyte heaps, a different default garbage collector and a self-tuning JVM.
  • Modularization of the JDK under Project Jigsaw.
  • Provided Money and Currency API.
  • Tight integration with JavaFX.
  • Java implementation of reactive streams.
  • More Concurrency Updates.
  • Provided Java Linker.
  • Automatic scaling and sizing.

Java SE 10

Java SE version was released on March 20, 2018, developed by Oracle. It was having so many additional features as

  • Remove primitive data types and move towards 64-bit addressable arrays to support large data sets.
  • Local-Variable Type Inference
  • Experimental Java-Based JIT Compiler: This is a Graal dynamic compiler to the integration with the Linux x64 platform.
  • Application Class-Data Sharing: This reduces the startup and footprint for java applications by placing application classes in shared archives.
  • Time-Based Release Versioning
  • Parallel Full GC for G1
  • Garbage-Collector Interface
  • Additional Unicode Language-Tag Extensions
  • Root Certificates
  • Thread-Local Handshakes
  • Heap Allocation on Alternative Memory Devices
  • Remove the Native-Header Generation Tool – javah
  • Consolidate the JDK Forest into a Single Repository

Java SE 11

Java SE version was released on September 25, 2018, and the version is open for bug fixes. It was having so many additional features as

  • JEP 309: Dynamic class-file constants
  • JEP 318: Epsilon: a no-op garbage collector
  • JEP 323: Local-variable syntax for lambda parameters
  • JEP 331: Low-overhead heap profiling
  • JEP 321: HTTP client (standard)
  • JEP 332: Transport Layer Security (TLS) 1.3
  • JEP 328: Flight recorder
  • JEP 333: ZGC: a scalable low-latency garbage collector
  • CORBA, JavaFX, and  Java EE modules have been removed from JDK
  • JEP 335: Deprecated the Nashorn JavaScript engine
  • Unicode 10.0.0 support (while the current version is Unicode 11.0.0, it’s only in Java 12)
  • Java web start and applets are no longer available.

Java SE 12

Java SE version was released on March 19, 2019, and the version is open for bug fixes. It was having so many additional features as

  • JEP 189: Shenandoah: A Low-Pause-Time Garbage Collector
  • JEP 230: Microbenchmark Suite
  • JEP 325: Switch Expressions
  • JEP 334: JVM Constants API
  • JEP 340: One AArch64 Port, Not Two
  • JEP 341: Default CDS Archives
  • JEP 344: Abortable Mixed Collections for G1
  • JEP 346: Return Unused Committed Memory from G1 Promptly

References

https://en.wikipedia.org/wiki/Java_version_history

“Learn From Others Experience"

%d bloggers like this: