Strings in Switch case - Java 7 Tutorial and Example

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 statement. But Java Switch and case statement has a limitation, you cannot use String in them. Since String is one of the most used class in Java, and almost every program, starting from Hello World to complex multi-tier Java application uses them, it makes a lot of sense to allow them in 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 corresponding wrapper class e.g. Byte, Character, Short, and Integer.

How to count Vowels and Consonants in Java String Word

Java Program to count Vowels and Consonants in a word using JavaIn this article, we will take on a popular programming exercise of counting vowels in a word. You need to write a Java program to count how many vowels in a String, which is entered from the command prompt. It's similar to the program of counting the occurrence of characters in a String, in fact, it's a special case, where you need to count occurrences of all vowels, which includes five characters a, e, i, o and u. We will further use Scanner to get input from the user, as shown in this article. Though I have put down all code inside the main method for quick testing, if you are asked to write this program as part of your homework or during the interview, better writing a method called public int countVowels(String word) and put the logic of counting vowels there. That's a better coding style than writing everything inside the main method.

Difference between RegularEnumSet and JumboEnumSet in Java

The difference between RegularEnumSet and JumboEnumSet in Java was asked in a recent Java interview to one of my friend, unfortunately, he hasn't explored this topic well and couldn't answer this question precisely, but he made sure to learn about EnumSet after that. When he discussed this topic to me, I really liked it because, despite the usefulness of EnumSet and it's fast implementation, not many developers know about it, despite being mentioned in Java classic Effective Java. This makes me write this post, where we will mainly discuss a couple of differences between RegularEnumSet and JumboEnumSet in Java, but we will also touch base upon some of the important properties of EnumSet.

Best Way to Compare Two Strings in Java Alphabetically with 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. When you compare two strings using the == operator, it may or may not return true, especially if you are expecting result based on contents. It will only return true if both reference variables are pointing to the same objects, like in the case of interned string or String literals. Otherwise, it will return false, even if the content of String remain same.

How to Iterate over Array in Java 1.5 using foreach loop Example

Though there are many ways to loop over Array in Java, including classical for loop, while loop with length counter, nothing matches the elegance of Java 1.5 foreach loop, which makes iteration super easy and super cool. When we need to iterate through each element of an array and has to perform some operation on them e.g. filtering, transformation or simply printing, foreach loop comes to its full glory. There is not much difference between traditional for loop and Java 1.5 foreach loop, except that former has counter and condition, which is checked after each iteration, on the other hand, foreach loop does this task under the hood. But this elegance comes at the cost of control, as you can not control iteration using counter, so depending upon your need, you have to choose between them. 

Can we Override Private Method in Java? Inner Class?

No, you cannot override private methods in Java, private methods are non-virtual in Java and access differently than non-private one. Since method overriding can only be done on derived class and private methods are not accessible in a subclass, you just can not override them. By the way, one more possibility of overriding private methods in an inner class, since private methods are accessible in an inner class, and that’s why it is one of the tricky java interview questions. Anyway, this will also not work because private methods are bonded during compile time and only Type (or Class) is used to locate a private method. For Example in below code where it looks like that nested class is an overriding private method, but if you call privateMethod() with a type of super class but the object of the subclass, it will only execute privateMethod() declared in the parent class, which is not exactly method overriding. 

Best Way to Iterate Over Each Entry of HashMap in Java

What is the best way to Iterate over HashMap in Java? and not just HashMap, but any Map implementation including old Hashtable, TreeMap, LinkedHashMap and relatively newer ConcurrentHashMap, is a frequently asked query from Java Programmers, with some experience under his belt. Well, when it comes to choosing between different ways to iterate over Map in Java, it's you need, which plays an important role. For example, if you just want to iterate over each entry of HashMap, without modifying Map, then iterating over entry set using Java 1.5 foreach loop seems the most elegant solution to me. The reason, it just two lines of code using a foreach loop and Generics, and by getting the set of entries, we get key and value together, without further searching in HashMap. This makes it also the fastest way to loop over HashMap in Java. 

