Category Archives: Java

[Solved] SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “No appropriate protocol (protocol is disabled or cipher suites are inappropriate)


This issue “SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “No appropriate protocol (protocol is disabled or cipher suites are inappropriate)” was happening to me when upgrade from jDK 8_271 to JDK_8_341 and MSSQL driver.

Below are the stacktrace of the issue.

Stacktrace

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "No appropriate protocol (protocol is disabled or cipher suites are inappropriate)".
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1368)
	at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1412)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1058)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
	at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
	at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
	at java.sql.DriverManager.getConnection(DriverManager.java:664)
	at java.sql.DriverManager.getConnection(DriverManager.java:208)
	at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
	at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
	at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
	at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120)
	at org.springframework.batch.item.database.AbstractCursorItemReader.initializeConnection(AbstractCursorItemReader.java:422)
	... 30 more
Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
	at sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:171)
	at sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:106)
	at sun.security.ssl.TransportContext.kickstart(TransportContext.java:238)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:410)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:389)
	at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1379)
	... 41 more

Solutions

SQL Server JDBC Driver versions are specific to JDK versions. Till JDK_8.271, JDBC driver versions supported as 4.1 however for the latest version JDK_8_341 use the SQL Server JDBC driver 8.4.1.

In my case this issue got resolved by updating the jar file as below:

Old Jar : mssql-jdbc4-2.0.jar

New Jar: mssql-jdbc-8.4.1.jre8.jar

Please refer below the complete SQLServer JDBC driver support matrix specific to Java/JDK versions.

https://learn.microsoft.com/en-us/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server-support-matrix?view=sql-server-ver16#java-and-jdbc-specification-support

Please share your comments if this solutions help you to resolve this issue.

Happy Learning !!!

[Solved] SQLServerException: The TCP/IP connection to the host ABCKXYZ356, port 1345 has failed


This is most common exception when connecting with database through Spring boot application. It’s happen because of connection failed to the database.

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host ABCKXYZ356, port 1345 has failed. Error: "ABCKXYZ356. 
Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. 
Make sure that TCP connections to the port are not blocked by a firewall.".    
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:285) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2434) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:659) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2546) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2216) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2067) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1204) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:825) ~[mssql-jdbc-8.2.1.jre8.jar:na]    
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-4.0.3.jar:na]    
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-4.0.3.jar:na]

Reason of Exception

These are main reason of this Exception:

  • This issue can occurred because of wrong properties configured for database connection.
  • This issue can also occurred if the database is not running.
  • This issue can also occurred if database only allow to access through vpn.

Solutions

These are some most common solution to resolve this issue:

  • Verify the connection properties.
  • Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port.
  • Make sure that TCP connections to the port are not blocked by a firewall.
  • Check the vpn connection if DB access allow over the vpn.

Hope these solutions help you to resolve this issue. Please share in comments.

Happy Learning !!!

Write a program to convert a non-negative integer number to its English words representation


In this program converting Non-negative numbers to English words through Java Program. You can use the same logic to implement with other languages like C, C++, C#, Python, etc.

This program is most frequently asked in programming label tests or interviews to check your logical skills. You can also utilize the same code while generating invoices, bills, reports where want to show sum, average, gross total etc. in form of words.

For Example :

InputOutput
123One Hundred Twenty Three
1234One Thousand Two Hundred Thirty Four
12345Twelve Thousand Three Hundred Forty Five
123456One Hundred Twenty Three Thousand Four Hundred Fifty Six
1234567One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
1234568One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Eight
12345670Twelve Million Three Hundred Forty Five Thousand Six Hundred Seventy
123456709One Hundred Twenty Three Million Four Hundred Fifty Six Thousand Seven Hundred Nine
1234567090One Billion Two Hundred Thirty Four Million Five Hundred Sixty-Seven Thousand Ninety
Program to convert numbers to English Words

Java Program

To convert a number to English word core logic is to check 10th position of the number the add words for the same. Based on the range between billion to thousand then take reminder and add word (thousand, million or billion) etc. then further dividend of the number by the range and further pass for convert as long as not reaching to less than thousand. Finally, when numbers reach to between 1-20 take the words from map 1-20 range.

Source Code:

package programming;

import java.text.DecimalFormat;

public class NNNumberToWordExample {
	// array of string type for one digit numbers
	private static final String[] doubleDigits = { "", " Ten", " Twenty", " Thirty", " Forty", " Fifty", " Sixty",
			" Seventy", " Eighty", " Ninety" };
	// array of string for two digits numbers
	private static final String[] singleDigit = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven",
			" Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen",
			" Seventeen", " Eighteen", " Nineteen" };

	// converts a number to words (up to 1000)
	private static String convertUptoThousand(int number) {
		String soFar;
		if (number % 100 < 20) {
			soFar = singleDigit[number % 100];
			number = number / 100;
		} else {
			soFar = singleDigit[number % 10];
			number = number / 10;
			soFar = doubleDigits[number % 10] + soFar;
			number = number / 10;
		}
		if (number == 0)
			return soFar;
		return singleDigit[number] + " Hundred " + soFar;
	}

	// converts a long number (0 to 999999999) to string
	public static String convertNumberToWord(long number) {
		// checks whether the number is zero or not if number is zero return zero
		if (number == 0) {
			return "zero";
		}
		// convert long value to string
		String num = Long.toString(number);
		// for creating a mask padding with "0"
		String pattern = "000000000000";
		/**
		 * Convert to DecimalFormat using the specified pattern and also provides the
		 * symbols to default locale
		 */
		DecimalFormat decimalFormat = new DecimalFormat(pattern);
		// format a number of the DecimalFormat
		num = decimalFormat.format(number);
		/**
		 * format: XXXnnnnnnnnn the subString() method returns a new string that is a
		 * substring of this string the substring begins at the specified beginIndex and
		 * extends to the character at index endIndex - 1 the parseInt() method converts
		 * the string into integer
		 */
		int billions = Integer.parseInt(num.substring(0, 3));
		// format to: nnnXXXnnnnnn
		int millions = Integer.parseInt(num.substring(3, 6));
		// format to: nnnnnnXXXnnn
		int hundredThousands = Integer.parseInt(num.substring(6, 9));
		// format to: nnnnnnnnnXXX
		int thousands = Integer.parseInt(num.substring(9, 12));

		String tradBillions;

		switch (billions) {
		case 0:
			tradBillions = "";
			break;
		case 1:
			tradBillions = convertUptoThousand(billions) + " Billion ";
			break;
		default:
			tradBillions = convertUptoThousand(billions) + " Billion ";
		}

		String result = tradBillions;
		String tradMillions;
		switch (millions) {
		case 0:
			tradMillions = "";
			break;
		case 1:
			tradMillions = convertUptoThousand(millions) + " Million ";
			break;
		default:
			tradMillions = convertUptoThousand(millions) + " Million ";
		}
		result = result + tradMillions;

		String tradHundredThousands;
		switch (hundredThousands) {
		case 0:
			tradHundredThousands = "";
			break;
		case 1:
			tradHundredThousands = "One Thousand ";
			break;
		default:
			tradHundredThousands = convertUptoThousand(hundredThousands) + " Thousand ";
		}
		result = result + tradHundredThousands;

		String tradThousand;
		tradThousand = convertUptoThousand(thousands);
		result = result + tradThousand;

		// removing extra space if any
		return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
	}

	public static void main(String args[]) {
		// Test cases to convert number to words
		System.out.println(convertNumberToWord(5));
		System.out.println(convertNumberToWord(89));
		System.out.println(convertNumberToWord(656));
		System.out.println(convertNumberToWord(1301));
		System.out.println(convertNumberToWord(13512));
		System.out.println(convertNumberToWord(567319));
		System.out.println(convertNumberToWord(90908890));
		System.out.println(convertNumberToWord(2000000000));
		System.out.println(convertNumberToWord(569999999));
		System.out.println(convertNumberToWord(3233000000L));
		System.out.println(convertNumberToWord(5000000));
		System.out.println(convertNumberToWord(333333333));
		System.out.println(convertNumberToWord(5000400));
		System.out.println(convertNumberToWord(600000));
		System.out.println(convertNumberToWord(4000000));
	}
}

Output

Five
Eighty Nine
Six Hundred Fifty Six
One Thousand Three Hundred One
Thirteen Thousand Five Hundred Twelve
Five Hundred Sixty Seven Thousand Three Hundred Nineteen
Ninety Million Nine Hundred Eight Thousand Eight Hundred Ninety
Two Billion 
Five Hundred Sixty Nine Million Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine
Three Billion Two Hundred Thirty Three Million 
Five Million 
Three Hundred Thirty Three Million Three Hundred Thirty Three Thousand Three Hundred Thirty Three
Five Million Four Hundred 
Six Hundred Thousand 
Four Million 

Hope this program help you and clear your logics. Please share in comments.

Happy Learning !!!

[Solved] SQLServerException: String or binary data would be truncated


This SQLServerException is common with the applications using the MSSQL database. Once it occurs it generate the below stackTrace.

Exception Stack Trace

com.microsoft.sqlserver.jdbc.SQLServerException: String or binary data would be truncated. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)

Reason of Exception

This exception occurred when you are trying to insert text in a column of type varchar which is more than the size of defined column size then SQL server through this exception “SQLServerException: String or binary data would be truncated“.

Solutions

You can follow any of these processes to resolve this issue:

  • Apply validation for text length on the source frontend/client where you in insert the values. It should be less than or equal to size of column.
  • Apply truncation on text before inserting to the database and it should be less than the column size.
  • Increase the sufficient size of the column based on you requirement to resolve this issue.

Hope these processes resolved this issue. Please share your response in comments.

Happy Learning !!!

Springboot Framework Exception Hierarchy


Springboot framework having following exceptions. These Spring exceptions occurred while developing applications.

Springboot Framework Exception Hierarchy

References

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/NestedRuntimeException.html

Top [70] HR & Manager Round Interview Questions


HR & Managerial round interview questions can cover a diverse range of discussion topics apart from Technical. These questions asked generally asked by laterals or experienced persons to check his/her personality/behaviour. In some organizations, this is also called a behaviour round of interviews. Generally, the interviewer observes these areas from your answers:

  1. Observe your expressions
  2. Check your leadership skills/soft skills
  3. Team handling skills
  4. Fit for organization cuture or not
  5. Client handling skills
  6. Handling on critical, stressed and pressurise work environment.
How to introduce yourself

The interviewer can create different scenarios for organization culture, team conflicts situation and some cases ask for combination with technology-related questions. Based on answered will ask for further questions. In such type questions, the interviewer wants to understand how you cope with change, approach learning, and overcome challenges and obstacles.

In this article, we share some behaviour round interview questions with sample answers and also provide an overview of some additional example questions to prepare with a scenario that will fit your profile.

Do you have any questions?

How to answer to such behaviour and situational quetions?

To prepare for these questions, take a moment to think of a number of challenging situations you have faced, such as difficulty with new technology, project, timeline, customer, ambiguity, process, or even a team member. Think of situations where you were challenged with what was the right thing to do. What did you do and how did you handle it? and how you can fit your previous experiences with current organization requirements.

Always keep in mind the STAR rule to answer such behavioural questions.

  • S – Situation. What was the situation? Describe in brief. (This is the challenge you were facing.)
  • T – Task. What was the task you were assigned? What was your responsibility?
  • A – Action. What action did you take?
  • R – Result. What happened because of your action?

You can use examples for reference and resolution you provided on a particular case.

What are your strengths?

Some of most frequently asked questions in behavioural interview

Common Interview Questions

These are common interview questions that can be asked in technical as well as in behavioural/manager/HR rounds of interviews. Through these questions, the interviewer wants to check your communication, understanding of your educational and professional background
and your core technical skills instead of going through the complete CV.

  1. Tell Me About Yourself. Example
  2. Do you have any questions for us? Example
  3. What is your technical streagths and rate yourself in out of 10 points? Example
  4. Tell us about your educational and technical background. Example

Behavioural Questions


These questions are to check your personality, how you are socially connected, motivated and performed as an individual as part of the team so that interviewer can understand your compatibility with your current position requirement.

  1. How might you describe yourself? Example
  2. How might your friends describe you? Example
  3. What is your work ethic like? Example
  4. What are your strengths and weaknesses? Example
  5. Where Do You See Yourself In 5 Years? Example
  6. Why do you believe you are a good fit for this position? Example
  7. What is your idea of a friendly work environment? Example
  8. How do you react to sudden changes in the work you are doing? Example
  9. Share with us reasons you think we should hire you. Example
  10. If you could work in any position, what job might you want and why? Example
  11. Where did you learn about this open position? Example
  12. Have you ever worked in a leadership position? Example
  13. Share with us how you have emerged as a leader in the past. Example
  14. Talk to us about your skills, and how you believe they can help you excel in this position. Example
  15. How do you intend to continue expanding your professional skills? Example
  16. What roles have you previously worked in? Example
  17. What companies have you previously worked for? Example
  18. Do you have any references from previous experiences that we can contact? Example
  19. Explain the duties you have handled in the past. Example
  20. Have you ever received recognition for being a leader? Example
  21. How do you introduce new ideas or operations to teams? Example
  22. Why are you interested in leaving your current job? Example
  23. What feedback have previous managers given you about your work? Example
  24. How do you prioritise your tasks? Example
  25. Can you explain this gap in your resume? Example
  26. What are your salary expectations? Example
  27. Why Do You Want to Work Here? Example
  28. Why Should We Hire You? Example
  29. What Are Your Career Goals? Example
  30. What Is Your Greatest Accomplishment? Example

Situational Questions


These questions generally asked for lateral roles as lead or manager where you need to handle team or more on interacting with clients.

  1. What process might you use to make presentations for clients? Example
  2. Have you faced any hard time with client? Example
  3. What is your greatest professional accomplishment? Example
  4. Have you faced any critism from client or coworker? if yes, how you handled it? Example
  5. Have you faced any conflict with team or your manager? How did you deal with it? Example
  6. Have you resolved any conflict between team members? How did you deal with it? Example
  7. How do you handle workplace pressures? Example or
  8. Tell me about a time when you were under a lot of pressure. How did you handle it? Example
  9. Tell me about a time when you faced conflict at work. Example
  10. What is your greatest achievement? Example
  11. Tell me about a time you went above and beyond for work. Example
  12. Give me an example of a time you made a mistake. How did you manage the consequences? Example
  13. How would you respond to a request for doing a task you’ve never done before? Example
  14. Did you ever have to collaborate with a difficult coworker? How did you manage the situation? Example
  15. Tell me about a time when you handled a challenging situation. Example
  16. Was there a time when you were overwhelmed with work? How did you handle the situation? Example
  17. Sometimes almost impossible todo what are the things in our todo list. What you will do when your list of responsibilities overwhelming. Example
  18. Tell me a situation where you took the initiative to fix a problem. Example
  19. Tell me about a time when you and the team you were managing had opposing views on an issue. How did you get to a conclusion? Example
  20. How you accomplish task when there is tight deadline. Example
  21. Describe a long term project you managed. How did you make sure everything was running smoothly. Example
  22. Tell me about a time you had to deal with a client that was asking the impossible. Example
  23. Was there a time when you had to be very strategic in order to meet a goal?
  24. Give me an example of a situation when you showed initiative and took charge of a situation.
  25. Tell me about a time when you went above and beyond your duties for a job or task.
  26. Did you ever have to correct one of your superiors when they were wrong? How did you approach that situation?
  27. Have you ever had to work under a tight deadline?
  28. How do you deal with coworkers that don’t cooperate or can’t contribute enough?
  29. Tell me about a time when a client was asking for the impossible. How did you explain and communicate this to them?
  30. Give me an example of a time when you didn’t meet a client’s expectations. How did you deal with the situation?
  31. Is there a situation you think you could’ve handled better or differently?
  32. How do you adapt to sudden changes in the workplace? Could you give me an example? Example
  33. Tell me about a time when you had to think on your feet in order to deal with a situation.
  34. Sometimes employers put too much on their employees’ plates. Was there a time when you were overwhelmed with work? How did you handle the situation?
  35. Tell me about a time when you had the liberty to be creative with your work. Was it exciting or difficult for you?

You can go through these questions to prepare any interview with your scenarios that best fit your roles and responsibility.

Share your thoughts about these questions and also share if you faced any other questions to help others.

Happy Learning !!!

[Solved] OpenShift : MetaSpace Issue with SpringBoot based Micro-services


The java.lang.OutOfMemoryError: Metaspace indicates that allocated native memory for Java class metadata is exausted. That’s why issue occured in standalone and cloud based applications.

In Java 8 and later versions, the maximum amount of memory allocated for Java classes (MaxMetaspaceSize) is by default unlimited, so in most cases there is no need to change this setting. On the other hand, if you want to fix the amount of memory allocated for Java classes, you can set it as follows:

java -XX:MaxMetaspaceSize=1024m

This JVM parameter -XX:MaxMetaspaceSize is just an set the upper limit of MetaSpace. The current Metaspace size (i.e. committed) will be smaller. In fact, there is a setting called MaxMetaspaceFreeRatio (default 70%) which means that the actual metaspace size will never exceed 230% of its occupancy.

And for it to grow it first would have to fill up, forcing a garbage collection in an attempt to free objects and only when it cannot meet its MinMetaspaceFreeRatio (default 40%) goal it would expand the current metaspace. That can however not be greater than 230% of the occupancy after the GC cycle.

Monitoring MetaSpace Size with Java Native Memory tracking

A good way to monitor the exact amount of Metadata is by using the NativeMemoryTracking, which can be added through the following settings:

-XX:+UnlockDiagnosticVMOptions -XX:NativeMemoryTracking=detail -XX:+PrintNMTStatistics

When Native Memory Tracking is enabled, you can request a report on the JVM memory usage using the following command:

$ jcmd <pid> VM.native_memory

OutOfMemoryError: Metaspace on OpenShift/Kubernetes

When using openjdk Image on OpenShift/Kubernetes, the default maxium value for the Metaspace is XX:MaxMetaspaceSize=100m. You might have noticed that setting this value through the JAVA_OPTIONS environment variable, doesn’t work as the default value is appended to the bottom:

VM Arguments: -Xms128m -Xmx1024m -XX:MetaspaceSize=128M -XX:MaxMetaspaceSize=256m    -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:+ExitOnOutOfMemoryError

