Category Archives: Java

[Solved] com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `int` from String “C21”: not a valid Integer value


InvalidFormatException is subclass of MismatchedInputException. InvalidFormatException occurred because of bad formatting or format not match with the presepecified format of value to deserialize.

InvalidFormatException Example

The issue is passing type is String while deserialization expecting as Int.

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;

	//getter and setter of class
	}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample2 {

	public static void main(String[] args) {

	    String json="{\"rollNumber\":\"C21\" , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

InvalidFormatException Stacktrace


{"rollNumber":"C21" , "firstName":"Saurabh" , "lastName":"Gupta"}
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `int` from String "C21": not a valid Integer value
 at [Source: (String)"{"rollNumber":"C21" , "firstName":"Saurabh" , "lastName":"Gupta"}"; line: 1, column: 15] (through reference chain: com.fiot.json.jackson.exceptions.StudentDetail["rollNumber"])
    at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1549)
    at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:911)
    at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer._parseInteger(NumberDeserializers.java:522)
    at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer.deserialize(NumberDeserializers.java:474)
    at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer.deserialize(NumberDeserializers.java:452)
    at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:138)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:18)

Solutions

Pass value as the compatible type, here in this case number value roll number can’t accept as a text string with an alphanumeric.

In such cases, if your organization is using rollNumber as alphanumeric then convert int to String to make compatible. or ask your client application to pass the value of rollNumber as an int value.

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/InvalidFormatException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

Advertisements

Solved] com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String “MM/dd/yyyy”: not a valid representation for date format


InvalidFormatException is subclass of MismatchedInputException. InvalidFormatException occurred because of bad formatting or format not match with the prespecified format of value to deserialize.

InvalidFormatException Example

This example throwing InvalidFormatException because JSONis having the format “MM/dd/yyyy” for dob which is not compatible with standard date format for deserializations. Below is a standard format for a date as JACKSON support:

  • yyyy-MM-dd’T’HH:mm:ss.SSSZ
  • yyyy-MM-dd’T’HH:mm:ss.SSS
  • EEE, dd MMM yyyy HH:mm:ss zzz
  • yyyy-MM-dd
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonFormat;

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private Date dob;
	//getter and setter of class
	}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample2 {

	public static void main(String[] args) {

	    String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\",  \"dob\":\"12/13/1985\"}";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

InvalidFormatException Stacktrace


com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "12/13/1985": not a valid representation (error: Failed to parse Date value '12/13/1985': Cannot parse date "12/13/1985": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: (String)"{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta",  "dob":"12/13/1985"}"; line: 1, column: 71] (through reference chain: com.fiot.json.jackson.exceptions.StudentDetail["dob"])
    at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1549)
    at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:911)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:524)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:467)
    at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer._parseDate(DateDeserializers.java:195)
    at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:285)
    at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:268)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)

Solutions

  1. Pass date format for JSON as the standard one for deserializations.
    • yyyy-MM-dd’T’HH:mm:ss.SSSZ
    • yyyy-MM-dd’T’HH:mm:ss.SSS
    • EEE, dd MMM yyyy HH:mm:ss zzz
    • yyyy-MM-dd
  2. Use annotation @JsonFormat as below to support some other new date format.
    public class StudentDetail {
    	private int rollNumber;
    	private String firstName;
    	private String lastName;
    	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy")
    	private Date dob;
    	//getter and setter of class
    	}
    

Preferences

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/InvalidFormatException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

[Solved] com.fasterxml.jackson.databind.exc. InvalidDefinitionException: No serializer found for class ABC and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)


InvalidDefinitionException is an intermediate exception which is used as the base class for all JsonMappingExceptions that occurred due to problems with target type definition. Generally a problem with properties or annotations used on a class.

Exception Example

Here this InvalidDefinitionException is occurring because of StudentDetail class is not having any getter and setters.  That’s what while the time of deserialization found bean as empty.

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	public StudentDetail(int rollNumber, String firstName, String lastName) {
		super();
		this.rollNumber = rollNumber;
		this.firstName = firstName;
		this.lastName = lastName;
	}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample3 {

	public static void main(String[] args) {

		try
		{
		StudentDetail student=new StudentDetail(10011,"Saurabh","Gupta");
	    ObjectMapper mapper = new ObjectMapper();
	    //convert java object to JSON
	    String json=mapper.writeValueAsString(student);
	    System.out.println(json);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

Exception Stacktrace


com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.fiot.json.jackson.exceptions.StudentDetail and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77)
    at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1191)
    at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:313)
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:71)
    at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:33)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3905)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3219)
    at com.fiot.json.jackson.exceptions.TestJacksonExample3.main(TestJacksonExample3.java:17)

Solutions

There is a couple of solution to resolve this issue:

  1. If you have the option to edit source, add getter and setter of properties of the class.
  2. On class, level add annotation @JsonAutoDetect(fieldVisibility = Visibility.ANY) to StudentDetail class to resolve this issue.
    @JsonAutoDetect(fieldVisibility = Visibility.ANY)
    public class StudentDetail {
    	private int rollNumber;
    	private String firstName;
    	private String lastName;
    	public StudentDetail(int rollNumber, String firstName, String lastName) {
    		super();
    		this.rollNumber = rollNumber;
    		this.firstName = firstName;
    		this.lastName = lastName;
    	}
    
  3. We can resolve this issue by setting configuring of ObjectMapper visibility for fields as Visibility.ANY.
    try
    	{
    	StudentDetail student=new StudentDetail(10011,"Saurabh","Gupta");
    	ObjectMapper mapper = new ObjectMapper();
    	mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    	//convert java object to JSON
    	String json=mapper.writeValueAsString(student);
    	System.out.println(json);
    		}
    		catch(IOException ex)
    		{
    			ex.printStackTrace();
    		}
    		catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}
    
    	}
    

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

JSON Overview


JSON (JavaScript Object Notation) is a lightweight, language-independent, text-based data storage and data-interchange format to sharing between systems.

Below are some properties make JSON an ideal data-interchange language:

  • JSON is “self-describing” and easy for humans to read and write.
  • JSON is text, written with JavaScript object notation.
  • JSON represent values in form of key/value pairs.
  • JSON is easy for API’s to parse and generate.
  • JSON is a text format that is supported by many languages because of language-independent

Points to remember

The JSON file extension is “.json”
The JSON text MIME type is “application/json”.

Why use JSON?

There are so many reasons to use JSON:

  1. JSON represents values in form of key/value pairs which is easy to understand and supported by most programming languages For Ex: C, C++, C#, Java, JavaScript, Perl, Python, and many others.
  2. The JSON format is text, it can easily exchange browser to and from a server,
  3. Current enterprise application uses JSON for communications to the server with REST services, Communication to the server with Ajax call, convert Javascript object to JSON or vice versa.
  4. JSON extensively used by NoSQL database to store records as JSON documents. For Ex: MongoDB, Oracle NoSQL Database, and Oracle Berkeley DB.
  5. Traditional relational databases constantly gaining more JSON capabilities like PostgreSQL, Oracle, etc. supports JSON data for certain features such as transactions, indexing, declarative querying, and views.

JSON Example

You can refer below JSON  object to represent Student Detail. Corresponding is a description of the representation of each field in JSON with respect to the data type.

JSON Data Type & Syntax

Student JSON Object

Above JSON is generated with respect to below Student JAVA object. You can follow below link to know about JSON supported Data Type and Syntax.

Student Java Object

The same Student and JSON object will refer in the subsequent example related to JAVA for more JSON + JAVA handling example.

JAVA JSON API’s

Below is the list of the library that developed by java open source community to handle (JAVA +JSON) development.

  • JACKSON
  • GSON
  • Boon
  • JSON.org

Follow below link to know in-depth knowledge of JSON parsers and in which case should be used specifically.

JSON Parsers

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

 

JSON Data Types & Syntax


In previous post, JSON Overview explain about background of JSON, reason to use JSON with data exchange web page to/from servers and No SQL database storage with JSON. Now here we discuss about to JSON supporting Data Types and JSON syntax representation with respect to each data types.

JSON Object Syntax

JSON is language independent because of universal data format structures which is almost support by all modern languages. JSON Object follows below syntax for handling different type of data:

  • JSON object are surrounded with curly braces ({}).
  • JSON object data are written in key/value pairs to represent an object, record, Map, list, array etc.
  • JSON key and value are separated by a colon.
  • JSON objects each key/value pair is separated by a comma (,).
  • JSON keys are strings, written in double quotes(“”) and values can be any data type supported by JSON.
  • JSON Object for list of values (an array, vector, list or sequence) are store in form of array and represent as square braces ([]).

JSON Supported Data Types

JSON data can be represent with following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

JSON Example

Here is Student detail JSON representation which considers all the above data types and Syntax rules. This example will help you to understand JSON representation with respect to each type of data.

Student JSON Object

JSON for String Value

In JSON string values are represented in double quote (“”);

{
	"firstName" : "Saurabh",
	"lastName" : "Gupta"
}

JSON for Number Value

In JSON, number values such as (integer, float, double) values are not required  double quotes.

{"rollNumber" : 11}

JSON for Boolean Value

In JSON, to represent Boolean allowed values are true/false and not required double quotes.

{"permanent" : false}

JSON for an Array

In JSON, Array values are represent in square braces ([]) as shown for cities and phoneNumbers.

{
"phoneNumbers" : [ 2233445566, 3344556677 ],
"cities" : [ "Dallas", "San Antonio", "Irving" ]
}

JSON for a Map

In JSON, Map represent as object with in curly braces and each key and value of Map write same way as write properties of Object.

{
"properties" : {
    "play" : "Badminton",
    "interst" : "Math",
    "age" : "34 years"
  }
}

JSON for an Object

In JSON, Object represent with in curly braces. Here address is internal object of student.

{
	"address" : {
		"addressLine" : "Lake Union Hill Way",
		"city" : "Atlanta",
		"zipCode" : 50005
  }
}

JSON for Null

In JSON, null values are write as below.

{"middleName" : null}

Now you have learned about JSON supported data types and there representation in JSON. In next post you will learn about JSON parsers for serialization and deserialization to/from Java objects. JSON Parsers

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

 

[Solved] com.fasterxml.jackson.databind.exc. MismatchedInputException: Cannot deserialize instance of `XYZ` out of START_ARRAY token


MismatchedInpuException is base class for all JsonMappingExceptions. It occurred when input is not mapping with target definition or mismatch between as required for fulfilling the deserialization. This exception is used for some input problems, but in most cases, there should be more explicit subtypes to use.

Example of MismatchedInputException

Here MismatchedInpuException issue is happening because of type mismatch because passing JSON as an array of StudentDetail while deserialization is mapped for single StudentDetail object.

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;

	//getter and setter of class
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample2 {

	public static void main(String[] args) {
	    String json=" ["
	    				+ "{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}, "
	    				+ "{\"rollNumber\":22 , \"firstName\":\"Abhishek\" , \"lastName\":\"Garg\"}"
	    		+ "]";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
		//issue is here
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

MismatchedInputException Stacktrace


 [{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}, {"rollNumber":22 , "firstName":"Abhishek" , "lastName":"Garg"}]
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.fiot.json.jackson.exceptions.StudentDetail` out of START_ARRAY token
 at [Source: (String)" [{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}, {"rollNumber":22 , "firstName":"Abhishek" , "lastName":"Garg"}]"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1139)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1093)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1461)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:185)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:22)

Solutions

To resolve this issue, change the type from StudentDetail to as array StudentDetail[]

public static void main(String[] args) {
	    String json=" ["
	    				+ "{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}, "
	    				+ "{\"rollNumber\":22 , \"firstName\":\"Abhishek\" , \"lastName\":\"Garg\"}"
	    		+ "]";
	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
		//Convereted to Type as array
	    StudentDetail[] students= mapper.readValue(json,  StudentDetail[].class );
	    System.out.println(students);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/MismatchedInputException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

[Solved] com.fasterxml.jackson.databind.exc. MismatchedInputException: Root name ‘ABC’ does not match expected (‘XYZ’) for type [simple type, class ClassName]


MismatchedInpuException is base class for all JsonMappingExceptions. It occurred when input is not mapping with target definition or mismatch between as required for fulfilling the deserialization. This exception is used for some input problems, but in most cases, there should be more explicit subtypes to use.

Example of MismatchedInputException

When we deserialize JSON data with property DeserializationFeature.UNWRAP_ROOT_VALUE then it will check root name as className. Here in this case class name “StudentDetail” while passing JSON having a root name as “student” that’s what throwing MismatchedInputException because of mismatch of root name.

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	//getter and setter of class
	}
import java.io.IOException;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample2 {

	public static void main(String[] args) {
	    String json="{\"student\":{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}}";

		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    //Before  deserialize this properties will unwrap the json.
	    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

Stacktrace of MismatchedInputException


com.fasterxml.jackson.databind.exc.MismatchedInputException: Root name 'student' does not match expected ('StudentDetail') for type [simple type, class com.fiot.json.jackson.exceptions.StudentDetail]
 at [Source: (String)"{"Student":{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}}"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1356)
    at com.fasterxml.jackson.databind.ObjectMapper._unwrapAndDeserialize(ObjectMapper.java:4087)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4011)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:19)

Solution

To resolve this issue use the annotation @JsonRootName as below so that overwrite root name as “student” on default root name (StudentDetail)

@JsonRootName(value = "student")
public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	//getter and setter of class
	}

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/MismatchedInputException.html

 

[Solved] com.fasterxml.jackson.core.JsonParseException: Unexpected character (”’ (code 39)): was expecting double-quote to start field name


JsonParseException is subclass of JsonProcessingException. This exception occurred because parsing issues or non-well-formed content because of not fulling JSON syntax specification.

JsonParserException Example

Here JSonParserException occurred because not fulfilling the syntax specification because properties name  and String values in JSON should always write in double-quotes (“);

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;
	//getter and setter of class
	}
public class TestJacksonExample2 {

	public static void main(String[] args) {

	    String json="{\'rollNumber\':21 , \'firstName\':\'Saurabh\' , \'lastName\':\'Gupta\'} ";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

	}

}

Exception Stacktrace


{'rollNumber':21 , 'firstName':'Saurabh' , 'lastName':'Gupta'} 
com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name
 at [Source: (String)"{'rollNumber':21 , 'firstName':'Saurabh' , 'lastName':'Gupta'} "; line: 1, column: 3]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:693)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:591)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddName(ReaderBasedJsonParser.java:1767)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:692)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:18)

Solutions

There are two solutions to resolve this issue:

  1. Send JSON in a standard format as with properties name and String value in double-quotes.
     String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";
    
  2. By configuring the ObjectMapper to allow single quotes as below:
    public static void main(String[] args) {
    String json="{\'rollNumber\':21 , \'firstName\':\'Saurabh\' , \'lastName\':\'Gupta\'} ";
    
    System.out.println(json);
    try
       {
    	//add to allow single quote
    	JsonFactory factory = new JsonFactory();
    	factory.enable(Feature.ALLOW_SINGLE_QUOTES);
    	ObjectMapper mapper = new ObjectMapper(factory);
    
    	StudentDetail student= mapper.readValue(json, StudentDetail.class);
    	System.out.println(student);
        }
     catch(IOException ex)
    {
    	ex.printStackTrace();
    }
    catch(Exception ex)
    {
    	ex.printStackTrace();
    }
    }
    

 

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://fasterxml.github.io/jackson-core/javadoc/2.2.0/com/fasterxml/jackson/core/JsonParseException.html

[Solved] com.fasterxml.jackson.core.JsonParseException: Unexpected character (‘{‘ (code 123)): was expecting double-quote to start field name


JsonParseException is subclass of JsonProcessingException. This exception occurred because parsing issues or non-well-formed content because of not fulling JSON syntax specification.

JsonParserException Example

Here JSonParserException occurred because not fulfilling the syntax specification because two curly brackets ({) used continuously

public class StudentDetail {
	private int rollNumber;
	private String firstName;
	private String lastName;

	//getter and setter of class
}
public static void main(String[] args) {

	    String json="{{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}} ";

	    System.out.println(json);
		try
		{
	    ObjectMapper mapper = new ObjectMapper();
	    StudentDetail student= mapper.readValue(json, StudentDetail.class);
	    System.out.println(student);
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}

JsonParserException Stacktrace


 {{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}} 
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
 at [Source: (String)" {{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}} "; line: 1, column: 4]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:693)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:591)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddName(ReaderBasedJsonParser.java:1767)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:692)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:155)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample2.main(TestJacksonExample2.java:23)

Solutions

To fix this issue remove one level of the curly bracket from start and end so that fulfill JSON specification. The correct JSON for this example would be :

 String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";

As per JSON specification after curly bracket ({) only allow double quote for showing properties name or square bracket ([) if need to show set of objects or values.

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://fasterxml.github.io/jackson-core/javadoc/2.2.0/com/fasterxml/jackson/core/JsonParseException.html

[Solved] com.fasterxml.jackson.databind.exc. InvalidDefinitionException: Cannot construct instance of `XYZ` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)


InvalidDefinitionException is intermediate exception which is used as the base class for all JsonMappingExceptions that occurred due to problems with target type definition. Generally a problem with properties or annotations used on a class.

Example of InvalidDefinitionException

In this given example deserialing String JSON to Student object. Here Student class is not having default constructor that’s causing issue as “No able to construct object as no default constructor found”


public class Student {
private int rollNumber;
private String firstName;
private String lastName;

public Student(int rollNumber, String firstName, String lastName)
{
this.rollNumber=rollNumber;
this.firstName=firstName;
this.lastName=lastName;
}
// getter and setter of class
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample {

public static void main(String[] args) {

   String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";

try
{
   ObjectMapper mapper = new ObjectMapper();
   Student student= mapper.readValue(json, Student.class);
   System.out.println(student);
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}

}

Stacktrace of InvalidDefinitionException


com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.fiot.json.jackson.exceptions.Student` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample.main(TestJacksonExample.java:18)

Solutions

To solution of this issue just add a default constructor as below


public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
        //default constructor
	public Student()
	{
	 super();
	}
	public Student(int rollNumber, String firstName, String lastName)
	{
		this.rollNumber=rollNumber;
		this.firstName=firstName;
		this.lastName=lastName;
	}
	// getter and setter of class
	}
	

Note:

Jackson looks for POJO class for deserialization. As per definition of POJO (Plain Old Java Object) is the class with out any restriction, having getter and setter methods, if required can also implement object class methods like equals(), toString() etc.

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/InvalidDefinitionException.html

[Solved] com.fasterxml.jackson.databind.exc. InvalidDefinitionException: Cannot construct instance of `XYZ` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information


InvalidDefinitionException is an intermediate exception which is used as the base class for all JsonMappingExceptions that occurred due to problems with target type definition. Generally a problem with properties or annotations used on a class.

Example of InvalidDefinitionException

Here Publication class is abstract that’s causing issues because we can’t directly create an instance of an abstract class. Here at the time  of JSON deserialization to author object not able to create an instance of Publication class.

public class Author {
	  private String name;
	  public Publication publication;

	  public Author()
	  {

	  }

	  //getter and setter of properties
	}

	public abstract class Publication {
	public String title;

	public Publication() {

	}
	// getter and setter of properties
}
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
public abstract class Publication {
	public String title;

	public Publication() {

	}
	// getter and setter of properties
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample {

public static void main(String[] args) {
String json = "{\"name\":\"Saurabh Gupta\",\"publication\":{\"title\":\"Facing Issues On IT\",\"type\":\"Drama\" }}";

try
{
   ObjectMapper mapper = new ObjectMapper();
   Author author= mapper.readValue(json, Author.class);
   System.out.println(author);
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

Stacktrace of InvalidDefinitionException


com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.fiot.json.jackson.exceptions.Publication` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (String)"{"name":"Saurabh Gupta","publication":{"title":"Facing Issues On IT"}}"; line: 1, column: 39] (through reference chain: com.fiot.json.jackson.exceptions.Author["publication"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028)
    at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:265)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.exceptions.TestJacksonExample.main(TestJacksonExample.java:17)

Solutions

As a solution to the current issue, Not declare Publication class as abstract because we can’t directly create an instance of an abstract class only allowed instance through subclass. 

Recommend Solution

We can solve this problem by using simple @JsonDeserialize on the abstract class as mentioned as a subtype.

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

//@JsonDeserialize(as = Book.class)
public abstract class Publication {
	public String title;

	public Publication() {

	}
	// getter and setter of class
}

If abstract class having more than one subtype, then mentioned all the classes as SubTypes.

@JsonSubTypes(
{
	@Type(value = Book.class, name = "book"),
	@Type(value = Magzine.class, name = "magzine"),
        @Type(value = Comics.class, name = "comics")
})
public abstract class Publication {
}

Note:

Jackson looks for POJO class for deserialization. As per the definition of POJO (Plain Old Java Object) is the class without any restriction, having getter and setter methods, if required can also implement object class methods like equals, toString(), etc.

References

https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/exc/InvalidDefinitionException.html

You would like to see

Follow below link to learn more on JSON and  JSON issues solutions:

[Solved] com.fasterxml.jackson.databind.exc. MismatchedInputException: Cannot construct instance of `XYZ` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor


MismatchedInpuException is base class for all JsonMappingExceptions. It occurred when input is not mapping with target definition or mismatch between as required for fulfilling the deserialization. This exception is used  for some input problems, but in most cases there should be more explicit subtypes to use.

MismatchedInputException Example

Here MismatchedInputException is occurring because of StudentDetail class define as private but Jackson always looks for class POJO for deserialization.

package com.fiot.json.jackson.annotations;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fiot.json.jackson.pojo.Address;
import com.fiot.json.jackson.pojo.Student;

public class JsonIgnoreUnknownProperties {

	public static void main(String[] args) {

	String json="	{\"id\" : 11,\"firstName\" : \"Saurabh\",\"middleName\" : \"Kumar\",\"lastName\" : \"Gupta\"}";

	System.out.println(json);
	try {
		// ObjectMapper new instance
		ObjectMapper objectMapper = new ObjectMapper();
		//convert json data to respective java object
		StudentDetail student = objectMapper.readValue(json, StudentDetail.class);
		// print java student java object
		System.out.println(student);
	} catch (JsonMappingException ex) {
		ex.printStackTrace();
	} catch (JsonGenerationException ex) {
		ex.printStackTrace();
	} catch (IOException ex) {
		ex.printStackTrace();
	}
	}
	@JsonIgnoreProperties(ignoreUnknown = true)
	private class StudentDetail
	{
			@JsonProperty(value = "id")
			private int rollNumber;

			@JsonProperty(value = "firstName")
			private String firstName;

			@JsonProperty(value = "lastName")
			private String lastName;

			//Getter and Setter

	}
}

Stacktrace of Exception


com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.fiot.json.jackson.annotations.JsonIgnoreUnknownProperties$StudentDetail` (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor
 at [Source: (String)"  {"id" : 11,"firstName" : "Saurabh","middleName" : "Kumar","lastName" : "Gupta",}"; line: 1, column: 3]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1032)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1294)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
    at com.fiot.json.jackson.annotations.JsonIgnoreUnknownProperties.main(JsonIgnoreUnknownProperties.java:27)

Solutions

As solution of this exception for current issue define StudentClass as public because Jackson looks for POJO class for deserialization.

As per definition of POJO (Plain Old Java Object) is the class with out any restriction, having getter and setter methods, if required can also implement object class methods like equals, toString() etc.

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

References

https://stackoverflow.com/questions/43923914/com-fasterxml-jackson-databind-exc-mismatchedinputexception-can-not-deserialize

[Solved] com.fasterxml.jackson.databind.exc. UnrecognizedPropertyException: Unrecognized field XYZ (class ABC), not marked as ignorable (X known properties: ])


UnrecognizedPropertyException occurred on time of deserialization of JSON. When no match of getter and setter method found for properties specified in JSON.

Jackson ObjectMapper required POJO class with respect to JSON to convert JSON to JAVA object.

UnrecognizedPropertyException Example

In this example to convert JSON to JAVA object , Student  class is not having any getter and setter method as basic requirement of POJO class. That’s causing the issue and throw UnrecognizedPropertyException.

public class Student {
private int rollNumber;
private String firstName;
private String lastName;
//no getter and setter for above properties
}
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJacksonExample {

public static void main(String[] args) {
   String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\"}";
try
{
   ObjectMapper mapper = new ObjectMapper();
   mapper.reader().forType(Student.class).readValue(json);
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}

}

}

UnrecognizedPropertyException Stacktrace


com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "rollNumber" (class com.fiot.json.jackson.exceptions.Student), not marked as ignorable (0 known properties: ])
 at [Source: (String)"{"rollNumber":21 , "firstName":"Saurabh" , "lastName":"Gupta"}"; line: 1, column: 17] (through reference chain: com.fiot.json.jackson.exceptions.Student["rollNumber"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:823)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1153)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1589)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1567)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1611)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1219)