Difference between Comparator and Comparable in Java - Interview Question

Comparator and Comparable are two interfaces in Java API, which is used to compare two objects in Java. Though both are used for comparison there are some differences between them, a major difference between Comparable and Comparator is that former is used to define the natural ordering of object e.g. lexicographic order for java.lang.String, while later is used to define any alternative ordering for an object.  The main usage of java.lang.Comparable and java.util.Comparator interface is for sorting a list of objects in Java. For example to sort a list of Employee by their Id, we can use Comparable interface and provide additional sorting capability, we can define multiple comparators e.g. AgeComparator to compare the age of the employee, SalaryComparator to compare the salary of employees etc.  This brings another important difference between Comparator and Comparable interface in Java, you can have only one ordering via Comparable e.g. natural ordering while you can define multiple Comparator for alternative ordering as discussed above.

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 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, 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 there Mobile or Laptop. For users, there is not much they can do, but to restart the application. When you restart your application, previous memory get reclaimed by OS and it's a fresh start for your application, but you may lose data, which is not saved, especially if you are playing Java games like Minecraft.

Purging Tables in SQL Using TRUNCATE and DELETE command

While working with the database we often need to delete data, sometimes to create more space, sometimes just remove all data to make table ready for next day's transaction or sometimes just selectively remove stale data. SQL provides a couple of handy commands to remove data e.g. truncate, delete and drop. The last one is bit different because instead of removing data it just deletes table. What is the difference between truncate and delete command in SQL or when to use truncate vs delete is one of the most frequently asked SQL interview question? Knowledge of this critical command is not only useful for interviews, but also while working with a big database with a large number of records, especially while writing SQL scripts for purging transaction databases. An Incorrect choice of SQL command can result is either very slow processor can even blow up the log segment; if too much data needs to be removed and log segment is not enough. That's why it's critical to know when to use truncate and delete command in SQL

Difference between == and === Equal Operator in JavaScript

In one of the recent JavaScript interview for a Java web development position, one of my readers was asked this questions, What is the difference between comparing variables in JavaScript using "==" and "===" operator?  My reader got shocked because he was from Java background and doesn't have great exposure to JavaScript, though he was pretty much familiar with some JavaScript function, event handling, and some jQuery tricks, he wasn't aware of subtle details of JavaScript. He did the right think, politely said that he is not aware of the difference between == and === operator. Though It did not affect his interview performance much, he was keen to know about this as soon as he finished his interview. He asked to me as well, and that's the reason of this post. In one word, main difference between "==" and "===" operator is that formerly compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn't allow that, because it not only checks the value but also type of two variable, if two variables are not of the same type "===" return false, while "==" return true. 

15 Java Enum Interview Questions for Developers with Answers

Enum was introduced in Java 5 and since then it's been very popular among Java developers and widely used in different Java applications. Since Enum in Java is much more versatile than Enum in C or C++, it also presents lots of interesting use cases, couple of them, we have seen in my article 10 ways to use Enum in Java. But, despite being so popular, many Java programmer are still not aware of functionality provided by Enum and subtle details of using Enum in Java code. I realized this fact, when couple of my readers asked me some of the questions e.g. Can Enum implement an interface in Java or Why we can not create Enum instances outside of Enum, stating that these has been asked to them in there Java Interviews. This motivates me to put together a list of frequently asked question in Java Enum, which not only helps to do well in Interviews, but also open new path for learning. As I had said before, lot of time a question in Interviews, makes you to take a topic more seriously than otherwise, which is not a bad thing, and given the power and facilities offered by Java Enum, I think it's high time to get master of it.

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. As I said in the first line, the main difference between this and super in Java is that this represents current instance of a class, while super represent current instance of the parent class. Now where does this and super variables used, well you might have seen examples of calling one constructor from other i.e. constructor chaining, that's achieved by using this and super keyword? 