Once the MetaSpace get full in your application it will stop the service and through exception as below in your logs.

oc logs XYZ-service-7b856cc89-kpc6k  | grep -i metaspace
INFO exec  java -javaagent:/usr/share/java/jolokia-jvm-agent/jolokia-jvm.jar=config=/opt/jboss/container/jolokia/etc/jolokia.properties -XX:+UseParallelOldGC -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=20 -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -XX:MaxMetaspaceSize=100m -XX:+ExitOnOutOfMemoryError -cp "." -jar /deployments/XYZ-service-0.0.1-SNAPSHOT.jar
Picked up JAVA_TOOL_OPTIONS:  -Dappdynamics.agent.accountAccessKey=600a90af-582a-4ae2-87b1-4599708b65dd -Dappdynamics.agent.reuse.nodeName=true -Dappdynamics.socket.collection.bci.enable=true -XX:MaxMetaspaceSize=1024m -javaagent:/opt/appdynamics-java/javaagent.jar
Terminating due to java.lang.OutOfMemoryError: Metaspace

Solutions

The correct way to set the MaxMetaspaceSize is through the GC_MAX_METASPACE_SIZE environment variable. Here are the different cases ti implement this solutions:

  • Jenkins Pipeline: For example, if you are using a jenkins pipeline to deploy your application or services then you can meke following changes in the json template to refelect these changes in deployment.yaml file to deploy your application with JKube, the following settings will override the default values for the MaxMetaspaceSize and MaxMetaspaceSize:
spec:
  template:
    spec:
      containers:
      - env:
        - name: JAVA_OPTIONS
          value: '-Xms256m -Xmx1024m'
        - name: GC_MAX_METASPACE_SIZE
          value: 1024
        - name: GC_METASPACE_SIZE
          value: 256
  • Manual Deployment through S2I: You can directly pass these MetaSpace parameters while deploying your service manually.
oc new-app xyz-service -e JAVA_OPTIONS="-Xms256m -Xmx1024m" -e GC_MAX_METASPACE_SIZE=1024 -e GC_METASPACE_SIZE=256

Note : After deploying your service over OpenShift/Kernates validate the deployment configuration file(deployment.yml) for these parameters. In case not not reflecting then delete your pods completly and reploy the application.

In case, you want make changes on other parameters also for improving the puformance of your applictaion then you can follow these documents to list of parameters for OpenShift.

Let me know your thought on this post. if this solution was helpful for you make comment on the post.

Happy Learning !!!

[Solved]: Python ValueError: invalid literal for int() with base 10


Python supports explicit type conversion by converting values to different data types. In Python you can convert integers to strings, strings to integers, floats to integers but one conversion Python does not support a float as a string to an integer. In if you try to convert from float as an string to integer then it throw exception as “ValueError: invalid literal for int() with base 10“.

Example: ValueError: invalid literal for int() with base 10

Let’s take a below example where asking weight as input from user, as you know weight can be float value. In this example if user input weight more than 10 KG then user will get discount of 100 Rs. otherwise not discount.

sugar_weight = input("Enter how much sugar you want: ")

sugar_weight_as_int = int(sugar_weight)

if sugar_weight_as_int > 10:
    print("You have discount of 100/- Rs.")
else:
    print("You do not have discount on sugar.")

Output

Enter how much sugar you want: 6.5
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    sugar_weight_as_int = int(sugar_weight)
ValueError: invalid literal for int() with base 10: '6.5'

In this example throw exception as “ValueError: invalid literal for int() with base 10: ‘6.5’” because here user insert the sugar weight as 6.5 which is float string value now to comparing with integer value type casting as int but Python doesn’t support type casting from float string to integer that’s why Python will throw exception as “ValueError: invalid literal for int() with base 10: ‘6.5’“.

If you noticed the above error messages have two parts:

1: ValueError: This error occured when there is an issue with the value stored in a particular object.
2: Error Message “invalid literal for int() with base 10: ‘6.5’” : This means the value we have passed through an int() method cannot be converted because the int() method does not allow you to pass a float represented as a string.

Solution

To resolve this issue, you should convert this passing float string value to float then this exception will get resolve because Python allows float string to float conversion.

sugar_weight = input("Enter how much sugar you want: ")

sugar_weight_as_int = int(float(sugar_weight))

if sugar_weight_as_int > 10:
    print("You have discount of 100/- Rs.")
else:
    print("You do not have discount on sugar.")

Output

Enter how much sugar you want: 6.5
You do not have discount on sugar.

Conclusion

In Python “ValueError: invalid literal for int() with base 10” error is occurred when you try to convert a string value that is not formatted as an integer. To overcome this issue you can use the float() method to convert a floating-point number in a string to an integer. Then, you can use int() to convert your number to an integer.

If this solution does not work, make sure the input value of a string does not contain any letters because Strings with letters cannot be converted to an integer unless those letters have a special meaning.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving ValueError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

[Solved]: Python KeyError: XYZ in Python


In Python, KeyError occurred when try access a value in dictionary by key name but key don’t exist. If key found in dictionary will return a value if doesn’t exist then through KeyError : key_name .

How to handle KeyError in Python?

You can handle KeyError while accessing the key from dictionary by following ways:

  • Check for key in advance for accessing the key
  • Use the ‘in’ keyword to check for key
  • Use try and except block.

Example of KeyError in Python

Lets take simple example where user want to access key from dictionary to retrieve value. In this example if user input key name, age or city either of them then it will return value. if user input other value as key that doesn’t exist in dictionary then it will throw exception as KeyError: passing_key.

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}

key_name=input("What information you want to get? (name, age, city)")
print(key_name+" :"+user[key_name])

Now as suggested above solution to KeyError, lets fix the above to problem to exception handle and show message in case user input other keys except in dictionary.

Solution 1 : Iterate all key and value

Lets take first solution to get keys from dictionary then retrieve values from dictionary.

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}
#iterate user dictionary
for key, value in user.items():
    print("Key:", key)
    print("Value:", str(value))

In this solution user will able to print all values w.r.t each key.

Solution 2 : Advance check by in

Lets take second solution to fix this problem to check key in dictionary first by using ‘in’ in if statement. if key not available in dictionary then print else statement.

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}

key_name=input("What information you want to get? (name, age, city)")
if key_name in user:
    print(key_name+" :"+user[key_name])
else:
    print(key_name +" key is not available in user")

in this solution if user input any key like name, age or city then print value otherwise print as key is not available.

Solution 3 : try and except

Lets take third solution to solve KeyError by using exception handling through try and except.

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}

key_name=input("What information you want to get? (name, age, city)")
try:
    print(key_name+" :"+user[key_name])
except KeyError:
    print(key_name +" key is not available in user")

In this solution if key is correct then print value w.r.t key in dictionary. if key doesn’t exist and KeyError exception occurs the print statement as “Key is not available in user”.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving KeyError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

Python: Nested Loop


A loop within a loop is known as nested loop.

Assume that there are 5 passengers and each of them have 2 baggage. The below code will make sure that all baggage of each passenger have undergone the security check.

Example

num_of_pasngrs=5
num_of_bag=2
security_check=True
for pasngr_count in range(1, num_of_pasngrs+1):
	  for bag_count in range(1,num_of_bag+1):
	      if(security_check==True):
	          print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage cleared")
	      else:
	          print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage not cleared")

Output

Security check of passenger: 1 — baggage: 1 baggage cleared
Security check of passenger: 1 — baggage: 2 baggage cleared
Security check of passenger: 2 — baggage: 1 baggage cleared
Security check of passenger: 2 — baggage: 2 baggage cleared
Security check of passenger: 3 — baggage: 1 baggage cleared
Security check of passenger: 3 — baggage: 2 baggage cleared
Security check of passenger: 4 — baggage: 1 baggage cleared
Security check of passenger: 4 — baggage: 2 baggage cleared
Security check of passenger: 5 — baggage: 1 baggage cleared
Security check of passenger: 5 — baggage: 2 baggage cleared

The same code in the inner loop can also be written using while loop instead of for loop as shown below:

num_of_pasngrs=5
num_of_bag=2
security_check=True
for pasngr_count in range(1, number_of_passengers+1):
	bag_count =1
	while (bag_count<=num_of_bag):
	   if(security_check==True):
	      print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage cleared")
	   else:
	      print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage not cleared")
	   bag_count+=1	 

Similarly, the outer loop can also be written using while loop.

Java : Array & Arrays Class


In this post we will discuss about Java Array and Arrays class to deal with array and perform different operation by  API’s.  Initially will discuss about Array for understanding and once you will get knowledge of Array then end of this post will discuss about Arrays API’s with examples.

“Array is collection (or group of) of homogeneous (same data type) items  referred to single variable, which store in contiguous space in memory.”

Note : Java works differently then they do in C/C++, In Java array elements are not stored in continuous locations.

For example: You have 10 integer numbers and want minimum, maximum and  average of these numbers. One way is take 10 variables and perform comparison and operations of these numbers. If numbers are in hundreds very difficult to deal with that because need to handle 100 variables. That’s what array come on picture to deal with same type data.

See Also: Java: Arrays vs Collections

Points to remember:

  • Array always keep elements of same type such as primitive type or objects.
  • Array in Java array is dynamically allocated.
  • Array size always specified in int value not in short or long.
  • If number of elements in array are n ,then indexing of array start from 0…n-1.
  • Array is object in Java , if need to find  length, check for member length. To check length of array in C/C++ use sizeof.
  • Array can be use as static field, a local variable or a method parameter.
  • In java direct super class of Array is Object and implements java.lang.Cloneable and java.io.Serializable interface.
  • Time Complexity Access : Θ(1)
  • Time Complexity Search : Θ(n)
  • Time Complexity Insertion : Θ(n)
  • Time Complexity Deletion : Θ(n)
  • Space Complexity: O(n)

In data structure array are two types:

  • One dimensional arrays
  • Multi dimensional arrays

One Dimensional Array

One dimensional array also called as linear array.

Single Dimentional Array

Declaration of Array

Declaration show the reference of values as array and each value in array specified as type.

type var-name [];
or
type [] var-name;

Example to declare array of different types.

// both are valid way of declarations
int numbers[];
or int[] numbers; 

byte byteArr[];
short shortsArr[];
boolean booleanArr[];
long longArr[];
float floatArr[];
double doubleArr[];
char charArr[];
//array of reference objects of Class Type MyTestClass
MyTestClass myClassArray[]; 

//Array of unknown type object, as oBject is super class of class class
Object[]  objectArr,
//Array of unknown type of collection as Collection is super interface in Collection framework
Collection[] callectionArr;

Instantiation of Array

On array declaration only the reference of array created, to allocate memory to array need specified the size of array as below. where the size is always a integer value greater than zero.


var-name = new type[size];

For Example:

int numbers[]; //declaration
numbers=new int [10];//create an instance of array of 10 numbers.

Object[] objectArr; //declaration

objectArr=new Object[10]; //create an instance of array of 10 Objects.

Note:

  • For primitive type array instantiation, array elements values by default initialize with specified primitive default value. For example : primitive type int default value is 0, all the  elements array by default initialize with 0.
  • For reference type array instantiation, array element values by default initialize with specified primitive default value. For example : reference type Object default value is null, all the  elements array by default initialize with null.

Array Instantiation with Literals

If you already know the elements of an array , use literals in array to instantiation and assignment of values at same time.

//Array with int literals
int [] numbers={10,, 50, 70 , 90, 80};
//Array with String literals
String [] names= {"Saurabh", "Gaurav", "Raghav"};

Accessing of array

To access/assign the elements of an array, use index position within range 0 to n-1 for the size of array length n. If trying to access array beyond this range (0…n-1) for primitive and reference type, get an exception as ArrayIndexOutOfBoundException in case of String will throw StringIndexOutOfBoundsException

//accessing/assign value on array
arrName[index];

Example

//access value from array on index position 2, will result 70
int number=numbers[2];

//Assign value on index position , new change value 80
numbers[2]=80;

Java Program for Single Dimensional Array

Here is example of single line array , considering all above cases;


public class OneDimentionalArray {

	public static void main(String[] args) {

		//declaration by both ways
		int numbers[];

		//Instantion for array of int type size 10
		//By default initialize with 0 for primitive type int
		numbers=new int[10];

		//instantition with literals
		String []names= {"Saurabh","Gaurav","Raghav"};

		System.out.println("Print Numbers :");
		//access array with for loop
        for(int i=0; i<=numbers.length-1;i++)
		{
			System.out.println(numbers[i]);
		}

		System.out.println("\nPrint Name :");
		//access array with for each loop
		for(String name:names)
		{
			System.out.println(name);
		}

		// Assign values to Arrays by for loop
		for(int i=0; i<=numbers.length-1;i++)
		{
			numbers[i]=i*10;
		}

		//manually assign values,Raghav will replace with Ramesh
		names[2]="Ramesh";

		System.out.println("\n\nUpdate Values from arrays");

		//access array with for loop
                for(int i=0; i<=numbers.length-1;i++)
		{
			System.out.println(numbers[i]);
		}

		System.out.println("\nPrint Name :");
		//access array with for each loop
		for(String name:names)
		{
			System.out.println(name);
		}

	}

}

Output

Print Numbers :
0
0
0
0
0
0
0
0
0
0

Print Name :
Saurabh
Gaurav
Raghav

Update Values from arrays
0
10
20
30
40
50
60
70
80
90

Print Name :
Saurabh
Gaurav
Ramesh

Multi Dimensional Array

Multi-dimensional arrays also called Jagged Arrays, are arrays of arrays with each element of the array holding the reference of another array. A multi-dimensional array is created by appending square brackets ([]) per dimension.
For Example

int[][] intArr=new int [2][3]; //2D array
int numbers[][][]=new int [2][3][4]; //3D array

//2D representation with literals
//Create an array of size [2][3] and assign given values
int [][]numbers ={{2,5,7},{4,6,9}}

Two Dimentional Array

Java Program for Two Dimensional Array


public class TwoDimentionalArray1 {

	public static void main(String[] args) {

		//declaration
		int numbers[][] = {{2,5,7},{4,6,9}};

		//access in array of two dimensional array
        for(int i=0; i<=numbers.length-1;i++)
		{
        	for (int j=0; j<numbers[i].length;j++)
			System.out.println("numbers["+i+"]["+j+"]="+numbers[i][j]);
		}

		System.out.println("\n\nUpdate Values from arrays");

		numbers[0][1]=20;
		numbers[1][2]=30;
		numbers[0][0]=40;

		for(int i=0; i<=numbers.length-1;i++)
		{
        	for (int j=0; j<numbers[i].length;j++)
			System.out.println("numbers["+i+"]["+j+"]="+numbers[i][j]);
		}
	}

}

Output

numbers[0][0]=2
numbers[0][1]=5
numbers[0][2]=7
numbers[1][0]=4
numbers[1][1]=6
numbers[1][2]=9

Update Values from arrays
numbers[0][0]=40
numbers[0][1]=20
numbers[0][2]=7
numbers[1][0]=4
numbers[1][1]=6
numbers[1][2]=30

 

Maven Vs Gradle


Gradle is a built tool developed over Maven and Ant. It’s having lots of differences when compared with Maven.

See Also:

Maven Gradle
Maven uses XML Gradle doesn’t use XML
Maven written in Java Gradle written in Java, Kotlin and Gradle
Maven scripts are not shorter and clean Gradle Scripts are shorter and clean
Maven is a software project management and builds tool developed for Java-based applications. Gradle is an open-source, build automation system built on concepts of maven and ant.
Maven makes build process easier, provides best guidelines for development and allow to migrate new features Gradle allows structuring of build and supports for multi projects builds. Gradle increases productivity provides ways to migrate and builds applications.

Maven Vs Ant


Ant was the first “modern” java application build tool released in 2000. It was famous in a short time because easy to learn, based on procedural programming and not required any additional preparation.

Ant was having some issues in terms of, build time, performance and big scripts and other problems of developers.

Maven releases in 2004 which covers all the problems of Ant and having a complete life cycle.

See Also:

Maven vs Ant

Here are some main differences between Maven and Ant build tool.

Ant Maven
Ant required build script per project. Maven describes the project over configuration.
Ant invoke project-specific targets Maven invoke defined goals (target)
Ant is for “just” build process Maven required knowledge of the project.
Ant scripts are too complex. Maven creates standard project layout and builds in the lifecycle.
Ant scripts are not reusable. Maven plugins and repository are reusable.

 

[Solved] TESSDATA_PREFIX environment variable is set to the parent directory of your “tessdata” directory.


This exception happen when you trying to read text of image by using tessdata API’s. It try to get defalt path of environment variable TESSDATA_PREFIX in you application root diectory/tessdata/lang.traineddata. but if this folder and file not found then throw below exception.

Stacktrace


Exception in thread "main" java.lang.Error: Invalid memory access
    at com.sun.jna.Native.invokePointer(Native Method)
    at com.sun.jna.Function.invokePointer(Function.java:470)
    at com.sun.jna.Function.invoke(Function.java:404)
    at com.sun.jna.Function.invoke(Function.java:315)
    at com.sun.jna.Library$Handler.invoke(Library.java:212)
    at com.sun.proxy.$Proxy0.TessBaseAPIGetUTF8Text(Unknown Source)
    at net.sourceforge.tess4j.Tesseract.getOCRText(Tesseract.java:437)
    at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:292)
    at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:213)
    at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:197)
    at com.fiot.ImageTextReading.crackImage(ImageTextReading.java:22)
    at com.fiot.ImageTextReading.main(ImageTextReading.java:10)
    
Error opening data file ./tessdata/eng.traineddata
Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your "tessdata" directory.
Failed loading language 'eng'
Tesseract couldn't load any languages!
    

Solutions

Follow these steps to resolve this issue:

  1. First download tessdata from this location https://github.com/tesseract-ocr/tessdata .
  2. Rename this unzip folder to tessdata.
  3. Copy this folder and paste it to your applciation root directory.

For all steps and environment setup follow this example: Java : Read Text from and Image Example

Java: Read Text from an Image


Java provides net.sourceforge.tess4j library to read and extract text from the image. It makes developer life easy for applications where image reading is required.