at com.fiot.json.jackson.exceptions.TestJacksonExample.main(TestJacksonExample.java:15)

Solutions

There are couple of solutions to solve this issue:

  1. Jackson work with POJO classes, so write getter and setter of class properties to resolve above issue.
  2. Write @JsonIgnoreProperties(ignoreUnknown = true) on class level so that If any unknown property will receive in JSON that is not match with POJO object getter and setter then time of deserialization will ignore and no any exception occurred.
  3. For example : When you replace above JSON with this one as it’s having new property middleName which is not match with properties in Student POJO object. This will again through same exception with different exception message.

    String json="{\"rollNumber\":21 , \"firstName\":\"Saurabh\" , \"lastName\":\"Gupta\", \"middleName\":\"Kumar\"}";
    

    No exception occurred when add annotation as @JsonIgnoreProperties(ignoreUnknown = true)

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Student {
    private int rollNumber;
    private String firstName;
    private String lastName;
    //write getter and setter of properties
    }
    
  4. To resolve this issue, you can also disable ObjectMapper checking for unknown properties.

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    

You would like to see

Follow below link to see more JSON issues solutions:

JSON Issues Solutions

 

[Solved] java.nio.file.NoSuchFileException: XYZ


NoSuchFileException occurred when trying to attempt access a file or directory which is not exist in given location.

NoSuchFileException is sub class of FileSystemException. This exception  introduced in Java 7.

Example for NoSuchFileException

This example is throwing NoSuchFileException because trying to access a file student_data.json which is not exist on default location.

package com.fiot.json.jackson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fiot.json.jackson.pojo.Student;

public class ConvertJsonToArrayList {

	public static void main(String[] args) {
		try
		{
		byte[] mapData = Files.readAllBytes(Paths.get("student_data.json"));
		Student[] studentArr = null;

		ObjectMapper objectMapper = new ObjectMapper();
		studentArr = objectMapper.readValue(mapData, Student[].class);
		List studentList=Arrays.asList(studentArr);
		System.out.println("Student 1 \n"+studentList.get(0));
		System.out.println("Student 2 \n"+studentList.get(1));

		}
		catch(JsonMappingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}

	}

}

Exception Stacktrace


java.nio.file.NoSuchFileException: student_data.json
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
    at java.nio.file.Files.newByteChannel(Unknown Source)
    at java.nio.file.Files.newByteChannel(Unknown Source)
    at java.nio.file.Files.readAllBytes(Unknown Source)
    at com.fiot.json.jackson.ConvertJsonToArrayList.main(ConvertJsonToArrayList.java:18)

Solutions

There are couple of solutions to handle such situations:

  1. Use fully qualified file path such as “C:/data/student_data.json” but that will help only when your program is going to run on local machine. While working with enterprise application always use relative paths.
  2. If your file in source directory use path as “src/student_data.json”
  3. If your project is maven project, always write script to copy file which you want to access or keep in resource folder to access because maven project create different directory structure after build.

Solution depend on your project requirement. You can use below code to get qualified full path of a file

public static void main(String [] args) {

    String filename="student_data.json";
    //To get path of file
    Path path = Paths.get(filename);
    //To print absolute path of file
    System.out.println(path.getAbsolutePath());

You would like to see

Follow below link to see more Java issues solutions

[Solved] org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database may be already in use: null


Here JdbcSQLNonTransientConnectionException exception occurred because trying to connect H2 database through application while it’s already connected through eclipse data source explorer. That’s why when running application will through exception as “Database may be already in use :null“.

JdbcSQLnonTransientConnectionException Stacktrace


org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database may be already in use: null. Possible solutions: close all other connection(s); use the server mode [90020-199]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:617) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:427) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.message.DbException.get(DbException.java:194) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.db.MVTableEngine$Store.convertIllegalStateException(MVTableEngine.java:193) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:173) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.db.MVTableEngine.init(MVTableEngine.java:95) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Database.getPageStore(Database.java:2739) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Database.open(Database.java:769) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Database.openDatabase(Database.java:319) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Database.(Database.java:313) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Engine.openSession(Engine.java:69) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Engine.openSession(Engine.java:201) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:178) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Engine.createSession(Engine.java:161) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Engine.createSession(Engine.java:31) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:336) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:169) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:148) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.Driver.connect(Driver.java:69) ~[h2-1.4.199.jar:1.4.199]

Solutions

Follow below steps to resolve this issue. You just need to follow disconnect steps. Connect steps are just to reference to reach Data source explorer.

Steps to connect with H2 database with Eclipse

  • Go to eclipse
  • Go to tab Window -> View -> Type “Data” – Click on “Data Explorer”.
  • Select “Generic JDBC”
  • Fill properties as below.
  • Then click on Finish.

H2 database connection

Steps to disconnect database through eclipse

  • Go to “Data Explore”.
  • Expend Database connection.
  • Right click on H2DB database
  • Select option Disconnect.

Now run  application your issue get resolved.

You would like to see

Follow below link to see more JDBC, Hibernate and JPA issues solutions.

 

[solved] org.h2.jdbc.JdbcSQLSyntaxErrorException: Column count does not match


JdbcSQLSyntaxErrorException occurred when the executing query has violated SQL syntax rules.

JdbcSQLSyntaxErrorException Example

In this example throwing JdbcSQLSyntaxException with message “Column count does not match” because table having two columns while inserting row with only one value without column name. Here DBMS will confuse like passing value is for which column and throw exception as below “Column count does not match”.

Entity Class

@Entity
@Table(name = "author")
public class Author {

	@Id
	@GeneratedValue
	private Long id;

	@NotNull
    @Size(max = 100)
    @Column(unique = true)
	private String name;

	//getter and setter
	}

Query to insert

#wrong way
insert into author  values('Saurabh Gupta');
insert into author  values ('Gaurav Gupta');

Exception Stacktrace

 
    Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Column count does not match; SQL statement:
     insert into author values('Saurabh Gupta') [21002-199]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:451) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:427) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.message.DbException.get(DbException.java:170) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.command.dml.Insert.prepare(Insert.java:314) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.command.Parser.prepareCommand(Parser.java:689) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Session.prepareLocal(Session.java:627) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.engine.Session.prepareCommand(Session.java:565) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1292) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:217) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:205) ~[h2-1.4.199.jar:1.4.199]

Solutions

Thumb rule for database insert query is always mention the column name as below while inserting records so that if new column add on table or position change of columns in table then no code and query change required.

For above example the solution would be as below.

insert into author values(10001,'Saurabh Gupta');
insert into author values(10002,'Gaurav Gupta');

Recommend Solution

Here inserting records with column name.

insert into author (id, name) values(10001,'Saurabh Gupta');
insert into author (id, name) values(10002,'Gaurav Gupta');

You would like to see

Follow below link to see more JDBC, Hibernate and JPA issues solutions.

[Solved] java.lang.IllegalStateException: The file is locked


Here this exception occurred because trying to connect H2 database through application while it’s already connected through eclipse data source explorer. That’s why when running application will through exception as “the file is locked.


java.lang.IllegalStateException: The file is locked: nio:C:/Users/saurabh.gupta1/testdb.mv.db [1.4.199/7]
    at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:883) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.FileStore.open(FileStore.java:172) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.MVStore.(MVStore.java:390) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.MVStore$Builder.open(MVStore.java:3343) ~[h2-1.4.199.jar:1.4.199]
    at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:162) ~[h2-1.4.199.jar:1.4.199]

Solutions

Follow below steps to resolve this issue. You just need to follow disconnect steps. Connect steps are just to reference to reach Data source explorer.

Steps to connect with H2 database with Eclipse

  • Go to eclipse
  • Go to tab Window -> View -> Type “Data” – Click on “Data Explorer”.
  • Select “Generic JDBC”
  • Fill properties as below.
  • Then click on Finish.

H2 database connection

Steps to disconnect database through eclipse

  • Go to “Data Explore”.
  • Expend Database connection.
  • Right click on H2DB database
  • Select option Disconnect.

Now run  application your issue get resolved.

You would like to see

Follow below link to see more JDBC, Hibernate and JPA issues solutions.

[Solved] org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect’ not set


Here this issue occurred while connecting to database through Hibernate and not declared dialect while mentioning all connection properties. In hibernate dialect is required properties so that hibernate known what type of queries need to generate because every database have different queries patterns.

Exception Stacktrace


Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]

Solutions

Below is example to connect to H2 database by hibernate. You can update properties values according to your database. Added hibernate.dialect to connect H2 database.

Hibernate Supported Dialect List

In hibernate.cfg.xml

<property name="dialect">
org.hibernate.dialect.H2Dialect
</property>

In application.properties with Spring boot + JPA

spring.jpa.database-platform=org.hibernate.dialect

References

https://stackoverflow.com/questions/24655684/spring-boot-default-h2-jdbc-connection-and-h2-console

Mask Aadhar Number On Page


What is Aadhaar?

Aadhaar is a verifiable 12-digit identification number issued by UIDAI (“Authority”) to the resident of India for free of cost after satisfying the verification process laid down by the Authority.
Any individual, irrespective of age and gender, who is a resident of India, may voluntarily enrol to obtain Aadhaar number based on demographic and biometric information.

What is Masked Aadhaar?

Aadhar number is very senstive information by which we can track an individual complete information thats why UIDAI provide both the options for down load Aadhar card.

1) Regular Aadhar Card : All digits visible
2) Masked Aadhar Card : Replacing of first 8 digits of Aadhaar number with some characters like “xxxx-xxxx” while only last 4 digits of the Aadhaar Number are visible.

How to Mask Aadhaar in your web page?

Making aadhar number Replacing of first 8 digits of Aadhaar number with some characters like “xxxx-xxxx” while only last 4 digits of the Aadhaar Number are visible. In web page
aadhar number text box when user click/focus or hover on text box will display regular aadahr number otherwise will display as masked.

See Also :

Mask Aadhar Number Example

how to mask aadhar number on web page masked aadhar number on page

HTML Changes

Create a text box on your page with below html.

Aadhar Number: <input type="text" id="txtAadhar" />

Java Script/JQuery Changes

Copy below java script in your head section of page.


var originalVal;
$(document).ready(function()
{
       if($('#txtAadhar').val().length>0)
		 {
		 if($('#txtAadhar').val().indexOf("X")==-1)
			{
			  originalVal=$('#txtAadhar').val();
			}
		    maskAadhar(this);
		 }

	    $('#txtAadhar').blur( function(e)
		{
	    	if($('#txtAadhar').val().indexOf("X")==-1)
	    	{
	    	  originalVal=$('#txtAadhar').val();
	    	}
	    	 maskAadhar(this);
		});

		$('#txtAadhar').focus( function(e)
		{
			$(this).val(originalVal);
		});
});
function maskAadhar(regularAadhar)
{
	 var varlen =$(regularAadhar).val().length;
	 if(varlen > 12)
	 {
	 $("#error").text('Not Valid Aadhar Number.');
	 }
	 else
	 {
	 $("#error").text('');
	 var str = $(regularAadhar).val();

	 var mask = varlen > 0 ? varlen > 1 ? varlen > 2 ? varlen > 3 ? varlen > 4 ? varlen > 5  ? varlen > 6 ? varlen > 7 ?
	        'XXXX XXXX'
          : 'XXXX XXX'
          : 'XXXX XX'
          : 'XXXX X'
          : 'XXXX'
		  : 'XXX'
		  : 'XX'
		  : 'X'
          : '';
          if (varlen < 9) {
          $(regularAadhar).val(mask);
          } else {
          $(regularAadhar).val(mask +' '+ $(regularAadhar).val().substring(8));
          }
   }
}

Download Source code

To download the source code of this example, click on below given download link.

Mask Aadhar Card

Drop me your questions in comments section.

References

https://www.uidai.gov.in/my-aadhaar/about-your-aadhaar.html
https://www.uidai.gov.in/283-faqs/aadhaar-online-services/e-aadhaar/1887-what-is-masked-aadhaar.html

Java : Keywords with Categories


Java programming language is having 57 reserved words that’s called as keyword. These keyword can not be used as name for variables, methods, classes, interfaces or as any other identifier.

Java Keywords 

abstract assert boolean break byte
case catch char class continue
default do double else enum
exports extends final finally float
for for if implements import
instanceof int interface long module
native new package private protected
public requires return short static
strictfp super switch synchronized this
throw throws transient try void
volatile while true null false
const go

Note : Out of these 57 keywords only 55 are used by programmers other 2 (const and go) are not used.

Primitive Type Keyword

Primitive types are most basic data types available in Java language which are having predefined fixed size, range , default values and no methods. These types serve as  building blocks of data manipulation in java language.

Primitive Type: boolean, byte, char, short, int, long, float and double.

See Also:

Literal Value Keywords

A literal is the source code representation of a fixed value and assigned directly to variable without requiring computation.

Literal assigned to primitive type variable as it’s not required new keyword. Primitive types are special data types built into the language; they are not objects created from a class. Below are some literal values for Boolean type (true and false) and Non primitive objects (null).

  • true : A boolean literal value.
  • false : A Boolean literal value.
  • null : A reference literal value.

See Also:

Control Flow Keywords

Generally statements in java code executed from top to bottom, in the same order as they appears. Control flow statements change or break the flow of execution by implementing decision making, looping and branching of program to execute particular blocks of code based on certain conditions.

Control Flow statement categories as below:

  • Decision-making statements : if-then, if-then-else, switch-case
  • Looping statements : for, while, do-while
  • Branching statements : break, continue, return

See also :

  • Control Flow Statements with examples

Exception Handling keywords

Keyword Description
try The try block governs the statements that are enclosed within it and defines the scope of exception handler associated with it. Try block follows catch or finally or both.
catch The catch block is used to handle the exception. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.
finally When an exception is raised, the statement in the try block is ignored, some times it is necessary to process certain statements irrespective of wheather an exception is raised or not, the finally block is used for this purpose.
throw The throw class is used to call exception explicitly. You may want to throw an exception when the user enters a wrong login ID and password, you can use throw statement to do so. The throw statement takes an single argument, which is an Object of exception class.
throws The throws statement species the list of exception that has thrown by a method. If a method is capable of raising an exception that is does not handle, it must specify the exception has to be handle by the calling method, this is done by using the throw statement.

See Also :

Access Modifiers

Java access modifiers helps to restrict the scope of a class, constructor , variable , method or data member. There are four types of access modifiers available in java:

  • default (No Keyword Required)
  • private
  • protected
  • public

Below are the scope of each access modifiers:

default
private protected public
Same Class Yes Yes Yes Yes
Same Package Subclass Yes No Yes Yes
Same Package non Sub Class Yes No Yes Yes
Different Package Sub Class No No Yes Yes
Different Package Non Sub Class No No No Yes

See Also :

Non Access Modifiers

Below are some keywords that use as non-access modifiers to achieve many other functionalities:

Modifiers Description
static Used to declare a field, method, or inner class as a class field.

  • static with class fields:
    Classes maintain one copy of static fields regardless of how many instances exist of that class. These static fields also called as class variables.
  • static with method:
    These methods are bound to the class instead of to a specific instance, and can only operate on class variables. These static method also called as class methods.

Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.

final Used to declare an entity that can not be changed or nor derived later.

  • final with variable :
    • A final variable can explicitly assigned only once.
    • If a reference variable declared final can never be reassigned to refer to an different object. However, the data within the object can be changed.
    • A final modifier often is used with static to make the constant a class variable.
  • final with method :
    A final method can not be override.
  • final with class :
    A final class can not be sub classed. All methods in a final class are implicitly final.
abstract A abstract keyword is used with methods and classes to provide abstraction in Java.

  • abstract with methods :
    A method with no definition must be declared as abstract and the class containing it must be abstract.
  • abstract with class :
    • An abstract class can not be instantiated. it must be implemented in sub classes.
    • An abstract class not required to have a abstract method.
    • An abstract class may contain both abstract methods as well normal methods.A class cannot be both abstract and final (since a final class cannot be extended)

    Note : abstract keyword can not be used with variables and constructors.

