Private in Java: Why should you always keep fields and methods private?

Making members private in Java is one of best coding practice. Private members (both fields and methods) are only accessible inside the class they are declared or inside inner classes. private keyword is one of four access modifier  provided by Java and its a most restrictive among all four e.g. public, default(package), protected and private. Though there is no access modifier called package, rather its a default access level provided by Java. In this Java tutorial we will see why should we always make members of class by default as private and answer to one of popular Java interview question can override private methods in Java.

This article is in continuation of my earlier post on Java e.g. 10 Object Oriented Design principles Java programmer should know and 10 best practice to follow while writing comments. If you haven’t read them already you may find them interesting and worth reading.

How to Compare two String in Java - String Comparison Example

String comparison is a common programming task and Java provides several way to compare two String in Java. String is a special class in Java, String is immutable and It’s used a lot in every single Java program starting from simple test to enterprise Java application. In this Java String compare tutorial we will see different ways to compare two String in Java and find out how they compare String and when to use equals() or compareTo() for comparison etc.

Here are four examples of comparing String in Java
1) String comparison using equals method
2) String comparison using equalsIgnoreCase method
2) String comparison using compareTo method
4) String comparison using compareToIgnoreCase method

We will see String compare Example using each of this method in example section, before that let's get some theory:

This article is in continuation of my earlier post on String  e.g. Difference between String and StringBuffer in Java and How to replace String in java using regular expression etc. If you haven’t read them already you may find them useful and worth reading.

How to loop ArrayList in Java - List Itrator Traversal Code Example

Looping ArrayList in Java or Iteration over ArrayList is very similar to looping Map in Java. In order to loop ArrayList in Java we can use either foreach loop, simple for loop or Java Iterator from ArrayList. We have already touched iterating ArrayList in 10 Example of ArrayList in Java and we will see here in detail. We are going to see examples of all three approaches in this ArrayList tutorial and find out which one is clean and best method of looping arraylist in Java. Before start writing an example for loop in ArrayList let's think why do we need to iterate, traverse or loop an ArrayList if it’s based on index and backed by Array. If we know the index of element than we can directly get that particular element from ArrayList but if you want to print all elements of arraylist and do some operation one by one on each of them, only looping or traversing will help you.

This article is in continuation of my earlier tutorial on ArrayList e.g. How to sort ArrayList in Java on descending order and How to convert Array to ArrayList in Java. If you haven’t read them already then you may find them useful and interesting.

Difference between start and run method in Thread – Java Tutorial

Why do one call start method of thread if start() calls run() in turn" or "What is difference by calling start() over run() method in java thread" are two widely popular beginner level multi-threading interview question. When a Java programmer start learning Thread, first thing he learns is to implement thread either overriding run() method of Thread class or implementing Runnable interface and than calling start() method on thread, but with some experience he finds that start() method calls run() method internally either by looking API documentation or just poking around, but many of us just don’t care at that time until its been asked in Java Interview. In this Java tutorial we will see What is difference between calling start() method and run() method for starting Thread in Java.

This article is in continuation of my earlier post on Java multi-threading e.g. Difference between Runnable and Thread in Java and How to solve Producer Consumer problem in Java using BlockingQueue. If you haven’t read them already you may find them interesting and useful.

Why use PreparedStatement in Java JDBC – Example Tutorial

PreparedStatement in Java is one of several ways to execute SQL queries using JDBC API. Java provides Statement,
PreparedStatement and CallableStatement for executing queries. Out of these three, Statement is used for general purpose queries, PreparedStatement is used for executing parametric query and CallableStatement is used for executing Stored Procedures. PreparedStatement is also a popular topic in java interviews. Questions like Difference between Statement and PreparedStatement in Java and How to prevent SQL Injection attacks in Java are popular java interview questions. In this Java JDBC tutorial we will see why should you use use PreparedStatement in Java, What are the major advantages of using PreparedStatement in Java and how PreparedStatement prevents SQL Injection attacks in Java.