Example of Reading/Extract Text from Image

  1.  In the hospital, If you have scanned your doctor given a prescription and then some hospitals maintain patient records based on detail. then in the next visit after so many days, if you forget to carry it and the doctor asked about the previous prescription then based on your mobile number, name or date can reprint your doctor prescribed detail.
  2. In Big Data where need to do some analysis based on the above cases can extract detail from images and show reports.

How Text Reading from image works?

In an image extracting text means finding out the text components and then extract the geometric shape components. These text components are extract with geometric components as well and the relationship between these components built up by flow lines between components. These extracted components are a form of metadata (XML format), stored in a knowledge base or shared with others.

Environment Setup

Download tessdata from below git directory and rename to tessdata. Place this folder to your application root directory as below.

https://github.com/tesseract-ocr/tessdata

Read Text from Image Directory

Dependency

Add below dependency in your you application pom.xml


    <dependency> 
        <groupId>net.sourceforge.tess4j</groupId> 
        <artifactId>tess4j</artifactId> 
        <version>3.2.1</version> 
    </dependency>

 

Java Code to Read Text from Image

In this example, you will see complete steps to read/extract text from an image.

Sample Image

test image

Java Code

In this below image you will see complete java lines of code to extract text from the image and output of sample image.

Java Code to Read Text from Image

Java Program : Get all possible values of X such that A % X = B


Question:  Write a java program to get  all possible values of X such that A % X = B. Input two integers A and B. The task is to find the  all possible values X such that A % X = B. If there are infinite number of possible values then print -1.

Examples:

  1. Input: A = 21, B = 5
    Output: 2
    8 and 16 are the only valid values for X.
  2. Input: A = 5, B = 5
    Output: -1
    X can have any value > 5

Algorithm

  • Step 1: Ask the user to input values of A and B
  • Step 2: Find out all possible factors of (A-B) which are greater than B
  • Step 3: Use StringJoiner to print the possible value in comma separated form.

Java Program

public class Program1 {
public static void main(String[] args) {
System.out.println("Enter values of A and B to get possible values of X from expression A % X = B");

Scanner input = new Scanner(System.in);
System.out.print("Please Enter an integer A: ");
int A = input.nextInt();

System.out.print("Please Enter an integer B: ");
int B = input.nextInt();

System.out.println("Possible Values of X :" + getAllowedValues(A, B));
}

private static String getAllowedValues(int A, int B) {
//Use to print value in comma separated form
StringJoiner joiner = new StringJoiner(",");

if (A - B > 0) {
//find out all possible factor of(A-B) which are greater than B
for (int C = (A - B); C > 0 & C > B; C /= 2) {
if ((A - B) % C == 0)
joiner.add(Integer.toString(C));
}
} else {
joiner.add("-1");
}
return joiner.toString();
}

}

Output


Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 21
Please Enter an integer B: 5
Possible Values of X :16,8

Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 5
Please Enter an integer B: 5
Possible Values of X :-1

[Solved] org.apache.tika.mime.MimeTypeException


MimeTypeException is a subclass of TikaException. This exception occurred when there is a mismatch with selected parser and document mime type or Mime Type not supported by TIKA.

public class MimeTypeException extends TikaException

Constructors

  • MimeTypeException(String message) :Constructs a MimeTypeException with the specified detail message.
  • MimeTypeException(String message, Throwable cause)
    Constructs a MimeTypeException with the specified detail message and root cause.

References

https://tika.apache.org/1.22/api/org/apache/tika/mime/MimeTypeException.html

Apache Tika Introduction


Apache Tika provides generic API for all document type content detection, analysis and content extraction from multiple file formats. Tika internally uses various documents parsers to extract metadata and structured text content from the various file types. For Example PDF, Spreadsheet, text file, images, etc.

Tika latest version 1.22 released on 1st Aug 2019 by Apache software foundation. Tika completely has written in Java and supports cross-platform.

Tika Version History

Year Development
2006 The idea of Tika was proposed in front of the Lucene Project Management Committee.
2006 The concept of Tika and its benefits in the Jackrabbit project was discussed.
2007 Tika entered into Apache.
2008 Both 0.1 and 0.2 Versions were released and Tika graduated from the incubator to the Lucene sub-project.
2009 This year Tika Versions 0.3, 0.4, and 0.5 were released.
2010 Both 0.6 and 0.7 Version was released and Tika graduated into the top-level Apache project.
2011 Tika 1.0 was released with book “Tika in Action” was also released in the same year.
2019 Tika 1.22 was release for additional CSV and HWP files type.

Why Tika?

As per https://filext.com/, there are around 25k to 50K file extensions (Structured and Non Structured) and these are growing day by day. To deal with so many types of format Tika provides universal Java API to support around 1400 file types that cover most common and popular formats.

Tika provides content extraction, metadata extraction, and language identification capabilities. Tika written in Java, still used by other languages also by calling restful services and CLI tools.

Where to use Apache Tika?

  • Search Engine: Tika uses the search engine to create search indexing for text in digital documents.
  • Document Analysis: Analysis of the documents like images, pdf to do analysis based on extract content.
  • Digital Asset Management (DAM): It’s used with an organization where maintains a library of documents, images, videos, ebooks, drawings to classify based on common features.
  • Content Analysis: Analyse the content from the web site and care of user’s interest like amazon shows movies, products based on the user’s visit. Machine learning based on content.

Features of Tika

  • Unified parser Interface: Tika internally uses best suitable parser libraries within a single parser interface. Due to this feature Tika, reduce the burden of developer from the burden of selecting the suitable parser library and use it according to the file type encountered.
  • Low memory usage: Tika consumes fewer memory resources, therefore, it is easily embedded with Java applications. We can also use Tika within the application which runs on platforms with fewer resources like mobile PDA.
  • Fast processing: Tika can quickly extract and detect content from applications.
  • Flexible metadata: Tika understands all type of metadata models which are used to define files.
  • Parser integration: Tika supports various parser libraries available for each document type in the same application.
  • MIME-type detection: Tika can extract and detect content from all MIME types.
  • Language detection: Tika includes language identification feature, therefore it can be used in documents based on language type in multilingual websites.

Java: Collection Framework Introduction


A collection is an object (also called container) to deal with a group of objects or elements as a single unit. These objects called as elements of Collection. Collections are used to perform operations like the store, retrieve, manipulate, communicate and aggregate.

A collection can have a different type of data. Based on data can decide the type collection data structure.

  • Homogeneous
  • Heterogeneous
  • Unique
  • Duplicate

See Also: 

Real-life Example of Collection

Here are some real-life examples of collections:

  • LinkedList: Your web page visiting history.
  • LinkedList: Train Coaches are connected to each other.
  • LinkedList: Our brain, when we remember something memory follow association because of one memory link to another.  This way recall in sequence.
  • Stack & LinkedList: Stack of Plates or Towel at the party. The top plate always picks first.
  • Queue & LinkedList: Queue/line of the person standing on the railway ticket window or for food in the mess.
  • A classroom is a collection of students.
  • A money bank is a collection of coins.
  • A school bag is a collection of books.

Why need collection?

There are four ways in Java to store values by JVM.

1:Variable approach

If we need to handle one, two or three or fewer numbers of values then the variable approach is a good bit if need to deal with so many objects like 5000 then variable approach have some drawback:

  • The limitation of a variable is that it can store only one value at a time.
  • Readability and reusability of the code will be down.
  • JVM will take more time for the execution.

2: Using a class object approach

Using a class object, we can store multiple “fixed” numbers of values of different types. For example, suppose we are creating a class named Person.

class Person{
String Name ;
int age ;
}

If you create the object of Person class like this

Person p1=new Person(); // So can you think how many values can store in this person object?

The answer is only two i.e name and age. but if you will want to store the third value, it will not possible.

3: Using an array object approach

Array improved the readability of code, by using a single variable for a huge number of values but there are various problems and limitations with the array.


Student[] st=new Student[5000];
  1. Array allow to store only homogeneous data type.
  2. Array is static and fixed in length size.
  3. Array concept help with standard data structure, but when need to deal with the sorting of objects, search for a specific item, etc.

4: Collection Object:

By using a collection object, we can store the same or different data without any size limitation.

What is a Framework in Java?

A framework is a set of several classes and interfaces which provide a readymade architecture.

What is a Collections Framework?

A collection framework provides a unified readymade architecture for storing and manipulating a group of objects. All collections frameworks contain the following:

  • Interfaces: Interfaces generally forms a hierarchy and allow collections object to be manipulated independently of the details of their representation.
  • Implementations: Provides a concrete representation by data structure and implementation of  collections interfaces.
  • Algorithms: The methods that perform useful operations, such as searching and sorting, on objects that implement collection interfaces.

Benefits of Collections Framework

Collections Framework provides lots of benefits:

  • Reduces programming effort: The Collections framework provides useful data structures and algorithms so that developers can concentrate on programming logic only.
  • Increases program performance and quality: Collections Framework provides high-quality data structures and algorithms implementations for good performance. These collections interface APIs are interchangeable so that easily tuned by switching collection implementations.
  • Allows interoperability among unrelated APIs: These data structures are interchangeable so that choose data structure and algorithms according to requirement.
  • Reduces effort to learn and to use new APIs: Most of APIs are common for collections framework because of the inherent Collection interface. only some APIs need to remember that are specific to the data structure.
  • Reduces effort to design new APIs: If new data structure and algorithm change create polymorphism of API and change the internal algorithm of APIs.
  • Fosters software reuse: If new data structure added use standard APIs so that easy to learn for developers.

References

Java : Collection Framework Hierarchy


All the classes and interfaces of the collection framework are in java.util package. This hierarchy for the collection framework specifically mentioned the class and interface with respect to each type.

Java Collection Framework Hierarchy

Iterable Interface

The Iterable interface is the root interface for all the collection classes because the Collection interface extends the Iterable interface, therefore, all the subclasses of Collection interface also implement the Iterable interface.

The iterable interface contains only one abstract method.

  • Iterator iterator(): It returns the iterator over the elements of type T.

Iterator Interface

The iterator interface provides the facility of iterating the elements in a forward direction only.
For more detail: Java: Iterator Interface methods and Examples

Collection Interface

The Collection interface builds the foundation for the Collection framework. The collection interface is one of the interfaces which is implemented by all the Collection framework classes. It provides common methods to implement by all the subclasses of collection interfaces.
For more detail: Java: Collection Interface methods and Examples

List Interface

List interface is the subtype/child interface of the Collection interface. It stores objects/elements in list type data structure in ordered form and also allowed duplicate values.

Implementation classes for List interface are ArrayList, LinkedList, Vector, and Stack.

For Example: To instantiate List Interface with Implementation classes follow:


List  list1= new ArrayList();  
List  list2 = new LinkedList();  
List  list3 = new Vector();  
List  list4 = new Stack();

For more detail: Java: List Interface methods and Examples

ArrayList Class

The ArrayList implements the List interface. It’s having the following features:

  • ArrayList uses a dynamic array data structure to store objects and elements.
  • ArrayList allows duplicate objects and elements.
  • ArrayList maintains the insertion order.
  • ArrayList is non-synchronized.
  • ArrayList elements/objects can be accessed randomly.

For more detail: Java: ArrayList Interface methods and Examples

LinkedList Class

LinkedList implements the List interface. It’s having the following features:

  • LinkedList uses a doubly linked list data structure to store elements.
  • LinkedList allowed storing the duplicate elements.
  • LinkedList maintains the insertion order.
  • LinkedList is not synchronized.
  • LinkedList manipulation is fast because no shifting is required.

For more detail: Java: LinkedList Class methods and Examples

Vector Class

Vector Class implements List interface. It’s having the following features:

  • Vector is similar to the ArrayList class.
  • Vector class uses data structure as a dynamic array to store the data elements.
  • Vector is synchronized.
  • Vector contains many methods that are not the part of Collection Framework.

For more detail: Java: Vector Class methods and Examples

Stack Class

The Stack is the subclass of the Vector class. It’s having the following features:

  • Stack implements the Vector data structure with the (LIFO)last-in-first-out.
  • Stack contains all of the methods of the Vector class.
  • Stack also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its features.

For more detail: Java: Stack Class methods and Examples

Queue Interface

Queue Interface extends the Collection interface. It’s having the following features:

  • Queue interface maintains the FIFO (first-in-first-out) order.
  • Queue can be defined as an ordered list that is used to hold the elements which are about to be processed.
  • Queue interface implemented by the various classes like PriorityQueue, Deque, and ArrayDeque.

Queue interface can be instantiated as:

Queue q1 = new PriorityQueue();  
Queue q2 = new ArrayDeque();  

For more detail: Java: Queue Interface methods and Examples

Here are detail about classes which implements Queue Interface.

PriorityQueue

The PriorityQueue class implements the Queue interface.

  • PriorityQueue holds the elements or objects which are to be processed by their priorities.
    PriorityQueue doesn’t allow null values to be stored in the queue.

For more detail: Java: PriorityQueue Class methods and Examples

Deque Interface

Deque stands for the double-ended queue which allows us to perform the operations at both ends.interface extends the Queue interface.

  • Deque extends the Queue interface.
  • Deque allows remove and add the elements from both the side.
Deque d = new ArrayDeque(); 

For more detail: Java: Deque Interface methods and Examples

ArrayDeque Class

ArrayDeque class implements the Deque interface.

  • ArrayDeque facilitates us to use the Deque.
  • ArrayDeque allows add or delete the elements from both the ends.
  • ArrayDeque is faster than ArrayList and has no capacity restrictions.

For more detail: Java: ArrayQueue Class methods and Examples

Set Interface

Set Interface extends Collection Interface and present in java.util package.

  • Set doesn’t allow duplicate elements or objects.
  • Set store elements in an unordered way.
  • Set allows only one null value.
  • Set is implemented by HashSet, LinkedHashSet, and TreeSet.

We can create an instantiation of Set as below:

Set s1 = new HashSet();  
Set s2 = new LinkedHashSet();  
Set s3 = new TreeSet();

For more detail: Java: Set Interface methods and Examples

HashSet

HashSet class implements Set Interface. It’s having the following features:

  • HashSet internally uses data structure like a hash table for storage.
  • HashSet uses hashing technique for storage of the elements.
  • HashSet always contains unique items.

For more detail: Java: HashSet Class methods and Examples

LinkedHashSet

LinkedHashSet class implements Set Interface. It’s having the following features:

  • LinkedHashSet store items in LinkedList.
  • LinkedHashSet store unique elements.
  • LinkedHashSet maintains the insertion order.
  • LinkedHashSet allows null elements.

For more detail: Java: LinkedHashSet Class methods and Examples

SortedSet Interface

SortedSet Interface extends Set Interface. It’s having the following features:

  • SortedSet provides a total ordering on its elements.
  • SortedSet elements are arranged in the increasing (ascending) order.
  • SortedSet provides additional methods that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

SortedSet set = new TreeSet();  

For more detail: Java: SortedSet Interface methods and Examples

TreeSet Class

TreeSet class implements the SortedSet interface.  It’s having the following features:

  • TreeSet uses a tree data structure for storage.
  • TreeSet also contains unique elements.
  • TreeSet elements access and retrieval time is quite fast.
  • TreeSet elements stored in ascending order.

For more detail: Java: TreeSet Class methods and Examples

Map Interface

In the collection framework, a map contains values on the basis of key and value pair. This pair is known as an entry. A map having the following features:

  • Map contains unique keys.
  • Map allows duplicate values.
  • Map is useful to search, update or delete elements on the basis of a key.
  • Map is the root interface in Map hierarchy for Collection Framework.
  • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
  • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
  • Map can’t be traversed, for traversing needs to convert into the set using method keySet() or entrySet().

For more detail: Java: Map Class methods and Examples

HashMap Class

HashMap class implements Map interface. It’s having following features:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

For more detail:

LinkedHashMap Class

LinkedHashMap class extends the HashMap class. It’s having the following features:

  • LinkedHashMap contains values based on the key.
  • LinkedHashMap contains unique elements.
  • LinkedHashMap may have one null key and multiple null values.
  • LinkedHashMap is not synchronized.
  • LinkedHashMap maintains the insertion order.
  • LinkedHashMap default initial capacity is 16 with a load factor of 0.75.

For more detail: Java: LinkedHashMap Class methods and Examples

TreeMap Class

TreeMap class implements the SortedMap interface. it’s having the following features:

  • TreeMap uses data structure as red-black tree.
  • TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • TreeMap contains only unique elements.
  • TreeMap doesn’t allow null keys and values.
  • TreeMap is not synchronized.
  • TreeMap maintains an ascending order.

For more detail: Java: TreeMap Class methods and Examples

HashTable Class

Hashtable class implements a Map interface and extends Dictionary class to store key and values as pairs. It’s having the following features:

  • HashTable store values as an array of the list where each list is known as a bucket of the node(key and value pair).
  • HashTable class is in java.util package.
  • Hashtable contains unique elements.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is synchronized.
  • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

For more detail: Java: HashTable Class methods and Examples

See Also:

Java: Arrays vs Collections


In Java, Arrays and Collections both are to deal with a group of objects but there are lots of differences in terms of data structure or performing operations.

Here are some most common differences:

Difference between Arrays & Collections

Arrays Collections
Arrays is having fixed-length.. Collections are growable in nature i.e increase or decrease.
Arrays are not recommended in terms of memory concerns. Collections use different data structures and recommended to use with respect to memory.
Arrays are used with respect to performance. Collections are not recommended to use with respect to performance.
Arrays can store only homogeneous (same type) of data. Collections can hold both homogeneous and heterogeneous elements.
Arrays do not have a single API. Collections having big list of methods.
Arrays can work with primitives and object types. Collections can hold only objects but not with primitive. If you pass as primitive internally convert to object.
See Also: Array & Arrays Class Examples See Also: Collection Framework and Examples

Java: Constructors


In Java, Constructors are used to creating and initializing the object’s state. The constructor also contains collections of statements to execute at time object creation.

Type of Constructors:

  • Default Constructor: A Constructor without any argument.
  • Parametrize Constructor: A Constructor with a number of arguments.

Points to Remember for Constructor

  • Constructor always has the same name as the class name in which it exists.
  • Constructor can not be used with keywords final, abstract, synchronized and static.
  • Constructors declaration with access modifiers can be used to control its access i.e so that restricts other classes to call the constructor.
  • All java classes must have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
  • If you declare any parameterize constructor then that is must write a default constructor.
  • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