synchronized The synchronized keyword used to declare a method or code block to acquire mutex lock for an object so that only one thread access at a time. The mutex lock is automatically released when execution exits the synchronized code.

  • The synchronized modifier can be applied with any of the four access level modifiers.
  • For static methods, the object locked is the class’s Class.
  • Fields, classes and interfaces cannot be declared as synchronized.
transient An instance variable is marked transient to indicate the JVM to skip the particular variable when serializing the object containing it. When object deserialized transient values will initialize with default value.
volatile A volatile keyword used in field declarations to specify that the variable is modified asynchronously by concurrently running threads. Volatile variable cached in main memory so that synchronizes value between threads.

  • Volatile can only be applied to instance variables, which are of type object or private.
  • A volatile object reference can be null.
  • This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.
  • Methods, classes and interfaces can not be  declared volatile, nor can local variables or parameters.
strictfp java strictfp keyword is used to restricting floating-point and round of calculations (float and double) and ensuring same result on every platform while performing operations with floating point variable.

See Also: strictfp modifier uses and example

Class , objects and methods related keywords

package

Java package is a group of similar classes and interfaces that used as namespace to resolve conflict between same name class. Packages are declared with the package keyword.

class

A class is template that defines the implementation of a particular kind of object.

  • A class definition defines instance and class fields, methods, and inner classes as well as specifying the interfaces the class implements and the immediate super class of the class.
  • If the super class is not explicitly specified, the super class is implicitly Object.
  • The class keyword can also be used in the form Class.class to get a Class object without needing an instance of that class. For example, String.class can be used instead of doing new String().getClass().

interface

An interface is used to declare a special type of class that provide abstraction.

  • An interface only contains abstract or default methods, constant (static final) fields and static interfaces.
  • It can later be implemented by classes that declare the interface with the implements keyword.
  • As multiple inheritance is not allowed in Java, interfaces are used to circumvent it. An interface can be defined within another interface.

import

Used at the beginning of a source file to specify classes or entire Java packages to be referred to later without including their package names in the reference.

  • import statements can import static members of a class. (java 5+)

extends

  • Used in a class declaration to specify the super class.
  • Used in an interface declaration to specify one or more super interfaces.
  • Class X extends class Y to add functionality, either by adding fields or methods to class Y, or by overriding methods of class Y. Class X is said to be a subclass of class Y.
  • An interface Z extends one or more interfaces by adding methods. Interface Z is said to be a sub interface of the interfaces it extends.
  • Also used to specify an upper bound on a type parameter in Generics.

implements

Included in a class declaration to specify one or more interfaces that are implemented by the current class. A class inherits the types and abstract methods declared by the interfaces.

new

  • Used to create an instance of a class or array object.
  • It is used to say completely new object need to create. (String Pool)

super

Inheritance basically used to achieve dynamic binding or run-time polymorphism or re-usability in java.

  • Used to access members of a class inherited by the class in which it appears.
  • Allows a subclass to access overridden methods and hidden members of its super class.
  • The super keyword is also used to forward a call from a constructor to a constructor in the super class.
  • Also used to specify a lower bound on a type parameter in Generics.

this

Used to represent an instance of the class in which it appears.

  • The this can be used to access class members and as a reference to the current instance.
  • The this keyword is also used to forward a call from one constructor in a class to another constructor in the same class

return

Used to finish the execution of a method. It can be followed by a value required by the method definition that is returned to the caller.

void

The void keyword is used to declare that a method does not return any value.

instanceof

A binary operator that takes an object reference as its first operand and a class or interface as its second operand and produces a boolean result. The instanceof operator evaluates to true if and only if the runtime type of the object is assignment compatible with the class or interface.

native

Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language.[7]

Others Keyword

enum

A Java keyword used to declare an enumerated type. Enumerations extend the base class Enum. This keyword available in java 5  and later.

See Also:

assert

Assert describes a predicate (a true–false statement) placed in a Java program to indicate that the developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort. Optionally enable by ClassLoader method. This keyword available in java 4  and later.

module

The module keyword is used to declare a module inside of a Java application. This keyword is only available in Java 9 and later.

requires

Used to specify the required libraries inside of a module. This keyword is only available in Java 9 and later.

exports

Used in modular java to export a package with a module. This keyword is only available in Java 9 and later.

References

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

Java : Branching statements


Mainly these keywords (break, continue and return)  are use as branching statements which is use to change continuous execution of program.

Branching statements: break, continue, return

break

The break keyword is use to exit from while, do-while, for and switch statements. When a break is executed then execution of statements after break will stop and directly jump to next statement after current block of while, do-while or switch.

Example
In this example print the index of first even number found.

package statements.branching;

public class BreakExample {

	public static void main(String[] args) {

	int[]numbers= {1,5,7,4,6,9,6,10,23,98,46,34};
	boolean firstEven=false;
	int row=0;

	for(row=0;row<numbers.length;row++)
	{
		if(numbers[row]%2==0)
		{
		 firstEven=true;
		 break ;
		 //break will exit from current loop
		 //execute next statement after that
		 }
	}
	if(firstEven)
	{
		System.out.println("First Even Found at :["+row+"]");
	}
    }
}

Output


First Even Found at :[3]

The break will exit from current loop and continue to execute next statement after the loop.

continue

The continue keyword is use inside a while, do- while, and for loop. When a continue is executed, the rest of the loop’s body is skipped and directly jump to the boolean expression for further execution.

Example
This program is to print even numbers between 1 to 20.

package statements.branching;

public class ContinueExample {
public static void main(String[] args) {
     for(int i=1;i<=20;i++)
     {
    	 if(i%2!=0)
    	 {
    		 //if odd number will continue not print statement for even
    		 continue;
    	 }
    	 System.out.println("Even Number :"+i);
     }
 }
}

Output


Even Number :2
Even Number :4
Even Number :6
Even Number :8
Even Number :10
Even Number :12
Even Number :14
Even Number :16
Even Number :18
Even Number :20

When odd number will find out then continue statement in loop will skip next statements inside loop and  go to next condition expression to check for further loop execution.

break and continue with label

The break keyword can optionally use a label to indicate which loop or switch you want a break to operate on, or which loop you want a or continue to operate on. This enables you to easily break out of nested loops or switch statements, or to continue nested loops. To do so you must label the beginning of the loop or switch statement:

Break Label example

public class BreakLabelExample {

public static void main(String[] args) {
	int[][]numbers= {{1,5,7},{4,6},{9,6,10,23},{98,46,34}};
	boolean firstEven=false;
	int row=0, col=0;
	loop:	for(row=0;row<numbers.length;row++)
		{
		  for(col=0; col<numbers[row].length;col++)
			{
			if(numbers[row][col]%2==0)
			{
			firstEven=true;
			break loop;//label break
			}
		 }
	}
	if(firstEven)
	{
	System.out.println("First Even Found at :["+row+"]["+col+"]");
	}
    }
}

Output


First Even Found at :[1][0]

When the break loop statement is executed, the for loop labeled loop (the outer loop) is exited.
Continue Label Example

package statements.branching;
import java.util.Arrays;
public class BreakLabelExample {
	public static void main(String[] args) {
	int[][]numbers= {{1,6,7},{4,6},{9,6,10,23},{98,46,34}};
	loop:	for(int i=0;i<numbers.length;i++)
		{
		boolean allEven=true;
		for(int number:numbers[i])
		{
			if(number%2!=0)
			{
			allEven=false;
			continue loop;//label continue
			}
		}
		if(allEven)
		{
	System.out.println("Processing the array of all even numbers :"+Arrays.toString(numbers[i]));
		}
	}
   }
}

Output


Processing the array of all even numbers :[4, 6]
Processing the array of all even numbers :[98, 46, 34]

When continue loop statement executed, the for loop labeled loop( the outer loop) will continue.

The return Statement

The return statement returns from a method, potentially returning a value. If the method is declared as void, you must use a simple return statement :

retrun;

Otherwise, you must indicate a return value with a type that matches the return type of the method. For example, a method declared with a boolean return type could have the following statement:

return true;

Example

Program to get even numbers with in given range as starting number and ending number.

package statements.branching;

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

public class ReturnExample {

	public static void main(String[] args) {
		int startNumber=5, endNumber=35;
        System.out.println("Even Numbers between : "+startNumber+" and "+endNumber);
        //calling method returning value
        Integer []numbers=evenNumbers(startNumber,endNumber);
        //calling method not returning value
        printNumbers(numbers);
	}
	/**
	 * Method with retrun value
	 */
	public static Integer[] evenNumbers(int startNumber,int endNumber)
	{
		 List list=new ArrayList();
		int i=0;
		while(startNumber<=endNumber)//while loop
	     {
	    	 if(startNumber%2==0)
	    	 {
	    		 list.add(startNumber);
	    	 }
	    	 startNumber++;
	     }
		//convert Arraylist to array
		return list.toArray(new Integer[list.size()]);
	}
	/**
	 * Method without return value
	 */
	public static void printNumbers(Integer[]numbers)
	{
		if(numbers==null ||numbers.length==0)
		{
			System.out.println("No Numbers find out");
			return;
			//return without value;
			//No statement executed after
		}
		for(int number:numbers)//for each loop
		System.out.println( number);

	}
}

Output


Even Numbers between : 5 and 35
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34

In this example using return with value in method evenNumbers() when returning integer array of even numbers. While in method printNumbers() having return type as void , use return statement without value because we don’t want to further execute statements of method when passing array is blank or empty.

Java : Expression Statements


The expression statement in java is a one kind of statement that usually created to produce some new value. Expressions are built using values, variables, operators and method calls. Although, Sometimes an expression assigns a value to a variable .

Types of Expressions

While an expression frequently produces a result, it doesn’t always. There are three types of expressions in Java:

  1. Expression that produce a value
    (4 + 5);
    
  2. Expression that assign a variable
    result=(4 + 5);
    
  3. Expression that have no result but might have a “side effect” because an expression can include a wide range of elements such as method invocations or increment operators that modify the state (i.e., memory) of a program. A method invocation that declared as void.
     i++;
     k--;
     ++i;
     --k;
    
    exception.printStackTrace();
    

Expression that produce a value

Expressions that produce value use wide range of operators to generate result.

  • Arithmatic Operators : +,-,*,/,%
  • Conditional Operators :||,&&, ? :
  • Comparison Operators : ==, !=, > , >=, <, <=,

These expressions produce a value:

4*5

5/3

5% 2

pi + (20 * 3)

Expressions that assign a value

While some expressions produce no result, they can have a side effect which occurs when an expression changes the value of any of its operands or methods with return type as void.

//Declaration statements with assignment;
int secondsInDays=0;
int daysInWeek=7;
int hoursInDay=24;
int minutesInHour=60;
int secondsInMinute=60;
boolean calculateWeek=true;
//Varible assignment expression
int secondsInDays=secondsInMinute * minutesInHour * hoursInDay;
System.out.println("The number of seconds in a day is: " + secondsInDay);

Here in the first six lines of the code, are expression with assignment operator where assign value on the right side variable of the left. After that where calculating value for variable secondsInDays is an expression statement which is built up through use of more than one operator.

Expressions with no Result

try{
	int k=0;
	int x=0;

	//expressions not return any value or assign variable
	//but side effects are more
	x++;
	++x;

	//expression statement with operator
	k=(x/k);
}
catch(Exception ex)
{
	//expression not returning any value
	//because method return type is void
	ex.printStackTrace();
}

In above example using prefix and postfix increment that changing it’s own value but not returning or assigning any variable. Same as in catch block method printStackTrace() return type is void but it’s print exception stack trace in console logs.

References

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
https://www.thoughtco.com/expression-2034097

Java : Declaration Statements


Java declaration statements are one kind of statement, where declare a variable with specifying it’s data type and name.

A variable is named container (identifier) that holds values used in a Java program. A variable can be initialize with some value and can also have calculated values from expressions which can vary over time.

Example of variable declarations in Java

The following statements are declaration of variables of int, boolean and String. Here these variables will initialize with default values.

See also: Java : Primitive Type Default Value and Range

Note: Declaration statements always end with semicolon(;).

int perk;
int salary;
boolean isValid;
boolean isCompleted;
String empFirstName;
String empLastName;

In statement declaration, apart from declare variable and type we can also initialize with some literal values.

int perk=20000;
int salary=50000;
boolean isValid=true;
boolean isCompleted=false;
String empFirstName="Saurabh";
String empLastName="Gupta";

To reduce number of lines of code and more clarity, we can also declare same type, more than one variable on same line with comma separated.

int salary, perk=20000;
boolean isValid=true,isCompleted;
String empFirstName="Saurabh",empLastName="Gupta";

Java : strictfp Modifier


What is strictfp in Java?

java strictfp keyword is modifier. strictfp used to restricting floating-point and round of  precision calculations (float and double) and ensuring same result on every platform while performing operations with floating point variable.

Why strictfp in java?

In java floating point calculations are platform dependent i.e. different precision output(floating point values) is achieved when a class file is run on different platforms(16/32/64 bit processors).

To solve such issues strictfp keyword was introduced in java 1.2 and later version by following IEEE 754 standards for floating-point calculations.

Where can we use strictfp?

Below are cases where strictfp use:

Allowed:

  • strictfp modifier is used with classes, interfaces and methods only.
  • When a class or an interface is declared with strictfp modifier, then all methods declared in the class/interface, and all nested types declared in the class, are implicitly follow strictfp.

Not Allowed

  • strictfp cannot be used with abstract methods. However, it can be used with abstract classes/interfaces.
  • strictfp cannot be used with any method inside an interface because methods of an interface are implicitly abstract,

How to use strictfp in java?

strictfp with class

strictfp class TestClass
{
    // all concrete methods here are
    // implicitly strictfp.
}

strictfp with interface

strictfp interface Test
{
    // all  methods here becomes implicitly
    // strictfp when used during inheritance.
}

strictfp with methods

class TestClass
{
    // strictfp applied on a concrete method
    strictfp void calculateSalary(){}
}

Note: strictfp cannot be used with any method inside an interface.

strictfp interface TestClass
{
    double sum();
    strictfp double multiply(); // compile-time error here
}

Example 

In this example applying strictfp in method where performing calculation and calling method where showing results so that show same result as calculated after applying strictfp.

public class StrictfpExample {

	public strictfp double addition(double a , double b)
    {
         return (a+b);
    }
	public strictfp double substraction(double a , double b)
    {
         return (a-b);
    }
	public strictfp double multiplication(double a , double b)
    {
         return (a*b);
    }
	public strictfp double division(double a , double b)
    {
         return (a/b);
    }
	public static void main(String[] args) {

		double num1 = 12e+10; 

        double num2 = 8e+08;

        StrictfpExample test=new StrictfpExample();

        System.out.println("Addition :"+test.addition(num1,num2));
        System.out.println("Substraction :"+test.substraction(num1,num2));
        System.out.println("Multiplication :"+test.multiplication(num1,num2));
        System.out.println("Division :"+test.division(num1,num2));
	}

}

Output


Addition :1.208E11
Substraction :1.192E11
Multiplication :9.6E19
Division :150.0

References

https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.3

Java : Access Modifiers/Specifiers


Java access modifiers helps to restrict the scope of a class, constructor , variable , method or data member. There are four types of access modifiers available in java:

  • default (No Keyword Required)
  • private
  • protected
  • public

Note : Some people also called as access specifiers.

Points to remember :

  • Try to use most restrictive access level that make sense for member
  • Try to use private as long as not having reason to not use.
  • Use constants value as public.

Scope of Access Modifiers

Below are the scope of each access modifiers:

default private protected public
Same Class Yes Yes Yes Yes
Same Package Subclass Yes No Yes Yes
Same Package non Sub Class Yes No Yes Yes
Different Package Sub Class No No Yes Yes
Different Package Non Sub Class No No No Yes

Below are in-depth description about each access modifiers with example.

Default

When no access modifier is specified for a class , method or data member. It is considered as having the default access modifier by default.

  • Default access modifiers are accessible only within the same package.

Example
In this example, created two packages (pkg1 and pkg2) and the respective classes (TestClass1 and TestClass2) which are not having access modifiers. By this example trying to access TestClass1 from pkg1 to another pkg2 that’s not allowed thats why through compile time issue.

//Java program to illustrate default modifier
package pkg1; 

//TestClass1 is having Default access modifier
class TestClass1
{
    void display()
       {
           System.out.println("Welcome to Facing Issues On IT!");
       }
}
//Java program to illustrate error while
//using class from different package with
//default modifier
package pkg2;
import pkg1.*; 

//This class is having default access modifier
class TestClass2
{
    public static void main(String args[])
       {
          //accessing class TestClass1 from package pkg1
          TestClass1 obj = new TestClass1(); 

          obj.display();
       }
}

Output


Compile time error

private

The private keyword is used in the declaration of a method, field, or inner class; private members can only be accessed by other members of their own class in which they are declared.

  • private means “only visible within the enclosing class”.
  • Any other class of same package will not be able to access these private members.
  • private can be applied on nested classes but not on top level Classes or interface.

Example
In this example, created class TestClass1 in package pkg1 where method display having access modifiers as private. This method is trying to access in TestClass2 but due to private restriction not allowed to access out side of class thats why through compile time issue.

//Java program to illustrate error while
//using class from different package with
//private modifier
package pkg1; 

class TestClass1
{
   private void display()
    {
         System.out.println("Welcome to Facing Issues On IT!");
    }
}
class TestClass2
{
   public static void main(String args[])
      {
          TestClass1 obj = new TestClass1();
          //trying to access private method of another class
          obj.display();
      }
}

Output


error: display() has private access in A
        obj.display();

protected

The protected keyword is used in the declaration of a method, field, or inner class; protected members can only be accessed by members of their own class, that class’s subclasses or classes from the same package.

  • protected means “only visible within the enclosing class and any subclasses”
  • The methods or data members declared as protected are accessible within same package or sub classes in different package.

Example
In this example, created two packages (pkg1 and pkg2) and the respective classes (TestClass1 and TestClass2) which are having access modifiers as public. Class TestClass1 is having method display with protected access modifiers. Here we are extending TestClass2 with super class TestClass1 and accessing method display()of super class.

//Java program to illustrate
//protected modifier
package pkg1; 

//Class TestClass1
public class TestClass1
{
   protected void display()
    {
        System.out.println("Welcome to Facing Issues On IT!");
    }
}
//Java program to illustrate
//protected modifier
package pkg2;
//importing all classes in package pkg1
import pkg1.*; 

//Class TestClass2 is subclass of TestClass1
class TestClass2 extends TestClass1
{
   public static void main(String args[])
   {
       TestClass2 obj = new TestClass2();
       obj.display();
   }
}

Output:


Welcome to Facing Issues On IT!

public

The public keyword is used in the declaration of a class, method, or field; public classes, methods, and fields can be accessed by the members of any class.

  • There is no restriction on the scope of a public data members.
  • The public access modifier has the widest scope among all other access modifiers.

Example
In this example, created two packages (pkg1 and pkg2) and the respective classes (TestClass1 and TestClass2) which are having access modifiers public. By this example trying to access TestClass1 method display() having public access from pkg1 to another package pkg2 class TestClass2 .

//Java program to illustrate
//public modifier
package pkg1;
public class TestClass1
{
   public void display()
      {
         System.out.println("Welcome to Facing Issues On IT!");
      }
}
package pkg2;
import pkg1.*;
class TestClass2
{
    public static void main(String args[])
      {
          TestClass1 obj = new TestClass1();
          obj.display();
      }
}

Output


Welcome to Facing Issues On IT!

Java : Wrapper Classes


Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.

Wrapper classes  implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Advantages of Wrapper Class

Wrapper classes helps where we can’t use primitive type values only need objects. Compiler automatically converts primitive type to correspoing Wrapper classes as required.
Below are some most common advantages of wrappe classes:

  • Wrapper class required to convert the primitive data types in to objects. (Objects required when handling with collections)
  • In Generics programming, can be used with classes only not with primitive types.
  • Package java.util(Collections) contains only classes which only handles objects.
  • In multi threading, we need object to support synchronization.
  • These classes in java.lang package so no need to explicitly import it.

The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes are given below:

Primitive Type Wrapper Description
boolean Boolean The Boolean class wraps a value of the primitive type boolean in an object.
char Character The Character class wraps a value of the primitive type char in an object.
byte Byte The Byte class wraps a value of primitive type byte in an object.
short Short The Short class wraps a value of primitive type short in an object.
int Integer The Integer class wraps a value of the primitive type int in an object.
long Long The Long class wraps a value of the primitive type long in an object.
float Float The Float class wraps a value of primitive type float in an object.
double Double The Double class wraps a value of the primitive type double in an object.

