Monday, 18 June 2018

Java 10 – Local Variable Type Inference

In this article we will see a Java10 feature called Local Variable Type Inference proposed as part of JEP 286. From the first version of Java it is strongly typed language where we need to mention each variable data type. We all were feeling Java is verbose language and expecting precise, compact way of writing Java . Java 8 addressed this concern some what.

Java 10, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Study Materials

Java 10 added Local Variable Type Inference with initializer to eliminate verbosity. For example,

jshell> Map<String,String> map = new HashMap<>();
jshell> var map = new HashMap<>(); //This is valid with Java10

Here LHS variable datatype will be determined by RHS statement. For example,

jshell> var i = 3;
i ==> 3 //based on RHS, the LHS datatype is int.
jshell>int i=3,j=4; //Valid Declaration
but,
jshell> var j=4,k=5; //Not a Valid Declaration
| Error:
|'var' is not allowed in a compound declaration
| var j=4,k=5;
|^

You can use this feature for enhanced for loop and for loop as well.

jshell> List names = Arrays.asList("ABC","123","XYZ");
names ==> [ABC, 123, XYZ]
jshell> for(var name : names){
...> System.out.println("Name = "+ name);
...> }

Name = ABC
Name = 123
Name = XYZ

We can use Local Variable Type Inference in the for loop as well.

jshell> int[] arr = {1,2,3,4};
arr ==> int[4] { 1, 2, 3, 4 }

jshell> for (var i=0;i<arr.length;i++){
   ...> System.out.println("Value = "+i);
   ...> }
Value = 0
Value = 1
Value = 2
Value = 3

There are certain scenarios where this feature is not valid to use. For example,

◈ Not valid for constructor variables
◈ Not valid for instance variables
◈ Not valid for method parameters
◈ Not valid to assign NULL value
◈ Not valid as return type

Let us see examples for above statements.

jshell> public class Sample {
   ...>    private var name = "xyz";
   ...>    public Sample(var name) {
   ...>     this.name=name;
   ...>    }
   ...>    public void printName(var name){
   ...>      System.out.println(name);
   ...>    }
   ...>    public var add(int a, int b) {
   ...>     return a+b;
   ...>    }
   ...> }