Example of Constructors

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
	//Parameterize constructor
	//Constructor Overriding
	public Animal(String name, String breed)
    {
        this.name = name;
        this.breed = breed;
    } 

}

Object Creation By Constructor

Here you will see both ways to create objects of Animal Class by using the default and parameterize constructors.

public TestClass
{
	public static void main(String[] args)
	{
	 //Instance Default Constructor
	 Animal dog_tommy=new Animal();

	 //Instance with Parameterize Constructor
     Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
	}
}

Does the Constructor return any value?

A constructor doesn’t have return type while implementation, but the constructor returns the current instance of the class. We can write return statements inside the class.

Constructor Overloading

Similar to methods, we can overload constructors also by creating an object in many ways. Java compiler differentiates between these constructors based on signature (i.e numbers, type, and order of parameters).

What is Constructor Chaining?

Constructor chaining is the process of calling a constructor from another constructor for the current object.

Constructor chaining can be performed in two ways:

  • Within the same class: Use this() keyword for same class constructors.
  • From base class: Use super() keyword to call a base class constructor.

Rules of constructor chaining

  • The this() expression should always be the first line of statment in the constructor.
  • There should always be at least one constructor without this() keyword.
  • Constructor chaining can be performed in any order.

Constructor Chaining Example: Within Same Class

Use this() keyword for constructors in the same class. Here you will see the last constructor with two arguments calling the constructor with the keyword this() for four arguments.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
	//Parameterize constructor
	//Constructor Overriding
	public Animal(String name, String breed)
    {
	   //constructor chaining
	    this(name,breed,1,"black");
    }
}

Constructor Chaining Example: From Base Class

Use super() keyword to call a constructor from the base class. Here Constructor chaining occurs through inheritance. A sub-class constructor’s call the super class’s constructor first so that sub class’s object starts with the initialization of the data members of the superclass. There could be multilevel of classes in the inheritance chain. Every subclass constructor calls up the chain till class at the top is reached.


public class Person{
    private String name;
    protected String citizenship;

    public Person()
    {
    }

    public Person(String name, String citizenship) {
        super();
        this.name = name;
        this.citizenship = citizenship;
    }

    public void print() {
		System.out.println("Citizen:"+ citizenship + ",Name:" + name);
	}

}

 

public class Employee extends Person {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen) {
			}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		// super keyword use to call parent constructor
		//constructor chaining to parent class
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

}

What is the use of constructor chaining?

Constructor chaining is the mechanism to perform multiple tasks in a single constructor rather than creating a separate constructor for each task and make their chain. Constructor Chaining makes the program more readable.

Constructors Vs Methods

Constructor Method
Constructor(s) must have the same name as the class within which it defined. The method does not have the same name as the class in which defined.
Constructor(s) does not return any type. method(s) have the return type or void if does not return any value.
A constructor is called only once at the time of Object creation. Method(s) can be called any number of times.
In case constructor not present in class, the default constructor provided by the compiler. In the case of Method, the compiler doesn’t provide the default method.
Constructs invoked implicitly Methods invoked explicitly.

Java: Object


Pre-Requisite: Java:Class
In the previous post, you learn about the Java Class declaration, implementation, and types of classes. Here we will discuss Object which is the basic unit of Object-Oriented paradigm to represent real-life entities.

When an instance of a class is created is known as Object. These instances share attributes and behaviors i.e methods of the class. These values of attributes will be unique for each object i.e called state.

A java program may have lots of objects and these objects interact with each other by invoking methods. An object consists of :

  • Identity: It gives a unique name to the identification of an object and enables one object to interact with other objects.
  • State: It is represented by attributes/properties values of an object.
  • Behavior: It is represented by methods of an object to behave in a particular state.

Object Class

Let’s consider a class of Animal, which can have an object like Dog, Cow, Lion, Elephant, etc. Each of these animals has different properties like name, breed, age, and color.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

Example of an object: Dog

Declaration of Object

We declare a variable or object like (type variable_name;). This indicates to the compiler that this variable refers to data whose type is type. In the case of the primitive type, declaration allocates space for the variable as per type but in case of a reference variable, the type must be a concrete class name. Generally, In java, we don’t create an object of Abstract class and interface.

Syntax

access_modifier class_name object_name;

Example

Animal dog_tommy;

As declared above for variable dog_tommy, show this variable is of type Animal but this will not create any object instance i.e point to undetermined value (null) as long as an object not created.

Creation & Initializing an object

When we create an instance of an object by using the new operator. It will allocate memory for a new object and return a reference to that memory. This new operator also called the class constructor to initialize the attributes of the class.

Syntax

//default constructor
access_modifier class_name object_name=new class_name();
//parameterize constructor
access_modifier class_name object_name=new class_name(arg1,arg2..);

Example

//Default Constructor
Animal dog_tommy=new Animal();

//Parameterize Constructor
Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");

Note :

  • All classes have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
  • If you declare any parameterize constructor then that is must write a default constructor.
  • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

Complete Example

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

public TestClass
{
	public static void main(String[] args)
	{
	 //Instance Default Constructor
	 Animal dog_tommy=new Animal();

	 //Instance with Parameterize Constructor
     Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
	}
}

Output


Animal [name=Default, breed=null, age=0, color=null]
Animal [name=Tommy, breed=Small Dog, age=5, color=Black]

Ways to create an object of a class

This is the most common way to create an instance of an object by using new operators. Java also provides other ways to create instances of an object but internally uses a new keyword only.

  1. Object by new Operator
  2. Object by Class.forName().newInstance()
  3. Object by clone() method
  4. Object by Deserialization
  5. Object for Anonymous Class

Follow this link to know about each object creation ways in detail: Java: Object Creation Ways

 

Java: Types of Classes


Pre-Requisite: Java: Class
In a previous post, you have got an understanding of java class declaration and creation.

Types of classes

Java supports lots of types of classes:

  • Concrete Class
  • Abstract Class
  • POJO Class
  • Static Class
  • Nested Class/Inner Class
  • Final Class
  • Anonymous Class
  • Lambda Expression

Here we will discuss these classes in detail.

Concrete Class

A concrete class is a normal class that is not declared with Non-access modifiers as abstract, final, etc. This class can have an implementation of a parent, interfaces or own class methods.

Example: Concrete Class

//Example Concrete Class
public class CalculatorTest {
    static int add(int a , int b)
    {
    	return a+b;
    }
    static int substract(int a , int b)
    {
    	return a-b;
    }
    static int multiply(int a , int b)
    {
    	return a*b;
    }
    static int division(int a , int b)
    {
    	return a/b;
    }
	public static void main(String[] args) {
      System.out.println("4+5 ="+add(4,5));
      System.out.println("4-5 ="+substract(4,5));
      System.out.println("4*5 ="+multiply(4,5));
      System.out.println("4/5 ="+division(4,5));
	}
}

See Also: Java: Concrete Class Examples

Abstract Class

A class that is declared with the keyword abstract is known as an abstract class in Java. It can have abstract and concrete methods (method with the body). An abstract class can not be instantiated but need to extend to implement abstract methods.

Example: Abstract Class

args)
{
Vehicle v=new Car();
v.engine();
v=new Bike();
v.engine();
v=new Truck();
v.engine();
v=new Bus();
v.engine();
}
}

See Also: Java: Abstract Class Examples

POJO Class

A class with only private variables and public getter and setter methods is called as POJO(Plain Old Java Object) class. These getter and setter methods use private variables. This class is completely encapsulated.

Example: Pojo Class

//POJO Class
public class Animal {
	//private  variables
    private String name;
    private String breed;
    private int age;
    private String color;
    //Getter and setter methods
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getBreed() {
		return breed;
	}
	public void setBreed(String breed) {
		this.breed = breed;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
}

See Also: Java: Pojo Class Examples

Static Class

A static class is a nested class declared as a static member of the class.

Example: Static Class

import java.util.Scanner;

public class StaticClasses {
	static int s;// static variable

	// static method
	static void printSum(int a, int b) {
		s = a + b;
		System.out.println(a + "+" + b + "=" + s);
	}

	static class NestedStaticClass//static class
	{
		static//static block
		{
			System.out.println("Inside Nested Class Static Block");
		}

		public void display()
		{
			Scanner scanner=new Scanner(System.in);
			System.out.println("Enter value of a:");
			int a= scanner.nextInt();
			System.out.println("Enter value of b:");
			int b= scanner.nextInt();

			printSum(a,b);
			System.out.println("Sum of numbers a+b:" +s);

		}
	}
}

public class StaticClassTest {

	public static void main(String[] args) {
		StaticClasses.NestedStaticClass nss=new StaticClasses.NestedStaticClass();
		//call method of nested class method
		nss.display();
	}
}

See Also: Java: Static Keyword & Examples

Nested Class/Inner Class

A Class declared inside of another class is called Nested Class/Inner Class.

Example: Nested Class/Inner Class

public class OuterClass {

	//nested/Inner Class: Class inside the class
	class NestedClass
	{
		public void innerMethod()
		{
			System.out.println("Inner Class Print");
		}
	}

	public static void main(String[] args) {
		System.out.println("Outer Class Print");

	}

}

See Also: Java: Nested/Inner Class Examples

Final Class

A Class declared with the final keyword is known as Final Class. This class can not be extended by another class. For Example java.lang.System, java.lang.String

Example: Final Class

public final class FinalClass {
 public void display()
 {
	 System.out.println("Display final class method.");
 }
}

//show compiler error :
//"The type BaseClass can not subclass the final class FinalClass"
class BaseClass extends FinalClass{
	public void display()
	 {
		 System.out.println("Display base class method.");
	 }
}

See Also: Java: Final Keyword & Examples

Anonymous Inner Class

Anonymous Class is an inner class without a name and for which only a single object is created. Such class is useful when you need to create an instance of an object such as overloading methods of a class or interface, without having to actually subclass a class.

Anonymous inner classes are mostly used in writing implementation classes for listener interfaces in graphics programming.

Example: Anonymous Class

//Using Anonymous Inner class Thread that extends a Class
class MyThread
{
    public static void main(String[] args)
    {
        //Here we are using Anonymous Inner class
        //that extends a class i.e. Here a Thread class
        Thread t = new Thread()
        {
            public void run()
            {
                System.out.println("Child Thread");
            }
        };
        t.start();
        System.out.println("Main Thread");
    }
}

See Also: Java: Anonymous Class Examples

Lambda Expression

Lambda expressions added in Java 8. It useful to create instances of functional interfaces (An interface with single abstract method). For Example: java.lang.Runnable is having one abstract method as run().

Example: Lambda Expression

public class LamdaTest {
	public static void main(String[] args) {
		new Thread(() -> System.out.println("This is Lamda test")).start();
	}
}

See Also: Java: Lamda Expression Examples

 

Java: Class


A Class is a blueprint or prototype from which objects are created. A class has properties and behaviors i.e methods that are common to all objects of the same type.

Object Class

Syntax of Class Declaration


Access_Modfier Non_access_modiers class class_name 
    extends super_class 
    implements interface1, interface 2..
{
fields
......
default constructor
......
parametrize constructor
......
methods
......
}
  • Access Modifiers: A modifier defined access scope of class, fields, and methods. If specifically not mentioned consider as default. See Also: Java: Access Modifiers/Specifiers
  • Class name: The class name should begin with an initial capital letter follow camel notation. See Also: Java: Identifier Naming Conventions
  • Non-Access Modifiers (if any): non-access modifiers can also be used on the class level to make a class special. See Also: Java: Non-Access Modifiers
  • Superclass(if any): A class can extend only one class i.e called parent class or superclass.
  • Interfaces(if any): A class can implement one or more interfaces. Their interfaces proceed by keyword implements and separated by a comma.
  • Body: A class body is surrounded by curly braces, { }.
    Fields: A class fields are variables that provide the state of class and it’s objects.
  • Methods: class methods are defined to implement the behavior of class and objects. See Also: Java Methods
  • Constructors: Java class constructors are used to initialize new objects. See Also: Java: Constructors

Note:

  • If a class is declared with access modifier public then java file name would also be the same. One Java file can have only one public class.
  • All the class extends Object Class i.e Object class is the superclass of all the classes.See Also: Java: java.lang.Object Class & Methods

Java Class Example

This is a very simple example of a class name as Animal. It’s having variables, constructors, methods and overriding method of superclass Object.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

Now we have got a basic understanding of class declaration and implementation. In the further post, you will learn about the types of classes and uses.

Types of classes

Java supports lots of types of classes:

  • Concrete Class
  • Abstract Class
  • POJO Class
  • Static Class
  • Nested Class/Inner Class
  • Final Class
  • Anonymous Class
  • Lambda Expression

Follow this link to know about all these classes and uses.

See Also: Java: Type of classes

Java: EnumSet Class


Java EnumSet class is the specialized Set implementation for use with enum types. It inherits AbstractSet class and implements the Set interface.

EnumSet class hierarchy

The hierarchy of EnumSet class is given in the figure given below.
EnumSet

EnumSet class declaration

Let’s see the declaration for java.util.EnumSet class.

public abstract class EnumSet<E extends Enum> extends AbstractSet implements Cloneable, Serializable  

Methods of Java EnumSet Class

Method Description
static <E extends Enum> EnumSet allOf(Class elementType) It is used to create an enum set containing all of the elements in the specified element type.
static <E extends Enum> EnumSet copyOf(Collection c) It is used to create an enum set initialized from the specified collection.
static <E extends Enum> EnumSet noneOf(Class elementType) It is used to create an empty enum set with the specified element type.
static <E extends Enum> EnumSet of(E e) It is used to create an enum set initially containing the specified element.
static <E extends Enum> EnumSet range(E from, E to) It is used to create an enum set initially containing the specified elements.
EnumSet clone() It is used to return a copy of this set.

Example :EnumSet

import java.util.*;
enum days {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample {
  public static void main(String[] args) {
    Set set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);
    // Traversing elements
    Iterator iter = set.iterator();
    while (iter.hasNext())
      System.out.println(iter.next());
  }
}

Output :


TUESDAY
WEDNESDAY

Java EnumSet Example: allOf() and noneOf()

import java.util.*;
enum days {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample {
  public static void main(String[] args) {
    Set set1 = EnumSet.allOf(days.class);
      System.out.println("Week Days:"+set1);
      Set set2 = EnumSet.noneOf(days.class);
      System.out.println("Week Days:"+set2);
  }
}

Output :


Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Week Days:[]

Java: ArrayList Vs Vector Class


java.util.ArrayList and java.util.Vector both implements List interface and maintains insertion order. It’s having many differences as below:

ArrayList vs Vector

ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList increases 50% of the current array size if the number of elements exceeds its capacity. Vector increase 100% means doubles the array size when the total number of elements exceeds its capacity.
ArrayList is not a legacy class. It is introduced in JDK 1.2. Vector is a legacy class.
ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in the runnable or non-runnable state until the current thread releases the lock of the object.
ArrayList uses the Iterator interface to traverse the elements. A Vector can use the Iterator interface or Enumeration interface to traverse the elements.
See Also:ArrayList Class See Also:Java: Vector Class

ArrayList Example: traversing by the iterator

import java.util.*;
class ArrayListExample{
 public static void main(String args[]){    

  //creating arraylist of String
  List al=new ArrayList();
 //adding objecta in arraylist
  al.add("Saurabh");
  al.add("Mahesh");
  al.add("Jonny");
  al.add("Anil");
  //traverse elements using Iterator
  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}

Output

Saurabh
Mahesh
Jonny
Anil

Vector Example: Traversing by Enumerator

import java.util.*;
class VectorExample{
 public static void main(String args[]){
  Vector v=new Vector();//creating vector
  v.add("Umrao");//method of Collection
  v.addElement("Isha");//method of Vector
  v.addElement("Kush");
  //traverse elements using Enumeration
  Enumeration e=v.elements();
  while(e.hasMoreElements()){
   System.out.println(e.nextElement());
  }
 }
}

Output

Umrao
Isha
Kush

Java: Abstract Class Vs Interface


Abstract class and interface in java used to provide abstraction but there are lots of differences:

Abstract Class Interface
Abstraction(0 to 100%) Abstraction(100%)
Abstract class implemented by keyword ‘extends Interface implemented by using keyword ‘implements
Abstract class also can not be instantiated but can be invoked if the main() method exists. Interface is completely abstract i.e can not create an instance of it.
Abstract class can have abstract and non-abstract methods. Interface methods are implicitly abstract and can not have an implementation(nobody)
Abstract class allowed final, non-final and static variables also. Interface allowed only final and static variables
Abstract class members are private, protected, etc. Interface members are public by default.
Abstract class can extend only one class but implements multiple java interfaces. Interface can extend other interfaces only.
Abstract class is fast compare to interface Interface is slow because it required extra indirection.
See Also: Java Abstract Class Examples See Also: Java Interface Examples

See Also:

Java: Interface


An interface is the blueprint of a class to achieve total abstraction.

  • Abstract Class: Abstraction (0 to 100%)
  • Interface: Abstraction (100%)

Points to remember for Interface in Java

  • Interface in java use interface keyword to declare.
  • Interface in java allows only abstract methods i.e methods don’t have a body.
  • Interface in java allows static constants.
  • Interface in java supports multiple inheritance.
  • Interface in java not required to declare the method as public and abstract, internally all methods are public and abstract.
  • Interface in java having all fields as public, static and final.
  • Interface in java represents the IS-A relationship.
  • Interface in java can not be instantiated just like an abstract class.

Note:
There are some enhancements in the interface as per Java versions:

Why use Java interface?

There is the main reason to use interface in java:

  • Interface in java used to achieve abstraction.
  • Interface in java is used to support the multiple inheritance functionality.
  • Interface in java is used to achieve loose coupling.

How to declare an interface?

Interface in java is declared by using the interface keyword. All interface methods declared with the empty body are by default public and abstract. All declared fields inside the interface are public, static and final by default.

If a java class that implements an interface must implement all the methods declared in the interface.

Syntax:

interface interface_name{  
     // declare constant fields by default public , static and final  
    // declare methods that public and abstract by default   
} 

Note: If you are not adding any modifier in methods and variables in Java interface. The compiler adds as below while compilation:

  • Java compiler will add the public and abstract before the interface methods.
  • Java compiler will add public, static and final before fields inside java interface.

Java Classes and Interface Relationship

In java a class extends another class, an interface extends another interface, but a class implements an interface.

Interface Example

In the given example, the Shape interface has only one method as draw(). This method is implemented by Rectangle and Circle classes.

In a real scenario, an interface provides an abstraction to users i.e interface is defined by someone else, but its method implementation is provided by different providers. Moreover, it is used by someone else to interact with the method but the implementation part is hidden by the user.


interface Shape{
	void draw();
}
class Rectangle implements Shape{
public void draw(){System.out.println("Drawing Rectangle Shape");}
}
class Circle implements Shape{
public void draw(){System.out.println("Drawing Circle Shape");}
}  

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

Shape d=new Circle();
      d.draw();
	  d=new Rectabgle();
      d.draw();
}}

Output


Drawing Circle Shape
Drawing Rectangle Shape

Multiple inheritances in Java by the interface

Multiple inheritance in java class can be achieve by implements multiple interfaces, or an interface by extends multiple interfaces.

interface Printable{
void print();
}
interface Shape{
void draw();
}
class Rectangle implements Shape,Printable{
public void draw(){System.out.println("Drawing Rectangle Shape");}
public void print(){System.out.println("Print Rectangle Area");}
}
class Circle implements Shape,Printable{
public void draw(){System.out.println("Drawing Circle Shape");}
public void print(){System.out.println("Print Circle Area");}
}
class TestMultipleInterface{
public static void main(String args[]){
Shape d=new Circle();
d.draw();
d.print();
d=new Rectabgle();
d.draw();
d.print();
}
}

Output


Drawing Circle Shape
Print Circle Area
Drawing Rectangle Shape
Print Rectangle Area

Multiple inheritances are not supported through the class in java, but it is possible by an interface, why?

Multiple inheritances are not supported in the case of class because of ambiguity but supported by the interface because there is no ambiguity. It is because this method implementation is provided by the implementation class.

As shown in the below example,  Showable and Printable interface have the same display() methods but its implementation is provided by class MultipleInterfaceExmple, so there is no ambiguity.

interface Printable{
void display();
}
interface Showable{
void display();
}

class MultipleInterfaceExmple implements Printable, Showable{
public void dispaly(){
System.out.println("Print Test Multiple Inheritance in java");
}
public static void main(String args[]){
MultipleInterfaceExmple obj = new MultipleInterfaceExmple();
obj.display();
}
}

Output

Print Test Multiple Inheritance in java 

Interface inheritance

A class implements an interface, but one interface can extend another interface.

interface Printable{
void display();
}
interface Showable extends Printable{
void display();
}
class InterfaceInheritanceExmple implements Showable{
public void print(){System.out.println("Print Interface Inheritance in java");}
public void display(){System.out.println("Display Interface Inheritance in java");}

public static void main(String args[]){
InterfaceInheritanceExmple obj = new InterfaceInheritanceExmple();
obj.print();
obj.display();
}
}

Output

Print Interface Inheritance in java
Display Interface Inheritance in java

What is a marker or tagged interface?

An interface that has no methods is known as a marker or tagged interface, for example, Cloneable, Serializable, Remote, etc. Marker Interface in Java is used to provide information to the JVM so that JVM treats these objects specially.

Follow below link to get Detail knowledge of Marker interface with examples:

Marker Interface in Java and Uses

What is nested Interface?

An interface declared within another interface or class is called a nested interface.

Follow below link to get detail knowledge of nested interface with examples:

Java: Nested Interface

 

Java: Nested Interface


An interface declared within another interface or class is called a nested interface.

The nested interfaces in java are used to group related interfaces so that easily maintain. The nested interface can’t be accessed directly. For accessing must be referred to by the outer interface or class.

For example, the Nested interface is just like almirah inside the room, for accessing almirah, first need to enter the room.

In the java collection framework,  Entry is the subinterface of Map i.e. accessed by Map. Entry.

Points to remember for nested interfaces

  • Nested interfaces are declared static implicitly.
  • Nested interface can have any access modifier while inside the class but if use inside interface then it must be public.

Syntax of Nested Interface inside Class

class class_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}

Syntax of Nested Interface inside Interface

interface interface_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}  

Example of Nested Interface: Interface within Interface

interface Readable{
  void show();
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Interface

we are accessing the Message interface by its outer interface Readable because it cannot be accessed directly.

class NestedInterfaceExample1 implements Readable.Message{

 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
  //upcasting here
  Readable.Message message=new NestedInterfaceExample1();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Note: For the above example when you compile Readable class, compiler internally creates the public and static interface as given below:

public static interface Showable$Message
{
  public abstract void messageDetail();
}

As you can see in the above example, The java compiler internally creates the public and static interface.

Example of Nested Interface: Interface within Class

In the below example you will see, interface implementation inside the class and how can we access it.

class ClassA{
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Class

class NestedInterfaceExample2 implements ClassA.Message{
 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
 //upcasting here
  ClassA.Message message=new NestedInterfaceExample2();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Can we define a class inside the interface?

Yes, If we implement a class inside the interface, the java compiler automatically creates a static nested class. In this example you will see how can we define a class within the interface:

interface M{
class A{}
}

 

Java: this Keyword


In Java, this keyword used as a reference variable that refers to the current object. Java this keyword having many uses:

  • this to refer current class instance variable.
  • this to invoke current class method (implicitly)
  • this() to invoke the current class constructor.
  • this to pass as an argument in the method call.
  • this to pass as an argument in the constructor call.
  • this to return the current class instance from the method.

this Keyword: Example

In the highlighted lines, you will see all the ways of using this keyword

public class Employee  {
	private int employeeId;
	protected String name;
    protected String citizenship;
    private  String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen) {
		// this keyword to resolve name ambiguity
		this.name=name;
		this.citizenship=citizen;
		this.employeeId = employeeId;
		this.department = department;
	}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		// this keyword use to call another constructor
		this(employeeId, name, department, citizen);
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	public void display() {
		// this to call method and pass as argument
		this.print(this);
	}

	public Employee getEmployee(){
		//This keyword to return current object
		return this;
	}

	public void print(Employee employee) {
		System.out.println("Id :" + employeeId + ", Department :" + department
				+ ", Salary:" + salary + ",Citizen:"
				+ citizenship + ",Name:" + name);
	}

}

Java: static Keyword


In Java, static keyword is used for memory management mainly. Static elements below to the class. It can apply with:

  • Static Variable (also known as a class variable)
  • Static Method (also known as a class method)
  • Static Block
  • Static Nested class
  • Static Import

Note: These static variables and method access by class name it doesn’t require any class instance.

Java Static Variable

A variable declares as static is known as static variable or class variable. This variable value would be common among all the instances of class because these variables take memory in the class area only once when the class first loaded.
Advantage: The static variable makes program memory efficient because of saves memory.

static variable.png

static Variable Example

public class Employee {

	int id;
	String name;
	static String organization = "Facing Issues On IT";

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

	public String display() {
		return "Id:" + id + " Name:" + name + " Organization:" + organization;
	}
}
public class StaticVariableTest {

	public static void main(String[] args) {
		Employee e1=new Employee(1,"Saurabh Gupta");
		Employee e2=new Employee(2,"Gaurav Kumar");

		System.out.println(e1.display());
        System.out.println(e2.display());
        //Change Static value
        Employee.organization="Learn from Others Experience";//Print before change
        System.out.println(e1.display());
        System.out.println(e2.display());
	}

}

Output


Id:1 Name:Saurabh Gupta Organization:Facing Issues On IT
Id:2 Name:Gaurav Kumar Organization:Facing Issues On IT
Id:1 Name:Saurabh Gupta Organization:Learn from Others Experience
Id:2 Name:Gaurav Kumar Organization:Learn from Others Experience

Counter Example with instance and static Variable

public class Counter {
	// instance variable count get memory each time when instance get created
	int count = 0;
	// class variable count will get memory once once when class loaded
	static int staticCount;

	public Counter() {
	//increase the value of each count
     count++;
     staticCount++;
     System.out.println("Count :"+count +" Static Count :"+staticCount);
	}
}
public class CounterExample {

	public static void main(String[] args) {
		new Counter();
		new Counter();
		new Counter();
	}

}

Output


Count :1 Static Count :1
Count :1 Static Count :2
Count :1 Static Count :3

Java Static Method

a static keyword with any method is known as a static method or class method.

  • A static method belongs to the class rather than the instance of a class.
  • A static method can be invoked by class names without the need for creating an instance of a class.
  • A static method can access static data variables only change the value of it.

Restrictions for the static method

There are mainly two restrictions for the static method:

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super keyword cannot be used in static context.

Why Java main() method is static?

The static method doesn’t require an object to call because it’s called my Class Name. If the main() method were a non-static method, JVM creates an object first then call a main() method that would be the problem of extra memory allocation.

Java Static Method Example

public class Employee {

	int id;
	String name;
	static String organization = "Facing Issues On IT";

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

	public String display() {
		return "Id:" + id + " Name:" + name + " Organization:" + organization;
	}
	//static method static member only
	public static void change(String org)
	{
		organization=org;
		//these non static member will throw compile time issues.
		//id=5;
		//name="Rajesh";
	}
}

public class StaticMethodTest {

	public static void main(String[] args) {
		Employee e1=new Employee(1,"Saurabh Gupta");
		Employee e2=new Employee(2,"Gaurav Kumar");

		System.out.println(e1.display());
        System.out.println(e2.display());
        //Change Static value by calling static method
        Employee.change("Learn from Others Experience");
        System.out.println(e1.display());
        System.out.println(e2.display());
	}

}

Output


Id:1 Name:Saurabh Gupta Organization:Facing Issues On IT
Id:2 Name:Gaurav Kumar Organization:Facing Issues On IT
Id:1 Name:Saurabh Gupta Organization:Learn from Others Experience
Id:2 Name:Gaurav Kumar Organization:Learn from Others Experience

Java Static Block

  • A static block is executed before the main method at the time of classloading.
  • A static block is used to initialize the static data variables and members.
public class StaticBlockExample {

	static {
		System.out.println("Static block is executed");
	}

	public static void main(String args[]) {
		System.out.println("Main method executed");
	}

}

Output


Static block is executed
Main method executed

Can we execute a program without main() method?

It was possible till JDK 1.6. by executing the static block. Since JDK 1.7, it is not possible to execute a java class without the main method.

class Test{
  static{
  System.out.println("Static block is executed");
  System.exit(0);
  }
}

JDK 1.6


Static block is executed

JDK 1.7


Error: Main method not found in class Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Java Static Import

The static import feature introduced in Java 5 to access any static member of a class directly. There is no need to qualify class name.

Static Import Advantage

Less coding is required: if need to use some static member frequently.

Static import Disadvantage

If you overuse the static import statement, then it creates problem to understand and maintain code.

Example of Static Import

import static java.lang.System.*;

public class StaticImportExample {
	public static void main(String args[]) {
		// Now no need of write System.out
		out.println("Facing Issues on IT");
		out.println("Learn from Other Experinces");

	}
}

Output


Facing Issues on IT
Learn from Other Experinces

What is the difference between import and static import?

import static import
The import statement allows the java programmer to access classes of a package without package qualification. The static import statement allows to access the static members of a class without the class qualification.
The import statement provides accessibility to classes and interface. The static import statement provides accessibility to static members of the class.

Java : Non Primitive Data Types


Non-primitive data types are also called as reference types because they refer to objects.

Examples:  Strings, Arrays, Classes, Interface, etc. are non-primitive type.

Note: Non-primitive data type also called a User Defined Type when declaring an object with Classes and Interfaces names.

See Also: Java: Primitive Type Size and Default Value

Primitive Vs Non-Primitive

These are the main difference between primitive and non-primitive data types:

  • Primitive types are predefined in Java. While Non-primitive types are created by the programmer and is not defined by Java (except for String).
  • Non-primitive types also be used to call methods to perform certain operations, while primitive types cannot.
  • The primitive type has always had value, while non-primitive types can be null.
  • The primitive type starts with a lowercase letter, while non-primitive types start with an uppercase letter.
  • The primitive type size depends on the data type, while non-primitive types have all the same size.

Java: How HashSet Work?


A Set interface represents a group of unique elements arranged like an array. When we try to pass the duplicate element that is already available in the Set, then it will not store into the Set.

HashSet class

HashSet class implemnets Set interface and extends AbstractSet class.A HashSet class uses Hash Map internally for storing elements by using hashing technique.HashSet store unique elements and does not guarantee the order of elements.

Suppose, you want to create a HashSet to store a group of Strings, then create the HashSet object as:


HashSet hs=new HashSet();  

Where is the generic type parameter to represent HashSet allows only String type objects.

HashSet default constructor create instance of initial capacity 16 and capacity may increase automatically when number of elements reach to load factors. For uniqueness of object generate key as hashcode value. HashSet class doesn’t have method to retrieve object of Instance only way is retrieve object by iteration.

Note: To set your own capacity and loadfactor for HashSet. you can use below constructor.


HashSet hs=new HashSet(int capacity, float loadfactor);  

Here, loadfactor determines when number of elements in HashSet reach to that capacity limit increase capacity internally.the point where the capacity of HashSet would be increased internally.
The initial default capacity of HashSet is 16. The default load factor is 0.75. then 16*0.75=12 when no of elements reach to 12 increase capacity of HashSet to store more elements.

Example HashSet:

import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample1 {
	public static void main(String[] args) {
      HashSet countries=new HashSet();
      countries.add("India");
      countries.add("Pakistan");
      countries.add("China");
      countries.add("Nepal");
      countries.add("Afganistan");
      countries.add("Canada");
      countries.add("Brazil");
      countries.add("Canada");
      countries.add("Brazil");
      countries.add("Thailand");
      countries.add("Malasia");
      countries.add("Russia");
      countries.add("London");
      countries.add("Switzerand");
      //Till that point threshold/capacity value is 12
      System.out.println("Countries Name:"+countries);
      System.out.println("Total Countries:"+countries.size());
      //Duplicate elements not allowed
      System.out.println("Add Dubai:"+countries.add("Dubai"));
      System.out.println("Add Dubai :"+countries.add("Dubai"));//return false when duplicate
      //After adding 13th element Threshold/capacity reach to 24 just double
      System.out.println("Countries Name:"+countries);
      System.out.println("Total Countries:"+countries.size());

     //iteration of Hashset elements
      System.out.println("\n\nPrint Countries by for each:");
      for(String country:countries)
      {
    	 System.out.println(country);
      }

      System.out.println("\n\nPrint Countries by for iterator:");
      Iterator it=countries.iterator();
      while(it.hasNext())
      {
    	  System.out.println(it.next());
      }

	}
}

Output


Countries Name:[Canada, Pakistan, China, Malasia, Brazil, London, Afganistan, Thailand, Nepal, Switzerand, India, Russia]
Total Countries:12
Add Dubai:true
Add Dubai :false
Countries Name:[Malasia, Thailand, Dubai, India, Russia, Canada, Pakistan, China, Brazil, London, Afganistan, Nepal, Switzerand]
Total Countries:13


Print Countries by for each:
Malasia
Thailand
Dubai
India
Russia
Canada
Pakistan
China
Brazil
London
Afganistan
Nepal
Switzerand


Print Countries by for iterator:
Malasia
Thailand
Dubai
India
Russia
Canada
Pakistan
China
Brazil
London
Afganistan
Nepal
Switzerand

In this example we have added duplicate values as Dubai in HashSet. When added it first time by add method return true because Dubai was not in HashSet. When added again return false because it was already added.

How HashSet work?

Now question comes how HashSet, add() method returns true and false. When you will open HashSet implementation of the add() method in Java APIs i.e. rt.jar, you will see the following code in it:

public class HashSet&ltE> extends AbstractSet
{
private transient HashMap map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet()
{
map = new HashMap();
}
public boolean add(E e)
{
return map.put(e, PRESENT)==null;
}
}

In this HashSet, add(object) methods use HashMap delegated to put(key, value) internally. Where key is the object added on HashSet and value is constant object as PRESENT in java.util.HashSet.

When we create HashSet Object, internally create an object of HashMap. As we know in HashMap each key is unique so, When we call add(E e) method this passing object set as key of HashMap and dummy object (new Object()) which is referred by Object reference PRESENT pass as value.

In HashMap put(key, value):

  • If the Key is unique and added then it will return null
    If the Key is duplicate, then map will return the old value of the key.

Let consider above example, when add country as countries.add(“Dubai”), java internally call HashMap put(“Dubai”,PRESENT) method to add element in map.

public boolean add(E e)
{
return map.put(e, PRESENT==null);
}

If the method map.put(key, value) returns null, then the method map.put(e, PRESENT)==null will return true internally, and the element added to the HashSet.
If the method map.put(key, value) returns the old value of the key, then the method map.put(e, PRESENT)==null will return false internally, and the element will not add to the HashSet.

As per given implementation when country “Dubai” added first time put() method return as null because “Dubai” not added before (unique) then add method return true. But when “Dubai” added again put() method will return old object and add method will return false on that case because of duplicate.

Retrieving Object from the HashSet

We use iterator() method of HashSet to retrieve objects. Internally HashSet iterator method called map.keySet().iterator() method.

public Iterator iterator()
{
return map.keySet().iterator();
}

Java: Collections Class Methods and Examples


java.util.Collections class extends Object class. Collections also called as utility class is used exclusively with static methods that operate on or return collections.

Points to remember