Wrapper Type Class Hierarchy

Java Wrapper Classes for primitive Type
Java Wrapper Classes for Primitive Type

Note : The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.

Now you have learned about primitive type and corresponding wrapper Type and it’s class hierarchy. In further section you will lean about Autoboxing and Unboxing i.e conversion from primitive type to wrapper class or wrapper class to primitive type.

Autoboxing/Unboxing (Java 5+)

  • Autoboxing: Automatically converts primitive type into object/Wrapper Class.
    int a=30;
    //Manually covert int to Integer
    Integer k=Integer.valueOf(a);
    //Autoboxing, compiler will automatically convert to Integer and internally generate Integer.valueOf(a)
    Integer j=a;
    
  • Unboxing: Automatically converts object/Wrapper Class into primitive type.
    Integer a=new Integer(30);
    //Manually convert Integer to int
    int j=a.intValue();
    //Unboxing , compiler will automatically convert to int and internally generate a.intValue();
    int j=a;
    

From above example you can understand how internally conversion happen between primitive to wrapper class and wrapper class to primitive type.

Now here  corresponding to each wrapper class link you will get list of Constants, methods and exceptions.

References

https://docs.oracle.com/javase/8/docs/api/?java/lang/Integer.html
https://docs.oracle.com/javase/tutorial/java/data/numberclasses.htmlhttps://docs.oracle.com/javase/tutorial/java/data/numberclasses.html

Java : Primitive Type


Primitive types are most basic data types available in Java language which are having predefined fixed size, range , default values and no methods. These types serve as  building blocks of data manipulation in java language.

Primitive Type: boolean, byte, char, short, int, long, float and double.

See Also:

Primitive types further classified in three categorize:

  • Numeric Primitive: short, int, long, float and double. These primitive data types can hold only numeric data . We can perform arithmetic and comparison operation with this data.
  • Textual Primitive: byte and char. These primitive data type can hold characters. We can perform operation as compare character , add characters to make words etc. byte and char also used for arithmetic operations
  • Boolean and null primitives: boolean and null.
Java Primitive Type Keywords
Java : Primitive Type , size , range and default value

Points to remember about Primitive Type :

  • These primitive types are pre-defined java keyword. These type can not use as identifiers.
  • These keywords can also used to declare a method return type.
  • Character literals should be surrounded with single quote (‘ ‘) i.e ‘a’ or ‘A’.
  • Floating values should have end character as f or F. i.e 1.35f.
  • Decimal values should have end character as d or D i.e  3.245d.
  • A floating point number can also be a scientific number with an “e” to indicate the power of 10.

Numbers

Numeric primitive type divided into two groups :

  1. Integer Types : Stores whole numbers, positive and negative values (-25 or 430 etc.),  without decimal points. Valid types are byte, short, int and long.
  2. Floating Types : Stores numbers with fractional parts, contains one or more decimals. Valid types are float and double.

Note: The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

Representation of Primitive Type

Below are example of all primitive types:

int myAge = 15;               // Integer (whole number)
float salary = 50000.99f;    // Floating point number
char sex = 'M';              // Character
boolean employed = true;     // Boolean
Scientific Numbers
A floating point number can also be a scientific number with an “e” to indicate the power of 10.
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

References

https://en.wikibooks.org/wiki/Java_Programming/Primitive_Types

java.lang.Boolean Class & Methods


The java.lang.Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.  This class provides many methods for converting a boolean to a String and a String to a boolean, as well as other constants and methods useful when dealing with a boolean.

Boolean class implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Constants

  • static Boolean FALSE :The Boolean object corresponding to the primitive value false.
  • static Boolean TRUE :The Boolean object corresponding to the primitive value true.
  • static Class TYPE :The Class object representing the primitive type boolean.

Constructors

  • Boolean(boolean value) :Allocates a Boolean object representing the value argument.
    Boolean(String s) :Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string “true”.

Methods

  • boolean booleanValue() :Returns the value of this Boolean object as a boolean primitive.
  • static int compare(boolean x, boolean y) :Compares two boolean values.
  • int compareTo(Boolean b) :Compares this Boolean instance with another.
  • boolean equals(Object obj) :Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.
  • static boolean getBoolean(String name) :Returns true if and only if the system property named by the argument exists and is equal to the string “true”.
  • int hashCode() :Returns a hash code for this Boolean object.
  • static boolean parseBoolean(String s) :Parses the string argument as a boolean.
  • String toString() :Returns a String object representing this Boolean’s value.
  • static String toString(boolean b) :Returns a String object representing the specified boolean.
  • static Boolean valueOf(boolean b) :Returns a Boolean instance representing the specified boolean value.
  • static Boolean valueOf(String s) :Returns a Boolean with a value represented by the specified string.

References

java.lang.Character Class & Methods


The java.lang.Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char.  This class provides several methods for determining a character’s category (lowercase letter, digit, etc.) and for converting characters from uppercase to lowercase and vice versa.

Character information is based on the Unicode Standard. The methods and data of class Character are defined by the information in the UnicodeData file that is part of the Unicode Character Database maintained by the Unicode Consortium. This file specifies various properties including name and general category for every defined Unicode code point or character range.

Character class implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Sub Class

  • static class Character.Subset :Instances of this class represent particular subsets of the Unicode character set.
  • static class Character.UnicodeBlock :A family of character subsets representing the charater blocks in the Unicode specification.
  • static class Character.UnicodeScript :A family of character subsets representing the character scripts defined in the Unicode Standard Annex #24: Script Names.

Constants

  • static byte COMBINING_SPACING_MARK :General category “Mc” in the Unicode specification.
  • static byte CONNECTOR_PUNCTUATION :General category “Pc” in the Unicode specification.
  • static byte CONTROL :General category “Cc” in the Unicode specification.
  • static byte CURRENCY_SYMBOL :General category “Sc” in the Unicode specification.
  • static byte DASH_PUNCTUATION :General category “Pd” in the Unicode specification.
  • static byte DECIMAL_DIGIT_NUMBER :General category “Nd” in the Unicode specification.
  • static byte DIRECTIONALITY_ARABIC_NUMBER :Weak bidirectional character type “AN” in the Unicode specification.
  • static byte DIRECTIONALITY_BOUNDARY_NEUTRAL :Weak bidirectional character type “BN” in the Unicode specification.
  • static byte DIRECTIONALITY_COMMON_NUMBER_SEPARATOR :Weak bidirectional character type “CS” in the Unicode specification.
  • static byte DIRECTIONALITY_EUROPEAN_NUMBER :Weak bidirectional character type “EN” in the Unicode specification.
  • static byte DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR :Weak bidirectional character type “ES” in the Unicode specification.
  • static byte DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR :Weak bidirectional character type “ET” in the Unicode specification.
  • static byte DIRECTIONALITY_LEFT_TO_RIGHT :Strong bidirectional character type “L” in the Unicode specification.
  • static byte DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING :Strong bidirectional character type “LRE” in the Unicode specification.
  • static byte DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE :Strong bidirectional character type “LRO” in the Unicode specification.
  • static byte DIRECTIONALITY_NONSPACING_MARK :Weak bidirectional character type “NSM” in the Unicode specification.
  • static byte DIRECTIONALITY_OTHER_NEUTRALS :Neutral bidirectional character type “ON” in the Unicode specification.
  • static byte DIRECTIONALITY_PARAGRAPH_SEPARATOR :Neutral bidirectional character type “B” in the Unicode specification.
  • static byte DIRECTIONALITY_POP_DIRECTIONAL_FORMAT :Weak bidirectional character type “PDF” in the Unicode specification.
  • static byte DIRECTIONALITY_RIGHT_TO_LEFT :Strong bidirectional character type “R” in the Unicode specification.
  • static byte DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC :Strong bidirectional character type “AL” in the Unicode specification.\
  • static byte DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING :Strong bidirectional character type “RLE” in the Unicode specification.
  • static byte DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE :Strong bidirectional character type “RLO” in the Unicode specification.
  • static byte DIRECTIONALITY_SEGMENT_SEPARATOR :Neutral bidirectional character type “S” in the Unicode specification.
  • static byte DIRECTIONALITY_UNDEFINED :Undefined bidirectional character type.
  • static byte DIRECTIONALITY_WHITESPACE :Neutral bidirectional character type “WS” in the Unicode specification.
  • static byte ENCLOSING_MARK :General category “Me” in the Unicode specification.
  • static byte END_PUNCTUATION :General category “Pe” in the Unicode specification.
  • static byte FINAL_QUOTE_PUNCTUATION :General category “Pf” in the Unicode specification.
  • static byte FORMAT :General category “Cf” in the Unicode specification.
  • static byte INITIAL_QUOTE_PUNCTUATION :General category “Pi” in the Unicode specification.
  • static byte LETTER_NUMBER :General category “Nl” in the Unicode specification.
  • static byte LINE_SEPARATOR :General category “Zl” in the Unicode specification.
  • static byte LOWERCASE_LETTER :General category “Ll” in the Unicode specification.
  • static byte MATH_SYMBOL :General category “Sm” in the Unicode specification.
  • static int MAX_CODE_POINT :The maximum value of a Unicode code point, constant U+10FFFF.
  • static char MAX_HIGH_SURROGATE :The maximum value of a Unicode high-surrogate code unit in the UTF-16 encoding, constant ‘\uDBFF’.
  • static char MAX_LOW_SURROGATE :The maximum value of a Unicode low-surrogate code unit in the UTF-16 encoding, constant ‘\uDFFF’.
  • static int MAX_RADIX :The maximum radix available for conversion to and from strings.
  • static char MAX_SURROGATE :The maximum value of a Unicode surrogate code unit in the UTF-16 encoding, constant ‘\uDFFF’.
  • static char MAX_VALUE :The constant value of this field is the largest value of type char, ‘\uFFFF’.
  • static int MIN_CODE_POINT :The minimum value of a Unicode code point, constant U+0000.
  • static char MIN_HIGH_SURROGATE :The minimum value of a Unicode high-surrogate code unit in the UTF-16 encoding, constant ‘\uD800’.
  • static char MIN_LOW_SURROGATE :The minimum value of a Unicode low-surrogate code unit in the UTF-16 encoding, constant ‘\uDC00’.
  • static int MIN_RADIX :The minimum radix available for conversion to and from strings.
  • static int MIN_SUPPLEMENTARY_CODE_POINT :The minimum value of a Unicode supplementary code point, constant U+10000.
  • static char MIN_SURROGATE :The minimum value of a Unicode surrogate code unit in the UTF-16 encoding, constant ‘\uD800’.
  • static char MIN_VALUE :The constant value of this field is the smallest value of type char, ‘\u0000’.
  • static byte MODIFIER_LETTER :General category “Lm” in the Unicode specification.
  • static byte MODIFIER_SYMBOL :General category “Sk” in the Unicode specification.
  • static byte NON_SPACING_MARK :General category “Mn” in the Unicode specification.
  • static byte OTHER_LETTER :General category “Lo” in the Unicode specification.
  • static byte OTHER_NUMBER :General category “No” in the Unicode specification.
  • static byte OTHER_PUNCTUATION :General category “Po” in the Unicode specification.
  • static byte OTHER_SYMBOL :General category “So” in the Unicode specification.
  • static byte PARAGRAPH_SEPARATOR :General category “Zp” in the Unicode specification.
  • static byte PRIVATE_USE :General category “Co” in the Unicode specification.
  • static int SIZE :The number of bits used to represent a char value in unsigned binary form, constant 16.
  • static byte :SPACE_SEPARATOR :General category “Zs” in the Unicode specification.
  • static byte START_PUNCTUATION :General category “Ps” in the Unicode specification.
  • static byte SURROGATE :General category “Cs” in the Unicode specification.
  • static byte TITLECASE_LETTER :General category “Lt” in the Unicode specification.
  • static Class TYPE :The Class instance representing the primitive type char.
  • static byte UNASSIGNED :General category “Cn” in the Unicode specification.
  • static byte UPPERCASE_LETTER :General category “Lu” in the Unicode specification.

Constructors

  • Character(char value) :Constructs a newly allocated Character object that represents the specified char value.

Methods

  • static int charCount(int codePoint) :Determines the number of char values needed to represent the specified character (Unicode code point).
  • char charValue() :Returns the value of this Character object.\
  • static int codePointAt(char[] a, int index) :Returns the code point at the given index of the char array.
  • static int codePointAt(char[] a, int index, int limit) :Returns the code point at the given index of the char array, where only array elements with index less than limit can be used.
  • static int codePointAt(CharSequence seq, int index) :Returns the code point at the given index of the CharSequence.
  • static int codePointBefore(char[] a, int index) :Returns the code point preceding the given index of the char array.
  • static int codePointBefore(char[] a, int index, int start) :Returns the code point preceding the given index of the char array, where only array elements with index greater than or equal to start can be used.
  • static int codePointBefore(CharSequence seq, int index) :Returns the code point preceding the given index of the CharSequence.
  • static int codePointCount(char[] a, int offset, int count) :Returns the number of Unicode code points in a subarray of the char array argument.
  • static int codePointCount(CharSequence seq, int beginIndex, int endIndex) :Returns the number of Unicode code points in the text range of the specified char sequence.
  • static int compare(char x, char y) :Compares two char values numerically.
  • int compareTo(Character anotherCharacter) :Compares two Character objects numerically.
  • static int digit(char ch, int radix) :Returns the numeric value of the character ch in the specified radix.
  • static int digit(int codePoint, int radix) :Returns the numeric value of the specified character (Unicode code point) in the specified radix.
  • boolean equals(Object obj) :Compares this object against the specified object.
  • static char forDigit(int digit, int radix) :Determines the character representation for a specific digit in the specified radix.
  • static byte getDirectionality(char ch) :Returns the Unicode directionality property for the given character.
  • static byte getDirectionality(int codePoint) :Returns the Unicode directionality property for the given character (Unicode code point).
  • static String getName(int codePoint) :Returns the Unicode name of the specified character codePoint, or null if the code point is unassigned.
  • static int getNumericValue(char ch) :Returns the int value that the specified Unicode character represents.
  • static int getNumericValue(int codePoint) :Returns the int value that the specified character (Unicode code point) represents.
  • static int getType(char ch) :Returns a value indicating a character’s general category.
  • static int getType(int codePoint) :Returns a value indicating a character’s general category.
  • int hashCode() :Returns a hash code for this Character; equal to the result of invoking charValue().
  • static char highSurrogate(int codePoint) :Returns the leading surrogate (a high surrogate code unit) of the surrogate pair representing the specified supplementary character (Unicode code point) in the UTF-16 encoding.
  • static boolean isAlphabetic(int codePoint) :Determines if the specified character (Unicode code point) is an alphabet.
  • static boolean isBmpCodePoint(int codePoint) :Determines whether the specified character (Unicode code point) is in the Basic Multilingual Plane (BMP).
  • static boolean isDefined(char ch) :Determines if a character is defined in Unicode.
  • static boolean isDefined(int codePoint) :Determines if a character (Unicode code point) is defined in Unicode.
  • static boolean isDigit(char ch) :Determines if the specified character is a digit.
  • static boolean isDigit(int codePoint) :Determines if the specified character (Unicode code point) is a digit.
  • static boolean isHighSurrogate(char ch) :Determines if the given char value is a Unicode high-surrogate code unit (also known as leading-surrogate code unit).
  • boolean isIdentifierIgnorable(char ch) :Determines if the specified character should be regarded as an ignorable character in a Java identifier or a Unicode identifier.
  • static boolean isIdentifierIgnorable(int codePoint) :Determines if the specified character (Unicode code point) should be regarded as an ignorable character in a Java identifier or a Unicode identifier.
  • static boolean isIdeographic(int codePoint) :Determines if the specified character (Unicode code point) is a CJKV (Chinese, Japanese, Korean and Vietnamese) ideograph, as defined by the Unicode Standard.
  • static boolean isISOControl(char ch) :Determines if the specified character is an ISO control character.
  • static boolean isISOControl(int codePoint) :Determines if the referenced character (Unicode code point) is an ISO control character.
  • static boolean isJavaIdentifierPart(char ch) :Determines if the specified character may be part of a Java identifier as other than the first character.
  • static boolean isJavaIdentifierPart(int codePoint) :Determines if the character (Unicode code point) may be part of a Java identifier as other than the first character.
  • static boolean isJavaIdentifierStart(char ch) :Determines if the specified character is permissible as the first character in a Java identifier.
  • static boolean isJavaIdentifierStart(int codePoint) :Determines if the character (Unicode code point) is permissible as the first character in a Java identifier.
  • static boolean isJavaLetter(char ch) :Deprecated. Replaced by isJavaIdentifierStart(char).
  • static boolean isJavaLetterOrDigit(char ch) :Deprecated. Replaced by isJavaIdentifierPart(char).
  • static boolean isLetter(char ch) :Determines if the specified character is a letter.
  • static boolean isLetter(int codePoint) :Determines if the specified character (Unicode code point) is a letter.
  • static boolean isLetterOrDigit(char ch) :Determines if the specified character is a letter or digit.
  • static boolean isLetterOrDigit(int codePoint) :Determines if the specified character (Unicode code point) is a letter or digit.
  • static boolean isLowerCase(char ch) :Determines if the specified character is a lowercase character.
  • static boolean isLowerCase(int codePoint) :Determines if the specified character (Unicode code point) is a lowercase character.
  • static boolean isLowSurrogate(char ch) :Determines if the given char value is a Unicode low-surrogate code unit (also known as trailing-surrogate code unit).
  • static boolean isMirrored(char ch) :Determines whether the character is mirrored according to the Unicode specification.
  • static boolean isMirrored(int codePoint) :Determines whether the specified character (Unicode code point) is mirrored according to the Unicode specification.
  • static boolean isSpace(char ch) :Deprecated. Replaced by isWhitespace(char).\
  • static boolean isSpaceChar(char ch) :Determines if the specified character is a Unicode space character.
  • static boolean isSpaceChar(int codePoint) :Determines if the specified character (Unicode code point) is a Unicode space character.
  • static boolean isSupplementaryCodePoint(int codePoint) :Determines whether the specified character (Unicode code point) is in the supplementary character range.
  • static boolean isSurrogate(char ch) :Determines if the given char value is a Unicode surrogate code unit.
  • static boolean isSurrogatePair(char high, char low) :Determines whether the specified pair of char values is a valid Unicode surrogate pair.
  • static boolean isTitleCase(char ch) :Determines if the specified character is a titlecase character.\
  • static boolean :isTitleCase(int codePoint) :Determines if the specified character (Unicode code point) is a titlecase character.
  • static boolean isUnicodeIdentifierPart(char ch) :Determines if the specified character may be part of a Unicode identifier as other than the first character.
  • static boolean isUnicodeIdentifierPart(int codePoint) :Determines if the specified character (Unicode code point) may be part of a Unicode identifier as other than the first character.
  • static boolean isUnicodeIdentifierStart(char ch) :Determines if the specified character is permissible as the first character in a Unicode identifier.
  • static boolean isUnicodeIdentifierStart(int codePoint) :Determines if the specified character (Unicode code point) is permissible as the first character in a Unicode identifier.
  • boolean isUpperCase(char ch) :Determines if the specified character is an uppercase character.
  • static boolean isUpperCase(int codePoint) :Determines if the specified character (Unicode code point) is an uppercase character.
  • static boolean isValidCodePoint(int codePoint) :Determines whether the specified code point is a valid Unicode code point value.
  • static boolean isWhitespace(char ch) :Determines if the specified character is white space according to Java.
  • static boolean isWhitespace(int codePoint) :Determines if the specified character (Unicode code point) is white space according to Java.
  • static char lowSurrogate(int codePoint) :Returns the trailing surrogate (a low surrogate code unit) of the surrogate pair representing the specified supplementary character (Unicode code point) in the UTF-16 encoding.
  • static int offsetByCodePoints(char[] a, int start, int count, int index, int codePointOffset) :Returns the index within the given char subarray that is offset from the given index by codePointOffset code points.
  • static int offsetByCodePoints(CharSequence seq, int index, int codePointOffset) :Returns the index within the given char sequence that is offset from the given index by codePointOffset code points.
  • static char reverseBytes(char ch) :Returns the value obtained by reversing the order of the bytes in the specified char value.
  • static char[] toChars(int codePoint) :Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array.
  • static int toChars(int codePoint, char[] dst, int dstIndex) :Converts the specified character (Unicode code point) to its UTF-16 representation.
  • static int toCodePoint(char high, char low) :Converts the specified surrogate pair to its supplementary code point value.
  • static char toLowerCase(char ch) :Converts the character argument to lowercase using case mapping information from the UnicodeData file.
  • static int toLowerCase(int codePoint) :Converts the character (Unicode code point) argument to lowercase using case mapping information from the UnicodeData file.
  • String toString() :Returns a String object representing this Character’s value.
  • static String toString(char c) :Returns a String object representing the specified char.
  • static char toTitleCase(char ch) :Converts the character argument to titlecase using case mapping information from the UnicodeData file.
  • static int toTitleCase(int codePoint) :Converts the character (Unicode code point) argument to titlecase using case mapping information from the UnicodeData file.
  • static char toUpperCase(char ch) :Converts the character argument to uppercase using case mapping information from the UnicodeData file.
  • static int toUpperCase(int codePoint) :Converts the character (Unicode code point) argument to uppercase using case mapping information from the UnicodeData file.
  • static Character valueOf(char c) :Returns a Character instance representing the specified char value.

