Visitor Design Patterns In Java Examples Tutorial

Hello guys, if you want to learn Visitor design pattern in Java then you have come to the right place. Earlier, I have covered many design patterns like Decorator, Strategy, State, Composite, Adapter, Command, Template, Factory, Observer and even few Microservice patterns like SAGA and Database per service and in this article, I will talk about Visitor Design Pattern and how to implement in Java. You will learn things like what is Visitor design pattern, what problem it solves, what are pros and cons of Visitor design pattern, when to use Visitor pattern as well as any alternatives of Visitor Pattern in Java. I will also show you a real world example of Visitor design pattern, but, before we get to the 5 best examples that will teach you all about design patterns in Java, let me tell you a little bit more about what it really is.

Difference between 32-bit vs 64-bit JVM in Java?

Hello Java Programmers, if you want to learn Java virtual Machine in-depth and wondering what is the difference between a 32-bit and 64-bit JVM and which one should you use and why? then you have come to the right place. Earlier, I have shared the best JVM books and online JVM courses and in this article, I am going to talk about 32-bit vs 64-bit JVM and their pros and cons. This is also a common Java interview question for beginners and intermediate Java programmers. I have tried to answer this question to the point that's why this article is a short but informative one. You will find out what they are, how they are different, how much heap size, and the pros and cons of each of them. 

10 Examples Of Mockito + JUnit in Java for Unit Testing

Hello guys, if you are writing unit test in Java then you know how difficult it is to write especially if you are testing a class which is dependent upon other class like HttpClient and you cannot connect to actual server. At those time, a mocking library like Mockito comes to rescue. Given the increased focus on unit testing and code coverage, I have find myself using Mockito more and more along with JUnit in last a couple of years but I haven't written many articles on Mockito yet but that is chaging now. In this article, I am going to share 10 essential Mockito examples which I belive every Java programmer should know. But, before we get to the 10 best examples that will teach you everything there is to know about Mockito in Java, let me tell you a little bit more about what it really is.

How to convert Java 8 Stream to Array and ArrayList in Java? Example Tutorial

It's relatively easy to convert a Stream to an array in Java 8 by using the toArray() method of java.util.Stream class. By using this method you can convert any type of Stream to a corresponding array like a Stream of Strings can be converted into an array of String, or a Stream of integers can be converted into an array of Integers. The Stream.toArray() method is also overloaded, the one which doesn't take any parameter returns an Object[] which might not be very useful, particularly if you want to convert Stream of T to an array of T.

Array length vs ArrayList Size in Java [Example]

One of the confusing parts in learning Java for a beginner to understand how to find the length of array and ArrayList in Java? The main reason for the confusion is an inconsistent way of calculating the length between two. Calling size() method on arrays and length, or even length() on ArrayList is a common programming error made by beginners. The main reason for the confusion is the special handling of an array in Java.  Java native arrays have built-in length attribute but no size() method while the Java library containers, known as Collection classes like ArrayList<>, Vector<>, etc,  all have a size() method. 

How to create an ArrayList from Array in Java? Arrays.asList() Example Tutorial

One of the common problems faced by junior and less experienced Java developers is converting an array to ArrayList e.g. they are getting an array from somewhere in their code and then want to create an ArrayList out of that so that they can add more elements and use other library methods which operate with ArrayList or List. The simplest way to convert an array to ArrayList is by using the Arrays.asList() method, which acts as a bridge between Collection classes and array data structure. This method returns a List that contains elements from an array. 

Is it Possible to add static or private methods in Java interface?

Can you add a static or private method in an interface in Java? or is it possible to add a private or static method in Java interface? or can you add a non-abstract method on an interface in Java? are a couple of popular Java interview questions which often pop up during telephonic interviews. Well, prior to Java 8, it wasn't possible to add non-abstract methods in Java but nowadays you can add non-abstract static, default, and private methods in the Java interface. The static and default methods were supported as part of interface evolution in Java 8 and you can add private methods on an interface from Java 9 onwards.

10 Examples Of Scanner Class In Java

Hello guys, if you want to learn about Scanner class in Java, one of the most popular class to read input from command prompt or console then you have come to the right place. In this article, I will explain how to read input from command prompt, what is Scanner class and how you can use Scanner class to read various data types like String, int, long, boolean directly from console. You must have heard about famous nextInt(), nextDouble() methods which can read integer and double values from command prompt or console. But, before we get to the 10 best examples that will teach you everything you need to know about scanner class in Java, let me tell you a little bit more about what it really is.

What is Diamond operator in Java? Example Tutorial

Hello guys, if you are reading Java code and come across closed angle bracket with a diamond like shape and wondering what they are and what they do then you have come to the right place. They are known as Diamond operator in Java and I will explain you what they are and where should you use them in this article. The Diamond operator is a relatively new operator in Java which was first introduced in JDK 7  to improve type inference and reduce boilerplate Java coding. It is denoted with a closed angle bracket that resembles the shape of a diamond (<>) and that's why it's called the Diamond operator. If used correctly it can reduce typing and boilerplate coding in Java and result in much cleaner and readable code especially when you use Generics.  

Parallel Array Sorting in Java - Arrays.parallelSort() Example

There are multiple ways to sort array in Java. For example, you can use Array.sort() method to sort any primitive or object array in Java but Java 8 presents a new feature that is useful to sort array’s elements. It can implemented by using the package “java.util.Arrays” which represents several methods to sort the array. The biggest benefit is that parallel array sorting is that its faster than any other sorting method due to usage of multithreading conception. So multiple threads can break the array into parts and work simultaneously to sort it. 

Difference between Thread vs Process in Java? Example

Thread and Process are two closely related terms in multi-threading and the main difference between Thread and Process in Java is that Threads are part of the process. i.e. one process can spawn multiple Threads. If you run a Java program in UNIX based system e.g. Linux and if that program creates 10 Threads, it still one process and you can find that by using ps -ef | grep identifier command which is one of the most popular use of grep command in UNIX, Where identifier is UNIX the text which can be used as regular expression to find that Java process.