This article is in continuation of my earlier post on database and java like 4 tips to improve performance of Java application with database and Difference between truncate and delete in SQL.If you haven’t read  them already you may found  those tutorial useful and interesting.

SimpleDateFormat in Java is not Thread-Safe Use Carefully

SimpleDateFormat in Java  very common and used to format Date to String and parse String into Date in Java but it can cause very subtle and hard to debug issues if not used carefully because DateFormat and SimpleDateFormat both are not thread-safe and buggy. call to format() and parse() method mutate state of DateFormat class and should be synchronized externally in order to avoid any issue. here are few points which you should take care while using SimpleDateFormat in Java:

How to find file and directory size in Unix with Example - Linux tutorial

How to find size of directory in unix
Finding file size or directory size in Unix and Linux is not very difficult but if you came from windows background than it may sounds difficult to you because you need to remember unix commands for file and directory size. This is a common complain from windows user when they exposed to Unix operating system be it Linux or Solaris. but In my opinion having commands for doing things is more powerful because you can write powerful scripts for removing large files or taking backup of directories in unix which is not possible with GUI based operating systems like Windows. In this unix command tutorial we will see how to find size of file and directory in unix, how to find large files in unix, how to find disk space in file system and some other file and directory related stuff.

This article is continuation of my earlier post on Unix e.g. 10 Example of grep command in Unix, 10 example of chmod command in unix and How to sort files and directory in Unix using sort command. If you haven’t read them already, You may find them useful and interesting.

Difference between transient and volatile keyword in Java

Surprisingly "Difference between transient and volatile keyword in Java" has asked many times on various java interview. volatile and transient are two completely different keywords from different areas of Java programming language. transient keyword is used during serialization of Java object while volatile is related to visibility of variables modified by multiple thread during concurrent programming. Only similarity between volatile and transient is that they are less used or uncommon keywords and not as popular as public, static or final. Anyway its good to know what transient keyword do in Java or how to use volatile keyword in Java. In this article we will couple of points between volatile and transient which can be used to answer this interview question.

How to fix (Access is denied)

Earlier my impression was that (Access is denied) comes when you try to read a text or binary file for which you don't have permission from Java program but this can also come while you are using jar command. jar command internally use class to open any jar or war file which can throw (Access is denied). I was trying to see contents of war file which was created using recent build when I stumble upon this error, see the exact command below:

test@dev454:war-store/target jar -tvf maven-eclipse-web-demo maven-eclipse-web-demo (Access is denied)
        at Method)

Spring Security Example Tutorial - How to limit number of User Session in Java J2EE

Spring security can limit number of session a user can have. If you are developing web application specially secure web application in Java J2EE then you must have come up with requirement similar to online banking portals have e.g. only one session per user at a time or no concurrent session per user. You can also implement this functionality without using spring security but with Spring security its just piece of cake with coffee :). Spring Security provides lots of Out of Box functionality a secure enterprise or web application needed like authentication, authorization, session management, password encoding, secure access, session timeout etc. In our spring security example we have seen how to do LDAP Authentication in Active directory using spring security and in this spring security example we will see how to limit number of session user can have in Java web application or restricting concurrent user session.

What is Daemon thread in Java and Difference to Non daemon thread - Tutorial Example

Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks. Difference between Daemon and Non Daemon(User Threads)  is also an interesting multi-threading interview question, which asked mostly on fresher level java interviews. In one line main difference between daemon thread and user thread is that as soon as all user thread finish execution java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution. As soon as last non daemon thread finished JVM terminates no matter how many Daemon thread exists or running inside JVM. In this java thread tutorial we will see example of Daemon thread in Java and some more differences between Daemon and non daemon threads.

How to get ServletContext in Servlet, JSP, Action class and Controller.

How to get ServletContext in Servlet, jsp, spring controller or struts action class is common need of any Java web developer. As ServletContext is an application wide object and used to store variables in global scope, getting a reference of ServletContext is pretty important. Every web application can have only one ServletContext though they can have multiple ServletConfig objects. In this article we will see :