References

java.lang.Short Class & Methods


The java.lang.Short class wraps a value of primitive type short in an object. An object of type Short contains a single field whose type is short. This class provides several utility methods for converting a short to a String and a String to a short, as well as other constants and methods useful when dealing with a short.

Short class implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Constants

  • static short MAX_VALUE :A constant holding the maximum value a short can have, 215-1.
  • static short MIN_VALUE :A constant holding the minimum value a short can have, -215.
  • static int SIZE :The number of bits used to represent a short value in two’s complement binary form.
  • static Class TYPE :The Class instance representing the primitive type short.

Constructors

  • Short(short value) :Constructs a newly allocated Short object that represents the specified short value.
  • Short(String s) :Constructs a newly allocated Short object that represents the short value indicated by the String parameter.

Methods

  • byte byteValue() :Returns the value of this Short as a byte.
  • static int compare(short x, short y) :Compares two short values numerically.
  • int compareTo(Short anotherShort) :Compares two Short objects numerically.
  • static Short decode(String nm) :Decodes a String into a Short.
  • double doubleValue() :Returns the value of this Short as a double.
  • boolean equals(Object obj) :Compares this object to the specified object.
  • float floatValue() :Returns the value of this Short as a float.
  • int hashCode() :Returns a hash code for this Short; equal to the result of invoking intValue().
  • int intValue() :Returns the value of this Short as an int.
  • long longValue() :Returns the value of this Short as a long.
  • static short parseShort(String s) :Parses the string argument as a signed decimal short.
  • static short parseShort(String s, int radix) :Parses the string argument as a signed short in the radix specified by the second argument.
  • static short reverseBytes(short i) :Returns the value obtained by reversing the order of the bytes in the two’s complement representation of the specified short value.
  • short shortValue() :Returns the value of this Short as a short.
  • String toString() :Returns a String object representing this Short’s value.
  • String toString(short s) :Returns a new String object representing the specified short.
  • static Short valueOf(short s) :Returns a Short instance representing the specified short value.
  • static Short valueOf(String s) :Returns a Short object holding the value given by the specified String.
  • static Short valueOf(String s, int radix) :Returns a Short object holding the value extracted from the specified String when parsed with the radix given by the second argument.

Exceptions

References

java.lang.Long Class & Methods


The java.lang.Long class wraps a value of the primitive type long in an object. An object of type Long contains a single field whose type is long.
This class provides several utility methods for converting a long to a String and a String to a long, as well as other constants and methods useful when dealing with a long.

Long class implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Constants

  • static long MAX_VALUE :A constant holding the maximum value a long can have, 263-1.
  • static long MIN_VALUE :A constant holding the minimum value a long can have, -263.
  • static int SIZE :The number of bits used to represent a long value in two’s complement binary form.
  • static Class TYPE :The Class instance representing the primitive type long.

Constructors

  • Long(long value) :Constructs a newly allocated Long object that represents the specified long argument.
  • Long(String s) :Constructs a newly allocated Long object that represents the long value indicated by the String parameter.

Methods

  • static int bitCount(long i) :Returns the number of one-bits in the two’s complement binary representation of the specified long value.
  • byte byteValue() :Returns the value of this Long as a byte.
  • static int compare(long x, long y) :Compares two long values numerically.
  • int compareTo(Long anotherLong) :Compares two Long objects numerically.
  • static Long decode(String nm) :Decodes a String into a Long.
  • double doubleValue() :Returns the value of this Long as a double.
  • boolean equals(Object obj) :Compares this object to the specified object.
  • float floatValue() :Returns the value of this Long as a float.
  • static Long getLong(String nm) :Determines the long value of the system property with the specified name.
  • static Long getLong(String nm, long val) :Determines the long value of the system property with the specified name.
  • static Long getLong(String nm, Long val) :Returns the long value of the system property with the specified name.
  • int hashCode() :Returns a hash code for this Long.
  • static long highestOneBit(long i) :Returns a long value with at most a single one-bit, in the position of the highest-order (“leftmost”) one-bit in the specified long value.
  • int intValue() :Returns the value of this Long as an int.
  • long longValue() :Returns the value of this Long as a long value.
  • static long lowestOneBit(long i) :Returns a long value with at most a single one-bit, in the position of the lowest-order (“rightmost”) one-bit in the specified long value.
  • static int numberOfLeadingZeros(long i) :Returns the number of zero bits preceding the highest-order (“leftmost”) one-bit in the two’s complement binary representation of the specified long value.
  • static int numberOfTrailingZeros(long i) :Returns the number of zero bits following the lowest-order (“rightmost”) one-bit in the two’s complement binary representation of the specified long value.
  • static long parseLong(String s) :Parses the string argument as a signed decimal long.
  • static long parseLong(String s, int radix) :Parses the string argument as a signed long in the radix specified by the second argument.
  • static long reverse(long i) :Returns the value obtained by reversing the order of the bits in the two’s complement binary representation of the specified long value.
  • static long reverseBytes(long i) :Returns the value obtained by reversing the order of the bytes in the two’s complement representation of the specified long value.
  • static long rotateLeft(long i, int distance) :Returns the value obtained by rotating the two’s complement binary representation of the specified long value left by the specified number of bits.
  • static long rotateRight(long i, int distance) :Returns the value obtained by rotating the two’s complement binary representation of the specified long value right by the specified number of bits.
  • short shortValue() :Returns the value of this Long as a short.
  • static int signum(long i) :Returns the signum function of the specified long value.
  • static String toBinaryString(long i) :Returns a string representation of the long argument as an unsigned integer in base 2.
  • static String toHexString(long i) :Returns a string representation of the long argument as an unsigned integer in base 16.
  • static String toOctalString(long i) :Returns a string representation of the long argument as an unsigned integer in base 8.
  • String toString() :Returns a String object representing this Long’s value.
  • static String toString(long i) :Returns a String object representing the specified long.
  • static String toString(long i, int radix) :Returns a string representation of the first argument in the radix specified by the second argument.
  • static Long valueOf(long l) :Returns a Long instance representing the specified long value.
  • static Long valueOf(String s) :Returns a Long object holding the value of the specified String.
  • static Long valueOf(String s, int radix) :Returns a Long object holding the value extracted from the specified String when parsed with the radix given by the second argument.

Exceptions

References

 

java.lang.Integer Class & Methods


The java.lang.Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. This class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.

Integer class implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Constants

  • static int MAX_VALUE :A constant holding the maximum value an int can have, 231-1.
  • static int MIN_VALUE :A constant holding the minimum value an int can have, -231.
  • static int SIZE :The number of bits used to represent an int value in two’s complement binary form.
  • static Class TYPE :The Class instance representing the primitive type int.

Constructors

  • Integer(int value) :Constructs a newly allocated Integer object that represents the specified int value.
  • Integer(String s) :Constructs a newly allocated Integer object that represents the int value indicated by the String parameter.

Methods

  • static int bitCount(int i) :Returns the number of one-bits in the two’s complement binary representation of the specified int value.
  • byte byteValue() :Returns the value of this Integer as a byte.
  • static int compare(int x, int y) :Compares two int values numerically
  • int compareTo(Integer anotherInteger) :Compares two Integer objects numerically.
  • static Integer decode(String nm) :Decodes a String into an Integer.
  • double doubleValue() :Returns the value of this Integer as a double.
  • boolean equals(Object obj) :Compares this object to the specified object.
  • float floatValue() :Returns the value of this Integer as a float.
  • static Integer getInteger(String nm) :Determines the integer value of the system property with the specified name.
  • static Integer getInteger(String nm, int val) :Determines the integer value of the system property with the specified name.
  • static Integer getInteger(String nm, Integer val) :Returns the integer value of the system property with the specified name.
  • int hashCode() :Returns a hash code for this Integer.
  • static int highestOneBit(int i) :Returns an int value with at most a single one-bit, in the position of the highest-order (“leftmost”) one-bit in the specified int value.
  • int intValue() :Returns the value of this Integer as an int.
  • long longValue() :Returns the value of this Integer as a long.
  • static int lowestOneBit(int i) :Returns an int value with at most a single one-bit, in the position of the lowest-order (“rightmost”) one-bit in the specified int value.
  • static int numberOfLeadingZeros(int i) :Returns the number of zero bits preceding the highest-order (“leftmost”) one-bit in the two’s complement binary representation of the specified int value.
  • static int numberOfTrailingZeros(int i) :Returns the number of zero bits following the lowest-order (“rightmost”) one-bit in the two’s complement binary representation of the specified int value.
  • static int parseInt(String s) :Parses the string argument as a signed decimal integer.
  • static int parseInt(String s, int radix) :Parses the string argument as a signed integer in the radix specified by the second argument.
  • static int reverse(int i) :Returns the value obtained by reversing the order of the bits in the two’s complement binary representation of the specified int value.
  • static int reverseBytes(int i) :Returns the value obtained by reversing the order of the bytes in the two’s complement representation of the specified int value.
  • static int rotateLeft(int i, int distance) :Returns the value obtained by rotating the two’s complement binary representation of the specified int value left by the specified number of bits.
  • static int rotateRight(int i, int distance) :Returns the value obtained by rotating the two’s complement binary representation of the specified int value right by the specified number of bits.
  • short shortValue() :Returns the value of this Integer as a short.
  • static int signum(int i) :Returns the signum function of the specified int value.
  • static String toBinaryString(int i) :Returns a string representation of the integer argument as an unsigned integer in base 2.
  • static String toHexString(int i) :Returns a string representation of the integer argument as an unsigned integer in base 16
  • static String toOctalString(int i) :Returns a string representation of the integer argument as an unsigned integer in base 8.
  • String toString() :Returns a String object representing this Integer’s value.
  • static String toString(int i) :Returns a String object representing the specified integer.
  • static String toString(int i, int radix) :Returns a string representation of the first argument in the radix specified by the second argument
  • static Integer valueOf(int i) :Returns an Integer instance representing the specified int value.
  • static Integer valueOf(String s) :Returns an Integer object holding the value of the specified String
  • static Integer valueOf(String s, int radix) :Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument.

Exceptions

References

 

java.lang.Float Class and Methods


The java.lang.Float class wraps a value of primitive type float in an object. An object of type Float contains a single field whose type is float. This class provides several utility methods for converting a float to a String and a String to a float, as well as other constants and methods useful when dealing with a float.

Float class implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Constants

  • static int MAX_EXPONENT :Maximum exponent a finite float variable may have.
  • static float MAX_VALUE :A constant holding the largest positive finite value of type float, (2-2-23)·2127.
  • static int MIN_EXPONENT :Minimum exponent a normalized float variable may have.
  • static float MIN_NORMAL :A constant holding the smallest positive normal value of type float, 2-126.
  • static float MIN_VALUE :A constant holding the smallest positive nonzero value of type float, 2-149.
  • static float NaN :A constant holding a Not-a-Number (NaN) value of type float.
  • static float NEGATIVE_INFINITY :A constant holding the negative infinity of type float.
  • static float POSITIVE_INFINITY : constant holding the positive infinity of type float
  • static int SIZE :The number of bits used to represent a float value.
  • static Class TYPE :The Class instance representing the primitive type float.

Constructors

  • Float(double value) :Constructs a newly allocated Float object that represents the argument converted to type float.
  • Float(float value) :Constructs a newly allocated Float object that represents the primitive float argument.
  • Float(String s) :Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Methods

  • byte byteValue() :Returns the value of this Float as a byte (by casting to a byte).
  • static int compare(float f1, float f2) :Compares the two specified float values.
  • int compareTo(Float anotherFloat) Compares two Float objects numerically.
  • double doubleValue() :Returns the double value of this Float object.
  • boolean equals(Object obj) :Compares this object against the specified object.
  • static int floatToIntBits(float value) :Returns a representation of the specified floating-point value according to the IEEE 754 floating-point “single format” bit layout.
  • static int floatToRawIntBits(float value) :Returns a representation of the specified floating-point value according to the IEEE 754 floating-point “single format” bit layout, preserving Not-a-Number (NaN) values.
  • float floatValue() :Returns the float value of this Float object.
  • int hashCode() :Returns a hash code for this Float object.
  • static float intBitsToFloat(int bits) :Returns the float value corresponding to a given bit representation.
  • int intValue() :Returns the value of this Float as an int (by casting to type int).
  • boolean isInfinite() :Returns true if this Float value is infinitely large in magnitude, false otherwise.
  • static boolean isInfinite(float v) :Returns true if the specified number is infinitely large in magnitude, false otherwise.
  • boolean isNaN() :Returns true if this Float value is a Not-a-Number (NaN), false otherwise.
  • static boolean isNaN(float v) :Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.
  • long longValue() :Returns value of this Float as a long (by casting to type long).
  • static float parseFloat(String s) :Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.
  • short shortValue() :Returns the value of this Float as a short (by casting to a short).
  • static String toHexString(float f) :Returns a hexadecimal string representation of the float argument.
  • String toString() :Returns a string representation of this Float object.
  • static String toString(float f) :Returns a string representation of the float argument.
  • static Float valueOf(float f) :Returns a Float instance representing the specified float value.
  • static Float valueOf(String s) :Returns a Float object holding the float value represented by the argument string s.

Exceptions

References

java.lang.Double Class & Methods


The java.lang.Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double. This class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.

Double class implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Constants

  • static int MAX_EXPONENT : Maximum exponent a finite double variable may have.
  • static double MAX_VALUE :A constant holding the largest positive finite value of type double, (2-2-52)·21023.
  • static int MIN_EXPONENT :Minimum exponent a normalized double variable may have.
  • static double MIN_NORMAL :A constant holding the smallest positive normal value of type double, 2-1022.
  • static double MIN_VALUE :A constant holding the smallest positive nonzero value of type double, 2-1074.
  • static double NaN :A constant holding a Not-a-Number (NaN) value of type double.
  • static double NEGATIVE_INFINITY :A constant holding the negative infinity of type double.
  • static double POSITIVE_INFINITY :A constant holding the positive infinity of type double.
  • static int SIZE :The number of bits used to represent a double value.
  • static Class TYPE :The Class instance representing the primitive type double.

Constructors

  • Double(double value) :Constructs a newly allocated Double object that represents the primitive double argument.
  • Double(String s) :Constructs a newly allocated Double object that represents the floating-point value of type double represented by the string.

Methods

 

  • byte byteValue() :Returns the value of this Double as a byte (by casting to a byte).
  • static int compare(double d1, double d2) :Compares the two specified double values.
  • int compareTo(Double anotherDouble) :Compares two Double objects numerically.
  • static long doubleToLongBits(double value) :Returns a representation of the specified floating-point value according to the IEEE 754 floating-point “double format” bit layout.
  • static long doubleToRawLongBits(double value) :Returns a representation of the specified floating-point value according to the IEEE 754 floating-point “double format” bit layout, preserving Not-a-Number (NaN) values.
  • double doubleValue() :Returns the double value of this Double object.
  • boolean equals(Object obj) :Compares this object against the specified object.
  • float floatValue() :Returns the float value of this Double object.
  • int hashCode() :Returns a hash code for this Double object.
  • int intValue() :Returns the value of this Double as an int (by casting to type int).
  • boolean isInfinite() :Returns true if this Double value is infinitely large in magnitude, false otherwise.
  • static boolean isInfinite(double v) :Returns true if the specified number is infinitely large in magnitude, false otherwise.
  • boolean isNaN() :Returns true if this Double value is a Not-a-Number (NaN), false otherwise.
  • static boolean isNaN(double v) :Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.
  • double longBitsToDouble(long bits) :Returns the double value corresponding to a given bit representation.
  • long longValue() :Returns the value of this Double as a long (by casting to type long).
  • static double parseDouble(String s) :Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
  • short shortValue() :Returns the value of this Double as a short (by casting to a short).
  • static String toHexString(double d) Returns a hexadecimal string representation of the double argument.
  • String toString() :Returns a string representation of this Double object.
  • static String toString(double d) :Returns a string representation of the double argument.
  • static Double valueOf(double d) :Returns a Double instance representing the specified double value.
  • static Double valueOf(String s) :Returns a Double object holding the double value represented by the argument string s.

Exceptions

References

java.lang.Byte Class & Methods


The java.lang.Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte. This class provides several utility methods like converting a byte to a String and a String to a byte, as well as other constants and methods useful when dealing with a byte.

Byte class implements Comparable Interface that’s help while sorting list of Objects on natural order.

See Also:

Constants

  • static byte MAX_VALUE :A constant holding the maximum value a byte can have, 27-1.
  • static byte MIN_VALUE :A constant holding the minimum value a byte can have, -27.
  • static int SIZE :The number of bits used to represent a byte value in two’s complement binary form.
  • static Class TYPE : The Class instance representing the primitive type byte.

Constructors

  • Byte(byte value):Constructs a newly allocated Byte object that represents the specified byte value.
  • Byte(String s) :Constructs a newly allocated Byte object that represents the byte value indicated by the String parameter.

Methods 

  • byte byteValue() :Returns the value of this Byte as a byte.
  • static int compare(byte x, byte y) :Compares two byte values numerically.
  • int compareTo(Byte anotherByte) :Compares two Byte objects numerically.
  • static Byte decode(String nm) :Decodes a String into a Byte.
  • double doubleValue() :Returns the value of this Byte as a double.
  • boolean equals(Object obj) :Compares this object to the specified object.
  • float floatValue() :Returns the value of this Byte as a float.
  • int hashCode() :Returns a hash code for this Byte; equal to the result of invoking intValue().
  • int intValue() :Returns the value of this Byte as an int.
  • long longValue() :Returns the value of this Byte as a long.
  • static byte parseByte(String s) :Parses the string argument as a signed decimal byte.
  • static byte parseByte(String s, int radix) :Parses the string argument as a signed byte in the radix specified by the second argument.
  • short shortValue() :Returns the value of this Byte as a short.
  • String toString() :Returns a String object representing this Byte’s value.
  • static String toString(byte b) :Returns a new String object representing the specified byte.
  • static Byte valueOf(byte b) :Returns a Byte instance representing the specified byte value.
  • static Byte valueOf(String s) :Returns a Byte object holding the value given by the specified String.
  • static Byte valueOf(String s, int radix) :Returns a Byte object holding the value extracted from the specified String when parsed with the radix given by the second argument.

Exceptions

References

java.lang.Number Class & Methods


The abstract class java.lang.Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short. These must provide methods to convert the represented numeric value to byte, double, float, int, long, and short and additional methods as utility.

Constructors:

  • Number()

Methods :

  • byte byteValue(): Returns the value of the specified number as a byte.
  • abstract double doubleValue(): Returns the value of the specified number as a double.
  • abstract float floatValue(): Returns the value of the specified number as a float.
  • abstract int intValue(): Returns the value of the specified number as an int.
  • abstract long longValue(): Returns the value of the specified number as a long.
  • short shortValue(): Returns the value of the specified number as a short.

Exception :

[Solved] java.lang.NumberFormatException: For input string “AB.C”

Java : Widening ,Narrowing Type Casting and Type Promotion In Expression


 

Java Widening and Narrowing Type Casting
Java Widening and Narrowing Type Casting

Widening

Widening, also known as up-casting / automatic conversion that takes place in the following situations :

  • When a small primitive type value is automatically accommodated in a bigger/wider primitive data type.
  • When a reference variable of a subclass is automatically accommodated in the reference variable of its super class.

Note : Widening happen when data type are compatible or conversion from lower to bigger type. Widening is automatic process by Java compiler.

Primitive Type Widening Example

Order of Widening conversion

Byte->Short->Int->Long->Float->Double