Difference between yield and wait method in Java? Answer

Yield vs wait in Java
The yield and wait methods in Java, though both are related to Threads,  are completely different to each other. The main difference between wait and yield in Java is that wait() is used for flow control and inter-thread communication while yield is used just to relinquish CPU to offer an opportunity to another thread for running. In this Java tutorial, we will what are differences between the wait and yield method in Java and when to use wait() and yield(). What is important for a Java programmer is not only to understand the difference between the wait() and yield() method but also to know the implications of using the yield method. 

10 points about wait(), notify() and notifyAll() in Java Thread?

If you ask me one concept in Java that is so obvious yet most misunderstood, I would say the wait(), notify(), and notifyAll() methods. They are quite obvious because they are one of the three methods of a total of 9 methods from java.lang.Object but if you ask when to use the wait(), notify() and notfiyAll() in Java, not many Java developers can answer with surety. The number will go down dramatically if you ask them to solve the producer-consumer problem using wait() and notify()

How to run Threads in an Order in Java - Thread.Join() Example

Hello Java programmers, if you need to execute multiple threads in a particular order, for example if you have three threads T1, T2 and T3 and we want to execute them in a sequence such that thread 2 starts only when first thread finishes it job and T3 starts after T2, but with multithreading in Java there is no guarantee. Threads are scheduled and allocated CPU by thread scheduler which you cannot control but you can impose such ordering by using Thread.join() method. When you start a thread its not guaranteed that which thread will start first and whether the thread started first will finish first, if your application's logic depends upon a sequence its better to do all those operation on single thread because if all code is confined to one thread it will execute in order they were written provided some JIT optimization.

10 Examples Of Lombok Libarary In Java

Hello guys, if you are working in Java then you may have heard about Lombok, one of the popular Java library which alleviate pain Java developer by removing boiler plate code and provides improve development experience. Yes, Lombok can remove a lot of code like the one you put on equals() and hashCode, getter and setter, toString and constructor and much more. This means you can just create a Java class with fields much like Record of Java SE 17 and you can use it like a fully functional Java class, I mean you can create object using constructor or Builder and you can get and set values using gettter and setter, only difference is they are not visible in code. But then you may be thinking how does it work? Where does it get those getter and setter? why not compiler raise any problem?

10 Examples Of Ternary Operator In Java

Hello guys, if you are wondering how to use ternary operator in Java then you have come to the right place. Ternary operator is a great operator and you can use ternary operator to replace a simple if-else statement. Since ternary operator allows you to write code in one line, its much more succinct and readable and that's what many Java developer love it, including me. In the last article, I shared 10 example of XOR bitwise operator in Java and in this article, I am going to share 10 example of ternary operator in Java so that you not only know what is ternary operator but also you can use it effectively to write better Java code. But, before we get to the 10 best examples that will teach you everything there is to know about ternary operators in Java, let me tell you a little bit more about what it all really is.

10 Examples of XOR Operator In Java

Hello guys, if you are wondering what does the XOR operator do in Java then you have come to the right place. XOR is a bitwise operator in Java, much like AND and OR and its very important because you can perform XOR operation using this operator. If you don't remember, XOR return true if the two values which you are comparing are different like one is true and other is false or vice-versa but it returns false or 0 if both operands are same like both are true or both are false. By using this technique you can solve many coding problems as you can check if the bits you are comparing is same or not. In this article, I will show you different example of XOR operator in Java after that you will understand this operator better. 

How to convert float, double, String, Map, List to Set, Integer, Date in Java - Example Tutorial

Hello guys, converting one data type to another, for example String to Integer or String too boolean is a common task in Java and every Java programmer should be familiar with how to convert common data types like String, Integer, Long, Float, Double, Date, List, Map, Set, to each other. In the past, I have shared several tutorial where I have shown you how to carry out such conversion in Java and this article is nothing but a collection of such tutorial so that you can learn all of that knowledge in one place. You can also bookmark this page as I will be adding new data type conversion tutorials into this list as and when I write them, and you can also suggest if you struggle to convert a particular type to another and I will try to cover them here. 

Spring HelloWorld Example in Java Annotations and Autowiring [Tutorial]

Spring framework has gone a couple of releases since I last share the Spring hello world example with XML configuration. In this article, I am going to explain to you how to create a Spring hello world example with Spring 4.2 release and by using Annotation for dependency injection and autowiring. So no more XML files to specify bean dependencies. It's a simple program that shows how you can use the Spring framework to create Services that are loosely coupled. The example will show you the basic concept of dependency injection by creating a simple Java application that greets the user.

Top 50 Java Collections + Generics Interview Questions and Answers for 1 to 3 Years Experienced

Hello guys, if you are preparing for Java interviews and looking for frequently asked Java generics and Java Collections interview questions then you have come to the right place. In the past, I have shared 130+ core java questions and best courses for Java interviews and In this article, I am going to share the best Java collection and Java Generics interview questions to crack the interview. You will not only get exposure to frequently asked questions but also learn very useful Java topics that will help you in your day job.  By the way, Java Collection and Generic are very important topics for Java Interviews. They also present some of the hardest questions to a programmer when it comes to interviews, especially Generics.

Difference between HashMap vs IdentityHashMap in Java? Example

The IdentityHashMap is one of the lesser known Map implementations from JDK. Unlike general purposes Map implementations like HashMap and LinkedHashMap, it is very special and its internal working is quite different than HashMap. The main difference between IdentityHashMap and HashMap in Java is that the former uses the equality operator (==) instead of the equals() method to compare keys. This means you need the same key object to retrieve the value from IdentityHashMap, you cannot retrieve values by using another key that is logically equal to the previous key. 

How to set the logging level in Spring Boot application.properties - Example Tutorial