How get method of HashMap or Hashtable works internally in Java

In this article, I am revisiting a couple of interesting question related to the internal working of HashMap in Java, mostly asked senior Java developers, ranging from 4 to 6 and up to 8 years of experience. I did cover lot of these questions from HashMap, ranging from thread-safety to race conditions, in my post about internal working of Java HashMap, but I thought to revisit two of those questions, How get method of HashMap or Hashtable works internally in Java and What happens if two different keys return the same hashCode, how do you return value from HashMap in that case. These are the question, which is highly popular in investment banking domain, and preferred choice of interviewer, while interviewing experienced Java professional. 

How to Convert Array to Set and List in Java with Example

In this example we will learn how to convert an String array to Collection, Set or List in Java. This knowledge of converting array to Collection can be really useful to any Java developer, as most of legacy code tend to use array, which means you either need to pass them your input as array or they return result as array. Since newer Java code prefer Collection over array, which they should, because of flexibility offered by Collection classes, we often need to convert Array into different Collection classes e.g. List, Set or simply Collection. I have shown couple of techniques for converting array to arraylist, which equally applicable, when it comes to convert Array to List in Java. In this article, we will go couple of steps further and not only learn converting array to List, but also array to Set and array to Collection in Java. Well, it's only one method, which you need to know, Arrays.asList(), which accepts an array and return a List, later you can convert this List into any other Collection, by using copy constructor provided by Collection classes.

Difference between Deep and Shallow Copy in Java Object Cloning

Shallow copy and deep copy is related with cloning process so before go into the deep of shallow and deep copy we need to understand what is clone in java. Clone is nothing but the process of copying one object to produce the exact object, which is not guaranteed. We all know in Java object is referred by reference we can not copy one object directly to another object. So we have cloning process to achieve this objective. Now one question arises in mind why we need this process so the answer is whenever we need a local copy of the object to modify the object in some method but not in method caller.  So we can define Cloning as “create a copy of object  .I think now we are somehow clear about the cloning but there  is more to it depending on how we are doing this copy, we can divide cloning into two types.
  • Shallow Copy
  • Deep Copy
Before going into the deep of shallow and deep copy we need to understand how we achieve cloning in java.

Reading Input and Password in Java using - Java File Tutorial

Java 6 added a new utility class for reading input data from character based devices including command line. 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. Anyway, not only provides a way to read input from command prompt or Console but also reading passwords from the console without echoing it. Console.readPassword() method reads password and returns a character array and password is masked during entering so that any peeping tom can not see your password while you are entering it.

How to Override Equals, HashCode and CompareTo method in Java

Though modern IDE like Eclipse, IntelliJ or Netbeans allows you to generate equals, hashCode and compareTo methods for your value classes, it's equally important, you know how to do that by hand. By overriding equals and hashcode method by yourself, you know how they work, what kind of errors you can get, and most importantly, it's expected form you, as a Java programmer in any core Java interview. More often, you would see a coding question in Java, which ask you to override equals(), hashcode(), compare() and compareTo() methods for a value class. Since I have already shared some tips on How to override compareTo method in Java, and couple of example of writing your own Comparator in Java, here I am sharing another simple example of overriding equals and hashCode methods. If you know rules of overriding equals and hashCode, you might know that, whenever you override equals, you must have to override hashCode, otherwise your object will not behave properly on various collection classes e.g. Map or Set, which uses equals, compareTo, hashCode to implement there invariants e.g. Set implementations should not allow any duplicates.

How to Split String in Java using Regular Expression