How to get Servlet Context inside Spring MVC Controller?
How to find  Servlet Context inside Struts Action class?
How to get Servlet Context inside JSP File?
How to find Servlet Context inside HttpServlet Class?

Why character array is better than String for Storing password in Java

Why character array is better than String for storing password in Java was recent question asked to one of my friend in a java interview. he was interviewing for a Technical lead position and has over 6 years of experience.Both Character array and String can be used to store text data but choosing one over other is difficult question if you haven't faced the situation already. But as my friend said any question related to String must have a clue on special property of Strings like immutability and he used that to convince interviewer. here we will explore some reasons on why should you used char[] for storing password than String.

character array over string storing password javaThis article is in continuation of my earlier interview question post on String e.g. Why String is immutable in Java or How Substring can cause memory leak in Java, if you haven't read those you may find them interesting.Here are few reasons which makes sense to believe that character array is better choice for storing password in Java than String:

JDBC - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver Solution

"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"  is a frequent Exception Java programmer face while writing JDBC connectivity code for mysql, especially if you are trying to establish JDBC connection to mysql database first time. we have touched base on ClassNotFoundException in mysql on our earlier articles how to resolve ClassNotFoundException in Java and here we will see in detail what causes "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver" and how to fix com.mysql.jdbc.Driver error in Java.

Mixing static and non static synchronized method - Java mistake 2

Using static and non static synchronized method for protecting shared resource is another Java mistake we are going to discuss in this part of  our series “learning from mistakes in Java”. In last article we have seen why double and float should not be used for monetary calculation , In this tutorial we will find out why using static and non static synchronized method together for protecting same shared resource is not advisable.

I have seen some times Java  programmer mix static synchronized method and instance synchronized method to protect same shared resource. They either don't know or failed to realize that static synchronized and non static synchronized method lock on two different object which breaks purpose of synchronizing shared resource as two thread can concurrently execute these two method breaking mutual exclusive access, which can corrupt status of mutable object or even cause subtle race condition in Java or even more horrible deadlock in java.

What is GET and POST method in HTTP and HTTPS Protocol

GET and POST method in HTTP and HTTPS are two most popular methods used to transfer data from client to server using  HTTP(Hyper Text Transfer Protocol)  protocol. Both GET and POST can be used to send request and receive response but there are significant difference between them. Difference between GET and POST in HTTP or HTTPS is also a popular interview question in JSP and any web programming interview. Since HTML is independent of any web server technology like Java, ASP or PHP and HTTP is core protocol in space of internet, importance of clear understanding of GET and POST method can not be ignored. In this tutorial we will What is GET HTTP Request, What is POST HTTP Request, When to use GET and POST HTTP method and finally some difference between GET and POST method in HTTP protocol.

What is Static and Dynamic binding in Java with Example

Static and dynamic binding  in Java are two important concept which Java programmer should be aware of. this is directly related to execution of code. If you have more than one method of same name (method overriding) or two variable of same name in same class hierarchy it gets tricky to find out which one is used during runtime as a result of there reference in code. This problem is resolved using static and dynamic binding in Java. For those who are not familiar with binding operation, its process used to link which method or variable to be called as result of there reference in code. Most of the references is resolved during compile time but some references which depends upon Object and polymorphism in Java is resolved during runtime when actual object is available. In this Java tutorial we will see some examples of static and dynamic binding and differences between static binding and dynamic binding in Java.

10 points on finalize method in Java – Tutorial Example

finalize method in java is a special method much like the main method in java. finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc. The main issue with finalize method in Java is it's not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example, an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called it's not guaranteed it will be immediately collected. Because of above reason it makes no sense to finalize method for releasing critical resources or perform any time critical activity inside finalize. It may work in development in one JVM but may not work in other JVM.

What is Encapsulation in Java and OOPS with Example