Hello guys, if you are wondering how to set the logging level on spring boot then you have come to the right place. In the past, I have shared the best Spring Boot courses and free courses to learn Spring MVC and in this article, I will share how to set logging levels like DEBUG and INFO in Spring Boot.  How do we configure the logging level of our Spring boot application is one of the questions that arise when developing a large application. Because we need to trace errors, warnings, informational data when running our application and to this, Spring has introduced Spring boot logging configurations. 

How to use @ResponseBody and @RequestBody in Spring MVC and REST? Example Tutorial

Hello guys, if you are wondering what is @RequestBody and @ResponseBody annotation in Spring MVC and Spring Boot then you have come to the right place. Earlier, I have told you about the @RestController annotation and in this article, I am going to explain to you what is RequestBody and ResponseBody annotation, how to use them, and when to use them with simple examples. While working with REST API, we may need to bind HTTP requests and response bodies with the domain object. To bind this, we use we can use the @ResponseBody and @RequestBody annotations in Spring MVC. 

How to use lsof command in Linux? Example Tutorial

Hello guys, If you want to learn how to use lsof command in Linux then you have come to the right place. In the last few article, I talk about find, grep, mailx, crontable and du command in Linux and in this article I am going to talk about another useful Linux command, the lsof command. The lsof  command lists open files and that's why its named lsof. This command is very important for server side developer and IT support people who need to check which file is held by which process and find the deleted files which are hogging memory etc. It act as a useful debugging and troubleshooting tool in Linux.

How to Synchronize HashMap in Java? Collections.synchronizedMap() Example Tutorial

Hello guys, if you have used HashMap class in Java before than you will know that HashMap is not synchronized, which means you cannot use it on multi-threaded Java programs without external synchronization. In other words, if you share an instance of HashMap between multiple threads, where each of them is either adding, removing or updating entries then it's possible that HashMap may lose its structure and not behave as expected. In simple words, exposing HashMap to multiple threads can corrupt the Map and you may not able to retrieve the data you want. If you have read my earlier article about HashMap, you know that during re-sizing its possible that HashMap exposed to multiple threads, may end up in an infinite loop. 

Difference between WeakHashMap , IdentityHashMap, and EnumMap in Java?

Hello guys, if you are wondering what is the difference between WeakHashMap, IdentityHashMap, and EnumMap in Java then you are at  the right place. In last article, we have seen difference between HashMap, TreeMap, and LinkedHashMap in Java and in this article we will difference between WeakHashMap, EnumMap, and IdnetityHashMap in Java. Apart from popular implementation like HashMap and LinkedHashMap, java.util.Map also has some specialized implementation classes e.g. IdentifyHashMap which uses == instead of equals() method for comparing keys, WeakHashMap which uses WeakReference to wrap the key object and a key/value mapping is removed when the key is no longer referenced from elsewhere, and EnumMap where keys are Enum constants. 

Java HashMap keySet() , entrySet and values() Example - Tutorial

The java.util.Map interface provides three methods keySet(), entrySet() and values() to retrieve all keys, entries (a key-value pair), and values. Since these methods directly come from the Map interface, you can use them with any of the Map implementation classes e.g. HashMap, TreeMap, LinkedHashMap, Hashtable, ConcurrentHashMap, and even with specialized Map implementations like EnumMap, WeakHashMapand IdentityHashMap. In order to become a good Java developer, it's important to understand and remember key classes of Java API like Java's Collection framework.

What is static and instance Method in Java? Example Tutorial

Hello guys, if you have trouble understanding what is static method in Java and how to use it then you are at the right place. In this article, I will share everything I have learned bout static method in my 20 years of Java experience. Static methods are one of the important programming concepts in any programming language but unfortunately, it is also the most misunderstood and misused one. Talking about Java, almost all programmers know that. static methods belong to the class and non-static methods belong to the objects of the class, but hardly all of them understand what it means. That's why this is one of the popular weed-out questions on programming interviews. 

How to use Lambda Expression and method reference in Java? Example Tutorial

Hello guys, if you are wondering what is lambda expression and method reference in Java then you are at the right place. Earlier, I have shared 10 Stream API examples and in this article, I will share everything I know about Lambda expression with you. The Lambda expression is one of the most important features of Java 8 which has opened a whole new dimension of programming paradigm in Java. It is the feature which made the Functional Programming possible in Java because now you can pass the code to a function to execute as opposed to an object. You might be a bit surprised but if you look from a developer's point of view, it is nothing but a way to pass your code to a method in Java.

Composite Design Pattern Example in Java and Object Oriented Programming

Hello guys, if you are wondering how to use Composite design pattern in Java then you are at the right place. Composite design pattern is another object oriented design pattern introduced by Gang of Four in there timeless classic book Design pattern : Elements of Reusable software. Composite pattern as name suggest is used to compose similar things together, like similar objects. It implements an interface and also contains other objects which implements the same interface, also known as containee. One of the best example of Composite pattern from Java standard library is Swing's container classes e.g. Panel, which not only are Components by themselves, but also contains other components like JButton, Label, JTable etc. 

6 Advanced Comparator and Comparable Examples in Java 8

The JDK 8 release has completely changed the way you compare objects and sort them in Java. The new features of the Java 8 language e.g. lambda expression and method reference have made it easier to implement both Comparator and Comparable interface, as you don't need an Anonymous class for inline implementation. Now, you can create Comparators in just one line by using lambdas and method reference as we'll see in this article. Other features like providing default and static methods on interfaces have also made a huge difference when it comes to Comparator. They helped Java API designers to redesign and evolve existing interfaces, which wasn't possible earlier without breaking existing clients of those interfaces.

How to convert String to long in Java? Example

