Posts

Showing posts from December, 2018

Java 8 IntSupplier Interface Example

In this blog post, I will be explaining how the Java 8 functional interface IntSupplier works. To know more about functional interfaces, you can refer this blog post. Edit The  IntSupplier interface provides a method called getAsInt This method does not accept any arguments. It returns an Int data type. The IntSupplier interface is a specialization of the Supplier interface that returns an int. To see an example of the Supplier interface, refer to this blog post. IntSupplier example Consider the following code snippet: </pre>public class IntSupplierDemo {30public static void main(String[] args) {IntSupplier getRandom = () -> new Random().nextInt(100);System.out.println("Random number 1 = "+getRandom.getAsInt());System.out.println("Random number 2 = "+getRandom.getAsInt());}}<pre> Here, we have implemented the IntSupplier.getAsInt method using a lambda expression.  This getAsInt method simple returns a random integer less than 100. So when this

How to convert a String to uppercase

In this blog post, I will be explaining how you can convert a String to uppercase. Consider the following code snippet:   package learnjava.strings;public class StringUpperCaseDemo {public static void main(String[] args) {String str = "Hello World";str = str.toUpperCase();System.out.println(str);}}   There is a String.toUpperCase method. This converts the String object on which it is invoked to uppercase and returns the converted String. So when you run the above code, you will get the following output: HELLO WORLD

Java Enumerations explained

Just like the primitive data types, there is another data type supported by Java which is the enumerated type. In this blog post, I will be explaining Java enumerations in detail. Enum definition An enumerated type is a type whose values consist of a fixed set of constants. Common examples are days of the week which take the values Sunday,Monday, Tuesday,Wednesday,Thursday,Friday and Saturday . Another example could be Colors which could take values like Red,Blue,Yellow, Green corresponding to the colors. In Java, you can define an enumerated type by using the enum keyword. The syntax is as follows: enum NameOfEnum {value1,value2,value3.......,valuen} You can have as many values as you wish. For example, you can define an enum for the days of the week as follows: enum Days {Sunday,Monday, Tuesday,Wednesday,Thursday,Friday,Saturday} The values Sunday,Monday, etc are called enumeration constants. For the enum Days, these are the only values that are allowed. You should use enumerated

Checked Vs Unchecked exceptions

Image
In this blog post, I will be explaining the difference between checked and unchecked exceptions. Checked exceptions Checked exceptions are those scenarios which can be pre-determined but not prevented . So, during the application design, the developer can anticipate that the program might run into such an exception. However, the programmer can do nothing to prevent these exceptions. So the only course of action is to handle the exception . So in case the code is capable of throwing some checked exception, the compiler will cause a compilation error if the exception is not handled.   Unchecked exceptions Unchecked exceptions are caused either due to programming mistakes or due to hardware failure or some other system error. Because the programmer cannot anticipate them, the compiler does not require you to track unchecked exceptions. Consider the following diagram: exception hierarchy   The boxes in blue represent unchecked exceptions , while the ones in pink represent the ch

String vs StringBuffer vs StringBuilder

A very common interview question is to ask the difference between String, StringBuffer and StringBuilder . So in this blog post, I am going to explain how they are different.   What is a String? A String is a Java class. It is designed to hold a set of characters like alphabets, numbers, special characters, etc. String objects are constants, their values cannot be changed after they are created. So, String objects are also called immutable objects. For example, consider the following code snippet: String str = "abc"; //line 1str = str+"xyz"; //line 2 When the line 2 is executed, The object “ abc ” remains as it is and a new object is created  with the value “abc” appended with “xyz”.  The object reference “ str ” no longer points to the memory address of “ abc “, but it points to the address of “abc xyz “. And what about “ abc “? It continues to exist as it is until it is garbage collected.Refer this blog post to read more. What is a StringBuffer? StringBuff

Java Interfaces explained

In this blog post, I will be explaining what Java interfaces are and how they can be used. What is an interface? An interface is a java construct that is used to specify a behavior that classes must implement. It does this by specifying methods without any method bodies. The code for the methods within the interface must be provided by the classes that implement the interface. So using an interface , you can specify what a class must do, but not how it does it. For example, consider the following code snippet: public interface Animal {public void speak();} This interface keyword specifies that this is an interface. Instead of the class keyword, the interface keyword is used, otherwise its body is very similar to a class. There is a speak method within this interface. There is no code in the speak method. Methods specified in an interface have no method bodies.  Code is not allowed in a method in an interface since the basic concept of an interface is to use it to specify what should be

How are Java Strings immutable

Image
You might have heard a lot about Java Strings being immutable . You might have also faced interview questions where you are asked to explain this. In this blog post, I will be shedding some light on this with examples.   So yes, Java Strings are indeed immutable . So what does immutable mean? It means that String objects are constants, their values cannot be changed after they are created. Now consider the following code: String str= "abc";str= "xyz";   Is the above code valid?  Yes, the above lines are perfectly valid. Now this might appear confusing to a new programmer because we are changing the value of “ str”  from “ abc ” to “ xyz “.  But that is not so. The object “ abc ” remains as it is and a new object “ xyz ” is created.  The object reference “ str ” no longer points to the memory address of “ abc “, but it points to the address of “ xyz “. And what about “ abc “? It continues to exist as it is until it is garbage collected. The following diagram depict

Difference between Get and Load in Hibernate

In this blog post, I will be explaining the difference between the Hibernate load and get methods.  Both methods are used to load a record corresponding to an id. However, there are some differences between the two.    Edit Load Get If there is no record in the database corresponding to the id passed in, the load method throws an exception If there is no record in the database corresponding to the id passed in, the get method returns a null When the load method is used, it returns a proxy object with just the id field populated. All other fields are blank. The fields are only fetched from the database when they are accessed from the code. When the get method is used, it fetches the complete object i.e. it fetches all the fields of the object.  

What Are Java constructors?

A constructor is a special method that is invoked as soon as an object is created using the new operator. In this blog post, I will explaining constructors. Constructors are most commonly used to execute some code that needs to be run as soon as an object of a class is created like setting initial values to the instance variables. Consider the following code snippet: public class Person {private String firstName;private String lastName;public void setPersonDetails(String firstName,String lastName){this.firstName=firstName;this.lastName=lastName;}} Here, there is a Person class. There is a method called setPersonDetails . This method sets values to the firstName and lastName fields. However we need to invoke this method, each time we create a Person object. If we forget to invoke this method, the firstName and lastName fields will not be set . So we need some way for the person details to be automatically set when a Person object is created. Fortunately, Java supports this aut

LongPredicate Interface in Java 8 with code samples

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