public class PrimitiveWidening {

	public static void main(String[] args) {
		int i=200;
		float f=i;
		long l=i;

		System.out.println("Int :"+i);
		System.out.println("Float :"+f);
		System.out.println("Long :"+l);
	}
}

Output


Int :200
Float :200.0
Long :200

Here type conversion is from lower or upper that is widening of primitive type data and that’s not required any type of casting explicitly.

Reference Type Widening Example

public class Doctor {
	public void getDetail() {
		System.out.println("Doctor Detail !!!");
	}
}

public class Surgeon extends Doctor {
	public void getDetail() {
		System.out.println("Surgeon Detail !!!");
	}
}

public class ReferenceTypeWidening {

	public static void main(String[] args) {
		Surgeon s=new Surgeon();
        //Reference of Sub class(Surgeon) type is widened to the Super class (Doctor)
		Doctor d=s;
		d.getDetail();
	}
}

Output


Surgeon Detail !!!

In the previous code, we have a class Doctor extended by class Surgeon, hence Doctor is a super class and Surgeon is its subclass. Method getDetail() of super class Doctor is overridden in subclass Surgeon.
We have created an object of subclass Surgeon, which is assigned to its reference, s.
This subclass Surgeon reference, s is widened/up-casted and assigned to super class Doctor reference, d.

Narrowing

Narrowing also known as down-casting/explicit casting is conversion that take place in such situations:

  • Narrowing a wider/bigger primitive type value to a smaller primitive type value..
  • Narrowing the super class reference to the reference of its subclass, during inheritance.

Note : Narrowing happen when data type are incompatible or conversion from bigger to lower type. That require explicit casting of data. While narrowing of data type some of data values can lost.

Primitive Type Narrowing Example

Order of Narrowing conversion

Double->Float->Long->Int->Short->Byte

public class PrimitiveNarrowing {

	public static void main(String[] args) {
		double d=2567834.38;
		//Narrowing required explicitly type casting
		float f=(float)d;
		long l=(long)d;
		int i=(int)d;
		short s=(short)d;
		byte b=(byte)d;

		System.out.println("Double :"+d);
		System.out.println("Float :"+f);
		System.out.println("Long :"+l);
		System.out.println("Int :"+i);
		System.out.println("Short :"+s);
		System.out.println("Byte :"+b);
	}
}

Output


Double :2567834.38
Float :2567834.5
Long :2567834
Int :2567834
Short :11930
Byte :-102

Here type conversion is from upper or lower type that is narrowing of primitive type data and that’s required explicit type casting and will loss some of values because every smaller type data have limited range.

Reference Type Widening Example

public class Doctor {
	public void getDetail() {
		System.out.println("Doctor Detail !!!");
	}
}

public class Surgeon extends Doctor {
	public void getDetail() {
		System.out.println("Surgeon Detail !!!");
	}
}

public class ReferenceTypeNarrowing {

	public static void main(String[] args) {
		//Object of sub class is reference by reference of super class(Doctor)
		Doctor d=new Surgeon();
        //Reference of Superclass(Doctor) type is narrowing to the Sub class (Surgeon)
		Surgeon s=(Surgeon)d;
		s.getDetail();
	}

}

Output


Surgeon Detail !!!

In the previous code, we have a class Doctor extended by class Surgeon, hence Doctor is a super class and Surgeon is its subclass. Method getDetail() of super class Doctor is overridden in subclass Surgeon.
We have created an object of subclass(Surgeon), which is assigned to the reference of super class(Doctor), d.
This super class(Doctor) reference, d is narrowed/down-casted and assigned to subclass(Surgeon) reference, s.

Now we have understand the concept of Widening and Narrowing of data type/reference type values. These are straight forward case where we can easily understand like that required widening or narrowing of data.
In next part we will see how to handle widening or narrowing of data while executing an expression.

Type Promotion in Expressions

While execution of an expression intermediate value may exceed that range of operands and hence expression value will be promoted. Some conditions for type promotion are:

  • Java automatically promotes each byte, short, or char operand to int when evaluating an expression.
  • If one operand is a long, float or double the whole expression is promoted to long, float or double respectively.

Example

public class TypePromotionInExpression {

public static void main(String[] args) {
byte b = 52;
char c = 'b';
short s = 1026;
int i = 60000;
float f = 4.57f;
double d = .4231;

// The Expression
double result = (f * b) + (i / c) - (d * s);

//Result after all the promotions are done as double
System.out.println("Expression Result = " + result);

//Explicit Type Casting as Int. As Int is whole number
//that's what above double result will lost precision.
int intResult=(int)result;
System.out.println("Int Result = " + intResult);
}
}

Expression Result = 415.5394146484375
Int Result = 415

As per above type promotion conditions for expression there is one value type is double as bigger type that’s what complete expression result will convert to double type.

As we have learn about narrowing of data required between incompatible type or bigger to lower type conversion. Here expression result is double and want to convert as int that required explicit type conversion and that will lost precision value because int is whole number and not have any precision value.

References

https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

Java : Types of Literals


A literal is the source code representation of a fixed value and assigned directly to variable without requiring computation.

Literal assigned to primitive type variable as it’s not required new keyword. Primitive types are special data types built into the language; they are not objects created from a class.

Example of Literals:

boolean result 	= false;
char capitalM 	= 'M';
byte b 			= 200;
short s 		= 20000;
int i 			= 200000;

Type of Literals:

Java supports these types of Literals as below:

Java : Literal Types
Java : Types of Literals

Integer Literals

All integer values for primitive type byte, short, int and long are comes under Integer Literal. Below are some points that need to keep in mind while handling Integer Literals:

  • An integer literal is of type long if it ends with the letter L or l (Recommend use L); otherwise it is of type int.
  • Values of the integral types byte, short, int, and long can be created from int literals. Values of type long that exceed the range of int can be created from long literals.
  • Integer literals can be expressed by these number systems:
    • Decimal:Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day.
    • Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F. Prefix 0x represent hexadecimal.
    • Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later) .Prefix 0b represent Binary system.

Below are diffrent representation of decimal integer value 26:

Decimal :

int decVal = 26;

Hexadecimal :

int hexVal = 0x1a;

Binary :

int binVal = 0b11010;

Floating Literals :

All floating values for primitive type float and double comes under Floating Literals. Below are some points that need to keep in mind while handling Floating Literals:

    • Floating points literals for float ends with the letter F or f. (32-bit float literal)
    • Floating points literals for double ends with the letter D or d(Optional) (64-bit double literal; this is the default and by convention is omitted)
    • Floating points literals for float and double can also be expressed using E or e (for scientific notation).

A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.

Below are diffrent representation of decimal value 123.4:

Decimal :

double d1 = 123.4;

Decimal Scientific Notation :

double d2 = 1.234e2;

Floating :

float f1 = 123.4f;

 

Character and String Literals

Literals of types char and String may contain any Unicode (UTF-16) characters. Always use ‘single quotes’ for char literals and “double quotes” for String literals.

Java also support few special escape sequences for char and String literals:

\b (backspace)
\t (tab)
\n (line feed)
\f (form feed)
\r (carriage return)
\” (double quote)
\’ (single quote)
\ (backslash).

Note: If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a “Unicode escape” such as ‘\u0108’ (capital C with circumflex), or “S\u00ED Se\u00F1or” (Sí Señor in Spanish).

Note :Unicode escape sequences may be used elsewhere in a program , not just in char or String literals.

Boolean Literals

A Boolean Literals is of type boolean which allow values as true or false.
For Example:

boolean isValidUser=false;
boolean isPetrolCar=true;

Null Literals

null literal is often used in programs as a marker to indicate that refrence type object is unavailable. null may be assigned to any variable, except variables of primitive types.
For Example:

String employeeName=null;
Employee employee=null;

Class Literals

Class literal formed by taking a type name and appending “.class”; for example, String.class. This refers to the object (of type Class) that represents the type itself.

For Example:

class classType=String.class;

Underscore Characters in Numeric Literals (java 7+)

Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. After java 7 this feature enables to separate groups of digits in numeric literals, which can improve the readability of your code.
It’s similar to use an underscore character to separate digits in groups of three, as we use a punctuation mark like a comma, or a space, as a separator.

Restrictions to use underscore (_):

      • Underscore can be used between digits.
      • At the beginning or end of a number.
      • Adjacent to a decimal point in a floating point literal.
      • Prior to an F or L suffix
      • In positions where a string of digits is expected.

Valid Numeric Literals

long creditCardNumber 		= 1234_5678_9012_3456L;
long socialSecurityNumber 	= 999_99_9999L;
float pi 					=  3.14_15F;
long hexBytes 				= 0xFF_EC_DE_5E;
long hexWords 				= 0xCAFE_BABE;
long maxLong 				= 0x7fff_ffff_ffff_ffffL;
byte nybbles 				= 0b0010_0101;
long bytes 					= 0b11010010_01101001_10010100_10010010;
int x1 						= 5_2;
int x3 						= 5_______2;
int x6 						= 0x5_2;

Invalid Numeric Literals

    • Underscore adjacent to decimal point
      float pi1 = 3_.1415F;
      float pi2 = 3._1415F;
      
    • Underscore prior to an L suffix
      long socialSecurityNumber = 999_99_9999_L;
      
    • Underscore at the end of Literals
      int x2 = 52_;
      
    • Underscore in the 0x radix prefix
      int x4 = 0_x52;
      
    • Underscores at the beginning of a number
      int x5 = 0x_52;
      
    • Underscores at the end of a number
      int x7 = 0x52_;
      

Spring Scheduling Annotations List


After Spring Boot, Spring enhanced with scheduling and Asynchronous annotations which added with methods along with some information about to execute it, and Spring takes care of rest.

These annotations are from the org.springframework.scheduling.annotation package. Below are most common annotations which we use at time of development:

See Also :

Spring Scheduling Annotations

@EnableAsync

@EnableAsync annotation enable asynchronous functionality in Spring. It must use with @Configuration.

@Configuration
@EnableAsync
class VehicleFactoryConfig {}

Now, that we enabled asynchronous calls, we can use @Async to define the methods supporting it.

@EnableScheduling

@EnableScheduling annotation enable scheduling in the application. We should always use it in conjunction with @Configuration:

@Configuration
@EnableScheduling
class VehicleFactoryConfig {}

Now we are enabled with Schedule, we can now run methods periodically with @Scheduled.

@Async

@Async apply on methods which we want to execute on a different thread, hence run them asynchronously.

@Async
void repairCar() {
    // ...
}

If we apply @Aynch annotation to a class, then all methods will be called asynchronously.

Note: Before applying @Async on method first we need to enabled the asynchronous calls for this annotation to work, with @EnableAsync or XML configuration.

@Scheduled

@Scheduled annotation use to execute a method periodically at fixed interval or by Cron like expressions.

For Example : The first execution of the task will be delayed by 5 seconds and then it will be executed normally at a fixed interval of 2 seconds.

@Scheduled(fixedRate = 2000 , initialDelay=5000)
void checkVehicle() {
    // ...
}

After Java 8 with repeating annotations feature, @Scheduled can mark multiple times on a method with different period or Cron expressions.

For Example : The first execution of the task will be delayed by 5 seconds and then it will be executed normally at a fixed interval of 2 seconds and cron expression will execute on Monday to Saturday on 12 PM.

@Scheduled(fixedRate = 2000)
@Scheduled(cron = "0 * * * * MON-SAT")
void checkVehicle() {
    // ...
}

Note:

  • Before applying @Scheduled on method first we need to enabled the scheduling calls by applying @EnableScheduling configuration. that the method annotated with @Scheduled should have a void return type.
  • The method having @Scheduled should have a void return type.

@Schedules

@Schedules annotation use to specify multiple @Scheduled rules.

@Schedules({
  @Scheduled(fixedRate = 2000),
  @Scheduled(cron = "0 * * * * MON-SAT")
})
void checkVehicle() {
    // ...
}

Note: Same feature can achieve  since Java 8 with repeating annotations as described above.

Spring Bean Annotations List


Here you will know about most common Spring Bean Annotations to create different type of beans. We can create spring beans by declaring 3 ways:

  1. Declare bean using XML configuration
  2. Declare bean with @Bean annotations in @Configuration class.
  3. Declare bean with one on type from org.springframework.stereotype package and leave the rest to component scanning.

Here we will mainly focus on annotations which help for creating beans:

See Also :

Component Scanning

Spring can automatically scan a package or class if  component scanning is enabled.

We can configure component scanning parameter as below:

  • Use basePackages to scan @Configuration classes from package.
  • Use basePackageClasses to scan .
  • If no argument is specified, the scanning happens from the same package where the @ComponentScan annotated class is present.

Component Scan from Packages

@Configuration
@ComponentScan(basePackages = "com.fiot.annotations")
class VehicleFactoryConfig {}

Component Scan from Classes

@Configuration
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}

Both arguments are arrays so that we can provide multiple packages for each. After Java 8 we can use repeating annotation also.

@Configuration
@ComponentScan(basePackages = "com.fiot.annotations")
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}

or

@Configuration
@ComponentScans({
  @ComponentScan(basePackages = "com.fiot.annotations"),
  @ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
})
class VehicleFactoryConfig {}

Component Scan XML Configuration


@Component

@Component is a class level annotation. During the component scan, Spring Framework automatically detects classes annotated with @Component.

@Component
class CarUtility {
    // ...
}

Note: By default, the bean instances @Component class have the same name as the class name with a lowercase initial. On top of that, we can specify a different name using the optional value argument of this annotation.

Since @Repository, @Service, @Configuration, and @Controller are all meta-annotations of @Component, they share the same bean naming behavior. Also, Spring automatically picks them up during the component scanning process.

@Repository

@Repository annotation use to represent DAO or Repository classes of database access layer in an application.

@Repository
class VehicleRepository {
    // ...
}

Main  advantage of using @Repository annotation is that it has automatic persistence exception translation enabled. When using a persistence framework such as Hibernate, native exceptions thrown within classes annotated with @Repository will be automatically translated into subclasses of Spring’s DataAccessExeption.
To enable exception translation, we need to declare our own PersistenceExceptionTranslationPostProcessor bean:

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

@Service

@Service annotation use for service layer classes as business logic of an application usually resides within the service layer.

@Service
public class VehicleService {
    // ...
}

@Controller

@Controller is a class level annotation which tells the Spring Framework that this class serves as a controller in Spring MVC.

@Controller
public class VehicleController {
    // ...
}

@Configuration

Configuration classes can contain bean definition methods annotated with @Bean:

@Configuration
class VehicleFactoryConfig {

    @Bean
    Engine engine() {
        return new Engine();
    }
}

Stereotype Annotations with AOP

Spring stereotype annotations, makes easy to create a pointcut that targets all classes that have a particular stereotype.

For example: Suppose we want to measure the execution time and performance of methods from the DAO layer. We’ll create the following aspect (using AspectJ annotations) taking advantage of @Repository stereotype:

@Aspect
@Component
public class PerformanceAspect {
    @Pointcut("within(@org.springframework.stereotype.Repository *)")
    public void daoClassMethods() {};

    @Around("daoClassMethods()")
    public Object measureMethodExecutionTime(ProceedingJoinPoint joinPoint)
      throws Throwable {
        long start = System.nanoTime();
        Object returnValue = joinPoint.proceed();
        long end = System.nanoTime();
        String methodName = joinPoint.getSignature().getName();
        System.out.println(
          "Execution of " + methodName + " took " +
          TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
        return returnValue;
    }
}

In this example, we have created a pointcut that matches all methods in classes annotated with @Repository. We used the @Around advice to then target that pointcut and determine the execution time of the intercepted methods calls. Same approach can be apply on other layer of application.

Spring Core Annotations List


Here you will know about  all  Spring core related annotations which leverage the capabilities of Spring DI engine using annotations  in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages. I have categorize Sping core annotations in two categories:

  1. DI (Dependency Injection) Related Annotations
  2. Context Configuration Annotations

See Also :

DI Related Annotations

@Bean

@Bean marks as factory method which instantiates a Spring bean. Spring calls these methods when a new instance of the return type is required. Bean will have same name as factory method.

@Bean
Engine engine() {
    return new Engine();
}

If you want to name it differently, we can do so with the name of the value arguments of this annotation.

@Bean("engine")
Engine getEngine() {
    return new Engine();
}

Note : All these @Bean annotated methods must be in @Configuration classes.

@Autowired

@Autowired to mark a dependency which Spring is going to resolve and inject. We can use this annotation with a constructor, setter, or field injection.

Constructor injection:

class Car {
    Engine engine;

    @Autowired
    Car(Engine engine) {
        this.engine = engine;
    }
}

Setter injection:

class Car {
    Engine engine;

    @Autowired
    void setEngine(Engine engine) {
        this.engine = engine;
    }
}

Field injection:

class Car {
    @Autowired
    Engine engine;
}

Note :