Encapsulation in Java or object oriented programming language is a concept which enforces protecting variables, functions from outside of class, in order to better manage that piece of code and having least impact or no impact on other parts of a program due to change in protected code. Encapsulation in Java is visible at different places and Java language itself provide many constructs to encapsulate members. You can completely encapsulate a member be it a variable or method in Java by using private keyword and you can even achieve a lesser degree of encapsulation in Java by using other access modifiers like protected or the public. The true value of encapsulation is realized in an environment which is prone to change a lot and we know that in software requirements changes every day at that time if you have your code well encapsulated you can better manage risk with a change in requirement. Along with abstraction in java and polymorphism in Java, Encapsulation is a must know the concept. In this java tutorial,  we will see How to use encapsulation in Java, advantage and disadvantage of Encapsulation and various design patterns and real life problems which make use of Encapsulation object oriented concept. If you are looking for a quick guide on both OOPS and SOLID design principle in Java then you may find 10 Object Oriented Design principles Java programmer should know  interesting.

10 example of chmod command in UNIX Linux

chmod command in UNIX or Linux is used to change file or directory permissions. This is one of many UNIX basic commands which a UNIX or Linux user must be familiar with. In this UNIX command tutorial we will see how to change file permissions using chmod command, what are file permissions in UNIX, how to change permissions of directory and sub-directory using UNIX chmod command and finally how to create executable files in UNIX using chmod command. Before going directly into examples of chmod command let's spend few minutes on understanding file permissions in UNIX and why do we need to change file permissions etc.

Top 10 EJB Interview Question and Answer asked in Java J2EE Interviews

10 EJB Interview Questions and Answer from my collection of interview questions. I have been sharing interview questions on various topics like Singleton interview question, serialization interview question and most recently Spring interview questions. No doubt these questions are very important from performing better in J2EE and EJB interviews but also they open new path for learning as you may find some concept new even while revising your knowledge in EJB. EJB interviews has always been tough because its difficult to find people who has hands on experience on Enterprise Java Beans (EJB) and most of the guys either have worked only on sample project and not aware of critical functionalities like distributed transaction management, container managed persistence and various other services which EJB provides. We will see some of those in 10 interview questions on EJB. I have provided sample answers for these EJB questions but I suggest you to google and learn more in depth if time permits you.

If you are working in Java technology then you may find 10 multi-threading interview questions asked in Investment banks and Struts interview questions interesting .

java.lang.UnsatisfiedLinkError: no dll in java.library.path - Cause and Solution

"Exception in thread "main" java.lang.UnsatisfiedLinkError: no dll in java.library.path" is one of the frustrating error you will get if your application is using native libraries e.g. .DLL in Windows or .SO files in Linux. Java loads native libraries at runtime from either PATH environment variable or location specified by java.library.path system property depending upon whether your Java program is using System.load() or java.lang.System.loadLibarray() method to load native libraries. If Java doesn't find them due to any reason it throws "java.lang.UnsatisfiedLinkError: no dll in java.library.path". Some of the most common UnsatisfiedLinkError is "java.lang.UnsatisfiedLinkError: no ocijdbc10.dll in java.library.path" and "java.lang.UnsatisfiedLinkError: no ocijdbc11.dll in java.library.path", which comes when you try to connect to Oracle 10g or 11g database from Java program using OCI JDBC driver.

How to read Properties File in Java – XML and Text Example Tutorial

Reading and writing properties file in Java is little different than reading or writing text file in Java or  reading xml files in Java using xml parsers like DOM because Java provides special provision to properties file. For those who are not familiar with Properties file in java, It is used to represent configuration values like JDBC connectivity parameter or user preferences settings and has been a primary source of injecting configuration on Java application.  Properties file in Java is a text file which stores data in form of key and value, key being known as property. Java allows you to read value of property by providing its name which makes it easy to access configuration settings. Two popular example of properties file are often used to store database connection settings like URL, username and password and file which settings for java logging using log4j. There are also many frameworks which uses Java properties file like Struts, Spring, Displaytag etc. Another advantage of using properties file is that you can represent data either in xml format or in properties format. xml format will be particularly useful if you are sharing configuration or settings with some external tool which understands only xml. In this article we will see how to read and write into Properties file in Java on both xml and text format.