String class provides split() method to split String in Java, based upon any delimiter, e.g. comma, colon, space or any arbitrary method. split() method splits the string based on delimiter provided, and return a String array, which contains individual Strings. Actually, split() method takes a regular expression, which in simplest case can be a single word. split() is also overloaded method in java.lang.String class and its overloaded version take a limit parameter which is used to control how many times pattern will be applied during splitting process. if this limit is positive n, then the pattern will be applied at most n-1 times, if it's negative or zero then split operation is applied any number of time. For example, if we split String "First,Second,Third" on comma and provide limit as 2 then pattern will run one time, and split() will return String array with 2 Strings, "First" and "Second,Third". 

How to replace characters on String in Java

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 letter "b", how do you that? Well, 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? Since String is immutable in Java, every time you perform an operation on String either replacement or removing white space from String, it generates a new String object. The good thing about these methods is that they support regular expression, which means you can specify a pattern and all the characters which match the pattern will be replaced. 

Difference between notify and notifyAll in Java - Thread

wait, notify, and notifyAll methods are used for inter-thread communication in Java. wait() allows a thread to check for a condition, and wait if the condition doesn't meet, while notifying() and notifyAll() method informs waiting for a thread for rechecking condition, after changing the state of a shared variable. One good example of how to wait and notify method works is Producer consumer problem, where one thread produces and wait if the bucket is full; and another thread consumes and waits if the bucket is empty. Both Producer and Consumer thread, notify each other as well. Producer thread notifies consumer thread after inserting an item in the shared queue, while consumer thread notifies producer, after consuming item from the queue. Though Both notify() and notifyAll()  are used to notify waiting for threads, waiting on shared queue object, but there are some subtle differences between notify and notifyAll in Java.

How to convert String to int in Java

There are 3 main ways to convert String to int in Java, using the constructor of Integer class, parseInt() method of java.lang.Integer and Integer.valueOf() method. Though all those methods return an instance of java.lang.Integer, which is a wrapper class for primitive int value, it's easy to convert Integer to int in Java. From Java 5, you don't need to do anything, autoboxing will automatically convert Integer to int. For Java 1.4 or lower version, you can use intValue() method from java.lang.Integer class, to convert Integer to int. As the name suggest, parseInt() is the core method to convert String to int in Java. parseInt() accept a String which must contain decimal digits and first character can be an ASCII minus sign (-) to denote negative integers. parseInt() throws NumberFormatException, if provided String is not convertible to int value. 

HelloWorld Program in Java with Example

First of all, welcome to the exciting world of Java programming. If you are ready to write your first Java program i.e. HelloWorld in Java, it means you already crossed major hurdles to start Java programming, in terms of installing JDK and setting PATH for Java. If you haven't done so then you can follow those tutorials to install JDK in Windows 7 and 8 and setting PATH for Java. Before we start writing HelloWorld in Java, few notes about editors. Many Java beginners insist or try to use Eclipse or Netbeans IDE from the very start of the first program, which is not a good idea. In order to learn syntax and semantics of Java programming, you should code in notepad, word pad or any other text editor. I started coding in DOS Editor, but I won't suggest that to you. Notepad++ is best of both world, it support Java syntax highlighting, which helps to understand keywords better, and its also a pleasant coding experience. 

How to Iterate over Java Enum : values() Example

Enum Values() Example
In this Java programming tutorial, we will learn how to iterate over enum in Java. Since Enums are a collection of a finite number of well-known objects, often we need to iterate over them. Enums are also final in Java and has a private constructor, which means you can not create enum instances once declared. Iteration over Enum is extremely simple, provided you know about implicit values() method, which is a static method, provided by java.lang.Enum. Since every enum in Java extends java.lang.Enum, they all get this implicit values() method. Actually there are couple of them, e.g. valueOf(), name(), ordinal() etc. This method returns enum constants in the order they are declared in Enum class. Even the ordinal() method returns the same order.

How to use ArrayList in Java with Examples

