Posts

Showing posts from January, 2019

Update vs Merge in Hibernate

In this blog post, I will be comparing the Update and Merge methods in Hibernate. I will be explaining how they are similar. I will also be explaining the differences between them.   Similarities Both update and merge methods on the session interface. Both methods update a record in the database. Both move an entity from the detached state to the persistent state. Differences The following table lists the differences between the update and merge methods: Edit Update Merge Hibernate proprietary method Part of the JPA specification Does not return anything, returns a void Returns the updated object Makes the original object persistent. So if the original object is changed after invoking update, changes will get saved when the session is flushed Does not make the original object persistent, so even if the original object is changed after merge, changes will not get saved in the database. Instead, the merged object is tracked for changes Always performs an SQL update Only perf

How to use JUnit to unit test code

Image
In this blog post, I will be explaining how you can run JUnit unit tests to test your code. What is JUnit? JUnit is a unit testing framework for Java. It is used by developers to test individual code and ensure that code works the way it was intended to. The current version of JUnit is JUnit 5 .   Why JUnit? Consider the following code snippet: package demo;public class MathDemo {public int add(int a,int b){return a+b;}public int subtract(int a,int b){return a-b;}}   So this class has two methods, called add and subtract . The add method adds 2 numbers and returns the sum while the subtract methods returns the difference of the 2 input numbers.  Now traditionally, if you want to test if this code works, you would write a main method like this: public static void main(String args[]){MathDemo mathDemo = new MathDemo();int sum = mathDemo.add(5,4);int diff = mathDemo.subtract(9, 3);System.out.println("Sum is "+sum);System.out.println("Difference is "+diff);} The pro

How to replace a String with another String in Java

In this blog post, I will be demonstrating how you can replace a String with another String via Java. Consider the following code snippet: package learnjava.strings;public class ReplaceStringDemo {public static void main(String[] args) {String str = "Good Morning. Another String with the word Morning.";String newStr= str.replace("Morning", "Night");System.out.println("Original String="+str);System.out.println("new String="+newStr);}}   There is a String.replace method.  It accepts as input the String to be replaced and the value with which it should be replaced. It then replaces each occurrence of the first String with the second String. This method actually accepts   CharSequence  as input.  CharSequence  is an interface. The  String  class implements this interface and so you can pass in a String value to this method. So when you run the code above, it will print the following output to the console: Original String=Good Morning. Anot

How to read a CSV file via Java