You can parse a String literal containing valid long value into a long primitive type using parseLong() and valueOf() method of java.lang.Long class of JDK. Though there is a couple of difference between valueOf() and parseLong() method e.g. valueOf() method return a Long object while parseLong() method return a Long object, but given we have autoboxing in Java, both method can use for parsing String to create long values. In the last article, you have learned how to convert a Long value to a String in Java, and in this tutorial, you will learn the opposite, i.e. how to parse a String to a long value in Java

How to convert String to Double in Java and double to String with Example

There are three ways to convert a String to double value in Java, Double.parseDouble() method, Double.valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time. Out of all these methods, the core method is parseDouble() which is specially designed to parse a String containing floating-point value into the Double object. Rest of the methods like valueOf() and constructor uses parseDouble() internally. This method will throw NullPointerException if the string you are passing is null and NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters.

How to check if two String variables are same in Java? equals(), equalsIgnoreCase() and == operator Example

There are multiple ways to compare two strings alphabetically in Java e.g. == operator, equals() method or compareTo() method, but which one is the best way to check if two strings are equal or not? Programmers often confused between == operator and equals() method, and think that comparing strings using == operator should be faster than equals() method, and end up using that. Though they are not completely wrong, they often missed the point that == operator is designed to compare object equality, not String equality, which is actually defined in equals()method and compare Strings alphabetically. 

How to Read User Input and Password in Java from command line? Console Example

Hello guys, if you are wondering how to take user input from command prompt in Java like username and password then don't worry. Java provides several utilities like Scanner and BufferedReader to read input from command prompt in Java. Java 6 added a new utility class for reading input data from character based devices including command line. java.io.Console can be used to read input from command line, but unfortunately, it doesn't work on most of the IDE like Eclipse and Netbeans. As per Javadoc call to System.Console() will return attached console to JVM if it has been started interactive command prompt or it will return null if JVM has been started using a background process or scheduler job.

How to replace characters and substring in Java? String.replace(), replaceAll() and replaceFirst() Example

One of the common programming tasks is to replace characters or substring from a String object in Java. For example, you have a String "internet" and you want to replace the letter "i" with the letter "b", how do you that? Well, the String class in Java provides several methods to replace characters, CharSequence, and substring from a String in Java. You can call replace method on the String, where you want to replace characters and it will return a result where characters are replaced. What is the most important point to remember is that the result object would be a new String object? 

5 Difference between Hashtable vs HashMap in Java? Answer

Hashtable vs HashMap in Java
Hashtable and HashMap are two hash-based collections in Java and are used to store objects as key-value pairs. Despite being hash-based and similar in functionality there is a significant difference between Hashtable and HashMap and without understanding those differences if you use Hashtable in place of HashMap then you may run into series of subtle programs which is hard to find and debug. Unlike the Difference between ArrayList and HashMap, Differences between Hashtable and HashMap are more subtle because both are similar kinds of collections. Before seeing the difference between HashMap and Hashtable let's see some common things between HashMap and Hashtable in Java.

How to write a Parameterized Method in Java using Generics? Example

Hello guys, if you are wondering how to write a parameterized method in Java using Generics then you are at right place. Earlier, I  have shared Complete Java Generics tutorial as well as popular Generics Interview Questions and in this article, I will teach you how to write a parameterized method using Generics in Java step by step. A method is called a generic method if you can pass any type of parameter to it and it will function the same like it allows the same logic to be applied to different types. It's known as a type-safe method as well.

10 Examples of nslookup command in Linux and Windows

Hello guys, if you are wondering what is nslookup command and how to use in Linux and Windows then you are at right place. In the past, I have shared examples of crontab, find, grep, netstat, and curl command and In this article, I will share 10 different examples of nslookup command, each using its different powerful command line option to give you the tool you need to deal with networking  related queries. I often use nslookup command to convert a given IP address to hostname or a given hostname to IP address. For example, when I see an IP address in our log file and want to find which host that request is coming from, I use nslookup. 

Difference between Polymorphism vs Inheritance in Java and Object Oriented Programming - Example

Programmers often confused among different object-oriented concepts e.g. between Composition and Inheritance, between abstraction and encapsulation, and sometimes between Polymorphism and Inheritance. In this article, we will explore the third one, Polymorphism vs Inheritance. Like in the real world, Inheritance is used to define the relationship between two classes. It's similar to the Father-Son relationship. In object-oriented programming, we have a Parent class (also known as the superclass) and a Child class (also known as the subclass). Similar to the real world, a Child inherits Parents' qualities, like its attributes, methods, and code. 

How to convert ArrayList to Comma Separated or Delimited String in Java - Spring Example

Some time we need to convert ArrayList to String in Java programming language in order to pass that String to stored procedure, any method or any other program. Unfortunately Java collection framework doesn't provide any direct utility method to convert ArrayList to String in Java. But Spring framework which is famous for dependency Injection and its IOC container also provides API with common utilities like method to convert Collection to String in Java. You can convert ArrayList to String using Spring Framework's StringUtils class. StringUtils class provide three methods to convert any collection e.g. ArrayList to String in Java, as shown below:

10 Examples of head and tail command in Linux

Hello guys, if you are wondering how to use head and tail command in Linux then you have come to the right place. Both head and command are great tool to view content from files in Linux. As the name suggest, "head" is used to view the top portion of the file and "tail" is used to see the file content from bottom. For example when you say "head data.json" then it will display first 10 lines of the file and when you say "tail data.json" then it will display last 10 lines of the file. As a Java developer, I find myself using tail more often than head while checking logs. As you can use tail to see the last few lines of the log file and you can also use tail -f application.log to see the logs rolling in real time. I often use this command to track request and see what application is doing at a particular time. 

Difference between JDK and JRE in Java Platform

Java Platform offers JRE and JDK to run Java programs. JRE stands for Java runtime environment and JDK stands for Java development kit. JRE is meant for normal users, who wants to run Java program in their computer. JRE is normally used to run Java programs downloaded over internet e.g. Java Applets and Java Desktop application built using AWT and Swing. The main difference between JRE and JDK, comes from the fact that they are different tools. JDK is created for Java programmers and contains tools required for Java programming, like javac for compiling Java source files to .class files. Without JDK, you can not create Java applications and programs. 