How to add or list certificates from keystore or trustStore in Java - Keytool Example

How to add certificates on keystore in Java is primary questions when you start working on SSL connection and simple answer is keytool utility in Java is used to add or list Certificates into keystore. SSL is the industry standard for secure communication between two parties e.g. client and server. SSL offers two benefits, it encrypts data transferred between client and server to make it hard for someone to access and understand in between and SSL also verify the identity of two parties in communication and certificates are used for that purpose. SSL Setup in Java comes during various process e.g. Setting up SSL on tomcat, configuring messaging over SSL or JDBC over SSL are some examples of task where you need to deal with keyStore, certificates, and trustStores.

10 Object Oriented Design Principles Java Programmer should know

The Object-Oriented Design Principles are the core of OOP programming, but I have seen most of the Java programmers chasing design patterns like Singleton pattern, Decorator pattern or Observer pattern, and not putting enough attention on learning Object-oriented analysis and design. It's important to learn basics of Object-oriented programming like Abstraction, Encapsulation, Polymorphism, and Inheritance. But, at the same time, it's equally important to know object-oriented design principles, to create the clean and modular design. I have regularly seen Java programmers and developers of various experience level, who either don't hear about these OOP and SOLID design principle, or simply doesn't know what benefits a particular design principle offers, or how to apply these design principle in coding. 

java.lang.NoSuchMethodError: main Exception in thread "main"

How to solve java.lang.NoSuchMethodError: main Exception in thread "main"

java.lang.NoSucMethodError comes when Java code tries to call a method which is not existed on a class, this could be either static or non static method. most common manifestation of java.lang.NoSuchMethodError is running a class which doesn't have main method in Java. In this article we will see what is "java.lang.NoSuchMethodError: main Exception in thread "main"" , Why does java.lang.NoSuchMethodError comes and how to solve java.lang.NoSuchMethodError in Java.

How to create and execute JAR file in Java – Command line Eclipse Netbeans

Creating JAR file in java from command prompt is always been little tricky for many of us even if IDE like Netbeans and Eclipse provide support to export java program as JAR file simply because we don’t create jar often and not familiar with manifest file or jar command as whole. JAR file in Java is a kind of zip file which holds all contents of a Java application including Class files, resources such as images, sound files and optional Manifest file. JAR stands for Java Archive and provides a platform independent deliverable for java programs, libraries and framework. you can execute same jar file in any operating system e.g. Windows 7, windows 8, Macintosh or Linux. Apart from platform independence and standard delivery method jar file also provides compression of contents which results in faster download if you are downloading java program from internet specially in case of mobile devices where you install Java program by OTA. In this article we will some JAR command examples and learn how to create and execute jar file, how to view contents of jar file from command prompt and Eclipse and Netbeans.

How to format Decimal Number in Java - DecimalFormat Example

We often need to format decimal numbers in Java like formatting numbers upto 2 decimal places or 3 decimal places or we want to introduce leading zeros in front of numbers. Thankfully Java programming language provides many different ways to format numbers in Java like either using Math.round() or setScale() from BigDecimal but caveat is that they also do rounding of numbers i.e. 1.6 will be rounded on 2.0 if we use Match.round(). If we are just interested in formatting decimal numbers upto n decimal digits than DecimalFormat is way to go. java.text.DecimalFormat descends from NumberFormat and provides dynamic way of formatting numbers in Java. While creating instance of DecimalFormat you can pass an String pattern which describes on which format decimal number should be formatted and than DecimalFormat.format() method will do the rest for you. In this Java tutorial we will see how to format a decimal number in 2 decimal place, format upto 3 decimal place, using comma to separated 3 digits etc.