Java ArrayList Example
ArrayList in Java is one of the most popular Collection class. ArrayList is an implementation of List interface via AbstractList abstract class, and provides ordered and index based way to store elements. Java ArrayList is analogous to an array, which is also index based. In fact, ArrayList in Java is internally backed by an array, which allows them to get constant time performance for retrieving elements by index. Since an array is fixed length and you can not change their size, once created, Programmers, starts using ArrayList, when they need a dynamic way to store object, i.e. which can re-size itself. See the difference between Array and List for more differences. Though, apart from ArrayList, there are other collection classes like Vector and LinkedList which implements List interface and provides similar functionalities, but they are slightly different. ArrayList is different to Vector in terms of synchronization and speed. Most of the methods in Vector requires a lock on Collection which makes them slow. See the difference between ArrayList and Vector more differences.

How to use Iterator Java - Example Tutorial

The Iterator is used to iterate over all elements of a Collections in Java. By Iteration, I mean, going over each element stored in the collection and optionally performing some operation e.g. printing value of an element, updating object or removing an object from Collection. Iterator was not part of first Java release, and a similar class Enumeration was there to provide Iteration functionality. Iterator in Java was introduced from JDK 1.4 and it provides an alternative to Enumeration, which is obsolete nowadays. An iterator is different to Enumeration in two main ways, first, Iterator allows a programmer to remove elements from Collection during iteration.

10 Examples of HashMap in Java - Programming Tutorial

The HashMap in Java is one of the most popular Collection class among Java programmers. After my article on How HashMap works in Java, which describes theory part of Java HashMap and becomes hugely popular among Java programmers, I thought to share how to use HashMap in Java with some fundamental HashMap examples, but couldn't do that earlier and it was slipped. The HashMap is a data structure, based on hashing, which allows you to store an object as a key-value pair, an advantage of using HashMap is that you can retrieve object on constant time i.e. O(1) if you know the key.

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, e.g. javac for compiling Java source files to .class files. Without JDK, you can not create Java applications and programs. By the way, JDK comes with its own JRE, but when you run Java program using java command, the JRE which comes first in System PATH is used for execution.

Difference between JIT and JVM in Java - Interview Question

The main difference between JIT and JVM is that JIT is part of JVM itself and its main function is to improve the performance of JVM by directly compiling some hot code (code which executes above a certain threshold) into native instruction. JIT stands for Just In time compilation and JVM stands for Java Virtual Machine. JVM is a virtual machine used in Java programming platform to execute or run Java programs. The main advantage of JVM is that JVM  makes Java platform-independent by executing bytecodes. Java source code is compiled into class files, which contains bytecode. These byte codes are then executed by JVM. Now here comes JIT. Since the execution of bytecode is slower than the execution of machine language code, because JVM first needs to translate bytecode into machine language code.

Can abstract class have Constructor in Java - Interview Question

Yes, an abstract class can have a constructor in Java. You can either explicitly provide a constructor to abstract class or if you don't, the compiler will add default constructor of no argument in abstract class. This is true for all classes and it also applies to an abstract class. For those who want to recall what is an abstract class in Java, it's a class which can not be instantiated with new() operator or any other ways. In order to use an abstract class in Java,  You need to extend it and provide a concrete class. Abstract class is commonly used to define a base class for a type hierarchy with default implementation, which is applicable to all child classes. By the way, difference between interface and abstract class in Java is also one of the popular and tricky Java questions and should be prepared well for Java interviews.  

Class in Java and Object oriented programming language - Video Tutorial

Class and Object are two pillars of Java programming language. There are multiple ways you can describe Class in Java, for someone  Class is a user defined type, for others it's blueprint to create objects and for few of other it's just a way to model real world entity. Questions come why do we need Class in Java, well one thing I can think of is to combine multiple types into one structure. Class and Object along with core OOPS concept e.g. Abstraction, Encapsulation, Inheritance and Polymorphism is the first thing any Java programmer learn. I have just finished a basic Java presentation on Class for beginners which gives an introduction of What is Class in Java and details some important details about Java Classes.

JDBC - How to connect MySQL database from Java program with Example