Image
In this blog post, I will be covering how you can read a CSV file via Java. What is a CSV file? CSV stands for Comma Separated Values.  The fields in a CSV file are separated by commas.  So for example, a CSV file will be seen in Notepad as follows:   However, if you open the same CSV file in Excel and will be seen as follows:   A CSV file is used to store tabular data. You can open a CSV file in Microsoft Excel. Code to read CSV file Consider the following code sample: package learnjava.io;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class ReadCSVDemo {public static void main(String[] args) {String fileName="F:/Test.csv";try {BufferedReader br = new BufferedReader(new FileReader(fileName));String str = br.readLine();while(str != null){String[] contents = str.split(",");for(String cell:contents){System.out.print(cell);}str = br.readLine();System.out.println();}} cat

JDBC vs Hibernate

Image
In this blog post, I will be comparing JDBC and Hibernate and explaining the differences between the two.   What is JDBC? JDBC is nothing but an API to access a relational database from a java program. JDBC basically allows you to execute SQL statements from Java code, so basically any SQL statement which you can run on a database directly, you can run it from your Java code via JDBC.   Disadvantages of JDBC   In order to query a database table via JDBC, you will need code similar to the following: Class.forName("com.mysql.jdbc.Driver"); //Register JDBC Driver      Connection conn = DriverManager.getConnection(url, username, password); //Open a connection      Statement stmt = conn.createStatement(); //create a statement      ResultSet rs = stmt.executeQuery("Select * from book");// Execute a querywhile(rs.next()){ //iterate through the resultset      String bookName = rs.getString("book_name");      }         rs.close();      stmt.close();      conn.close

Difference between save and persist in Hibernate

In this blog post, I will be explaining the difference between the save and persist methods Hibernate. Both the save and persist methods insert a record into a database table. However, there are some differences between the two.   Edit Save Persist Hibernate Proprietary method Part of the JPA specification Returns ID of the saved object Returns a void Insert happens immediately in order to return the ID May not cause the database insert to happen immediately and the insert might happen later when the session is flushed    

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) > 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 Stri

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 manual me

How to add Maven dependencies via Eclipse

Image
In this blog post, I will be giving step by step directions on how you can add Maven dependencies via Eclipse. What is Maven Maven as you might probably know is a dependency management tool. It automatically downloads the necessary jar files for you.So you do not need to download the jar files and add them to your classpath explicitly. Maven uses a file named as pom.xml. This file has all the project configuration. The external jar files that are needed for the project need to be added as dependencies in this pom file. So for example, if you need Hibernate JAR files in your project, you will need to add Hibernate dependencies in the pom file. Maven then automatically downloads the jar files and adds them to the classpath. So let’s get started. Adding Maven Dependencies Via Eclipse Step 1 – Create your Maven project via Eclipse (Refer this post)   Step 2 – Right click on pom.xml. Click on Maven –> Add Depenency Step 3 – Enter group id, artifact id and version for the Dependency that

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  method.

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 parent

How to create a new file using Java

In this blog post, I will be demonstrating how you can create a new empty file via Java. Consider the following code snippet: package learnjava.io;import java.io.File;import java.io.IOException;public class CreateFileDemo {public static void main(String[] args) {String fileName = "C:/Test2.txt";File file = new File(fileName);try {if (file.createNewFile())System.out.println("File created successfully");elseSystem.out.println("There was an error in creating the file");} catch (IOException e) {System.out.println("There was an exception in creating the file:"+e.getMessage());}}} There is a method called File.createNewFile . This creates a new file corresponding to the path in the File object. It returns a boolean value if the file is created successfully. If there is already a file at the path with the same name or if there is any other issue in creating the file, then this method returns a false. Note that the  File.createNewFile can throw an IOExc

How to rename a file

In this blog post ,I will be showing you how you can rename a file. Consider the following code snippet: package learnjava.io;import java.io.File;public class RenameFileDemo {public static void main(String args[]){String fileName = "C:/Test.txt";String newFileName = "C:/test2.txt";File file = new File(fileName);if(file.exists()){File newFile = new File(newFileName);boolean renamed = file.renameTo(newFile);if(renamed)System.out.println("File renamed successfully");elseSystem.out.println("There was an error in renaming the file");}elseSystem.out.println("File is missing");}} If you run this code, it will produce the following output: File renamed successfully   There is a method called File.renameTo which can be used to rename a file. It accepts as argument a file object. The file object should be constructed with the new name to be given to the file. Note that the full path needs to be specified.

How to delete a folder in Java

In this blog post, I will be demonstrating how you can delete a folder in Java. Consider the following code snippet: </pre>package learnjava.io;import java.io.File;public class DeleteDirectory {public static void main(String[] args) {String fileName = "F:/TestFolder";File file = new File(fileName);if (file.exists()) {if (file.isDirectory()) {File[] files = file.listFiles();if (files.length == 0) {System.out.println("Folder is empty so deleting it");if (file.delete()) {System.out.println("Deleted file successfully");} elseSystem.out.println("Error in deleting file");} else {System.out.println("There are " + files.length + " files in the folder, so folder cannot be deleted");}} else {System.out.println("F:/Test.txt is not a folder");}} elseSystem.out.println("Folder F:/TestFolder1 is missing, so could not be deleted");}}<pre> There is a file.delete method that can be used to delete a folder. Howe

How to Delete a file

In this blog post, I will be demonstrating how you can delete a file in Java. Consider the following code snippet: package learnjava.io;import java.io.File;public class DeleteFile {public static void main(String[] args) {String fileName = "D:/Test.txt";File file = new File(fileName);if (file.exists()) {if (file.delete()) {System.out.println("Deleted file successfully");} elseSystem.out.println("Error in deleting file");} elseSystem.out.println("File is missing, so could not be deleted");}}   There is a File.delete method available to delete a file. It returns true, if the delete was successful, otherwise returns a false. So if you run the above code snippet, the following output will be printed (Assuming there is a file called test.txt on D Drive):   Deleted file successfully

How to check if a file exists at the specified path

In this blog post, I will be explaining how you can check if a file exists at a specified path. Consider the following code snippet: public class FileExists {public static void main(String args[]){String fileName = "C:/Test.txt";File file = new File(fileName);if(file.exists()){System.out.println("File is present");}elseSystem.out.println("File is missing");}}   Here the File.exists method is used. This returns a true if a file with the specified name exists at the path specified, otherwise it returns a false. If you run this code, you will get the following output (Assuming there is a file on C drive called test.txt): File is present

How to find the count of each character in a String in Java

In this blog post, I will be demonstrating how you can determine the number of occurrences of each character in a String. Consider the following code snippet: package learnjava.strings;import java.util.HashMap;import java.util.Map;public class CountCharactersDemo {public static void main(String[] args) {String str = "Hello World";Map&lt;Character,Integer&gt; characterCountMap = new HashMap&lt;Character,Integer&gt;(); //map stores each character and its countchar[] charsInStr = str.toCharArray();for(char c:charsInStr){if(characterCountMap.containsKey(c)){ //if the character is already in the map, just increment its countint count = characterCountMap.get(c);count++;characterCountMap.put(c, count);}else{ //if the character is not in the map, add it to the mapcharacterCountMap.put(c, 1);}}for(Character c:characterCountMap.keySet()){System.out.println("Character "+c+" occurs "+characterCountMap.get(c));}}}   The  characterCountMap defines a Has

How to convert a String to lowercase in Java

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

How to check if a number is a prime number

In this blog post, I will be demonstrating how you can check if a number is a prime number. Consider the following code snippet: public static void main(String[] args) {Scanner scanner= new Scanner(System.in);System.out.println("Input the number to be checked:");int num=scanner.nextInt();boolean isPrime = true;if (num == 0 || num == 1) {isPrime = false;}else{for (int i = 2; i &lt;= num / 2; i++) {if (num % i == 0) {isPrime = false;break;}}}if(isPrime)System.out.println("The number "+num+" is prime!");elseSystem.out.println("The number "+num+" is not prime!");}   The code first accepts a number from the user. It then checks if the number is 0 or 1, both of which are not prime numbers. It then iterates from 2 till the number/2. It checks if the remainder obtained after dividing the input number with the current index of the for loop is 0. If so, the number is not prime and so it exits the for loop. So if you run the code for the value

How to remove a character from a String via Java

In this blog post, I will be explaining how you can remove a character from a String via Java. Consider the following code snippet: package learnjava.strings;public class RemoveCharacterDemo {public static void main(String[] args) {String str = "Hello World";String modifiedStr = str.replace("l", "");System.out.println(modifiedStr);}}   There is a method String.replace . This replaces the specified character with another character. Here, we are replacing the character ‘l’ with an empty character. So effectively, it is like removing the character “l”. When you run this code, you will get the following output: Heo Word