  • Collection class supports polymorphic to operate on collections.
  • Collection class throws a NullPointerException if passing objects are null.

Collections Declaration

public class Collections extends Object 

Collections Class Methods

Methods Descriptions
static boolean addAll() Adds all of the specified elements to the given collection.
static Queue asLifoQueue() Returns a view of a Deque as a LIFO(Last in first out) Queue.
static int binarySearch() Searches the list for the specified object and returns their index position in a sorted list.
static Collection checkedCollection() Returns a dynamically type safe view of the given collection.
static List checkedList() Returns a dynamically type safe view of the given list.
static Map checkedMap() Returns a dynamically type safe view of the given map.
static NavigableMap checkedNavigableMap() Returns a dynamically type safe view of the given navigable map.
static NavigableSet checkedNavigableSet() Returns a dynamically type safe view of the given navigable set.
static Queue checkedQueue() Returns a dynamically type safe view of the given queue.
static Set checkedSet() Returns a dynamically type safe view of the given set.
static SortedMap checkedSortedMap() Returns a dynamically type safe view of the given sorted map.
static SortedSet checkedSortedSet() Returns a dynamically type safe view of the given sorted set.
static void copy() Copy all the elements from one list into a another list.
static boolean disjoint() Returns true if the two specified collections have no common elements.
static Enumeration emptyEnumeration() Get an enumeration that has no elements.
static Iterator emptyIterator() Get an Iterator that has no elements.
static List emptyList() Get a List that has no elements.
static ListIterator emptyListIterator() Get a List Iterator that has no elements.
static Map emptyMap() Returns an empty map which is immutable.
static NavigableMap emptyNavigableMap() Returns an empty navigable map which is immutable.
static NavigableSet emptyNavigableSet() Get an empty navigable set which is immutable in nature.
static Set emptySet() Get the set that has no elements.
static SortedMap emptySortedMap() Returns an empty sorted map which is immutable.
static SortedSet emptySortedSet() Get the sorted set that has no elements.
static Enumeration enumeration() Get the enumeration over the specified collection.
static void fill() Replace all of the elements of the specified list with the specified elements.
static int frequency() Get the number of elements in the specified collection equal to the given object.
static int indexOfSubList() Get the starting index position of the first occurrence of the specified target list within the specified source list. It returns -1 if there is no elements found in the specified list.
static int lastIndexOfSubList() Get the starting index position of the last occurrence of the specified target list within the specified source list. It returns -1 if there is no elements found in the specified list.
static ArrayList list() Get an array list containing the elements returned by the specified enumeration in the order in which they are returned by the enumeration.
static > T max() Get the maximum value of the given collection, according to the natural ordering of its elements.
static > T min() Get the minimum value of the given collection, according to the natural ordering of its elements.
static List nCopies() Get an immutable list consisting of n copies of the specified object.
static Set newSetFromMap() Return a set backed by the specified map.
static boolean replaceAll() Replace all occurrences of one specified value in a list with the other specified value.
static void reverse() Reverse the order of the elements in the given list.
static Comparator reverseOrder() Get the comparator that imposes the reverse of the natural ordering of elements on a collection of objects which implement the Comparable interface.
static void rotate() Rotate the elements in the specified list by a given distance.
static void shuffle() Randomly reorders the specified list elements using a default randomness.
static Set singleton() Get an immutable set which contains only the specified object.
static List singletonList() Get an immutable list which contains only the specified object.
static Map singletonMap() Get an immutable map, mapping only the specified key to the specified value.
static >void sort() Sort the elements presents in the specified list of collection in ascending order.
static void swap() Swap the elements at the specified positions in the given list.
static Collection synchronizedCollection() Get a synchronized (thread-safe) collection backed by the given collection.
static List synchronizedList() Get a synchronized (thread-safe) collection backed by the given list.
static Map synchronizedMap() Get a synchronized (thread-safe) map backed by the given map.
static NavigableMap synchronizedNavigableMap() Get a synchronized (thread-safe) navigable map backed by the given navigable map.
static NavigableSet synchronizedNavigableSet() Get a synchronized (thread-safe) navigable set backed by the given navigable set.
static Set synchronizedSet() Get a synchronized (thread-safe) set backed by the given set.
static SortedMap synchronizedSortedMap() Get a synchronized (thread-safe) sorted map backed by the given sorted map.
static SortedSet synchronizedSortedSet() Get a synchronized (thread-safe) sorted set backed by the given sorted set.
static Collection unmodifiableCollection() Get an unmodifiable view of the given collection.
static List unmodifiableList() Get an unmodifiable view of the given list.
static Map unmodifiableMap() Get an unmodifiable view of the given map.
static NavigableMap unmodifiableNavigableMap() Get an unmodifiable view of the given navigable map.
static NavigableSet unmodifiableNavigableSet() Get an unmodifiable view of the given navigable set.
static Set unmodifiableSet() Get an unmodifiable view of the given set.
static SortedMap unmodifiableSortedMap() Get an unmodifiable view of the given sorted map.
static SortedSet unmodifiableSortedSet() Get an unmodifiable view of the given sorted set.

Collections Example : Add elements in list

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

public class CollectionsExample1 {

	public static void main(String[] args) {
		 List list = new ArrayList();
	        list.add("C");
	        list.add("C++");
	        list.add("Python");
	        list.add("Lisp");
	        list.add("Java Script");
	        System.out.println("Initial collection value:"+list);
	        //add some more element in collection
	        Collections.addAll(list, "Servlet","JSP");
	        System.out.println("After adding elements collection value:"+list);
	        String[] strArr = {"C#", "Closure",".Net"};
	        //add some more elements
	        Collections.addAll(list, strArr);
	        System.out.println("After adding array collection value:"+list);
	}

}

Output :


Initial collection value:[C, C++, Python, Lisp, Java Script]
After adding elements collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP]
After adding array collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP, C#, Closure, .Net]

Collections Example :max()

import java.util.*;

public class CollectionsExample2 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Max element from the collection: " + Collections.max(list));
	}
}

Output :


Max element from the collection: 90

Output:

Collections Example :min()

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

public class CollectionsExample3 {
	public static void main(String a[]) {
		Listlist = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Min element from the collection: " + Collections.min(list));
	}
}

Output :


Min element from the collection: 2

Java: EnumMap Class Methods and Examples


java.util.EnumMap class inherits Enum and AbstractMap classes. It’s special type of Map for enum keys.

EnumMap Declaration

public class EnumMap,V> extends AbstractMap implements Serializable, Cloneable  
  • K: Represent as key in Map of type Enum
  • V:Represent as value with respect to K.

Constructors of EnumMap

Constructor Description
EnumMap(Class keyType) Create an empty enum map with the given key type.
EnumMap(EnumMap m) Create an enum map with the same key type as the given enum map.
EnumMap(Map m) Create an enum map initialized from the given map.

Methods of EnumMap

Method Description
clear() Clear all the mapping from the map.
clone() Copy the mapped value of one map to another map as sallow cloning.
containsKey() Check whether a given key is present in this map or not.
containsValue() Check whether one or more key is associated with a specified value or not.
entrySet() Create a set of keys/elements contained in the EnumMap.
equals() Compare two maps keys for equality.
get() Get the mapped value with respect to given key.
hashCode() Get the hashcode value of the EnumMap.
keySet() Return the set of the keys contained in the map.
size() Get count of the size of the EnumMap.
Values() Create a collection view of the values contained in this map.
put() Associate the given value with the specified key in this EnumMap.
putAll() Copy all the mappings from one EnumMap to another new EnumMap.
remove() Remove the mapping for the given key from EnumMap if the given key exist in EnumMap.

EnumMap Example : insert elements and traverse

import java.util.*;

public class EnumMapExample1 {
	// create an enum for keys
	public enum Days {
		Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
	};

	public static void main(String[] args) {

		// Insert elements in map
		EnumMap map = new EnumMap(Days.class);
		map.put(Days.Monday, "1");
		map.put(Days.Wednesday, "3");
		map.put(Days.Friday, "5");
		map.put(Days.Sunday, "7");
		// traverse map
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Monday 1
Wednesday 3
Friday 5
Sunday 7

EnumMap Example: insert objects and traverse

import java.util.EnumMap;
import java.util.Map;
class Magzine {
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}    

public class EnumMapWithObjectsExample {
	// Creating enum of keys
	public enum Key {
		One, Two, Three
	};

	public static void main(String[]args){
EnumMap map = new EnumMap(Key.class);
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzines to Map
		map.put(Key.One, m1);
		map.put(Key.Two, m2);
		map.put(Key.Three, m3);
		// Traversing EnumMap
		for (Map.Entry entry : map.entrySet()) {
			Magzine m = entry.getValue();
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


21 The Sun Sy Sunfranchy The Sun Company 8
22 Glimmer Trains Unknown Glimmer Train Press 4
23 Crazy horse Brett Lot College of Charleston 6

Java: Map Interface Methods and Examples


In the collection framework, a map contains values on the basis of key and value pairs. This pair is known as an entry.

Points to Remember

  • Map contains unique keys.
  • Map allows duplicate values.
  • Map is useful to search, update or delete elements on the basis of a key.
  • Map is the root interface in the Map hierarchy for Collection Framework.
  • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
  • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
  • Map can’t be traversed, for transversing needs to convert into the set using method keySet() or entrySet().

See Also:

Methods of Map Interface

Method Description
put(Object key, Object value) This method used to insert an entry on the map.
void putAll(Map map) This method inserts the specified map in the map.
V putIfAbsent(K key, V value) This method inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) This method used to delete an entry for the specified key.
boolean remove(Object key, Object value) This method removes the specified values with the associated specified keys from the map.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry> entrySet() It returns the Set view containing all the keys and values.
void clear() It is used to reset the map.
V compute(K key, BiFunction remappingFunction) This method computes a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) This method computes its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) This method computes a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value)  if some value equal to the value exists within the map then return true, else return false.
boolean containsKey(Object key) if some key equal to the key exists within the map return true, else return false.
boolean equals(Object o) It is used to compare the specified Object values with the Map.
void forEach(BiConsumer action) Mentioned action will perform for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key) Returns the object that contains the value with respect to the key.
V getOrDefault(Object key, V defaultValue) Returns the value with respect to key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
boolean isEmpty() Check if the map not having any element Returns true if the map is empty or false.
V merge(K key, V value, BiFunction remappingFunction) If the given key is not mapped with a value or with null, associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to the key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value with respect to the key.
void replaceAll(BiFunction function) It replaces each entry’s value with the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() Returns the number of elements in the map.

Map.Entry Interface

Entry is the subinterface of Map. So we will be accessed by Map.Entry name. It returns a collection-view of the map, whose elements are of this class. It provides methods to get key and value.

Methods of Map.Entry interface

Method Description
K getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
V setValue(V value) It is used to replace the value corresponding to this entry with the specified value.
boolean equals(Object o) It is used to compare the specified object with the other existing objects.
static ,V> Comparator<Map.Entry> comparingByKey() It returns a comparator that compare the objects in natural order on key.
static Comparator<Map.Entry> comparingByKey(Comparator cmp) It returns a comparator that compare the objects by key using the given Comparator.
static <K,V extends Comparable> Comparator<Map.Entry> comparingByValue() It returns a comparator that compare the objects in natural order on value.
static Comparator<Map.Entry> comparingByValue(Comparator cmp) It returns a comparator that compare the objects by value using the given Comparator.

Map Example: Legacy Style without Generics

import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
    Map map=new HashMap();
    //Adding elements to map
    map.put(1,"Anuj");
    map.put(5,"Raghav");
    map.put(2,"Jitendra");
    map.put(3,"Anuj");
    //Traversing Map Entry
	//Converting to Set so that we can traverse
    Set set=map.entrySet();
    Iterator itr=set.iterator();
    while(itr.hasNext()){
        //Type cast to Map.Entry so that we can get key and value separately
        Map.Entry entry=(Map.Entry)itr.next();
        System.out.println(entry.getKey()+" "+entry.getValue());
    }
}
}

Output :


1 Anuj
2 Jitendra
5 Raghav
3 Anuj

Map Example: With Generics

