Posts

Showing posts with the label Core Java

New Features in Java 11 Explained in Detail

Java 11, is the latest long-term support (LTS) version of the Java programming language. It brings along several exciting features and improvements. In this blog post, we’ll take high level look into the New Features in Java 11. Local Variable Syntax for Lambda Parameters One of the most important features in Java 11 is the ability to use the var keyword for lambda parameters. This allows for more concise and readable code when working with lambda expressions. Java 10 introduced the Local Variable Type Inference feature . However, the var keyword could not be used with lambda expressions. So, you would need to write a lambda expression as follows: (int a, int b) -> a + b This code can be rewritten in Java 11 as follows: (var a, var b) -> a + b   HTTP Client Improvements Java 11 introduces a new and modern HTTP client API that supports HTTP/1.1, HTTP/2, and WebSocket. This new client offers a more flexible and efficient way to make HTTP requests and process responses. ...

How to read a file on the classpath in Java

Image
There are often programming situations when you need to read a file on the classpath via Java. In this article, I will show you how to write code for this. Reading a file on the classpath Let us first take a look at the code that you need to write to read a file on the classpath. public class ReadFileFromClassPathDemo { public static void main(String[] args) throws IOException { // read in the file from the resources directory ClassLoader classLoader = ReadFileFromClassPathDemo.class.getClassLoader(); URL url = classLoader.getResource("input.txt"); String fileName = url.getFile(); File file = new File(fileName); String str = new String(Files.readAllBytes(file.toPath())); System.out.println(str); }} Java has an in-built class called ClassLoader .  It is used to dynamically load classes. It can also be used to load resources from the classpath. The code above first obtains a ClassLoader . It then invokes the getResource method on the classLoader . This l...

Difference between a local, instance and static variable in Java

Java supports three types of variables, local, instance and static. This post explains the difference between a local, instance and static variable in Java Local Variable Instance Variable Static Variable Defined within a method or a code block Defined outside a method at the class level Defined outside a method at the class level Is only accessible in the method/code block where it is declared Is accessible throughout the class Is accessible throughout the class Remains in memory as long as the method executes Remains in memory as long as the object is in memory Remains in memory as long as program executes Does not require any special keyword Does not require any special keyword but any access specifier (private, protected or public) can be specified. Typically, private or protected is used Requires the static keyword to be specified. In addition, any access specifier (private, protected or public) can be specified. Typically, public is used Requires to be initialized before it is us...

Difference between Comparator and Comparable

Java has two interfaces that you can use for sorting custom objects. These are the Comparator and Comparable interface. In this article, I will be explaining the differences between the two. Basic difference between Comparator and Comparable The main difference between the Comparator and Comparable interface is that you can use Comparator  to compare two independent objects. The Comparable on the other hand is used to compare the current object with another object. Consider the following Person class: public class Person { private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; }} Suppose you want to sort Person objects on the basis of the age fields. Let us understand how you can achieve this using both Comparator and Comparable. Sorting Using Comparator In order to sort using Comparator, you will first need to create a class that implements the Comparator interface.  The following code demonstrates this...

Java Callable Interface Explained with Code Samples

In this article, I will be explaining the Callable interface in Java. I will be explaining what is Runnable and Callable in Java and what is the use of the Callable interface. Runnable Interface Right from the start, the Runnable interface has been associated with multi-threaded programming.  The Runnable interface provides a run method that executes code in a separate thread. The following code demonstrates this: public class RunnableDemo { public static void main(String[] args) { System.out.println("Creating new thread in main"); Runnable r = () -> System.out.println("Executing thread body...."); Thread myThread = new Thread(r); myThread.start(); System.out.println("Completed main"); }} So this code first creates a new Runnable interface and uses a lambda expression to implement the run method.  The code then creates a new Thread and invokes the start method which spawns a new Thread and executes the code in the Runnable implementatio...

Java Protected Keyword explained With Code Samples

In this article, I will be covering the Java Protected Keyword. Introduction Just like private and public, protected is an access specifier. When the protected access specifier is used for a field or method, it becomes accessible in all the subclasses of the class in which the field is defined. The protected access specifier also makes the member accessible in other classes which are in the same package as the class having the protected member.   Accessing a protected field from a sub-class The following code snippet demonstrates how you can access a protected field in a sub-class: package demo;public class Base {private int a;protected int b;}public class Sub extends Base {public void subMethod() {super.a=4; //this causes compilation errorsuper.b=9;}} The class Base has a private field a and a protected field b The class Sub extends Base It has a method subMethod which assigns some values to a and b a=4; – This causes a compilation error since a is private b=9 – This ...

Compile time polymorphism vs Runtime polymorphism

Polymorphism is the process where the same action can be performed in a number of different ways. Java supports 2 types of polymorphism – Compile time and runtime. Compile time polymorphism Java supports compile-time polymorphism via method overloading.Method overloading allows us to define two or more methods with the same name within a class but with different parameter declarations. Consider the following code snippet: public class AdditionService {int add() {return 3+5;}int add(int i) {return i+i;}int add(int i,int j) {return i+j;}double add(double i,double j) {return i+j;}} This class has 4 methods with the name add. All four add methods differ in the parameters, so there is no compilation error. 1 st add method does not have any parameters, the 2 nd add method takes two integer parameters, the 3 rd add method takes one integer parameter and the 4 th add method takes two double parameters. So the add method is said to be “overloaded” four times. Since the same action can be pe...

JShell in Java 9

Image
One of the new features added by Java 9 is the JShell.  In this blog post,  I will be explaining how JShell works. What is JShell ? JShell provides REPL capabilities to Java. REPL stands for Read Evaluate Print Loop. Many languages like Python also provide REPL capabilities. REPL allows you to write Java code and test it without the need to compile it.   How to launch JShell Step 1 – Make sure you have JDK 9 installed   Step 2 -Open a Command prompt and navigate to the JDK\bin folder   Step 3 – Type JShell How to Use JShell Type the code that you want to test. I have typed 4+5. Press Enter   Step 5 – View the results Example 2  – Using a Sysout statement Example 3 – Assigning a value to a variable and using it How to exit JShell Type /exit

Why is Java Platform Independent

A very common interview question is to ask a candidate to explain how Java is platform independent. So let me explain this here. Consider the following simple Java code: public class HelloWorldDemo {public static void main(String[] args) {System.out.println("This is my first Java program!");}} So you can see that the code is in simple English text.  After you write the code you need to compile it. Compilation is the process where the code is converted into a format that is understood by the underlying machine. The underlying machine does not understand the code that we write in English, so it must be converted to a format that it understands. In languages like C or C++, the code is compiled into executable files (files with .exe extension) that are directly executed on the operating system.  So if you have an exe file of a C program for Windows, the exe file will not run as it is on a Linux machine. This is because the exe file created is operating system specific. On the oth...

Java 8 forEach loop explained with code samples

Java 8 introduced a lot of new features like functional interfaces, lambda expressions, etc. These provide a totally new way of programming for developers. One such feature is the forEach support added to the Collection interfaces. In this blog post, I will be covering this feature in detail. Edit What is forEach Java 8 added a new method called forEach to all the Collection interfaces via the Iterable interface. You can use this method to iterate through a Collection internally without the need for an explicit for loop. Before Java 8 Prior to Java 8, if we wanted to iterate through a Collection like a List , we had to write code similar to the following: public class ForEachDemo {public static void main(String args[]){List <Integer> list = Arrays.asList(5,3,11,15,9);for(int num:list){System.out.println("Number is "+num);}}} So you need to write a for loop to iterate through the elements in the List. In the body of the for loop, you can write the code that you wa...

How to obtain a list of files in a folder

In this blog post, I will be explaining how you can obtain a list of files in a folder. Consider the following code snippet: package learnjava.io;import java.io.File;public class FilesInFolderDemo {public static void main(String[] args) {String folderName = "F:/TestFolder";File file = new File(folderName);if (file.exists() && file.isDirectory()) { // check if file exists & is a folderFile[] files = file.listFiles(); //get list of filesif (files.length > 0) {System.out.println("There are " + files.length + " files in the folder");for(int i = 0; i < files.length;i++){System.out.println("File name is "+files[i]);}} else { //empty folder!System.out.println("Folder is empty !");}} else {System.out.println("Folder "+folderName+" is missing or is not a folder");}}}   There is a method called File.list on the file interface. If the File object corresponding to the specified path is a directory, then th...

Java Autoboxing explained

In this blog post, I will be explaining Java’s autoboxing feature in detail   What is Auto boxing? Java provides class equivalents for all the primitive datatypes. So for example, there is an Integer class which corresponds to the int datatype, a Float class that corresponds to the float data type and so on. Not only that, Java can automatically convert between the class and the corresponding primitive type. So if there is an Integer type, Java can automatically convert it to int and if there is an int type, Java can automatically convert it to Integer. This is known as autoboxing. Consider the following code snippet: public static void main(String[] args) {int i = 5;Integer integer = i;System.out.println("The value of integer is "+integer);} Here, we have defined an int variable called “i” and assigned it the value 5. After that we have defined an Integer variable called integer and assigned it the value “i” . So note that this does not ...

Nested Classes explained

Quite often, we come across the term “Nested Class” in Java. It is a very common interview topic as well. So in this blog post, I will be explaining what a nested class is in Java. What is a Nested Class? As the word suggests, a nested Java class is a class which lies within another Java class.  Consider the following code snippet: class OuterClass{class NestedClass{}}   The class NestedClass is like any other member of the OuterClass . It has access to other members that is methods and variables of the OuterClass even if a member is a private member. On compiling this code snippet, the compiler creates two class files. One will be the OuterClass.class and the other will be the OuterClass$NestedClass.class .  If you have more than one nested class, the compiler creates a separate class file for each one. However, each of them will be prefixed with the name of the enclosing class and the $ sign. Why do we need nested classes? The following are some reasons where you ...

How to check if a String is a substring of another String

In this blog post, I will be explaining how you can check if a String is a substring of another String. Consider the following code snippet: package learnjava.strings;public class CheckSubstringDemo {public static void main(String[] args) {String strToCheck = "Hello World";String valueToCheck = "Hello";//Method 1 - Use Containsif(strToCheck.contains(valueToCheck))System.out.println(valueToCheck+" is present in "+strToCheck);elseSystem.out.println(valueToCheck+" is NOT present in "+strToCheck);//Method 2 - Use startsWith and indexOfif(strToCheck.startsWith(valueToCheck) || strToCheck.indexOf(valueToCheck) &gt; 0)System.out.println(valueToCheck+" is present in "+strToCheck);elseSystem.out.println(valueToCheck+" is NOT present in "+strToCheck);}}   This code snippet demonstrates two ways to check if a String is a substring of another String. Method 1: This method uses the String.contains method. This returns true if the ...

How to check if a String has digits in Java

In this blog post, I will be explaining how you can check if a String has digits. There are several ways to do this. Consider the following code snippet:   package learnjava.strings;import java.util.regex.Pattern;public class CheckIfStringHasDigits {public static void main(String[] args) {String str = "Hello123";String regex = ".*[0-9].*";//Method 1 - Using String.matchesboolean matches = str.matches( regex );System.out.println("Using String.matches="+matches);//Method 2 - Using pattern.matchesmatches = Pattern.matches( regex , str);System.out.println("Using pattern.matches="+matches);//Method 3 - using pattern.compilematches = Pattern.compile( regex).matcher( str ).find();System.out.println("Using Pattern.compile="+matches);//Method 4 - Checking each characterboolean digitFound = false;char[] characters = str.toCharArray();for(char c:characters){if(Character.isDigit(c)){digitFound = true;break;}}System.out.println("Using manua...

How to split a String via Java

In this blog post, I will be explaining how you can split a String via Java. Consider the following code snippet: package learnjava.strings;public class SplitStringDemo {public static void main(String[] args) {String str = "This is a test String";String[] words = str.split(" ");System.out.println("There are "+words.length+" words");for(String word:words){System.out.println(word);}}} There is a method called String.split . It accepts any regular expression. It splits the String around matches of the specified regular expression. Here, I am simply using a space. This will split the input sentence into words. So if you run the above code, you will get the following output: There are 5 wordsThisisatestString  

How to find the free space in a drive via Java

In this blog post, I will be explaining how you can find the free space in a drive via Java. Consider the following code: package learnjava.io;import java.io.File;public class FindFreeSpaceDemo {public static void main(String[] args) {String fileName = "C:/";File file = new File(fileName);long freeSpace = file.getFreeSpace();System.out.println("freeSpace = "+freeSpace/1000000000+ " GB");}}   There is a method File.getFreeSpace . This returns the number of bytes available on the drive that is encapsulated by the current File object. According to the API documentation, the number of bytes is a hint and not a guarantee. There is another method called File.getUsuableSpace .  This returns the number of bytes available to the virtual machine. This method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than the  File.getFreeSpace  meth...

How to find the total space in a drive in Java

In this blog post, I will be explaining how you can find the total space available in a drive via Java. Consider the following code snippet:   package learnjava.io;import java.io.File;public class FindTotalSpaceDemo {public static void main(String[] args) {String fileName = "C:/";File file = new File(fileName);long totalSpace = file.getTotalSpace();System.out.println("totalSpace = "+totalSpace/1000000000+ " GB");}}   There is a method called File.getTotalspace . This returns the number of bytes available on the partition that is encapsulated by the file object.

How to make a file read-only in Java

Image
In this blog post, I will be explaining how you can make a file read-only in Java. Consider the following code snippet: package learnjava.io;import java.io.File;public class ReadOnlyDemo {public static void main(String[] args) {String fileName = "F:/Test1.txt";File file = new File(fileName);if(file.setReadOnly()){System.out.println("File is now readonly");}elseSystem.out.println("Failed to make the file readonly");}} There is a method called File.setReadOnly . This makes a file as read only. It returns true if the file is made readonly successfully. If the file does not exist at that path, or if any other issue occurs, it returns false. So if you run the above code snippet, the file “F:/Test1.txt” will be made as readonly. If you try to edit and save it, you will see the following error:

How to create a Directory in Java

In this blog post, I will be covering how you can create a directory in Java. Consider the following code snippet: package learnjava.io;import java.io.File;public class CreateDirectory {public static void main(String[] args) {String fileName = "C:/Parent/Demo";File file = new File(fileName);boolean created = file.mkdirs();if(created)System.out.println("Directory created successfully");elseSystem.out.println("Failed to created directories");}}   There is a File.mkdirs method. This creates the directory corresponding to the File object including any non-existent parent directories. It returns a true if the directory was created successfully, otherwise it returns a false. In this case, it will print the following output (Assuming there is no error in creating the directory): Directory created successfully There is also a File.mkdir method. This creates a directory corresponding to the path specified, but does not create parent directories. So if the par...