  • @Autowired has a boolean argument called required with a default value of true. If fields is autowired and Spring’s not find any suitable bean to wire then it will throw an exception to handle such case make Autowire as required false.
  • After version 4.3, we don’t need to annotate constructors with @Autowired explicitly unless we declare at least two constructors.

@Qualifier

@Qualifier use along with @Autowired to provide the bean id or bean name we want to use in ambiguous situations. For example :Following two beans implement the same interface

class Bike implements Vehicle {}
class Car implements Vehicle {}

If Spring needs to inject a Vehicle bean, it ends up with multiple matching definitions. To resolve such ambiguity , we can provide a bean’s name explicitly using the @Qualifier annotation.
Using constructor injection:

@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

Using setter injection:

@Autowired
void setVehicle(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

or

@Autowired
@Qualifier("bike")
void setVehicle(Vehicle vehicle) {
    this.vehicle = vehicle;
}

Using field injection:

@Autowired
@Qualifier("bike")
Vehicle vehicle;

@Required

@Required on setter methods to mark dependencies that we want to populate through XML.

@Required
void setColor(String color) {
    this.color = color;
}

<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Otherwise, BeanInitializationException will be thrown.

@Value

@Value use as placeholder for injecting property values into beans. It’s compatible with constructor, setter, and field injection.
Constructor injection:

Engine(@Value("10") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

Setter injection:

@Autowired
void setCylinderCount(@Value("10") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

or

@Value("10")
void setCylinderCount(int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

Field injection :

@Value("10")
int cylinderCount;

Placeholder from properties file : We can use placeholder strings in @Value to wire values defined in external sources, for example, in .properties or .yaml files.
Let’s assume the following .properties file having below value:

engine.fuelType=diesel

We can inject the value of engine.fuelType with the following:

@Value("${engine.fuelType}")
String fuelType;

We can use @Value even with SpEL.

@DependsOn

@DependsOn annotation use to initialize other beans before the annotated one. Usually, this behavior is automatic, based on the explicit dependencies between beans. @DependsOn use when the dependencies are implicit. For example : JDBC driver loading or static variable initialization.

@DependsOn  annotations need an array containing the dependency bean names.

@DependsOn("engine")
class Car implements Vehicle {}

Alternatively, if we define a bean with the @Bean annotation, the factory method should be annotated with @DependsOn:

@Bean
@DependsOn("fuel")
Engine engine() {
    return new Engine();
}

@Lazy

@Lazy  annotations use when  need to initialize our bean lazily when we request it. By default all singleton beans create eagerly at the startup/bootstrapping of the application context.

@Lazy annotation behaves differently depending on where we exactly place it :

  • A @Bean annotated bean factory method, to delay the method call (hence the bean creation).
  • A @Configuration class and all contained @Bean methods will be affected
  • A @Component class, which is not a @Configuration class, this bean will be initialized lazily.
  • An @Autowired constructor, setter, or field, to load the dependency itself lazily (via proxy).

By Default @Lazy annotation value is true. It is useful to override  the default behavior.
For example :

  • Marking beans to be eagerly loaded when the global setting is lazy.
  • Configure specific @Bean methods to eager loading in a @Configuration class marked with @Lazy.
@Configuration
@Lazy
class VehicleFactoryConfig {

    @Bean
    @Lazy(false)
    Engine engine() {
        return new Engine();
    }
}

@Lookup

@Lookup annotated method tells Spring to return an instance of the method’s return type when we invoke it.

@Primary

@Primary annotation use to make specified bean as default when define multiple beans of same type. Otherwise beans which are not having @Qualifier then injection will be unsuccessful because Spring has no clue which bean we need.
We can use @Primary to simplify this case: if we mark the most frequently used bean with @Primary it will be chosen on unqualified injection points.

@Component
@Primary
class Car implements Vehicle {}

@Component
class Bike implements Vehicle {}

@Component
class Driver {
    @Autowired
    Vehicle vehicle;
}

@Component
class Biker {
    @Autowired
    @Qualifier("bike")
    Vehicle vehicle;
}

In the previous example Car is the primary vehicle. Therefore, in the Driver class, Spring injects a Car bean. Of course, in the Biker bean, the value of the field vehicle will be a Bike object because it’s qualified.

@Scope

@Scope annotation use to define the scope of a @Component class or a @Bean definition. It can be either singleton, prototype, request, session, globalSession or some custom scope. By default scope of bean is singleton.
For example:

@Component
@Scope("prototype")
class Engine {}

Context Configuration Annotations

We can configure the application context with the annotations described in this section.

@Profile

When we want to use a specific @Component class or a @Bean method only when a specific profile is active, we can mark it with @Profile. We can configure the name of the profile with the value argument of the annotation:

@Component
@Profile("sportDay")
class Bike implements Vehicle {}

@Import

We can use specific @Configuration classes without component scanning with this annotation. We can provide those classes with @Import‘s value argument:

@Import(VehiclePartSupplier.class)
class VehicleFactoryConfig {}

@ImportResource

We can import XML configurations with this annotation. We can specify the XML file locations with the locations argument, or with its alias, the value argument:

@Configuration
@ImportResource("classpath:/annotations.xml")
class VehicleFactoryConfig {}

@PropertySource

With this annotation, we can define property files for application settings:

@Configuration
@PropertySource("classpath:/annotations.properties")
class VehicleFactoryConfig {}

@PropertySource leverages the Java 8 repeating annotations feature, which means we can mark a class with it multiple times:

@Configuration
@PropertySource("classpath:/annotations.properties")
@PropertySource("classpath:/vehicle-factory.properties")
class VehicleFactoryConfig {}

@PropertySources

We can use this annotation to specify multiple @PropertySource configurations:

@Configuration
@PropertySources({
    @PropertySource("classpath:/annotations.properties"),
    @PropertySource("classpath:/vehicle-factory.properties")
})
class VehicleFactoryConfig {}

Note: After Java 8+ we can achieve the same with the repeating annotations feature as described above.

Spring Web and REST Annotations List


Here you will know about  all  Spring Web & REST services related annotations which we mostly used while development of applications:

See Also :

Spring Web & REST Annotations

@RequestMapping

@RequestMapping can be configured using path, or it’s aliases, name and value. @RequestMapping annotations apply at class and method level as request handler methods inside the @Controller classes.
@RequestMapping parameters:

  • URL : the method is mapped to
  • method : compatible HTTP methods/li>
  • params : filters requests based on presence, absence or value of HTTP headers
  • headers : filters requests based on presence, absence or value of HTTP params
  • consumes: which media types the method can consume in the HTTP request body
  • produces: which media types the method can produce in the HTTP response body

@RequestMapping variants for HTTP methods:

  • @GetMapping :For GET method
  • @PostMapping : For POST method
  • @PutMapping : For PUT method
  • @DeleteMapping :For Delete Method
  • @PatchMapping : For Patch Method

Example : Method level

@Controller
class CarController {

    @RequestMapping(value = "/cars/welcome", method = RequestMethod.GET)
    String welcome() {
        return "Facing Issues On IT";
    }
}

Example :Class level (both are equivalent)
@RequestMapping at class level that provide default settings for all handler methods in as @Controller class and for method handler URL that will be combination of path at class level and method level.

@Controller
@RequestMapping(value = "/cars", method = RequestMethod.GET)
class CarController {

    @RequestMapping("/welcome")
    String welcome() {
        return "Facing Issues on IT";
    }
}

@RequestBody

@RequestBody map the body of Http request to an object. Deserialization is automatic and depend on content type of request.
Example

@RequestMapping(value="/car/create", method=RequestMethod.POST)
public ResponseEntity createCar(@RequestBody Car , UriComponentsBuilder ucBuilder){
    System.out.println("Creating Car "+car.getName());

    if(userService.isUserExist(user)){
        System.out.println("A Car with name "+car.getName()+" already exist");
        return new ResponseEntity(HttpStatus.CONFLICT);
    }

    carService.saveCar(car);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(car.getId()).toUri());
    return new ResponseEntity(headers, HttpStatus.CREATED);
}

@PathVariable

@PathVariable indicates that a method argument is bound to a URI template variable. We can specify the URI template with the @RequestMapping annotation and bind a method argument to one of the template parts with @PathVariable. We can achieve this with the name or its alias, the value argument.
Example : Path variable with different name

@RequestMapping("/{id}")
Car getCar(@PathVariable("id") long carId) {
    // ...
}

Example : Path variable with same name
If the name of the part in the template matches the name of method argument then no need to specify the @PathVariable annotation.

@RequestMapping("/{carId}")
Car getCar(@PathVariable long carId) {
    // ...
}

Example : Path variable as optional
We can make @PathVariable as optional by setting the argument required to false.

@RequestMapping("/{id}")
Car getCar(required = false) long id) {
    // ...
}

@RequestParam

@RequestParam use to access HTTP request parameters. It has the same configuration options as the @PathVariable annotation. We can access them with the annotations @CookieValue and @RequestHeader respectively.

Example

@RequestMapping
Car getCarDetailByParam(@RequestParam("id") long id) {
    // ...
}

Example : Set defaultValue to make required false
In @RequestParam can inject default value by setting defaultValue (i.e required false) that will consider when spring founds no and empty value in request.

@RequestMapping("/price")
Car buyCar(@RequestParam(defaultValue = "6") int seatCount) {
    // ...
}

@ResponseBody

Mark a request handler method with @ResponseBody then Spring treats the result of the method as the response itself.

If annotate a @Controller class with @ResponseBody annotation then all request handler methods will use it.

Example

@ResponseBody
@RequestMapping("/hello")
String hello() {
    return "Facing Issues on IT";
}

@ExceptionHandler

@ExceptionHandler can use to declare a custom error handler method. Spring calls this method when a request handler method throws any of the specified exceptions.The caught exception can be passed to the method as an argument:
Example


@ExceptionHandler(IllegalAccessException.class)
void onIllegalAccessException(IllegalAccessException exception) {
    // ...
}

@ResponseStatus

@ResponseStatus annotation use to specify the desired HTTP status of the response if we annotate a request handler method with this annotation. We can declare the status code with the code argument, or its alias, the value argument. Also, we can provide a reason using the reason argument and also use it along with @ExceptionHandler:
Example

@ExceptionHandler(IllegalAccessException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
void onIllegalAccessException(IllegalAcessException exception) {
    // ...
}

@Controller

We can define a Spring MVC controller with @Controller.
Example
As used in below example

@RestController

The @RestController combines @Controller and @ResponseBody.
Example
Both are alternate way to handle rest services

@Controller
@ResponseBody
class VehicleRestController {
    // ...
}

or

@RestController
class VehicleRestController {
    // ...
}

@ModelAttribute

@ModelAttribute annotation can access elements that are already in the model of an MVC @Controller, by providing the model key.

  • Like @PathVariable and @RequestParam no need to specify the model key if the argument has the same name.
  • If we annotate a method with @ModelAttribute Spring will automatically add the method’s return value to model.

Example

@PostMapping("/assemble")
void assembleCar(@ModelAttribute("car") Car carModel) {
    // ...
}

or here model attribute name is same.

@PostMapping("/assemble")
void assembleCar(@ModelAttribute Car car) {
    // ...
}

Before Spring calls a request handler method, it invokes all @ModelAttribute annotated methods in the class. We can use below either way to get value of vehicle model attribute.

@ModelAttribute("car")
Car getCar() {
    // ...
}

or

@ModelAttribute
Car car() {
    // ...
}

@CrossOrigin

@CrossOrign annotation enables cross-domain communication for the annotated request handler methods. If we mark a class with @CrossOrgin then it applies to all request handler methods in it.
Example

@CrossOrigin
@RequestMapping("/welcome")
String welcome() {
    return "Facing Issues On IT";
}

Java : Annotation Tutorial


What is Annotation?

Annotations, a form of metadata, provide data about a program that is not part of the program itself and  no direct effect on the operation of the code they annotate.

See Also :

Where to use Annotation?

Annotation can be use on following cases:

  1. Applied as Declaration : Annotation can be use as declaration of classes, fields, methods and other program elements.
  2. Information for the compiler : Annotations can be used by the compiler to detect errors or suppress warnings.
  3. Compile-time and deployment-time processing : Software tools can process annotation information to generate code, XML files, and so forth.
  4. Runtime processing : Some annotations are available to be examined at runtime.
  5. Applied as Type : After Java 8+, annotation can we use as type also.

Points to remember

  • The at sign character (@) indicates to the compiler that what follows is an annotation.
  • If the annotation has no elements, then the parentheses can be omitted.
  • The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages.
  • When annotation used as declaration, as convention each annotation often appears on its own line.

Format of Annotations

Below are some types of annotation and uses:

Pre-Defined Annotation without values

@Entity
public class Employee
{
}

@Override
public String toString()
{
return "FacingIssuesOnIT";
}

Annotations with multiple values

@Author(
name = "Saurabh Gupta",
date = "06/04/2017"
)
class MyTestClass() { ... }

Annotations with single value

@SuppressWarnings(value = "unchecked")
void myTestMethod() { ... }

or

//if there is only one value avoid use fields to make more clean code
@SuppressWarnings("unchecked")
void myTestMethod() { ... }

Use of Multiple annotation

@Author(name = "Saurabh Gupta")
@EBook
class MyTestClass { ... }

Repeatating Annotation (Java 8+)

If the annotations have the same type, then this is called a repeating annotation:

@Author(name = "Saurabh Gupta")
@Author(name = "Navin kumar")
class MyTestClass { ... }

Annotation as Type (Java 8+)

After Java 8 expended scope of using Annotation as below:

Class instance creation expression:

new @Interned MyTestClass();

Type cast:

myString = (@NonNull String) str;

Implements clause:

class UnmodifiableList implements
@Readonly List { ... }

Thrown exception declaration

void monitorSpeed() throws
@Critical SpeedException { ... }
This form of annotation is called a type annotation.

Now you have learn about Annotations , use of annotations  and enhancement in scope of annotations after java 8+. Now we will talk about predefined annotations and creation of custom annotation.

Predefined Annotation

  • @Deprecated : @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag,
  • @override : @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. use from Inheritance and interface.
  • @SuppressWarnings : @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.
    // use a deprecated method and tell
    // compiler not to generate a warning
    @SuppressWarnings("deprecation")
    void useDeprecatedMethod() {
    // deprecation warning - suppressed
    objectOne.deprecatedMethod();
    }
    @SuppressWarnings({"unchecked", "deprecation"})
    
  • @SafeVarargs: @SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
  • @FunctionalInterface: @FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

Annotations that apply on other annotations (Meta annotation). These annotations defined in java.lang.annotation.

    • @Retention:  @Retention annotation specifies how the marked annotation is stored:
      1. RetentionPolicy.SOURCE : Retained only in the source level and is ignored by the compiler.
      2. RetentionPolicy.CLASS : Retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
      3. RetentionPolicy.RUNTIME : Retained by the JVM so it can be used by the runtime environment.
    • @Documented: Indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.).
    • @Target: Marks another annotation to restrict what kind of Java elements that annotation can be applied to. A target annotation specifies one of the following element types as its value:
      1. ElementType.ANNOTATION_TYPE: applied to an annotation type.
      2. ElementType.CONSTRUCTOR: applied to a constructor.
      3. ElementType.FIELD : applied to a field or property.
      4. ElementType.LOCAL_VARIABLE : applied to a local variable.
      5. ElementType.METHOD : applied to a method-level annotation.
      6. ElementType.PACKAGE : applied to a package declaration.
      7. ElementType.PARAMETER: applied to the parameters of a method.
      8. ElementType.TYPE: applied to any element of a class.
    • @Inherited : This annotation applies only to class declarations. @Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class’ superclass is queried for the annotation type.
  • @Repeatable: @Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use.

Custom Annotation

We can define our own annotation i.e called as custom annotation. We have to follow below steps while creation of custom annotation:

  1. Create custom annotation with @interface.
  2. Define type of annotation, retention policy and where need to implement that.
  3. define values of annotation. if required set some default values by using keyword as default.

Here is custom annotation for document the class changes

 package com.common.annotations;

import java.lang.annotation.Documented;

@Documented
public @interface ChangeRecord {
	   String author();
	   String date();
	   int currentRevision() default 1;
	   String lastModified() default "N/A";
	   String lastModifiedBy() default "N/A";
	   // Note use of array
	   String[] reviewers();
}

Use of custom annotation over documentation of class changes.

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
*/
package com.common.annotations;

import java.lang.annotation.Annotation;

@ChangeRecord
(
	author = "Saurabh Gupta",
	date = "3/4/2019",
	currentRevision = 2,
	lastModified = "5/4/2019",
	lastModifiedBy = "Gaurav Gupta",
	reviewers = {"Rajkumar", "Raghav", "Rajesh"}
)
public class CustomAnnotationExample {

	public static void main(String[] args) {

	}
}

Repeatable Annotation Example

Java 8+ introduced repeatable annotation so that same annotation can be use multiple time. For example create custom annotation to implement as repeatable annotation.

Create Custom Repeatable Annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
*/
package com.common.annotations;
import java.lang.annotation.Repeatable;
/**
* Repeatable annotation introduced in <strong>java 8+</strong> to use repeatative task */

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

Create of array of repeatable annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
*/
package com.common.annotations;
public @interface Schedules {
Schedule[] value();
}

Use of repeatable annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved */
package com.common.annotations;
import java.util.Date;
public class RepeatableAnnotationExample {
    public static void main(String[] args) {
	// TODO Auto-generated method stub
	} 

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

Annotation Exceptions

Below are some annotation related exceptions which occurred at runtime:

Reflection for Annotation

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

Follow below link to get all  reflections apis for annotation:

Java : Reflection for Annotations

Conclusion

Here you have learned about annotation in depth knowledge:

  • Annotation and pre-defined annotation and uses.
  • Scope of annotations in Java 8+.
  • Implementation of annotation.
  • Custom Annotation with exmaple
  • Repeatable  Annotation with example.
  • Reflection for Annotations (Java 8+) APIs.
  • Exception occurred by annotations.

 

Spring Boot Annotations List


Here you will know about  all Spring Boot related annotations which we mostly used while development of applications:

See Also :

Spring Boot Annotations

Annotations & Description
@SpringBootAnnotation : This annotation is use to mark the main class of Spring boot application. It encapsulate below transactions with it’s default value.

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

Example

@SpringBootApplication
class CarFactoryApplication {

    public static void main(String[] args) {
        SpringApplication.run(CarFactoryApplication.class, args);
    }
}
@EnableAutoConfiguration : Spring boot looks for auto-configuration beans on its classpath and automatically applies them.
Note: Always use this annotaion with @Configuration.Usually, when we write auto-configuration, use them conditionally with @Configuration classes or @Bean methods. as given in below annotations:
Example

@Configuration
@EnableAutoConfiguration
class CarFactoryConfig {}
@ConditionalOnClass and @ConditionalOnMissingClass
These annotations use when need to marked auto-configuration bean if the class in the annotation’s argument is present/absent.
Example

@Configuration
@ConditionalOnClass(DataSource.class)
class DBConfiguration {
    //…
}
@ConditionalOnBean and @ConditionalOnMissingBean
These annotations use when need to define conditions based on the presence or absence of a specific bean.
Example

@Bean
@ConditionalOnBean(name = "dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    // …
}
@ConditionalOnProperty :
This annotation is use when need to apply condition based on properties values.
Example

@Bean
@ConditionalOnProperty(
    name = "useoracle",
    havingValue = "local"
)
DataSource dataSource() {
    // ...
}
@ConditionalOnResource :
This annotation will use a definition only when a specific resource is present.
Example

@ConditionalOnResource(resources = "classpath:database.properties")
Properties additionalProperties() {
    // ...
}
@ConditionalOnWebApplication and @ConditionalOnNotWebApplication :
Use these annotations, when condition need to check if the current application is or isn’t a web application.
Example

@ConditionalOnWebApplication
HealthCheckController healthCheckController() {
    // ...
}
@ConditionalExpression :
This annotation use in more complex situations and marked definition when the SpEL expression is evaluated to true.
Example

@Bean
@ConditionalOnExpression("${useoracle} && ${oracleserver == 'local'}")
DataSource dataSource() {
    // ...
}
@Conditional :
For more complex conditions, we can create a class for evaluating the custom condition.
Example

@Conditional(HibernateCondition.class)
Properties additionalProperties() {
    //...
}

Java : Identifier Naming Conventions


What is an identifier?

Identifier is the name of components like packages, classes, interfaces, variable, methods and constants.

How to decide name of an identifier?

  1. Name should be meaningful, don’t worry about lengthy name.
  2. Use Camel case when name is lengthy (except package and Constants) to make it more understandable.
  3. Follow Naming Conventions rules while deciding name of identifiers.

What are rules for Java Naming Conventions?

Java naming conventions follow below rules:

  1. A keyword cannot be used as an identifier.
  2. Identifiers are case sensitive.
  3. Identifiers must not contain white spaces.
  4. All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
  5. The name should not start with special characters like & (ampersand), $ (dollar), _ (underscore).
  6. After the first character, identifiers can have any combination of characters.
  7. For big identifiers names use Camel case.

Example of Legal Identifiers:
name, age, $salary, _amount, __1_amount.
Example of Illegal Identifiers:
123xyz, -amount.

Camel case:  It consists of compound words or phrases such that each word or abbreviation begins with a capital letter or first word with a lowercase letter, rest all with capital.

Lower Camel Case Example : hasChildren, firstName, isValidUser etc.

Upper Camel Case Example : AccountHolder, CustomerAccount, PlayingCard etc.

Java Naming Convention Identifiers
Java: Naming Convention Components

Advantage of  Naming Conventions

Java naming conventions must be followed while doing java programming so that improve maintenance and readability of  code. Because Naming conventions  :

  • Make code easily readable and understandably for themselves and for other programmers.
  • Less time of analysis , modify and fixing if any issue.

Note: These conventions are suggested by several Java communities such as Sun Microsystems and Netscape. It doesn’t forced to follow convention rule.

Naming Conventions for different Identifiers:

Package Naming Conventions

  • Name should be in lower case.
  • Make name as more understandable and know hierarchy of source code, name should be  sub divided  by dot(.).
  • Use prefix as company domain name to make it unique.
  • One of the top-level domain names, like com, edu, gov, mil, net, org. Subsequent components of the package name vary according to an organisation’s own internal naming conventions.
package com.faccingissuesonit.utilities

package com.faccingissuesonit.services

package com.faccingissuesonit.dao

package org.facingissuesonit.presentation

Class Naming Conventions

  • It should be a noun such as AccountHolder, Employee, Department etc.
  • It should start with the uppercase letter and long names should use camel case.
  • Use appropriate words, instead of acronyms.
class Employee
{

}

Interface Naming Conventions

  • It should be a adjective such as Runnable, Serialization, Cloneable etc.
  • It should start with the uppercase letter and long names should use camel case.
  • Use appropriate words, instead of acronyms.
interface  Account
{
}
class AccountHolder implements Account
{

}

Object/Variable Naming Conventions

  • Variable name should be short , yet meaningful.
  • Object/variable name should start from lower case letter.
  • Long names should use camel casing.
  • Avoid using variable/object name as x, y and z to make code more understandable.
  • Variable name should not start with underscore(_) or dollar($), even though both are allowed in variable/ object name.
class Account
{
    int accountNumber;
    double salary;
    AccountHolder accountHolder;
}

Methods Naming Conventions

  • Methods should be verbs, such as getEmployeeDetail() , getCurrentMonthStatement() etc.
  • It should be start with small letter and long name should use camel case.
class Engine{
      void changeGear(int newValue);
      void speedUp(int increment);
      void applyBrakes(int decrement);
}

Constants Naming Conventions

  • Should be all uppercase with words separated by underscores (“_”).
  • Always declared with identifiers static and final so that threat as constant.
// Some Constant variables used in predefined Float class
public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
public static final float NaN = 0.0f / 0.0f;

class Employee
{
static final int MIN_AGE= 18;
}

Conclusion

Here you learn about :

  1. Naming Convention Guidelines
  2. Advantage of naming Convention
  3. How to categorize identifiers based on Naming Conventions like Class, interface, methods and Constants etc.

References

https://www.oracle.com/technetwork/java/codeconventions-135099.html

JAVA : Daylight Saving Time (DST) Handling


Pre-Requisite : Java : Date and Time Handling Tutorial

Most of the United States practice of advancing clock during summer month in order to leverage an additional hour of natural light(saving heating power, illumination power, enhancing the mood, and so on).

When clocks change time

In United States Daylight Saving Time begins at 2:00 a.m. on the second Sunday in March and reverts to standard time on the first Sunday in November. In United States each time zone switches clocks at different time.

Daylight Saving Time on time zone

In United States , When Daylight Saving Time are being followed in EST then it’s become EDT. These names just are abbreviation and having different meaning in different continents.
Ex:

  • IST : Indian Standard Time
  • IST : Irish Standard Time
  • IST : Israel Standard Time

For United States (Follow Day Light Saving)

Standard Time Daylight Savings Time
CST : Central Standard Time (North America) CDT : Central Daylight Time
EST : Eastern Standard Time (North America) EDT : Eastern Daylight Time
PST : Pacific Standard Time (North America) PDT : Pacific Daylight Time

Complete List of timezone abbreviations

Note : The 3-letter abbreviations should be wholeheartedly avoided in favor of TZDB zone IDs. EST is not time zone such 3-4 letter codes are neither standardized nor unique, and further the confusion over Daylight saving time (DST). Whenever need to set time zone in code in the code always use proper time zone name in the “continent/region” format.

Complete List of time zone with continent/region

Example of Daylight Saving Time with Time Zone

In this example cover all the case for applying Daylight Saving Time on different time zone. Here I have try to apply with abbreviation, continent / region and show with standard time and Daylight saving time.

package datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;

public class DayLightSavingExample {

	public static void main(String[] args) {
	/**
	* DST = Daylight Saving Time (Begins Daylight Saving Time at 2:00 a.m.
	* on the second Sunday in March and reverts to standard time on the
	* first Sunday in November)
	*/
	SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'+|-hh:mm");
	String strWithDLS = "03/10/2019"; // MM/DD/YYYY
	String strWithOutDLS = "03/11/2019";
	try {
	     Date dateWithDLS = sourceFormat.parse(strWithDLS);
	     Date dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
		System.out.println("Default Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
		System.out.println("Default Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

		/**
		* Set time zone with EST (No difference in time) because 3 letter
		* time zone not consider DST (Day light saving time)
		*/
		sourceFormat.setTimeZone(TimeZone.getTimeZone("EST"));
		dateWithDLS = sourceFormat.parse(strWithDLS);
		dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
		System.out.println("EST Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
		System.out.println("EST Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

		/**
		* Set time zone with America/New_York (1 hour difference in time)
		* when you need to use day light saving always use with
		* continent/region format.
		*/
			sourceFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("America/New_York")));
dateWithDLS = sourceFormat.parse(strWithDLS);
dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
System.out.println("America/New_York Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
System.out.println(
"America/New_York Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

} catch (ParseException ex) {
			ex.printStackTrace();
}

	}

}

Output :


Default Timezone with Day Light Saving :2019-03-10T00:00:00Z+|-12:00
Default Timezone without Day Light Saving :2019-03-11T00:00:00Z+|-12:00
EST Timezone with Day Light Saving :2019-03-10T10:30:00Z+|-10:30
EST Timezone without Day Light Saving :2019-03-11T10:30:00Z+|-10:30
America/New_York Timezone with Day Light Saving :2019-03-10T10:30:00Z+|-10:30
America/New_York Timezone without Day Light Saving :2019-03-11T09:30:00Z+|-09:30

 

Here i have tried to cover all the points as developer prospects. If you know more ways to handle it and any issues related to date and time please suggest in comments.

Java 8+ Date Time Exmples


Pre-Requisite : Java Date and Time Tutorial

In this below example try to cover all possible cases and operations with date and time with Java 8+ APIs.

import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjusters;
import java.time.zone.ZoneRulesException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Java8DateTime {

	public static void main(String[] args) {
		//LocalDate lastDay_2014 = LocalDate.of(2014, 12, 32);
		//LocalTime lastDay_2014 = LocalTime.of(12, 12, 23,-1);
		currentDateTime();
		instantAPI();
		GregorianCalendarAPI();
		TimeZoneAPI();
		dateTimeFormattingAndParsing();
		localDateAPI();
		localDateTimeAPI();
		localTimeAPI();

		System.out.println("*********Set Date and Time Manually***************");
		LocalDateTime dateTimePoint=LocalDateTime.now();
		// Set Date and Time manually
		LocalDate datePoint = LocalDate.of(2012, Month.DECEMBER, 12);
		System.out.println("Local Date :" + datePoint);
		// Days after 1970
		datePoint = LocalDate.ofEpochDay(150);
		System.out.println("Local Date :" + datePoint);
		// set String
		LocalTime timePoint = LocalTime.parse("10:15:30");
		System.out.println("Local Time :" + timePoint);
		// Set hours and minutes
		timePoint = LocalTime.of(13, 18);
		System.out.println("Local Time :" + timePoint);

		// Retrieve values
		System.out.println("*********Get Date and Time Values***************");
		datePoint = dateTimePoint.toLocalDate();
		Month month = dateTimePoint.getMonth();
		int day = dateTimePoint.getDayOfMonth();
		int year = dateTimePoint.getYear();
		int hour = dateTimePoint.getHour();
		int minute = dateTimePoint.getMinute();
		int second = dateTimePoint.getSecond();
		System.out.println("Local Date :" + datePoint);
		System.out.printf("Local Date time Format : %d/%d/%d %d:%d:%d", day, month.getValue(), year, hour, minute,
				second);
		System.out.println();
		System.out.println("*********Operation On LocalDate***************");
		// Operation on Local Date
		// Period of 1 year 3 month 2 days
		Period period = Period.of(1, 3, 2);
		LocalDate startDatePoint = datePoint.minus(period);
		System.out.println("Local Date :" + startDatePoint);
		LocalDate endDatePoint = datePoint.plus(period);
		System.out.println("Local Date :" + endDatePoint);

		System.out.println("*********Diffrence of On LocalDate***************");
		// Difference of Date
		Period daysPeriod = Period.between(startDatePoint, endDatePoint);
		System.out.println("Days :" + daysPeriod.getDays());
		System.out.println("Months :" + daysPeriod.getMonths());
		System.out.println("Years :" + daysPeriod.getYears());
		// Another Way
		long days = ChronoUnit.DAYS.between(startDatePoint, endDatePoint);
		long months = ChronoUnit.MONTHS.between(startDatePoint, endDatePoint);
		long years = ChronoUnit.YEARS.between(startDatePoint, endDatePoint);
		System.out.println("Days :" + days);
		System.out.println("Months :" + months);
		System.out.println("Years :" + years);

		// Duration

		// A duration of 3 seconds and 5 nanoseconds
		Duration duration = Duration.ofSeconds(3, 5);
		// Duration oneDay = Duration.between(Temporal., yesterday);

	}

	private static void currentDateTime() {
		System.out.println("*********Current Date and Time***************");

		// Current Date and Time
		LocalDateTime dateTimePoint = LocalDateTime.now();
		System.out.println("Local Date Time :" + dateTimePoint);
		// Current Date
		LocalDate datePoint = LocalDate.now();
		System.out.println("Local Date :" + datePoint);
		// Current Time
		LocalTime timePoint = LocalTime.now();
		System.out.println("Local Time :" + timePoint);

		// Get Instant from java.util.Date
		Instant timestamp = new Date().toInstant();
		System.out.println("Current Timestamp = " + timestamp);

		// java.util.Calendar to Instant
		Instant time = Calendar.getInstance().toInstant();
		System.out.println(time);
	}

	private static void instantAPI() {
		System.out.println("*****************Instant API*******************");
		// Date to Instant
		Instant timestamp = new Date().toInstant();
		System.out.println("Current Timestamp = " + timestamp);
		// Now we can convert Instant to LocalDateTime or other similar classes
		LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.of(ZoneId.SHORT_IDS.get("PST")));
		System.out.println("Date = " + date);

		// Calendar to Instant
		Instant time = Calendar.getInstance().toInstant();
		System.out.println(time);

		// Date API to Legacy classes
		Date dt = Date.from(Instant.now());
		System.out.println(dt);

		// Instant from timestamp
		Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli());
		System.out.println("Specific Time = " + specificTime);

		// Duration example
		Duration thirtyDay = Duration.ofDays(30);
		System.out.println(thirtyDay);
	}

	private static void localDateAPI() {
		System.out.println("*****************Local Date API*******************");
		LocalDate today = LocalDate.now();

		System.out.println("Current Date=" + today);

		// Creating LocalDate by providing input parameters.
		// Here are chnaces of getting DateTimeException if pass as Invalidate
		// Date format
		LocalDate firstDay_2016 = LocalDate.of(2016, Month.JANUARY, 1);
		System.out.println("Specific Date=" + firstDay_2016);

		try {
			// Here with throw DateTimeException if pass as Invalidate Date
			// format
			LocalDate lastDay_2014 = LocalDate.of(2014, Month.FEBRUARY, 29);
			System.out.println("Specific Date=" + lastDay_2014);
		} catch (DateTimeException ex) {
			ex.printStackTrace();
		}

		// Current date in "Asia/Kolkata", you can get it from ZoneId
		LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Date in CST=" + todayKolkata);

		try
		{
		// Will throw java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		LocalDate todayIST = LocalDate.now(ZoneId.of("IST"));
		}
		catch(ZoneRulesException ex)
		{
			ex.printStackTrace();
		}

		// Getting date from the base date i.e 01/01/1970
		LocalDate dateFromBase = LocalDate.ofEpochDay(365);
		System.out.println("365th day from base date= " + dateFromBase);

        //Get 100 th day of year
		LocalDate hundredDay2014 = LocalDate.ofYearDay(2016, 100);
		System.out.println("100th day of 2014=" + hundredDay2014);

		//Other APIs and Operation on LocalDate

		// Get the Year, check if it's leap year
		System.out.println("Year " + today.getYear() + " is Leap Year? " + today.isLeapYear());

		// Compare two LocalDate for before and after
		System.out.println("Today is before 01/01/2017? " + today.isBefore(LocalDate.of(2017, 1, 1)));

		// Get LocalDateTime from LocalDate
		System.out.println("Current Time=" + today.atTime(LocalTime.now()));

		// plus and minus operations
		System.out.println("20 days after today will be " + today.plusDays(20));
		System.out.println("5 weeks after today will be " + today.plusWeeks(5));
		System.out.println("30 months after today will be " + today.plusMonths(30));

		System.out.println("20 days before today will be " + today.minusDays(20));
		System.out.println("5 weeks before today will be " + today.minusWeeks(5));
		System.out.println("30 months before today will be " + today.minusMonths(30));

		// TemporalAdjusters for adjusting the dates
		LocalDate firstDayOfMonth=today.with(TemporalAdjusters.firstDayOfMonth());
		System.out.println("First date of this month= " + firstDayOfMonth);

		LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
		System.out.println("Last date of this year= " + lastDayOfYear);

		Period period = today.until(lastDayOfYear);
		System.out.println("Period Format= " + period);
		System.out.println("Months remaining in the year= " + period.getMonths());

	}

	private static void localTimeAPI() {
		System.out.println("*****************Local Time API*******************");
		// Current Time
		LocalTime time = LocalTime.now();
		System.out.println("Current Time=" + time);

		// Creating LocalTime by providing input arguments
		LocalTime specificTime = LocalTime.of(12, 20, 25, 40);
		System.out.println("Specific Time of Day=" + specificTime);

		// Try creating time by providing invalid inputs
		// LocalTime invalidTime = LocalTime.of(25,20);
		// Exception in thread "main" java.time.DateTimeException:
		// Invalid value for HourOfDay (valid values 0 - 23): 25

		// Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
		LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Time in IST=" + timeKolkata);

		// java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		// LocalTime todayIST = LocalTime.now(ZoneId.of("IST"));

		// Getting date from the base date i.e 01/01/1970
		LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
		System.out.println("10000th second time= " + specificSecondTime);

	}

	private static void localDateTimeAPI() {
		System.out.println("*****************Local Date Time API*******************");
		// Current Date
		LocalDateTime today = LocalDateTime.now();
		System.out.println("Current DateTime=" + today);

		// Current Date using LocalDate and LocalTime
		today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
		System.out.println("Current DateTime=" + today);

		// Creating LocalDateTime by providing input arguments
		LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
		System.out.println("Specific Date=" + specificDate);

		// Try creating date by providing invalid inputs
		// LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28,
		// 25,1,1);
		// Exception in thread "main" java.time.DateTimeException:
		// Invalid value for HourOfDay (valid values 0 - 23): 25

		// Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
		LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Date in IST=" + todayKolkata);

		// java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		// LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST"));

		// Getting date from the base date i.e 01/01/1970
		LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
		System.out.println("10000th second time from 01/01/1970= " + dateFromBase);

	}

	private static void dateTimeFormattingAndParsing() {
		System.out.println("*****************Local DateTime Formatting API*******************");
		// Format examples
		LocalDate date = LocalDate.now();
		// default format
		System.out.println("Default format of LocalDate=" + date);
		// specific format
		System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
		System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));

		LocalDateTime dateTime = LocalDateTime.now();
		// default format
		System.out.println("Default format of LocalDateTime=" + dateTime);
		// specific format
		System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
		System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));

		Instant timestamp = Instant.now();
		// default format
		System.out.println("Default format of Instant=" + timestamp);

		// Parse examples
		LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
				DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
		System.out.println("Default format after parsing = " + dt);

	}

	private static void GregorianCalendarAPI() {
		System.out.println("*****************Gregorian Calendar API*******************");
		// ZonedDateTime from specific Calendar
		ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
		System.out.println(gregorianCalendarDateTime);

		GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime);
		System.out.println(gc);
	}

	private static void TimeZoneAPI() {
		System.out.println("*****************Time Zone API*******************");
		// TimeZone to ZoneId
		ZoneId defaultZone = TimeZone.getDefault().toZoneId();
		System.out.println(defaultZone);

		TimeZone tz = TimeZone.getTimeZone(defaultZone);
		System.out.println(tz);

	}

}

Output


*********Current Date and Time***************
Local Date Time :2019-05-16T11:50:59.302
Local Date :2019-05-16
Local Time :11:50:59.303
Current Timestamp = 2019-05-16T06:20:59.303Z
2019-05-16T06:20:59.358Z
*****************Instant API*******************
Current Timestamp = 2019-05-16T06:20:59.369Z
Date = 2019-05-15T23:20:59.369
2019-05-16T06:20:59.373Z
Thu May 16 11:50:59 IST 2019
Specific Time = 2019-05-16T06:20:59.369Z
PT720H
*****************Gregorian Calendar API*******************
2019-05-16T11:50:59.387+05:30[Asia/Calcutta]
java.util.GregorianCalendar[time=1557987659387,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2019,MONTH=4,WEEK_OF_YEAR=20,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=136,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=50,SECOND=59,MILLISECOND=387,ZONE_OFFSET=19800000,DST_OFFSET=0]
*****************Time Zone API*******************
Asia/Calcutta
sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null]
*****************Local DateTime Formatting API*******************
Default format of LocalDate=2019-05-16
16::May::2019
20190516
Default format of LocalDateTime=2019-05-16T11:50:59.551
16::May::2019 11::50::59
20190516
Default format of Instant=2019-05-16T06:20:59.551Z
Default format after parsing = 2014-04-27T21:39:48
*****************Local Date API*******************
Current Date=2019-05-16
Specific Date=2016-01-01
java.time.DateTimeException: Invalid date 'February 29' as '2014' is not a leap year
Current Date in CST=2019-05-16
365th day from base date= 1971-01-01
    at java.time.LocalDate.create(Unknown Source)
    at java.time.LocalDate.of(Unknown Source)
    at datetime.Java8DateTime.localDateAPI(Java8DateTime.java:160)
    at datetime.Java8DateTime.main(Java8DateTime.java:34)