Difference between this and super keywords in Java

this and super are two special keywords in Java, which is used to represent current instance of a class and it's super class. Java Programmers often confused between them and not very familiar with there special properties, which is asked at various core Java interviews. A couple of questions, which I remember about this and super keyword is  that, Can we reassign this in Java?  and the difference between this and super keyword in Java. Do you want to try that? Ok, I am not giving the answer now, rather I will let you know the answer at the end of this post. 

10 Examples of more and less command in Linux

Hello guys, if you have been working on Linux then you must have come across less and more commands. They are the most popular command to view content of a file, particular log file in Linux.  In fact, less is my favorite command to see the logs in Linux because you can open both normal log file as well as a gzip or compressed log file using less command for viewing. It's also very well designed and fast command and you easily open even large log files using less which you would otherwise struggle to open using Windows tool like Notepad or Notepad++.  In the past, I have shared examples of lsofcurl, netstat, and ssh command and in this article, I am going to share common examples of both less and more command.

How to use String literals in switch case in Java? Example Tutorial

Switch Statements are not new for any Programmer, it is available in C, C++, Java and in all major programming language. The switch statement in Java allows you to a clear, concise, and efficient multiple-branch statement without lots and lots of messy if-else statements. But Java Switch and case statement have a limitation, you cannot use String in them. Since String is one of the most used classes in Java, and almost every program, starting from Hello World to a complex multi-tier Java application uses them, it makes a lot of sense to allow them in the Switch case. In Java 6 and before, the values for the cases could only be constants of integral type e.g. byte, char, short, int, and enum constants. If you consider Autoboxing then you can also use the corresponding wrapper class like Byte, Character, Short, and Integer.

10 Example of SSH Command in UNIX and Linux

SSH command stands for Secure Shell which allows user to securely login into remote machine. If you are working on network on UNIX and Linux machine, SSH command is your friend because with ssh in UNIX you can not easily navigate from one host to other. SSH Command or SSH client in UNIX not only allow you to login into remote host but also allows you to execute command on remote machine without going to into remote server. which is quite convenient while writing bash scripts or getting general information about server like uptime of remote server. This article shows examples of ssh command in UNIX and different usage of ssh in UNIX along with basic concept of ssh command.

10 Examples of wget command in Linux

Hey there! Today's article will explain the "wget" command in Linux and 10 different examples. If you are a Linux user, this is a command you will commonly use almost every now and then.

WHAT IS THE "WGET" COMMAND?

Wget emanated from the GNU project. It is a non-interactive tool used to download files from the web. It is called non-interactive because it does not need human interaction before it operates. the user does not have to log on before it works.  This means that it works in the background. Wget supports HTTP, HTTPS, FTPS,SFTP.

"wget" is very beneficial in such a way that, If you are downloading a file and unfortunately the network connection becomes unstable and slow, It keeps retrying until the file is fully recovered. 
Before you can start using "wget" command, you must have installed that on your Linux. if not It won't recognize that command if you type it.

10 Examples of netstat command in Linux and UNIX

Hello guys, if you are wondering how to check which application is listening to a particular port or wondering what are active UDP and TCP post on your machine then don't worry, you can use the "netstat" command in Linux to get these details. Along with lsof and curl, netstat is another important utility command which I use on almost daily basis as a server side Java developer. Since most of the application I create follow client server model and most of them run on Linux, I often use netstat command during post implementation checks and troubleshooting during any production issue.

How to Fix java.lang.ArrayIndexOutOfBoundsException in Java [Solution]

The ArrayIndexOutOfBoundsException, also known as java.lang.ArrayIndexOutOfBoundsExcepiton is one of the most common errors in Java programs. It occurs when a Java program tries to access an invalid index like. an index that is not positive or greater than the length of an array or ArrayList. For example, if you have an array of String like String[] name = {"abc"} then trying to access name[1] will give java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 error because index 1 is invalid here. Why? because the index in the Java array starts with zero rather than 1, hence in an array of just one element the only valid index is index zero. 

10 Examples of ls command in Linux

Hey there, if you are wondering how to check what inside a directory or just wondering what is ls command in Linux and how to use it to list files then you have come to the right place. Earlier, I have shared examples of df command, du command, find command, grep command, tar command and chmod command and in  today’s article we shall be looking at 10 different examples of ls command in Linux. But before then you would need the meaning of ls and what it is being used for. The goal of this article is to get you comfortable with different things you could do with the ls command and this articles would show you in details how to use it, when to use it and it’s benefits. Let’s go

10 Reasons of java.lang.NumberFormatException in Java - Solution

The NumberFormatException is one of the most common errors in Java applications, along with NullPointerException. This error comes when you try to convert a String into numeric data types e.g., int, float, double, long, short, char, or byte. The data type conversion methods like Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), and Long.parseLong() throws NumberFormatException to signal that input String is not valid numeric value. 

3 ways to solve Eclipse - main class not found error

Like many Java programmers who get "Error: Could not find or load main class Main" while running the Java program in Eclipse, I was also getting the same problem recently. The "Error: Could not find or load main class" was rendered me puzzled even after my 10+ years of experience with Java errors and exceptions. Whenever I run my Java application either by Run configurations or right-click and run as a Java program, I get an annoying popup complaining about "could not find or load the main class, the program will exit". 

Can You declare Constructor inside Servlet Class in Java? Answer

Yes, Servlet can have Constructor, it's perfectly legal but it's not the right way to initialize your Servlet. You should use the init() method provided by the Servlet interface to initialize the Servlet. If you remember, Servlet's are special in the sense that they are instantiated by the container and managed by the container. A servlet container like Tomcat creates a pool of multiple Servlets to serve multiple clients at the same time.