import java.util.*;
class MapExample2{
 public static void main(String args[]){
  Map map=new HashMap();
  map.put(20,"Anuj");
  map.put(21,"Virendra");
  map.put(22,"Raghav");
  //Elements can traverse in any order
  for(Map.Entry m:map.entrySet()){
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}

Output :


22 Raghav
20 Anuj
21 Virendra

Map Example: comparingByKey() in ascending and descending order

import java.util.*;
class MapExample3{
 public static void main(String args[]){
Map map=new HashMap();
      map.put(20,"Anuj");
      map.put(21,"Virendra");
      map.put(22,"Raghav"); 

	  //ascending order
      //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByKey())
      //Performs an action for each element of this stream
      .forEach(System.out::println);  

	  //descending oder
	  //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
      //Performs an action for each element of this stream
      .forEach(System.out::println);
 }
}

Output :


20=Anuj
21=Virendra
22=Raghav

Map Example: comparingByValue() in ascending and descending Order

import java.uti
class MapExample5{
 public static void main(String args[]){
Map map=new HashMap();
      map.put(20,"Anuj");
      map.put(21,"Virendra");
      map.put(22,"Raghav");  

	  //ascending order 

      //Returns a Set view of the mappings contained in this map
      map.entrySet()
      //Returns a sequential Stream with this collection as its source
      .stream()
      //Sorted according to the provided Comparator
      .sorted(Map.Entry.comparingByValue())
      //Performs an action for each element of this stream
      .forEach(System.out::println);  

	  //descending order

	  //Returns a Set view of the mappings contained in this map
     map.entrySet()
     //Returns a sequential Stream with this collection as its source
     .stream()
     //Sorted according to the provided Comparator
     .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
     //Performs an action for each element of this stream
     .forEach(System.out::println);
 }
}

Output :


20=Anuj
22=Raghav
21=Virendra

21=Virendra
22=Raghav
20=Anuj

Java: TreeMap Class Methods and Examples


Java.util.TreeMap implements SortedMap interface and provides an efficient way to storing key-value pairs in sorted order. TreeMap implements the NavigableMap interface and extends AbstractMap class.

Points to Remember

  • TreeMap uses data structure as a red-black tree.
  • TreeMap contains values based on the key.
  • TreeMap contains only unique elements.
  • TreeMap cannot have a null key but can have multiple null values.
  • TreeMap is not synchronized.
  • TreeMap maintains an ascending order.

TreeMap Declaration

public class TreeMap extends AbstractMap implements NavigableMap, Serializable,Cloneable
  • K: Represent as key in Map
  • V: Represent as value with respect to K.

See Also:

What is the difference between HashMap and TreeMap?

HashMap TreeMap
HashMap can contain one null key. TreeMap cannot contain any null key.
HashMap maintains no order. TreeMap maintains an ascending order.

Constructors of TreeMap

Constructor Description
TreeMap() This constructor uses to create an empty treemap that will be sorted using the natural order of its key.
TreeMap(Comparator comparator) This constructor uses to an empty tree-based map that will be sorted using the comparator comp.
TreeMap(Map m) It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap m) This constructor uses to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.

Methods of TreeMap

Method Description
Map.Entry ceilingEntry(K key) It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key or null if there is no such key.
void clear() It removes all the key-value pairs from a map.
Object clone() It returns a shallow copy of TreeMap instance.
Comparator comparator() It returns the comparator that arranges the key in order, or null if the map uses the natural ordering.
NavigableSet descendingKeySet() This method returns a reverse order NavigableSet view of the keys contained in the map.
NavigableMap descendingMap() It returns the specified key-value pairs in descending order.
Map.Entry firstEntry() It returns the key-value pair having the least key.
Map.Entry floorEntry(K key) It returns the greatest key, less than or equal to the specified key, or null if there is no such key.
void forEach(BiConsumer action) It performs the mention action for each entry in the map until all entries processed or the action throws an exception.
SortedMap headMap(K toKey) It returns the key-value pairs whose keys are strictly less than toKey.
NavigableMap headMap(K toKey, boolean inclusive) It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey.
Map.Entry higherEntry(K key) It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key) It is used to return true if map contains a mapping for the specified key.
Set keySet() It returns the set of keys exist in the map.
Map.Entry lastEntry() It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry lowerEntry(K key) It returns a key and value mapping associated with the greatest key less than the given key or null if there is no such key.
K lowerKey(K key) It returns from map  the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet navigableKeySet() It returns a NavigableSet view of the keys contains in this map.
Map.Entry pollFirstEntry() It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry pollLastEntry() It removes and returns a key and value mapping associated with the greatest key in this map, or null if the map is empty.
V put(K key, V value) It inserts the specified value with respect to key in the map.
void putAll(Map map) It is used to copy all the key-value pair from one map to another map.
V replace(K key, V value) It replaces the value with respect to key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value with respect to key.
void replaceAll(BiFunction function) It replaces each entry’s value with the result of invoking the mentioned function on all entries have been processed or the function throw an exception.
NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) It returns key and value pairs whose keys match with in range fromKey to toKey.
SortedMap subMap(K fromKey, K toKey) It returns key and value pairs whose keys range match fromKey, inclusive, to toKey, exclusive.
SortedMap tailMap(K fromKey) It returns key and value pairs whose keys are greater than or equal to fromKey.
NavigableMap tailMap(K fromKey, boolean inclusive) It returns key and value pairs whose keys are greater than (o equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping with respect to  key.
boolean containsValue(Object value) It returns true if the map find one or more keys to the specified value.
K firstKey() It is used to return the first find lowest key currently in this sorted map.
V get(Object key) It is used to return the value to which the map maps the specified key.
K lastKey() It is used to return the last highest key currently in the sorted map.
V remove(Object key) It removes the key and value pair of the specified key from the map.
Set entrySet() It returns a set of the mappings contained in the map.
int size() It returns the number of key-value pairs that exists in the hashtable.
Collection values() It returns a collection  of values contained in the map.

TreeMap Example : insert and traverse elements

import java.util.Map;
import java.util.TreeMap;

class TreeMapExample1{
	 public static void main(String args[]){
	   TreeMap&lt;Integer,String&gt; map=new TreeMap&lt;Integer,String&gt;();
	      map.put(20,"Anuj");
	      map.put(22,"Ravi");
	      map.put(21,"Virendra");
	      map.put(23,"Raghav");    

	      for(Map.Entry m:map.entrySet()){
	       System.out.println(m.getKey()+" "+m.getValue());
	      }
	 }
	}

Output :


20 Anuj
21 Virendra
22 Ravi
23 Raghav

TreeMap Example : remove() elements

import java.util.*;

public class TreeMapExample2 {
	public static void main(String args[]) {
		TreeMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("\nBefore invoking remove() method");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		map.remove(22);
		System.out.println("\nAfter invoking remove() method");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :



Before invoking remove() method
20 Anuj
21 Virendra
22 Ravi
23 Raghav

After invoking remove() method
20 Anuj
21 Virendra
23 Raghav

Treemap Example : with NavigableMap

import java.util.*;
import java.util.NavigableMap;
import java.util.TreeMap;

class TreeMapExample3 {
	public static void main(String args[]) {
		NavigableMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");

		// Maintains descending order
		System.out.println("\ndescendingMap: " + map.descendingMap());
		// Returns key-value pairs whose keys are less than or equal to the
		// specified key.
		System.out.println("\nheadMap: " + map.headMap(22, true));
		// Returns key-value pairs whose keys are greater than or equal to the
		// specified key.
		System.out.println("\ntailMap: " + map.tailMap(22, true));
		// Returns key-value pairs exists in between the specified key.
		System.out.println("\nsubMap: " + map.subMap(20, false, 22, true));
	}
}

Output :


descendingMap: {23=Raghav, 22=Ravi, 21=Virendra, 20=Anuj}

headMap: {20=Anuj, 21=Virendra, 22=Ravi}

tailMap: {22=Ravi, 23=Raghav}

subMap: {21=Virendra, 22=Ravi}

TreeMap Example : SortedMap()

import java.util.*;
import java.util.SortedMap;
import java.util.TreeMap;

class TreeMapExample4 {
	public static void main(String args[]) {
		SortedMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Returns key-value pairs whose keys are less than the specified key.
		System.out.println("\nheadMap: " + map.headMap(22));
		// Returns key-value pairs whose keys are greater than or equal to the
		// specified key.
		System.out.println("\ntailMap: " + map.tailMap(22));
		// Returns key-value pairs exists in between the specified key.
		System.out.println("\nsubMap: " + map.subMap(20, 22));
	}
}

Output :


headMap: {20=Anuj, 21=Virendra}

tailMap: {22=Ravi, 23=Raghav}

subMap: {20=Anuj, 21=Virendra}

TreeMap Example : with objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}
import java.util.Map;
import java.util.TreeMap;

public class HashtableExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map&lt;Integer, Magzine&gt; table = new TreeMap&lt;Integer, Magzine&gt;();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		table.put(1, m1);
		table.put(2, m2);
		table.put(3, m3);
		// Traversing map
		for (Map.Entry&lt;Integer, Magzine&gt; entry : table.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

 

Java: Collections Utility Class Methods and Examples


java.util.Collections class inherits Object class. The Collections utility class is used exclusively with static methods that operate on or return collections.

Points to remember

  • Collections class supports the polymorphic to operate on collections.
  • Collections class throws a NullPointerException if passing objects are null.

See Also:

Collections Declaration

public class Collections extends Object 

Collections Utility Class Methods

Method Descriptions
static boolean addAll() It is used to adds all of the specified element to the specified collection.
static Queue asLifoQueue() It returns a view of a Deque as a Last-in-first-out (LIFO) Queue.
static int binarySearch() It searches the list for the specified object and returns its position in a sorted list.
static Collection checkedCollection() It is used to returns a dynamically typesafe view of the specified collection.
static List checkedList() It is used to returns a dynamically typesafe view of the specified list.
static Map checkedMap() It is used to returns a dynamically typesafe view of the specified map.
static NavigableMap checkedNavigableMap() It is used to returns a dynamically typesafe view of the specified navigable map.
static NavigableSet checkedNavigableSet() It is used to returns a dynamically typesafe view of the specified navigable set.
static Queue checkedQueue() It is used to returns a dynamically typesafe view of the specified queue.
static Set checkedSet() It is used to returns a dynamically typesafe view of the specified set.
static SortedMap checkedSortedMap() It is used to returns a dynamically typesafe view of the specified sorted map.
static SortedSet checkedSortedSet() It is used to returns a dynamically typesafe view of the specified sorted set.
static void copy() It is used to copy all the elements from one list into another list.
static boolean disjoint() It returns true if the two specified collections have no elements in common.
static Enumeration emptyEnumeration() It is used to get an enumeration that has no elements.
static Iterator emptyIterator() It is used to get an Iterator that has no elements.
static List emptyList() It is used to get a List that has no elements.
static ListIterator emptyListIterator() It is used to get a List Iterator that has no elements.
static Map emptyMap() It returns an empty map that is immutable.
static NavigableMap emptyNavigableMap() It returns an empty navigable map that is immutable.
static NavigableSet emptyNavigableSet() It is used to get an empty navigable set which is immutable in nature.
static Set emptySet() It is used to get the set that has no elements.
static SortedMap emptySortedMap() It returns an empty sorted map which is immutable.
static SortedSet emptySortedSet() It is used to get the sorted set that has no elements.
static Enumeration enumeration() It is used to get the enumeration over the specified collection.
static void fill() It is used to replace all of the elements of the specified list with the specified elements.
static int frequency() It is used to get the number of elements in the specified collection equal to the specified object.
static int indexOfSubList() It is used to get the starting position of the first occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list.
static int lastIndexOfSubList() It is used to get the starting position of the last occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list.
static ArrayList list() It is used to get an array list containing the elements returned by the specified enumeration in the order in which they are returned by the enumeration.
static > T max() It is used to get the maximum value of the given collection, according to the natural ordering of its elements.
static > T min() It is used to get the minimum value of the given collection, according to the natural ordering of its elements.
static List nCopies() It is used to get an immutable list consisting of n copies of the specified object.
static Set newSetFromMap() It is used to return a set backed by the specified map.
static boolean replaceAll() It is used to replace all occurrences of one specified value in a list with the other specified value.
static void reverse() It is used to reverse the order of the elements in the specified list.
static Comparator reverseOrder() It is used to get the comparator that imposes the reverse of the natural ordering on a collection of objects which internally implement the Comparable interface.
static void rotate() It is used to rotate the elements in the specified list by a given distance.
static void shuffle() It is used to randomly reorders the specified list elements using default randomness.
static Set singleton() It is used to get an immutable set that contains only the specified object.
static List singletonList() It is used to get an immutable list that contains only the specified object.
static Map singletonMap() Use to get an immutable map, mapping only the specified key to the specified value.
static >void sort() It is used to sort the elements present in the specified list of the collection in ascending order.
static void swap() It is used to swap the elements at the specified positions in the specified list.
static Collection synchronizedCollection() It is used to get a synchronized (thread-safe) collection backed by the specified collection.
static List synchronizedList() It is used to get a synchronized (thread-safe) collection backed by the specified list.
static Map synchronizedMap() It is used to get a synchronized (thread-safe) map backed by the specified map.
static NavigableMap synchronizedNavigableMap() It is used to get a synchronized (thread-safe) navigable map backed by the specified navigable map.
static NavigableSet synchronizedNavigableSet() It is used to get a synchronized (thread-safe) navigable set backed by the specified navigable set.
static Set synchronizedSet() It is used to get a synchronized (thread-safe) set backed by the specified set.
static SortedMap synchronizedSortedMap() It is used to get a synchronized (thread-safe) sorted map backed by the specified sorted map.
static SortedSet synchronizedSortedSet() It is used to get a synchronized (thread-safe) sorted set backed by the specified sorted set.
static Collection unmodifiableCollection() It is used to get an unmodifiable view of the specified collection.
static List unmodifiableList() It is used to get an unmodifiable view of the specified list.
static Map unmodifiableMap() It is used to get an unmodifiable view of the specified map.
static NavigableMap unmodifiableNavigableMap() It is used to get an unmodifiable view of the specified navigable map.
static NavigableSet unmodifiableNavigableSet() It is used to get an unmodifiable view of the specified navigable set.
static Set unmodifiableSet() It is used to get an unmodifiable view of the specified set.
static SortedMap unmodifiableSortedMap() It is used to get an unmodifiable view of the specified sorted map.
static SortedSet unmodifiableSortedSet() It is used to get an unmodifiable view of the specified sorted set.

See Also:

Collections Example : Add elements in list

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

public class CollectionsExample1 {

	public static void main(String[] args) {
		 List list = new ArrayList();
	        list.add("C");
	        list.add("C++");
	        list.add("Python");
	        list.add("Lisp");
	        list.add("Java Script");
	        System.out.println("Initial collection value:"+list);
	        //add some more element in collection
	        Collections.addAll(list, "Servlet","JSP");
	        System.out.println("After adding elements collection value:"+list);
	        String[] strArr = {"C#", "Closure",".Net"};
	        //add some more elements
	        Collections.addAll(list, strArr);
	        System.out.println("After adding array collection value:"+list);
	}

}

Output :


Initial collection value:[C, C++, Python, Lisp, Java Script]
After adding elements collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP]
After adding array collection value:[C, C++, Python, Lisp, Java Script, Servlet, JSP, C#, Closure, .Net]

Collections Example :max()

import java.util.*;

public class CollectionsExample2 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Max element from the collection: " + Collections.max(list));
	}
}

Output :


Max element from the collection: 90

Output:

Collections Example :min()

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

public class CollectionsExample3 {
	public static void main(String a[]) {
		List list = new ArrayList();
		list.add(15);
		list.add(50);
		list.add(3);
		list.add(90);
		list.add(2);
		list.add(16);
		System.out.println("Min element from the collection: " + Collections.min(list));
	}
}

Output :


Min element from the collection: 2

Java: LinkedHashMap Class Methods and Examples


LinkedHashMap class extends the HashMap class and implements Map Interface to store values in key and value pairs.

Points to Remember

  • LinkedHashMap class is in java.util package.
  • LinkedHashMap uses data structure Hashtable and LinkedList implementation of the Map interface.
  • LinkedHashMap contains values based on the key.
  • LinkedHashMap contains unique elements.
  • LinkedHashMap class may have one null key and multiple null values.
  • LinkedHashMap is not synchronized.
  • LinkedHashMap maintains the insertion order.
  • LinkedHashMap initial default capacity is 16 with a load factor of 0.75.

LinkedHashMap Declaration


public class LinkedHashMap extends HashMap implements Map  
  • K: Here K represent Key of Map
  • V: Here V represents value in the Map with respect to K.

Constructors of LinkedHashMap class

Constructor Description
LinkedHashMap() This is the default LinkedHashMap constructor.
LinkedHashMap(int capacity)  Use to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float loadFactor) Use to initialize both the capacity and the load factor.
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) Use to initialize both the capacity and the load factor with specified ordering mode.
LinkedHashMap(Map m) Use to initialize the LinkedHashMap with the elements from the given Map class m.

Methods of LinkedHashMap class

Method Description
V get(Object key) It returns the value object map to the specified key.
void clear() It removes all the key-value pairs from a map.
boolean containsValue(Object value) It returns true if one or more keys to the specified value.
Set<Map.Entry> entrySet() It returns a Set view of the mappings contained in the map.
void forEach(BiConsumer action) It performs the given action on each entry in the map until all entries have been processed or any action throws an exception.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key.
Set keySet() It returns a Set view of the keys contained in the map
protected boolean removeEldestEntry(Map.Entry eldest) It returns true on removing its eldest entry.
void replaceAll(BiFunction function) It replaces each entry’s value in map with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a Collection view of the values contained in this map.

LinkedHashMap Example : insert items and traverse

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample4 {

	public static void main(String args[]) {

		Map hm = new LinkedHashMap();

		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");

		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}

}

Output :


20 Anuj
21 Virendra
22 Raghav

LinkedHashMap Example : Key-Value pair

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample1 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(21, "Virendra");
		map.put(22, "Raghav");
		// Fetching key from LinkedHashMap
		System.out.println("Keys: " + map.keySet());
		// Fetching value from LinkedHashMap
		System.out.println("Values: " + map.values());
		// Fetching key-value pair from LinkedHashMap
		System.out.println("Key-Value pairs: " + map.entrySet());
	}

}

Output :


Keys: [20, 21, 22]
Values: [Anuj, Virendra, Raghav]
Key-Value pairs: [20=Anuj, 21=Virendra, 22=Raghav]

LinkedHashMap Example : remove()

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample2 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("Before remove: " + map);
		// Remove value for key 22
		map.remove(22);
		System.out.println("After remove: " + map);
	}

}

Output :


Before remove: {20=Anuj, 22=Ravi, 21=Virendra, 23=Raghav}
After remove: {20=Anuj, 21=Virendra, 23=Raghav}

LinkedHashMap Example : getOrDefault()

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample3 {

	public static void main(String args[]) {
		Map map = new LinkedHashMap();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Here it will retrieve values for key 21 and 25
		// if values not find out in HashTable then return default value
		System.out.println(map.getOrDefault(21, "Not Found"));
		System.out.println(map.getOrDefault(25, "Not Found"));
	}
}

Output :


Virendra
Not Found

LinkedHashMap Example : with objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}
public class LinkedHashMapExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map map = new LinkedHashMap();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		map.put(1, m1);
		map.put(2, m2);
		map.put(3, m3);
		// Traversing map
		for (Map.Entry entry : map.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

Java: HashTable Class Methods and Examples


The hashtable class implements a Map interface and extends Dictionary Class to store key and values as pairs.

Hashtable is an array of the list where each list is known as a bucket of the node (key and value pair). The position of the node is identified by calling the hashcode() method on key.

Points to remember

  • Hashtable class is in java.util package.
  • Hashtable contains unique elements.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is synchronized.
  • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

See Also:

Hashtable class declaration

Let’s see the declaration for java.util.Hashtable class.


public class Hashtable extends Dictionary implements Map, Cloneable, Serializable  
  • K: Represent as key in Map
  • V: Represent as value with respect to K.

Constructors of java.util.Hashtable class

Constructor Description
Hashtable() It creates an empty hashtable having the initial default capacity and load factor.
Hashtable(int capacity) It accepts an integer parameter and creates a hash table that contains a specified initial capacity.
Hashtable(int capacity, float loadFactor) It is used to create a hash table having the specified initial capacity and loadFactor.
Hashtable(Map t) It creates a new hash table with the same mappings as the given Map.

Methods of java.util.Hashtable class

Method Description
void clear() Use to reset the hash table.
Object clone() It returns a shallow copy of the Hashtable.
V compute(K key, BiFunction remappingFunction) It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
Enumeration elements() It returns an enumeration of the values in the hash table.
Set<Map.Entry> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) It performs the action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue) This method returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
Enumeration keys() This method returns an enumeration of the keys in the hashtable.
Set keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not found in hashTable then associates it with the given non-null value.
V put(K key, V value) It inserts the specified value with the specified key in the hash table.
void putAll(Map t)) It is used to copy all the key-value pairs from the map to the hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is mapped to null) in Hashtable then insert key and value.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the hashtable.
V replace(K key, V value) This method replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) This method replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) This method replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
String toString() It returns a string representation of the Hashtable object.
Collection values() It returns a collection view of the values contained in the map.
boolean contains(Object value) This method returns true if some value equal to the value exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the value exists within the hash table, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key exists within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty; returns false if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table and rehashes all of its keys.
V get(Object key) This method returns the object value associated with the key.
V remove(Object key) It is used to remove the key and its value. This method returns the value associated with the key.
int size() This method returns the number of entries in the hash table.

HashTable Example : add() key and value

import java.util.*;

public class HashTableExample1 {