When you start learning JDBC in Java, the first program you want to execute is connected to database from Java and get some result back by executing some SELECT queries. In this Java program, we will learn How to connect to MySQL database from Java program and execute a query against it. I choose MySQL database because it's free and easy to install and setup. If you are using Netbeans IDE then you can connect MySQL Server directly from Netbeans, Which means in one window you could be writing Java code and other you can write SQL queries. Another advantage of using MySQL database is that it provides type 4 JDBC driver bundled in mysql-connector-java-5.1.17-bin.jar which is easy to use. By the way, if you are using Oracle database then you can check Java program to connect Oracle database, to connect and run SQL queries against Oracle DB.

Difference between Set, List and Map in Java - Interview question

Set, List and Map are three important interfaces of Java collection framework and Difference between Set, List, and Map in Java is one of the most frequently asked Java Collection interview question. Sometimes this question is asked as When to use List, Set and Map in Java. Clearly, the interviewer is looking to know that whether you are familiar with fundamentals of Java collection framework or not. In order to decide when to use List, Set or Map, you need to know what are these interfaces and what functionality they provide. List in Java provides ordered and indexed collection which may contain duplicates. 

Difference between URL, URI and URN - Interview Question

All three URI, URL, and URN are used to identify any resource or name on the internet, but there is a subtle difference between them. URI is the superset of both URL and URN. By the way, the main difference between URL and URI is protocol to retrieve the resource. URL always include a network protocol e.g. HTTP, HTTPS, FTP etc to retrieve a resource from its location. While URI, in case of URN just uniquely identifies the resource e.g. ISBN numbers which are a good example of URN is used to identify any book uniquely. In this article, we will briefly see what is URI, URL, and URN and then see the main difference between URI, URL, and URN.

Difference between Self and Equi Join in SQL - INNER Join example MySQL

The main difference between Self Join and Equi Join is that In Self Join we join one table to itself rather than joining two tables. Both Self Join and Equi Join are types of INNER Join in SQL, but there is the subtle difference between two. Any INNER Join with equal as join predicate is known as Equi Join. SQL Joins are the fundamental concept of SQL similar to correlated and noncorrelated subqueries or using group by clause and a good understanding of various types of SQL join is the must for any programmer. By the way, If you have written INNER join using where clause than using comparison operator as = will be known as an equijoin. Equi join or Self join are not a formal JOIN or part of the syntax, instead, they are a just popular way to refer certain join examples.

Java 7 Improved Exception Handling - Multiple Catch block

Java 7 in many ways improved exception handling. Two of the feature of Java 7 which improves exception handling are the ability to catch the multiple exceptions in one catch block and closing resources automatically using Automatic resource management block. Java has long been criticized for its verbose exception handling code, mandatory to handle checked Exception in Java. Programmers always complained that it clutter the code and reduced readability. Java 7 somehow reduces this pain by improving Exception handling feature e.g. multiple catch and ARM blocks. In this Java 7 tutorial, we will see how to catch multiple exceptions in one catch block using JDK7.

Difference between synchronized block and method in Java Thread

Synchronized block and synchronized methods are two ways to use synchronized keyword in Java and implement mutual exclusion on critical section of code. Since Java is mainly used to write multi-threading programs,  which present various kinds of thread related issues like thread-safety, deadlock and race conditions, which plagues into code mainly because of poor understanding of synchronization mechanism provided by Java programming language. Java provides inbuilt synchronized and volatile keyword to achieve synchronization in Java. Main difference between synchronized method and synchronized block is selection of lock on which critical section is locked. Synchronized method depending upon whether its a static method or non static locks on either class level lock or object lock. Class level lock is one for each class and represented by class literal e.g. Stirng.class. Object level lock is provided by current object e.g. this instance, You should never mix static and non static synchronized method in Java.. On the other hand synchronized block locks on monitor evaluated by expression provided as parameter to synchronized block. In next section we will see an example of both synchronized method and synchronized block to understand this difference better.