10 Examples of ps command in Linux

In Today's article, You will be learning  about the "ps" command in Linux and  our objectives are: 

To know what Ps stands for, how it works with numerous options, and provide different examples and the usage of it.

PS stands for processes status. Basically used to list the processes that are running at the moment. As we all know that when a task needs to be implemented it must follow or have a process. There are different options you could use with it and this gives you a different result. 

How to fix "variable might not have been initialized" error in Java? Example

This error occurs when you are trying to use a local variable without initializing it. You won't get this error if you use an uninitialized class or instance variable because they are initialized with their default value like Reference types are initialized with null and integer types are initialized with zero, but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If the compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.

[Solved] Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg'

Hello guys, if you are getting "Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg'" error or just Error: could not open 'jvm.cfg and wondering what to do and how to solve this error then you have come to the right place. I will show you how I solved this error and how you can use my tips to solve your error as well. A couple of weeks back I updated my laptop to Windows 10 but after trying for one day, I reverted back to Windows 8.1. Everything was alright until I open Eclipse, which was throwing "Error: could not open 'C:\Program Files\Java\jre8\lib\amd64\jvm.cfg', as soon as I launch it. It was quite bizarre because everything was fine earlier. 

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java [Solution]

Problem: You are getting Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger error in your Java application, which is using Log4j Logger either directly or indirectly via some popular Java framework like Spring, Struts or Hibernate.

Cause : Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger error indicates that JVM is not able to found org.apache.log4j.Logger class in your application's CLASSPATH. The simplest reason for this error is the missing log4j.jar file. Since org.apache.log4j.Logger class belongs to this JAR file, if it's not available at run-time then your program will fail. 

How to Avoid/Fix ConcurrentModificationException while looping over ArrayList in Java [Example]

Apart from the NullPointerException and ClassNotFoundException, ConcurrentModificationException is another nightmare for Java developers. What makes this error tricky is the word concurrent, which always mislead Java programmers that this exception is coming because multiple threads are trying to modify the collection at the same time. Then begins the hunting and debugging, they spent countless hours to find the code which has the probability of concurrent modification. While in reality, ConcurrentModficationException can also come in a single-threaded environment. 

java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject [Solved]

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject error means that your Java program needed a class called org.apache.xmlbeans.XmlObject but JVM is not able to find that in your application's CLASSPATH. You can see the actual cause of this error is "java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject". The most probable reason for this error could be a missing JAR file. In order to solve this error, you need to first find out which JAR file this class belongs. If you look at the error message it's clearly saying that it's from xmlbeans package, it means this class belongs to XMLBeans library.

'javac' is not recognized as an internal or external command [Solution]

'javac' is not recognized as an internal or external command, operable program, or batch file error comes when you try to compile a Java source file using the javac command like javac Helloworld.java but your PATH is not set properly. It means that the javac.exe executable file, which exists in the bin directory of the JDK installation folder is not added to the PATH environment variable. You need to add the JAVA_HOME/bin folder in your machine's PATH to solve this error. You cannot compile and run a Java program until your add Java into your system's PATH variable

How to Fix java.lang.OufOfMemoryError: Direct Buffer Memory

Java allows an application to access non-heap memory by using a direct byte buffer. Many high-performance applications use a direct byte buffer, along with a memory-mapped file for high-speed IO. And, while the ByteBuffer object is small itself, it can hold a large chunk of non-heap memory, which is outside of the Garbage collection scope.  This means the garbage collectors can not reclaim this memory. It is often used to store large data like order or static data cache. Since generally, your program allocates the large buffer e.g. size of 1GB or 2GB, you get "Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory" error, when you try to allocate memory by running the following code

java.lang.OutOfMemoryError: Java heap space : Cause and Solution

So you are getting java.lang.OutOfMemoryError: Java heap space and run out of ideas on what to do, especially if you are a user of any Java application and not the programmer or developer, this could be a tricky situation to be in. I receive lots of emails from Minecraft user ( a popular Java game), along with junior developers who are using Tomcat, Jetty, Untow, JBoss, WebSphere, Android user, who uses Android apps and several other Swing-based Java desktop application user complaining about java.lang.OutOfMemoryError: Java heap space in their Mobile or Laptop. 

How to fix "class, interface, or enum expected" error in Java? Example

If you have ever written Java programs using Notepad or inside DOS editor, then you know that how a single missing curly brace can blow your program and throw 100s of "illegal start of expression" errors during compilation of Java Programmer. I was one of those lucky people who started their programming on DOS editor, the blue window editor which allows you to write Java programs. I didn't know about PATH, CLASSPATH, JDK, JVM, or JRE at that point. It's our lab computer where everything is supposed to work as much as our instructor wants. 

How to fix "illegal start of expression" error in Java? Example

The "illegal start of expression" error is a compile-time error when the compiler finds an inappropriate statement in the code. The java compiler, javac, compile your source code from top to bottom, left to right and when it sees something inappropriate at the start of an expression, it throws an "illegal start of expression" error. The most common reason for this is a missing semi-colon. You might know that every statement in Java ends with a semicolon, but if you forget one, you won't get an error that there is a missing semi-colon at the end of the statement because the compiler doesn't know the end.

[Solved] java.lang.unsupportedclassversionerror Unsupported major.minor version 55.0, 57.0, 60.0, 61.0 Error in Java? Examples

The java.lang.unsupportedclassversionerror unsupported major.minor version 60.0 error comes in Java environment when you compile your Java file in a higher Java version like Java 16 and then trying to run the same Java program in lower Java version like Java 11. Java is backward compatible, I mean you can run your Java 15 binary or JAR into Java or JRE 16 but vice-versa is not true. You can not run a Java program that is compiled in a higher Java version into lower JRE. class file version changes between every Java version and class file generated by the javac command of Java 16 installation is not appropriate for JRE of Java 15 Installation.