java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
    at java.time.zone.ZoneRulesProvider.getProvider(Unknown Source)
    at java.time.zone.ZoneRulesProvider.getRules(Unknown Source)
    at java.time.ZoneRegion.ofId(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)
    at datetime.Java8DateTime.localDateAPI(Java8DateTime.java:173)
    at datetime.Java8DateTime.main(Java8DateTime.java:34)
100th day of 2014=2016-04-09
Year 2019 is Leap Year? false
Today is before 01/01/2017? false
Current Time=2019-05-16T11:50:59.619
20 days after today will be 2019-06-05
5 weeks after today will be 2019-06-20
30 months after today will be 2021-11-16
20 days before today will be 2019-04-26
5 weeks before today will be 2019-04-11
30 months before today will be 2016-11-16
First date of this month= 2019-05-01
Last date of this year= 2019-12-31
Period Format= P7M15D
Months remaining in the year= 7
*****************Local Date Time API*******************
Current DateTime=2019-05-16T11:50:59.620
Current DateTime=2019-05-16T11:50:59.620
Specific Date=2014-01-01T10:10:30
Current Date in IST=2019-05-16T11:50:59.620
10000th second time from 01/01/1970= 1970-01-01T02:46:40
*****************Local Time API*******************
Current Time=11:50:59.620
Specific Time of Day=12:20:25.000000040
Current Time in IST=11:50:59.620
10000th second time= 02:46:40
*********Set Date and Time Manually***************
Local Date :2012-12-12
Local Date :1970-05-31
Local Time :10:15:30
Local Time :13:18
*********Get Date and Time Values***************
Local Date :2019-05-16
Local Date time Format : 16/5/2019 11:50:59
*********Operation On LocalDate***************
Local Date :2018-02-14
Local Date :2020-08-18
*********Difference of On LocalDate***************
Days :4
Months :6
Years :2
Days :916
Months :30
Years :2

Above solutions are my search to perform all type of operations with date and time with java 8 API generally face while development. If you face other issue apart from it. Please mention in comments that will help with others.

[Solved] Could not transfer artifact org.springframework:XYZ from/to central (https://repo.maven.apache.org/maven2)


Generally this error message shows in pom.xml when create new project with dependencies or add new dependencies in pom.xml.

Reason to cause this error

There are several reason to cause this error as below because maven is unable to connect to Maven repository at http://repo1.maven.org/maven2.

  1. Proxy
  2. Network issue
  3. .lastUpdate file for dependency

Could not transfer artifact org.springframework:spring-expression:jar:5.1.6.RELEASE from/to central (https://repo.maven.apache.org/maven2): C:\Users\saurabh.gupta1\.m2\repository\org
 \springframework\spring-expression\5.1.6.RELEASE\aether-fa07bf3e-4fa1-4911-bcad-3319e4b2480e-spring-expression-5.1.6.RELEASE.jar-in-progress (The system cannot find the file 
 specified) org.eclipse.aether.transfer.ArtifactTransferException:
 

Solutions

There are few ways i find out to resolve this issue:

Maven Force Update of Snapshot/Releases

Follow below steps to to resolve this issue and clear all dependencies error in eclipse.

  1. Right click on project.
  2. Go to Maven
  3. Update project , the check the above option “Force update of Snapshot/Releases“.
  4. Click on Ok.
  5. If not fixed restart your eclipse.

Maven Force Update 1

Maven Force Update 2

Maven access through Proxy

Update your proxy configuration in maven settings.xml file and put it inside .m2 folder

C:\Users\USER NAME.m2

proxy settings


<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0                               
http://maven.apache.org/xsd/settings-1.0.0.xsd">

 <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>user name</username>  <!-- Put your user name here -->
      <password>password</password>   <!-- Put your password here -->
      <host>127.56.8.64</host>        <!-- Put the IP address of your proxy server here -->
      <port>80</port>                 <!-- Put your proxy server's port number here -->
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts> <!-- Do not touch this setting unless you know what you're doing. -->
    </proxy>  
  </proxies>
</settings>

You don’t need to touch , and sections, unless you really know what are these tags.

After updating this setting restart eclipse and follow the steps in Maven Force update of Snapshot/Releases.

Remove .lastUpdated file

If this problem is not resolved yet got to .m2/repository/ to dependency sub directory and remove .lastUpdate file inside of it or delete complete directory for this particular dependency and again follow the steps in Maven Force update of Snapshot/Releases.

For Example as for above issue directory location showing in exception as

C:\Users\saurabh.gupta1.m2\repository\org
\springframework\spring-expression\5.1.6.RELEASE

Above solutions are my research to resolve this issue if you find out or know other ways please suggest in comments.