Difference between Callable and Runnable in Java - Thread Interview question

Difference between Callable and Runnable interface in Java is one of the interesting questions from my list of Top 15 Java multi-threading questions, and it’s also very popular in various Java Interviews. The Callable interface is newer than Runnable interface and added on Java 5 release along with other major changes e.g. Generics, Enum, Static imports and variable argument method. Though both Callable and Runnable interface are designed to represent a task, which can be executed by any thread, there is some significant difference between them. In my opinion, the major difference between Callable and Runnable interface is that Callable can return the result of an operation performed inside call() method, which was one of the limitations with Runnable interface.

10 Programming questions and exercises for Java Programmers

If you have just started learning basics of Java programming language or familiar with programming in either C or C++ then these Java programming questions and exercises for you. It doesn't focus on particular part of Java but these coding exercises will switch you in programming mode.These are also great way to master basic programming construct like if-else , loops like for and while, break and continue with loop,   Java operators e.g. arithmetic and logical operator, recursion, methods or functions and common Java API. You may also find these Java programming questions in most of Java courses taught in school, colleges and various Java training courses. Even I have started learning Java by doing these exercises multiple times with different ways. They are interesting, gives feeling of accomplishment if you complete it. These Java programs looks simple but they are still tricky for novice Java programmers. Try to solve these coding exercises by yourself but if you stuck you can check relevant links or of-course use google to get more insight on them. You can also see here more Java programming questions and exercises.

10 AWT Swing Interview Questions Answers in Java

AWT and Swing Interview Questions are part of any Java interviews which involves GUI development work. Since AWT(Abstract Windows Toolkit) and Swing offers most popular Java GUI solutions, Yes, JavaFX  has still lot of path to cover in terms of popularity and usability of Swing. In Investment banking, where Java rules on server side application development, Swing was heavily used in GUI development couple of years back. Now trends is shifting towards C# for GUI development due to couple of reasons e.g. good Swing developers are not easy to be found as compared to C# developers. By the way there are still many development work is going on Swing. One of the reason Swing developers are high in demand is because Swing is quickly becoming a niche technology. This is surprising because  Swing is part of Java, but given steep learning curve of Swing to master different layouts and components e.g. JTable or JList , I tend to believe it. In this article we will see some good Swing Interview questions for practice. Questions like InvokeLater vs InvokeAndWait are classic, which is always worth preparing.

How to use ALTER COMMAND in SQL - database tutorial

In this SQL tutorial  we will see how to use ALTER command command in table on database. ALTER command is mainly used to add, modify and drop columns, indexes and constraints on table in relational database e.g. MySQL, Oracle, Sybase and SQL Server.  Though ALTER is not part of classical CRUD operation but it’s one of the important DDL command. One of the most frequent use of ALTER command in SQL is adding and removing indexes to improve performance of SQL SELECT queries. In this SQL and database tutorial we will see different ways of using ALTER command. By using ALTER command we can add, edit or modify table, views and databases. We can add new column on the table, we can change value of column or we can rename column also.

How to format Date in Java - SimpleDateFormat Example

SimpleDateFormat in Java is used to format Date in Java. You can format date on any String format based upon various attribute available in SimpleDateFormat class e.g. mm, dd, YY etc. You can also put timezone information in formatted Date using Z attribute of DateFormat class. SimpleDateFormat is sub class of DateFormat and provide format() and parse() method to convert Date to and from String in Java. Worth noting is that SimpleDateFormat is not thread-safe and should not be shared with others. Avoid using static SimpleDateFormat in Java classes. If you want to share SimpleDateFormat or want to make it thread-safe, you can use ThreadLocal variable in Java to avoid sharing SimpleDateFormat among multiple threads. parse() method of SimpleDateFormat throws ParseException if String input is not a valid date or can not be parsed into mentioned format.