What is Subquery in SQL? Correlated and Non-Correalted SubQuery Example

If you are wondering what is correlated and non-correlated subqueries in SQL and looking to understand the difference between them then you have come to the right place. Earlier, I have shared free SQL and Database courses and today, I am going to talk about one of the common SQL concepts of subqueries, a query inside another query. There are two types of subqueries in SQL, correlated subquery and self-contained subquery, also known as nested, non-correlated, uncorrelated, or simply a subquery. The main difference between them is, self-contained (non-correlated) subqueries are independent of the outer query, whereas correlated subquery has a reference to an element from the table in the outer query.

Difference between ISNULL() and COALESCE() function in SQL? Example

Even though both ISNULL() and COALESCE() function provides alternate values to NULL in T-SQL and Microsoft SQL Server e.g. replacing NULL values with empty String, there are some key differences between them, which is often the topic of SQL Server interview. In this article, you will not only learn the answer to this question but also learn how to use COALESCE and ISNULL function properly. One of the main differences between them is that  COALESCE() is a standard SQL function but ISNULL() is Microsoft SQL Server-specific, which means it's not guaranteed to be supported by other database vendors like Oracle, MySQL, or PostgreSQL.

Difference between table scan, index scan, and index seek in SQL Server Database? Example

Hello guys, a good understanding of how the index works and how to use them to improve your SQL query performance is very important while working in a database and SQL and that's why you will find many questions based upon indexes on Programming Job interviews. One of such frequently asked SQL questions is the real difference between table scan, index scan, and index seek? which one is faster and why? How does the database chooses which scan or seek to use? and How you can optimize the performance of your SQL SELECT queries by using this knowledge. In general, there are only two ways in which your query engine retrieves the data, using a table scan or by using an index.

How to find Nth Highest Salary in MySQL and SQL Server? Example LeetCode Solution

Nth Highest Salary in MySQL and SQL Server - LeetCode Solution
---------------------------------------------------------------
Write a SQL query to get the nth highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

10 Examples of df Command in Linux and UNIX

Hello, In Today’s article we shall be talking about the df command in Linux. The objectives of this article are: What is the df command, and what does it mean? How is it used? I shall be providing 10 different examples or scenarios for it and when to use it

What does df mean?

The meaning of df in Linux is disk-free or disk file system. Which is used to display the file system in the likes of total storage space, available storage space and etc.

Df command in Linux is a command or syntax in Linux that you doing away with it is almost impossible

You may begin to wonder or ask Why or When do You need to use it?

How to use recursive grep command in Linux and UNIX? grep -iR Example tutorial

Hello guys, one of the most common tasks while working on programming projects is finding files containing some specific text like you have your application deployed in the Linux server, and you are migrating your database from one server to another. Now, you want to file all config files and scripts which are referencing your old database using the hostname or IP address, so that you can replace them with an alias. Well, you should always use an alias to connect to the database or any other system, but sometimes it happens you have to use a hostname. Anyway, how do you find all those files containing hostname in your Linux machine? Well, the grep command is here to help you.

Difference between Soft Link vs Hard Links in Linux/UNIX? Answer

Hello guys, if you are looking to find out the difference between a soft link and a hard link in Linux then you have come to the right place. Earlier, I have shared the free Linux courses for beginners and in this article, I am going to explain the soft links and hard links in UNIX operator systems like Linux. There are two types of links in the UNIX system, hard links and soft links, also known as symbolic links or symlinks. Though both points to some other source, there is a lot of difference between them. The most important difference is that a hard link is a direct pointer to the inode of the original file. If you compare the original file with the hard link there won't be any differences between them. 

6 Linux command Examples and One liners Every Programmer Should Remember

Hello guys, Linux is an important skill for any developer or DevOps engineer becuase most of the server-side applications run on Linux boxes. At least you should be familiar with essential Linux commands like ls, cat, ps, top, find, grep, awk, sort, uniq, kill, xargs, curl, lsof, etc. I have shared a lot of useful Linux tutorials in this blog and you can take a look at them to learn about those commands in detail. Today, I am going to share some of the useful Linux one-liners you can use in your day-to-day life. These one-liners are either example of one single command or multiple commands used together to do a certain task like finding duplicate rows in a text file or counting how many times each IP address appear in a text file, much like group by clause of SQL.

How to Find large Files and Directories with size in Linux and UNIX? find + du command Example Tutorial

One of the common problems while working in Linux is finding large files to free some space. Suppose, your file system is full and you are receiving an alert to remove spaces or if your host is run out of space and your server is not starting up, the first thing you do is find the top 10 largest files and see if you can delete them. Usually, old files, large Java heap dumps are good candidates for removal and freeing up some space. If you are running Java applications like core Java-based programs or web applications running on Tomcat then you can remove those heap dump files and free some space, but the big question is how do you find those? How do you know the size of the biggest file in your file system, especially if you don't know which directory it is? We'll try to find answers to some of those questions in this article.

How to send Email with Body and Attachment from Linux Machine? mutt and mailx command Example

One of the common tasks for programmers working in a Linux machine is to send emails and transfer files from Linux machine to Windows machine. While there are utilities like WinSCP which you can use to transfer files between Windows and Linux machine, I generally found using mailx command much easier, especially when you don't have WinSCP or any other utility. But, apart from transferring files between Linux and Windows, there are many more scenarios where you need to send emails from Linux machine, for example, your Java applications are running on Linux like RHEL 5 or RHEL 6 version and you need to send a report of all the clients connecting to your application.

How to set JAVA_HOME and PATH in Linux? Example

Hello guys, welcome to the world of Java application programming. One of the hardest things to mater is not any feature but environment-specific details which nobody teaches. To bridge that gap, I am going to cover a couple of very important environment variables like PATH and JAVA_HOME.  The JAVA_HOME environment variable points to the JDK installation directory and is used by many Java tools and applications like TomcatMaven, Eclipse, NetBeans or IntelliJIDEA, etc. to figure out Java executables as they need Java for running. 