|  Error:
|  'var' is not allowed here
|     private var name = "xyz"; //Instance variable
|             ^-^
|  Error:
|  'var' is not allowed here
|     public Sample(var name) { //Constructor variable
|                   ^-^
|  Error:
|  'var' is not allowed here
|     public void printName(var name){ //Method parameter
|                           ^-^
|  Error:
|  'var' is not allowed here
|     public var add(int a, int b) { //Method return type
|            ^-^


jshell> public class Sample {
   ...>    
   ...>    public static void main(String[] args) {
   ...>     var s = null;
   ...>    }
   ...> }
|  Error:
|  cannot infer type for local variable s
|    (variable initializer is 'null')
|      var s = null;
|      ^-----------^

When we migrate the from lower versions to Java10, we no need to worry about the Local Variable Type Inference as this has the backward compatibility.

Friday, 15 June 2018

Java 8 - Stream.collect() Example

The collect() method of Stream class can be used to accumulate elements of any Stream into a Collection. In Java 8, you will often write code which converts a Collection e.g. List or Set to Stream and then applies some logic using functional programming methods like the filter, map, flatMap and then converts the result back to the Collection e.g. List, Set or Map. In this last part, the collect() method of Stream helps. It accepts a Collector to accumulate elements of Stream into specified Collection. The Collector class provides different methods e.g. toList(), toSet(), toMap(), and toConcurrentMap() to collect the result of Stream into List, Set, Map, and ConcurrentMap in Java.

Thursday, 14 June 2018

Proven Steps to Preparing for Java 8 Certification for Outstanding Score

In many cases, certifications are regarded as proof of knowledge of a specific subject. This consideration makes people more willing to earn certification for personal satisfaction and showcasing their skills. Java certification is the most desirable certification listed in job postings for software developers. Specifically,
  • Java certification places you ahead of many job applicants for Java related jobs.
  • The certification exam contains tricky questions regarding Java. Therefore, in job interviews, you would be more prepared to answer tricky and hard questions than other candidates as you would likely to be exposed to them before.
  • Last but not least, the skills gained while preparing for a certification would help you create more quality and robust software.
Here are the steps to become a certified Java professional:

1. Learn About the Certification Paths   

First of all, try to get the most recent version of Java certification. As of now, Java 8 is the most recent version; therefore, start with the Oracle Certified Associate, Java SE 8 Programmer certification.  The exam of this certification is composed of basic Java and object oriented programming questions. You can find detailed information about this certification by visiting the Oracle Certified Associate, Java SE 8 Programmer certification site. In this link, there is also a chart on certification paths and a table about exam topics. This URL is a gate to all Oracle Java certifications.
1Z0-808 practice test, 1Z0-808 exam guide
Figure 1 -  Certification Path from Oracle Education
Exam Number
Exam
Name
Product
Version
Duration
(minutes)
# of
Questions
Passing
Score
Exam Format
1Z0-808
Oracle Certified Associate, Java SE 8 Programmer
SE
150
77
65%
Multiple Choice
1Z0-809
Oracle Certified Professional, Java SE 8 Programmer
SE
150
85
65%
Multiple Choice
1Z0-897
Oracle Certified Expert, Java EE 6 Web Services Developer
EE
90
55
65%
Multiple Choice
1Z0-807
Java EE 6 Enterprise Architect Certified Master
EE
150
60
71%
Multiple Choice
1Z0-865
Java (EE) Enterprise Architect Certified Master Assignment
EE
6 months
NA
Validity
Performance Based
1Z0-866
Java (EE) Enterprise Architect Certified Master Essay
EE
120
NA
Validity
Essay
Table 1 - Exam Summary Table from Oracle Education
Oracle Certified Professional, Java SE 8 Programmer exam requires that the applicant have an Oracle Certified Associate, Java SE 8 Programmer certification. This certification demonstrates deeper knowledge of Java development skills using JAVA SE APIs such as Concurrent API, JDBC API and etc.
There are many Oracle Certified Expert certifications on different specific subjects requiring advanced Java certification. For example, to apply for the Oracle Certified Expert, Java EE 6 Web Services Developer certification, one needs to earn the Oracle Certified Professional, Java SE 8 Programmer certification first. On the other hand, the Java EE Enterprise Architect certification has a different path; it does not require the Oracle Certified Associate, Java SE 8 Programmer certification. The steps for earning the Java EE Enterprise Architect certification are as follows:
  • Complete one of Oracle Academy Java courses
  • Pass Java EE 6 Enterprise Architect Certified Master 1Z0-807 exam
  • Pass Java (EE) Enterprise Architect Certified Master Assignment 1Z0-865 exam
  • Pass Java (EE) Enterprise Architect Certified Master Essay 1Z0-866 exam

2. Read Recommended Books

To be ready for tricky exam questions, whether or not you are very talented in Java, you should read books on certification. These books help improve and deepen your knowledge of Java. Furthermore, writers of these books share their knowledge and experiences about certifications that help you prepare for exams. My recommendations are;
  • OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808
  • OCA Java SE 8 Programmer I Certification Guide

3. Learn What Is New in the Latest version of Java

If you are experienced with Java 7, and if you want to earn a certification for Java 8, you can check which topics are new to you. For example, the Oracle Certified Associate, Java SE 8 Programmer certification exam brings in the following in comparison to the Oracle Certified Associate, Java SE 7 Programmer certification exam:
  • A new Date/Time API
  • Simple Lambda expressions just for the Predicate interface.
  • Default and Static Methods in Interface

4. Solve Sample Tests

It is better to prepare for solving as many questions similar to those encountered in the exams as possible. OracleStudy.com is one of the better test centers for Java certification, as referred to by many developers. I have also used this test center while preparing for the Oracle Certified Professional, Java SE 7 Programmer certification exam.
In the test center, for the Oracle Certified Associate Java SE 8 Programmer certification, there is one starter test along with six sample tests, and the last day exam is sufficient enough to obtain 90-100 points in the exam. Generally, one would receive 10 points more in a real exam than the score of the sample exams. The exam has multiple choice questions where respondents are asked to declare how many correct answers are available out of the choices from a list; but be careful, the possibility of a more than one correct answer makes the exam a bit difficult.
Here's OracleStudy's Java 8 SE certification page for more information.

5. Register and Buy Vouchers

To enter a certification exam you need to register with the Oracle Education System and buy an electronic voucher. One exam voucher is nearly $245. It is valid for 6 months from the date of purchase. In case you fail the exam, one can register again after 14 days to retake it.

6. Locate Exam Place and Time

After registration and buying a voucher, when you're ready to take the exam, you can use the Pearsonvue organization to find a suitable place and time to take the exam. Exams may also be rescheduled if need be prior to the exam date.

7. Check Your Results

Within 30 minutes after taking an exam, you can get your score via email. Therefore, you can learn the outcome of your exam very quickly. After all controls, 3-4 days after, certifications are sent electronically. You can check your eCertificate here.

Wednesday, 13 June 2018

What is double colon (::) operator in Java 8 - Example

The double colon (::) operator is known as the method reference in Java 8. Method references are expressions which have the same treatment as a lambda expression, but instead of providing a lambda body, they refer to an existing method by name. For example, to print all elements of the list you can use the forEach() method as follows.

Monday, 11 June 2018

Difference between ServletConfig and ServletContext in JSP Servlet J2EE

Difference between ServletConfig and ServletContext


ServletContext and ServletConfig these two are important interface of Servlet API which is used by Java J2EE programmer during web application development. Correct understanding of What is ServletContext and ServletConfig is very important for any J2EE application developer. Apart from that Difference between ServletContext and ServletConfig are a popular Servlet JSP interview questions and mostly asked on both fresher and experienced Java programmer during J2EE interviews. Both ServletContext and ServletConfig are basically configuration objects which are used by servlet container to initialize various parameter of web application. But they have some difference in terms of scope and availability so first we see what is ServletContext and ServletConfig objects are and then we will see difference between ServletConfig and ServletContext in Java J2EE.

Friday, 8 June 2018

How to escape HTML Special characters in JSP and Java

Escaping HTML special characters in JSP or Java is a common task for Java programmers. There are many ways to escape HTML meta characters in Java.  For those who are not familiar with HTML special characters, there are five e.g. < , >, &, ' and '' and if you want to print them literally just like here, Than you need to escape those character so < becomes &lt; , > becomes &gt; and so on. Of course, you can write your own custom tag or method for converting HTML special characters to entity format which browser understand but you don't need to do this because there are more easy and standard way to escape HTML special characters in JSP and Java. In this JSP and Java tutorial, we will learn about HTML special characters and explore some techniques to escape them in JSP pages and Java code. By the way, this is also a popular JSP Interview question mostly asked 2 years experience programmers.

Wednesday, 6 June 2018

Binary Search in Java without Recursion – Iterative algorithm

his week’s task is to implement binary search in Java, you need to write both iterative and recursive binary search algorithm. In computer science, a binary search or half-interval search is a divide and conquer algorithm which locates the position of an item in a sorted array. Binary search works by comparing an input value to the middle element of the array. The comparison determines whether the element equals the input, less than the input or greater. When the element being compared to equals the input the search stops and typically returns the position of the element. If the element is not equal to the input then a comparison is made to determine whether the input is less than or greater than the element. Depending on which it is the algorithm then starts over but only searching the top or a bottom subset of the array’s elements. If the input is not located within the array the algorithm will usually output a unique value indicating this.

Monday, 4 June 2018

Packages in Java

This post explains how to bundle classes and interfaces into packages, how to use classes that are in packages, and how to arrange your file system so that the compiler can find your source files.


Creating and Using Packages


To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related types into packages.

Friday, 1 June 2018

3 Ways to Convert String to Short in Java

I will show you how to convert String to Short in Java, but before that let's revise what is short data type in Java. The short is an integral data type similar to the int but it only takes 2 bytes to store data as compared to 4 bytes required by an int variable. Since it takes only 2 bytes or 16 bits to store data, the range of short is also shorter than int. It ranges from -32,768 to 32767 (inclusive) or -2^15 to 2^15 -1. You might be wondering why upper bound is 255 and lower bound is -256 but that's because we have included zero in between.

Wednesday, 30 May 2018

Introduction to Java Servlets

We all are aware of the need of creating dynamic web pages i.e the ones which have the capability to change the site contents according to the time or are able to generate the contents according to the request received by the client. If you like coding in Java, then you will be happy to know that using Java there also exists a way to generate dynamic web pages and that way is Java Servlet. But before we move forward with our topic let’s first understand the need for server-side extensions.
Servlets are the Java programs that runs on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, then send response back to the web server.