	public static void main(String args[]) {
		Hashtable hm = new Hashtable();

		//add values in hash table
		hm.put(20, "Anuj");
		hm.put(22, "Ravi");
		hm.put(21, "Virendra");
		hm.put(23, "Raghav");

		//print all values from HashTable
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


21 Virendra
20 Anuj
23 Raghav
22 Ravi

HashTable Example : remove()

import java.util.Hashtable;

public class HashTableExample2 {

	public static void main(String args[]) {
		Hashtable map = new Hashtable();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("Before remove: " + map);
		// Remove value for key 22
		map.remove(22);
		System.out.println("After remove: " + map);
	}

}

Output :


Before remove: {21=Virendra, 20=Anuj, 23=Raghav, 22=Ravi}
After remove: {21=Virendra, 20=Anuj, 23=Raghav}

Hashtable Example : getOrDefault()

import java.util.Hashtable;

public class HashTableExample3 {

	public static void main(String args[]) {
		Hashtable map = new Hashtable();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Here it will retrieve values for key 21 and 25
		// if values not find out in HashTable then return default value
		System.out.println(map.getOrDefault(21, "Not Found"));
		System.out.println(map.getOrDefault(25, "Not Found"));
	}
}

Output :


Virendra
Not Found

Hashtable Example : putAbsent()

import java.util.*;
class HashtableExample4{
 public static void main(String args[]){
   Hashtable map=new Hashtable();
     map.put(20,"Anuj");
     map.put(22,"Ravi");
     map.put(21,"Virendra");
     map.put(23,"Raghav");
     System.out.println("Initial Map: "+map);
     //insert value in hashtable only when not exist
     map.putIfAbsent(24,"Gaurav");
     System.out.println("Updated Map: "+map);
     //insert value in hashtable only when not exist
     map.putIfAbsent(21,"Virendra");
     System.out.println("Updated Map: "+map);
 }
}

Output :


Initial Map: {21=Virendra, 20=Anuj, 23=Raghav, 22=Ravi}
Updated Map: {21=Virendra, 20=Anuj, 24=Gaurav, 23=Raghav, 22=Ravi}
Updated Map: {21=Virendra, 20=Anuj, 24=Gaurav, 23=Raghav, 22=Ravi}

Hashtable Example : with Objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}    

public class HashtableExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map table = new Hashtable();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		table.put(1, m1);
		table.put(2, m2);
		table.put(3, m3);
		// Traversing map
		for (Map.Entry entry : table.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Java: Hashmap Working


What is Hashing?

Hashing is technique of converting an object into an integer value. For example hashcode() method always return int value. We can also override hashcode() method and implement own logic to get hashcode value.

Note : The integer value helps in indexing and faster searches.

What is HashMap

HashMap is a one type of collection in Java collection framework to store values in key and value pair. HashMap uses hashing technique for storing values. HashMap uses internal data structure as array and LinkedList for storing key and values. HashMap contains an array of nodes, and node presented by a class with respect to key.

See Also : Java: HashMap Class Methods and Examples

Contract between equals() and hashcode() method

Before discussing internal working of HashMap, need to understand hashCode() and equals() method contract in detail.

  • equals(): it’s Object class method to check the equality of two objects by comparing key, whether they are equal or not. It can be overridden.
  • hashCode(): it’s also object class methods which return memory reference of object in integer form. This value received from the hashcode() method is used as the bucket number or address of element inside Map. Hashcode value of null Key is 0.

If you override the equals() method, then it is mandatory to override the hashCod() method.

See Also: Java : java.lang.Object Class & Methods

Buckets: is an Array of the node, where each node has a data structure like a LinkedList. More than one node can use same bucket and may be different in capacity.

Working of HashMap

Insert Key, Value pair in HashMap

We use put() method to insert the Key and Value pair in the HashMap. The default capacity of HashMap is 16 (0 to 15).

Example: In the following example, we want to insert six (Key, Value) pair in the HashMap.

HashMap map = new HashMap();
map.put("Ankur", 35);
map.put("Saurabh", 36);
map.put("Gaurav", 32);
map.put("Raghav", 29);
map.put("Rajendra", 40);
map.put("Shailesh", 33);

When we call the put() method, then it calculates the hash code of the Key i.e “Ankur” hashcode is 63412443. Now to store the Key and value pair in memory, we have to calculate the index based on below formulae.

HashMap Representataion.jpg

Calculating Index Formulae:


Index = hashcode(Key) & (n-1)  
Where n is the size of the array.

Hence the index value for Ankur and others are as below:
Calculate Index for “Ankur”
Index = 63412443& (16-1) = 11
Calculate Index for “Saurabh”
Index = -758033668& (16-1) = 12
Calculate Index for “Gaurav”
Index = 2125849484& (16-1) = 12
Calculate Index for “Raghav”
Index = -1854623835& (16-1) = 5
Calculate Index for “Rajendra”
Index = 201412911& (16-1) = 15
Calculate Index for “Shailesh”
Index = -687212437& (16-1) = 11

The key “Ankur” calculated index value is 11. This key and value pair store in one of the node of HashMap.

Hash Collision

Hash Collisions occured when two or more keys are calculating index as same value.

From above calculated index value, keys “Ankur and “Shailesh” both index value is 11 having hash collision. Similarly for “Saurabh” and “Gaurav” having index value 12. In this case, equals() method compare both Keys are equal or not. If Keys are equal, replace the value with the current value. Otherwise, linked this node object (key and value pair) to the existing node object through the LinkedList.

Similarly, we will store the other keys with respect to below index positions.

HashMap get() method to retrieve values

HashMap get(Key) method is used to retrieve value by Key. This method calculate index position based on key hashcode value and capacity of hashmap and fetch result. If no matching key find out will return result as value null.

Suppose we have to fetch the Key “Ankur.” The following method will be called.


map.get(new Key("Ankur"));

It generates the hash code as 63412443. Now calculate the index value of 63412443 by using index formula. The index value will be 11. get() method search for the index value 11. It compares the given key value sequentially in bucket with respect to index position 11. If any equal key find out in bucket will return value object with respect to that key otherwise finally return null if not no match find out.

Let’s fetch another Key “Raghav.” The hash code of the Key “Raghav” is -1854623835. The calculated index value of -1854623835 is 5. Go to index 5 of the array and compare the first element’s Key with the given Key “Raghav”. It return the value object for match key.

Java: HashMap Class Methods and Examples


java.util.HashMap class inherits AbstractMap class and implements the Map interface. HashMap values store on the basis of key and value pair where each pair is known as an Entry.

  • K: It’s the type of Key in HashMap
  • V: It’s a type of value with respect to Key.

HashMap Class Declaration


public class HashMap extends implements Map, Cloneable, Serializable  

See Also:

Points to Remember:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

HashMap Representataion

Difference between HashSet and HashMap

HashSet Class contains only values whereas HashMap Class contains an entry (key and value pair).

HashMap Class Constructors

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map m) It is used to initialize the hash map by using the elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float loadFactor) It is used to initialize both the capacity and load factor of the hash map by using its arguments.

HashMap Class Methods

Method Description
void clear() Use to remove all of the mappings from this map.
boolean isEmpty() Use to return true if this map contains no key-value mappings.
Object clone() Use to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet() Use to return a collection view of the mappings contained in this map.
Set keySet() Use to return a set view of the keys contained in this map.
V put(Object key, Object value) Use to insert an entry in the map.
void putAll(Map map) Use to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value in the map only when  specified key is not already specified.
V remove(Object key) Use to delete an entry for the specified key.
boolean remove(Object key, Object value) removes the  values with the associated specified keys from the map.
V compute(K key, BiFunction remappingFunction) Use to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) Use to compute its value using the given mapping function, if the specified key is not mapped with a value or null, and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) Use to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value) It returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) It returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) Added in Java 8 to  performs the given action for each entry in the map  or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated with respect to key.
V getOrDefault(Object key, V defaultValue) Added in Java 8. It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty() It returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null then associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to specified key.
boolean replace(K key, V oldValue, V newValue) Replaces the old value with the new value with respect to specified key.
void replaceAll(BiFunction function) It replaces each entry’s value with entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() It returns the count of number of entries in the map.

Example: add elements

Here, you will learn different ways to insert elements.

import java.util.*;

class HashMapExample1 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		System.out.println("Initial hash map elements: " + hm );
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");

		System.out.println("\nAfter invoking put() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}

		hm.putIfAbsent(23, "Gaurav");
		System.out.println("\nAfter invoking putIfAbsent() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		HashMap map = new HashMap();
		map.put(24, "Ravi");
		map.putAll(hm);
		System.out.println("\nAfter invoking putAll() method ");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements: {}

After invoking put() method
20 Anuj
21 Virendra
22 Raghav

After invoking putIfAbsent() method
20 Anuj
21 Virendra
22 Raghav
23 Gaurav

After invoking putAll() method 
20 Anuj
21 Virendra
22 Raghav
23 Gaurav
24 Ravi

HashMap Example : remove()

Here you will see different ways to remove elements from HashMap

import java.util.*;
import java.util.HashMap;

public class HashMapExample2 {
	public static void main(String args[]) {
		HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(20, "Anuj");
		map.put(21, "Virendra");
		map.put(22, "Raghav");
		map.put(23, "Gaurav");
		System.out.println("Initial hash map elements: " + map);
		// key-based removal
		map.remove(20);
		System.out.println("\nUpdated hash map  elements: " + map);
		// value-based removal
		map.remove(21);
		System.out.println("\nUpdated hash map  elements: " + map);
		// key-value pair based removal
		map.remove(22, "Raghav");
		System.out.println("\nUpdated hash map  elements: " + map);
	}
}

Output :


Initial hash map elements: {20=Anuj, 21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {22=Raghav, 23=Gaurav}

Updated hash map  elements: {23=Gaurav}

HashMap Example : replace()

Here you will see different ways to replace() elements in HashMap

import java.util.*;

class HashMapExample3 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");
		System.out.println("Initial hash map elements:");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(22, "Gaurav");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(21, "Virendra", "Ravi");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replaceAll((k, v) -> "Anuj");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements:
20 Anuj
21 Virendra
22 Raghav

Updated hash map elements:
20 Anuj
21 Virendra
22 Gaurav

Updated hash map elements:
20 Anuj
21 Ravi
22 Gaurav

Updated hash map elements:
20 Anuj
21 Anuj
22 Anuj

HashMap Example: Objects handling

import java.util.*;
public class Magzine {
	int id;
	String name,author,publisher;
	int quantity;
	public Magzine(int id, String name, String author, String publisher, int quantity) {
	    this.id = id;
	    this.name = name;
	    this.author = author;
	    this.publisher = publisher;
	    this.quantity = quantity;
	}    

}
public class MapExample {
import java.util.HashMap;
import java.util.Map;

public class HashMapWithObjectsExample {

	public static void main(String[] args) {
	    //Creating map of Magzines
	    Map<Integer,Magzine> map=new HashMap<Integer,Magzine>();
	    //Creating Books
	    Magzine m1=new Magzine(21,"The Sun","Sy Sunfranchy","The Sun Company",8);
	    Magzine m2=new Magzine(22,"Glimmer Trains","Unknown","Glimmer Train Press",4);
	    Magzine m3=new Magzine(23,"Crazy horse","Brett Lot","College of Charleston",6);
	    //Adding Magzines to map
	    map.put(1,m1);
	    map.put(2,m2);
	    map.put(3,m3);  

	    //Traversing map
	    for(Map.Entry<Integer,Magzine> entry:map.entrySet()){
	        int key=entry.getKey();
	        Magzine m=entry.getValue();
	        System.out.println("\nMagzine "+key+" Details:");
	        System.out.println(m.id+" "+m.name+" "+m.author+" "+m.publisher+" "+m.quantity);
	    }
	}
}

Output :



Magzine 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Magzine 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Magzine 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

References

Java: Difference between HashMap and Hashtable


HashMap and Hashtable both implements Map interface and used to store data in key and value pairs. Both use hashing techniques to get unique keys.

Apart from some similarities, there are many differences between HashMap and Hashtable classes as follows:

java.util.HashMap java.util.HashTable
HashMap class introduced in JDK 1.2. Hashtable is a legacy class.
HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
HashMap is traversed by Iterator. Hashtable is traversed by the Enumerator and Iterator.
Hashmap, Iterator is fail-fast. Hashtable, Enumerator is not fail-fast.
HashMap is not synchronized and not-thread safe. Hashtable is synchronized and thread safe.
HashMap can be synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can’t be unsynchronized.
HashMap class allows only one null key and multiple null values. Hashtable doesn’t allow any null key or value.
HashMap is fast. Hashtable is slow.

For more detail:

 

Java: Unmodifiable Collection Methods and Example


In Collection Framework, to make collection type object as unmodifiable java.Util.Collections class provides static methods to make these object as unmodifiable.

Collections Class Unmodifiable Methods

static Collection
unmodifiableCollection(Collection<? extends T> c)
Returns an unmodifiable view of the specified collection.
static List
unmodifiableList(List<? extends T> list)
Returns an unmodifiable view of the specified list.
static <K,V> Map<K,V>
unmodifiableMap(Map<? extends K,? extends V> m)
Returns an unmodifiable view of the specified map.
static <K,V> NavigableMap<K,V>
unmodifiableNavigableMap(NavigableMap<K,? extends V> m)
Returns an unmodifiable view of the given map.
static NavigableSet
unmodifiableNavigableSet(NavigableSet s)
Returns an unmodifiable view of the given navigable set.
static Set
unmodifiableSet(Set<? extends T> s)
Returns an unmodifiable view of the given set.
static <K,V> SortedMap<K,V>
unmodifiableSortedMap(SortedMap<K,? extends V> m)
Returns an unmodifiable view of the given map.
static SortedSet
unmodifiableSortedSet(SortedSet s)
Returns an unmodifiable view of the given  set.

Example: Synchronized Collections

In this example creating the blank type of collection and making it Unmodified. You can assign the same with collection objects.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;

public class CollectionUnmodifiedExample {

	public static void main(String[] args) {
		Collection c = new ArrayList();
	    Collections.unmodifiableCollection(c);
	    Collections.unmodifiableList(new ArrayList());
	    Collections.unmodifiableMap(new HashMap());
	    Collections.unmodifiableSet(new HashSet());
	}

}

References

Java: Synchronized Collection Methods and Examples


In Collection Framework, only some of the classes are thread-safe or synchronized. If you need to work on a multi-threaded environment then you have to convert these non-synchronized type classes to Synchronized type collection.

Synchronized Collection

These are the classes only are synchronized:

  • Vector
  • HashTable

As a solution java.util.Collections class provides some static methods to make them Synchronized.

Collections Class Synchronized Methods

All these methods are static:

Collection synchronizedCollection(Collection c) Returns a synchronized collection.
List synchronizedList(List list) Returns a synchronized list.
Map<K,V>
synchronizedMap(Map<K,V> m)
Returns a synchronized map .
NavigableMap<K,V>
synchronizedNavigableMap(NavigableMap<K,V> m)
Returns a synchronized navigable map.
NavigableSet synchronizedNavigableSet(NavigableSet s) Returns a synchronized navigable set .
static Set synchronizedSet(Set s) Returns a synchronized set .
SortedMap<K,V>
synchronizedSortedMap(SortedMap<K,V> m)
Returns a synchronized sorted map .
SortedSet
synchronizedSortedSet(SortedSet s)
Returns a synchronized sorted set.

Example: Synchronized Collections

In this example creating the blank type of collection and making it Synchronized. You can assign the same with collection objects.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CollectionSunchronizationExample {

	public static void main(String[] args) {
		Collection c = Collections.synchronizedCollection(new ArrayList());
	    List list = Collections.synchronizedList(new ArrayList());
	    Set s = Collections.synchronizedSet(new HashSet());
	    Map m = Collections.synchronizedMap(new HashMap());

	}

}

References

Java: Properties Class Methods and Examples


java.util.Properties class is a subclass of HashTable. Properties class store values in key and value pairs both as String.

We can define our properties by properties (extension as .properties) or by Properties class. The main benefit of define properties in the properties file. If something needs to change then don’t need to recompile the Java Class.

Method of Properties Class

public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key, String value) sets the property in the properties object.
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String comment) writes the properties in the OutputStream object.
storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating the XML document.
public void storeToXML(Writer w, String comment, String encoding) writers the properties in the writer object for generating an XML document with the specified encoding.

Example: Create Properties File

import java.io.FileWriter;
import java.util.Properties;

public class CreateProprtiesFile {

	public static void main(String[] args) throws Exception {
		Properties p = new Properties();
		//append properties in class as key and value
		p.setProperty("name", "Saurabh Gupta");
		p.setProperty("email", "FacingIssuesOnIT@gmail.com");

		//Write in properties file
		p.store(new FileWriter("myinfo.properties"),
				"FacingIssuesOnIT Properties Example");
	}
}

Output

Properties file creation

Example: Read Properties File

In this example, you will learn to read properties from the file.

import java.io.FileReader;
import java.util.Properties;

public class ReadPropertiesFile {

	public static void main(String[] args) throws Exception{
		//Read properties file
		 FileReader reader=new FileReader("myinfo.properties");   

		    Properties p=new Properties();
		    //Load file as properties
		    p.load(reader);   

		    //retrieve value of property one by one
		    System.out.println(p.getProperty("name"));
		    System.out.println(p.getProperty("email"));
	}

}

Output


Saurabh Gupta
FacingIssuesOnIT@gmail.com

Example : Print System Level Properties

import java.util.Map;
import java.util.Properties;

public class PrintSystemProperties {

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

		//Get all properties from System class
		Properties properties=System.getProperties(); 

		//Print all System level properties
		System.out.println("Your Machine Properties :\n");
		for(Map.Entry entry:properties.entrySet())
		{
			System.out.println(entry.getKey()+" = "+entry.getValue());
		}

	}

}

Output


Your Machine Properties :

java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.8.0_73\jre\bin
java.vm.version = 25.73-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
file.encoding.pkg = sun.io
user.country = US
user.script = 
sun.java.launcher = SUN_STANDARD
sun.os.patch.level = 
java.vm.specification.name = Java Virtual Machine Specification
user.dir = F:\Workspace-Learning\Session8Examples
java.runtime.version = 1.8.0_73-b02
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Program Files\Java\jdk1.8.0_73\jre\lib\endorsed
os.arch = amd64
java.io.tmpdir = C:\Users\SAURAB~1\AppData\Local\Temp\
line.separator = 

java.vm.specification.vendor = Oracle Corporation
user.variant = 
os.name = Windows 10
sun.jnu.encoding = Cp1252
java.library.path = C:\Program Files\Java\jdk1.8.0_73\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_73/bin/server;C:/Program Files/Java/jre1.8.0_73/bin;C:/Program Files/Java/jre1.8.0_73/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Git\cmd;%JAVA_HOME%\bin;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\Saurabh Gupta\Desktop;;.
java.specification.name = Java Platform API Specification
java.class.version = 52.0
sun.management.compiler = HotSpot 64-Bit Tiered Compilers
os.version = 10.0
user.home = C:\Users\Saurabh Gupta
user.timezone = 
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.8
java.class.path = C:\Program Files\Java\jdk1.8.0_73\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\zipfs.jar;F:\Workspace-Learning\Session8Examples\bin
user.name = Saurabh Gupta
java.vm.specification.version = 1.8
sun.java.command = collections.properties.PrintSystemProperties
java.home = C:\Program Files\Java\jdk1.8.0_73\jre
sun.arch.data.model = 64
user.language = en
java.specification.vendor = Oracle Corporation
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode
java.version = 1.8.0_73
java.ext.dirs = C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
sun.boot.class.path = C:\Program Files\Java\jdk1.8.0_73\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_73\jre\classes
java.vendor = Oracle Corporation
file.separator = \
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding = UnicodeLittle
sun.cpu.endian = little
sun.desktop = windows
sun.cpu.isalist = amd64

Java 8: Lambda Expression


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

Where to use the Lambda Expression

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

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

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

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

Points to remember

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

Java Lambda expression Syntax

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


 (parameter_list) -> {function_body}

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

Note:

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

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

No Argument Syntax


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

One Argument Syntax


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

Two Argument Syntax


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

Method vs Lambda Expression in Java

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

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

Example 1: Lambda Expression with a predefined functional interface

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

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

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

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

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

Example 2: lambda Expression with your own functional interface

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

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

public class CalculateClass {

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

Output


Result: 220

Example 3: Lambda Expression with no arguments

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

Output


Welcome to Facing Issues on IT !!

Example 4: Lambda Expression for Collection Iteration

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

Output


Saurabh
Gaurav
Bharti
Herry
Henry

Note:

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

References

Java 8: Optional for handling NULL


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

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

Create Optional Object

Create Optional Object : Empty


Optional optionalObj=Optional.empty();

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


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

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


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

Check Optional Object for value present

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


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

Optional Object for value

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


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

Set Optional Object default value and actions

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


YourClass yourObj=optionalObj.orElse(new YourClass("defaut"));

We can use Optional.orElseThrow() method which instread of returning default value if Optional empty , throw an exception:


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

Java Optional Example 1

In this example, covered all the above case.


import java.util.Optional;
public class OptionalExamples {

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

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

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

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

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

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

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

}

Output


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

Java Optional Example 2

public class OptionalExaple2

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

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

	}

}

Output


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

References