Posts

Showing posts from November, 2018

What are Iterators in Java?

Java provides an interface called Iterator that is used to iterate over or loop through the elements in a collection. You can use an iterator on any Collection interfaces or any of its sub interfaces like List or Set .   Consider the following code snippet: public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i &amp;lt; 10; i ++){ list.add(i+2); } Iterator<Integer> itr = list.iterator(); while (itr.hasNext()){ int i = itr.next(); System.out.println("i="+i); } }   This code demonstrates how you can use iterator to iterate over a List. Here, we are iterating over a list of integers. But you can use it to iterate over any data type. The iterator method on the list interface returns an iterator instance. In the iterator variable declaration, we need to specify the data type that the iterator will iterate over. In this case, we are specifying Integer.  Once we obtain an iterator, we can use it

IntPredicate Interface in Java 8 with examples

In this blog post, I will be explaining how the Java 8 functional interface IntPredicate works. To know more about functional interfaces, you can refer this blog post. Edit The IntPredicate interface provides a method called test. This method accepts a parameter of Integer data type and returns a boolean. The  IntPredicate interface is a specialization of the Predicate interface. While the Predicate interface accepts any data type, the IntPredicate interface accepts an Integer value. To see an example of the Predicate interface, refer to  this  blog post. IntPredicate Example Consider the following code snippet: public class IntPredicateDemo {public static void main(String args[]){IntPredicate greaterThan10 = (input) -> input > 10;System.out.println("4 is greater than 10 = "+greaterThan10.test(4));System.out.println("15 is greater than 10 = "+greaterThan10.test(15));}} Here, the IntPredicate.test method checks if the input number is greater than 10. So

How to shuffle the elements in a List via Java

In this blog post, I will be explaining how you can shuffle list via Java.  Consider the following code snippet: package learnjava.collections;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class ShuffleDemo {public static void main(String[] args) {List<Integer> input = new ArrayList<Integer>();input.add(3);input.add(9);input.add(5);input.add(15);input.add(11);System.out.println("Before shuffling:"+input);Collections.shuffle(input);System.out.println("After shuffling:"+input);}}   This code uses the Collections.shuffle method. The Collections class contains static utility methods that operate on collections like List, Set etc.  When the Collections.shuffle  is invoked, it shuffles the input list randomly. The return type of this method is void, so the input list is modified. When you run this code, it will print output similar to the following: Before shuffling:[3, 9, 5, 15, 11]After shuffling:[15, 11, 3, 9, 5] Not

Introducing my Hibernate Course!!

Happy to announce that my new Hibernate course is now live!! https://www.udemy.com/hibernate-from-scratch This course covers all Hibernate essentials from scratch! As an introductory offer I am giving away a limited number of free coupons!! Just leave a comment below and I will send a free coupon!

public static void main explained

I’ve seen a lot of questions posted which ask the meaning of public static void main in Java. In this blog post, I’m going to explain these keywords which are used with the main method.   The main method is the starting point in any standalone Java application. However, whenever you write a main method in Java, you need to precede it with the public static void keywords. So why are they required?   Public –  Public is an access specifier. Refer this post to learn about the other access specifiers in Java.  When the public access specifier is used for a member, it indicates that the member is accessible by code which is outside the class.  So the main method needs to be public since it has to be accessible by the JVM when the program is run.   Static – The static keyword indicates that a member can be accessed  without requiring an object of a class. Refer this post for more information on the static keyword. So they keyword static allowes the main() method to be invoked even before

Java classes and objects explained

In this blog post, I will be explaining the distinction between classes and objects. The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. public class Book {String bookName;String bookAuthor;} This is a very simple class called Book. This class keyword is used to declare a class.You can see here that I’ve declared some variables in the class. These variables are called instance variables or fields . This Book class acts as a template and we can create many books using this class. Now consider the following code snippet: public class Demo {public static void main(String args[]){Book book = new Book();}} The first line creates a new object of type Book and assigns it to the variable book . This object book will have its own copies of the variables bookName and bookAuthor. Each object contains its own copy of each instance variable defined by the class. A class acts like a templa

Java prefix and postfix notation explained

You might have used the increment and decrement operators in Java.  You can use these in prefix and postfix form. In this blog post I will be explaining the difference between the two. When you use the increment or decrement operator before the operand it is said to be in prefix form. In such cases the increment or decrement operation is performed first before evaluating the expression. int i = 5;int j = ++i;System.out.println("j="+j);System.out.println("i="+i); This code prints the following output: j=6i=6 So here value of j is 6 because the increment operation is performed first. However when the increment or decrement operator is used after the operand it is said to be in postfix form. In such cases the increment or decrement operation is performed after evaluating the expression. int i = 5;int j = i++;System.out.println("j="+j);System.out.println("i="+i); This code prints the following output: j=5i=6 So here value of j is 5. This is because t

Java 8 BooleanSupplier Example

In this blog post, I will be explaining how the Java 8 functional interface BooleanSupplier works. To know more about functional interfaces, you can refer  this  blog post. Edit The  BooleanSupplier interface provides a method called getAsBoolean. This method does not accept any arguments. It returns a boolean value. The BooleanSupplier interface is a specialization of the Supplier interface that returns a boolean. To see an example of the Supplier  interface, refer to  this  blog post. BooleanSupplier example Consider the following code snippet: public class BooleanSupplierExample {public static void main(String[] args) {BooleanSupplier booleanSupplier = () -> true;System.out.println("Boolean flag = "+booleanSupplier.getAsBoolean());}} Here, we have implemented the getAsBoolean method using a lambda expression. This simply returns the value true. So when this code is executed, it will print the following output: Boolean flag = true You can get the source code for th

How to convert a String to a Date

In this blog post, I will be demonstrating how you can convert a String to a Date object. Consider the following code snippet: public class StringToDate {public static void main(String[] args) {System.out.println("Enter a date:");Scanner scanner = new Scanner(System.in);String dateStr = scanner.nextLine();System.out.println("Input date is "+dateStr);SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");try {Date date = simpleDateFormat.parse(dateStr);System.out.println("Date in date format is "+date);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}scanner.close();}} The input Date in String format is read using the  Scanner  class. The code uses the  SimpleDateFormat class. This is a class that provides date formatting functions. In the constructor, you need to specify the format in which the input date is specified as a String. So in this case, I have specified “ dd-MM-yyyy ” which means the d

Java Path and Classpath explained in detail

Image
In this blog post, I will be explaining Java PATH and CLASSPATH. Both PATH and CLASSPATH are environment variables that need to be set in order for Java programs to run. But there is a slight difference between the two.  Let’s find out. What is Path? The PATH environment variable is used to specify where the JDK binaries like “java” or “javac” are present. You will generally require these binaries to compile or run your program. The “javac” or “java” are exe files provided by Java to compile or run your code. These are present in the JDK_HOME\bin folder. So if you want to compile or run your program, you need to do one of the following: 1) Navigate to the JDK_HOME\bin and type the javac or java command along with the full path of your Java file: 2) Stay in the directory where your Java files exist but specify the full path of the JDK_HOME\bin folder with the java ir javac command.   Both these methods are cumbersome and so the easier alternative is to set the PATH variable. In the PATH