How to backup and load Cron Jobs from a File in Linux and UNIX? Crontab Command Example

Hello guys, If you have been using Linux for some time then you might know about cron jobs. They are the scheduler that can be used to automatically start processes in a Linux box. I have worked on many projects which used cron jobs to start the Java process and environment daily or weekly basis. They are similar to Autosys when it comes to scheduling jobs but cron is a Linux command as opposed to Autosys which is a separate application altogether. In Linux, the crontab command is used for scheduling and automating jobs or processes. You can also use it for loading cron jobs from a file, listing existing cron entries, and editing them. It manages the cron table that is used by the cron daemon in Linux to execute the cron jobs.

How to find swap space and usage in Solaris? Swap Command Example

Swap space in Solaris or any UNIX host is a vital disk space that is used for the swapping process from physical memory (RAM)  to disk. Virtual memory allows a process to run even if physical memory gets full by using swap space (which is located on your hard disk) to swap out memory pages that are not currently in use. This is a very important concept which every programmer and Linux user should know. It is even more important if you are working in IT support or as a system admin because if swap space is full then swapping will fail and no new process will be able to start. 

How to send Logging Messages to SysLog using Log4j2 SysLogAppender in Linux ? Java Example

Sometimes you may want to route your log messages to Syslog in UNIX-based environment like Linux. Since logger allows multiple appenders, you can print the same log messages to a log file, console, and route it to Syslog at the same time. In order to send log messages to Syslog using log4j2, you need to make some changes in your log4j2.xml file. This change is to include the Syslog appender and configure that, once you do that you also need to enable TCP or UDP reception by editing rsyslog.conf file. For faster transmission you can choose UDP protocol and configure a port number on which your Syslog is listening, In our example, Syslog is listening on port 618. Let's see the complete step-by-step guide to configure Syslog logging in log4j logger.

5 Ways to implement Singleton Design Pattern in Java? Examples

Hello guys, While Singleton is anti pattern nowadays and dependency injection is better choice as it helps unit testing, its good to know about Singleton pattern, especially if you are in the business of maintaining large and old code base. This article introduces the singleton design pattern and its 5 implementation variations in Java. You will learn different ways to implement a singleton pattern and understand the challenges of creating a singleton class, like thread-safety issues and serialization issues.

How to use Strategy Design Pattern in Java? Example Tutorial

Hello guys, you might have heard about it, Can you tell me any design pattern which you have used recently in your project, except Singleton? This is one of the popular questions from various Java interviews in recent years. I think this actually motivated many Java programmers to explore more design patterns and actually look at the original 23 patterns introduced by GOF. The Strategy design pattern is one of the useful patterns you can mention while answering such a question. It's very popular, and there are lots of real-world scenarios where the Strategy pattern is very handy. 

10 Examples Of du Command in Linux

 Here, we shall be looking at another command in Linux. The” du” command. Before giving the examples you can use with it I will be explaining the du itself, What is being used for and When to use it, and How to use it

So Firstly, What is DU or What does the command mean?

The full meaning of du is Disk usage. This helps in planning and maintaining the file’s space. The command is used to keep track of any files or directories that are taking up too many spaces in the hard disk drive. Now we shall be taking the examples one after the other.

3 Examples of for loop in Linux and Bash Script [Tutorial]

Hello guys, if you want to learn how to use for loop in bash or Linux then you have come to the right place. Earlier, I have shared free Linux courses and free bash scripting courses, and today, I am going to share three simple examples of using for loop in Linux.  If you are a Programmer, Software Engineer, or System Administrator working in a UNIX or Linux environment, then you will probably find the shell 'for' loop to be a handy tool for automating simple command-line tasks. This is the single command which has helped me a lot while doing production support and performing operational tasks. 

10 ways to Quit/Exit from Vim Editor in Linux/UNIX? Examples

Hello guys, if you are stuck inside VIM editor and looking for a way to come out then you have come to the right place. In the past, I have shared the free Linux courses and today, I am going to talk about Vim or VI editor, one of the most important tools for people working in Linux. You might not know but many developers struggle to get out of commands like Vim and telnet. I can say that because there was a time when I spend a good amount of time coming out from the telnet window.

10 Example of ps -ef command in Linux and UNIX

Hello guys, It's been a long time since I wrote about the Linux command in this blog. In my last article, I have shared free Linux courses for beginners which many of you guys have liked, that's why I am writing another post on Linux, this time about the "ps" command.  If you have worked on a Linux machine then you are likely to be familiar with the "ps" command. The "ps" command is used to check the process status. It stands for "process statistics" and you can use the ps command to see all the processes and find things like PID which can be used to interact with the process. For example, you can kill a process by passing PID to kill command in Linux as shown here.  

10 Examples of df Command in Linux

Hello, In Today’s article we shall be talking about the df command in Linux. The objectives of this article are: What is the df command, and what does it mean? How is it used? I shall be providing 10 different examples or scenarios for it and when to use it

What does df mean?

The meaning of df in Linux is disk-free or disk file system. Which is used to display the file system in the likes of total storage space, available storage space and etc.

Df command in Linux is a command or syntax in Linux that you doing away with it is almost impossible

You may begin to wonder or ask Why or When do You need to use it?

How to use PreparedStatement in Java - JDBC Example Tutorial

PreparedStatement is used to execute specific queries that are supposed to run repeatedly, for example, SELECT * from Employees WHERE EMP_ID=?. This query can be run multiple times to fetch details of different employees. If you use PreparedStatement like above then the database assists in query preparation, which is faster and more secure. Such kinds of queries are compiled, and their query plans are cached at the database side every time you execute it, you will get a faster response as opposed to using simple queries via Statement object, like SELECT * from Employees WHERE EMP_ID + emp_id.