المشاركات

عرض المشاركات من يوليو, 2021

Difference Between Abstract Class vs Interface in Java

When to use interface and abstract class is one of the most popular object-oriented design questions and is almost always asked in Java, C#, and C++ interviews. In this article, we will mostly talk in the context of the Java programming language, but it equally applies to other languages as well. The question usually starts with a difference between abstract class and interface in Java, which is rather easy to answer, especially if you are familiar with the syntax of the  Java interface and abstract class . Things start getting difficult when the interviewer asks about when to use abstract class and interface in Java, which is mostly based upon a solid understanding of popular OOPS concepts like Polymorphism , Encapsulation , Abstraction , Inheritance , and Composition . 

What is String args[] Argument in Java Main method? Example

What is String args is used for or Why we use String arg[] in the main method is a common doubt among Java beginners. The first thing newbies are exposed to while learning Java programming language is writing HelloWorldprogram in Java , Though HelloWorld is the smallest sort of program, it contains a lot of useful information and concept for newbies Java programmers, one of them is the main method and its different attributes. Though I covered a bit of String args[]  while discussing Why main is public static in Java , I thought to write this article to explain String args array in more detail. Let's see a simple Java HelloWorld again to understand more about String args in Java.

How to disable JUnit Test - @Ignore annotation Example

If you are using JUnit 4, then you can use @Ignore annotation to disable a test case; what this means is that any method which is annotated by  @Ignore , will not be executed by JUnit. Why would you want to disable a test? Well, It may be because that particular test is for functionality that is not yet implemented fully, and because of that your build is failing. Like that there could be some other scenarios where you would like to temporarily disable a test or a group of tests. From JUnit 4 onward test methods are annotated with @Test , so if they are also annotated with @Ignore will not be executed as tests.

Java Program to Multiply Two Matrices - Matrix Multiplication Example

How to write a Java program to multiply two matrices in Java is a very good programming exercise to get familiar with the two-dimensional array in Java. this example teaches about how to multiply arrays , how to access elements from a multi-dimensional array, how to pass them to a function etc. Since the matrix is a natural representation of a multi-dimensional array in Java, they are often used to illustrate real word matrix exercises e.g. the calculating sum of two matrices or calculating the difference of two matrices, etc.

The Ultimate Guide of Generics in Java - Examples

Java Generics Tutorial Generics in Java is one of the important features added in Java 5 along with Enum, autoboxing, and varargs, to provide compile-time type-safety. Generics are also considered to be one of the tough concepts to understand in Java and somewhat it’s true as well. I have read many articles on generics in Java, some of them are quite good and detailed but I still felt that those are either too technical or exhaustively detailed, so I thought to write a simple yet informative article on Java generics to give a head start to beginners without bothering their head too much. 

Difference between trunk, tags and branches in SVN? Answer

SVN or Subversion is one of the popular source control systems used in the Java world for source code management. There are a lot of source control systems available e.g. Git , Perforce , CVS , ClearCase , VSS , but SVN has its own place among Java developer a nd open source communities. Knowledge of source control systems is a must for any professional programmer. New users of subversion are often confused between three things trunk, tags, and branches. Questions like, what is the difference between a tag and a branch in subversion is frequently asked in various Java forums and chat rooms.

How to Check If Number is Even or Odd without using Modulus or Remainder Operator? Example

Write a Java program to find if a number is odd or even is one of the basic programming exercises, and anyone will be happy to see this in actual Java Interviews, wouldn't you? By the way, did I said easy, well there is a little twist there, you need to check odd and even without using modulus (%) or remainder operator in Java. Since many programmers, especially freshers are familiar with % operators, this nice little trick does put them into thinking mode, which is what the interviewer wants. This question is on a similar level of checking if a number is a palindrome or not if you have practiced such questions, it would be easy to find a solution.

Java Program to print Prime numbers in Java - Example Tutorial and Code

How to print Prime numbers in Java or how to check if a number is prime or not is classical Java programming questions , mostly taught in Java programming courses. A number is called a prime number if it's not divisible by any number other than 1 or itself and you can use this logic to check whether a number is prime or not . This program is slightly difficult than printing even or odd numbers which is relatively easier than Java exercises. This Simple Java program prints prime numbers starting from 1 to 100 or any specified number. It also has a method that checks if a number is prime or not .

How to Convert InputStream to Byte Array in Java - 2 Examples

Sometimes we need to convert InputStream to byte array in Java, or you can say reading InputStream as a byte array, In order to pass output to a method that accepts byte array rather than InputStream . One popular example of this, I have seen is an older version of Apache commons-codec, whi le converting byte array to the hex string . Though, a later version of the same library does provide a n overloaded method , to accept InputStream . Java File API provides excellent support to read files like image, text as InputStream in Java program, but as I said, sometimes you need String or byte array, instead of InputStream .

Java Program to Find Sum of Digits in a Number using Recursion? Example

Recently this question to ask was one of my readers, which inspired me to write this tutorial. There was a usual check to solve this problem using bot h recursion and iteration . T o be frank,  calculating the sum of digits of an integral number  is not difficult, but I have still seen quite a few programmers fumbles, even after providing hints in terms of division and modules operator. The key point here is to know how to use division and modulus operators in Java. This kind of exercise including reversing a number , whe re you need to find digits from a number, use division operator to remove right , and use modules operator or % to get rightmost digits .

How to compare two XML files in Java - XMLUnit Example

The XMLUnit library can be used to compare two XML files in Java . Similar to JUnit, XMLUnit can also be used to test XML files for comparison by extending the XMLTestcase class. It is a rich library and provides a detailed comparison of XML files. Btw, comparing XML is completely different than comparing String in Java or comparing objects using equals() , as two XML which contains different comments and whitespace can be equals, which is not true for String or character comparison. Also while comparing XML files, it's very important to know exactly which content or part is different and XMLUnit not only shows the content which is different but also the XPath of elements which is getting compared.

JAXB Date Format Example using Annotation | Java Date to XML DateTime String Conversion

One of the common problem while marshaling Java object to XML String using JAXB is the default format of date and time provided by JAXB. When JAXB converts any Date type object or XMLGregorianCalendar to XML String, precisely xsd:dateTime element, it by default prints unformatted date e.g. 2012-05-17T09:20:00-04:30 . Since most of the real world, Java application has a requirement to print date in a particular format like dd-MM-yyyy or include date and time in format dd-MM-yyyy HH:mm:ss , it becomes a problem . Thankfully, JAXB is very extensible and provides hooks and adapters to customize marshaling and unmarshaling process. You can define an extension of XmlAdapter to control and customize marshaling and unmarshaling or any Java type depending upon yours need.

How to convert double to int in Java? Example

Suppose you have a double primitive variable 4.444 and you want to convert it to the integer value 4 , how do you that in Java? Since double is bigger data type than int , you can simply downcast double to int in Java. double is 64-bit primitive value and when you cast it to a 32-bit integer, anything after the decimal point is lost. Btw, typecasting doesn't do any rounding or flooring, which means if you have 9.999999 and while casting to int you are expecting 10 then you would be disappointed, casting will give you just 9. If you need 10 then you need to use Math.round() method to first round the double value to the nearest integer and then truncate decimals.

Does making all fields Final makes the class Immutable in Java? Example

One of the common misconceptions among many Java Programmers is that a class with all final fields automatically becomes Immutable. This is not correct, you can easily break the immutability of a certain class if the final field it contains is a mutable one, as we'll see in this article. One of the most common examples of this is a java.util.Date fields e.g. birthDay , expirtyDate , or joiningDate sort of fields. You have to be extra cautious to keep your class' immutability intact with mutable fields. The most common mistake in this regard happens when a Java programmer returns a reference of the original object when a client asks like  getBirthDay() returns the date object pointed by birthDay field.

Top 10 Tips on Logging in Java - Tutorial

Java logging or logging in java is as much an art as science. knowing to write tools and API for java logging is definitely the science part but choosing the format of java logs, the format of messages, what to log in to java, which logging level to use for which kind of messages are purely experienced-based things, and sort of art which you learn by applying logging in java. Since its proven fact that java logging severely affects performance and I have seen latency of online stock trading application goes multiple times if they run in DEBUG mode than in WARN or higher level mode.

How to Setup Java Remote Debugging in Eclipse - Step by Step Guide

How to remote debug Java program in Eclipse Remote debugging is not a new concept and many of you are aware of this just for those who doesn’t know what is remote debugging? It’s a way of debugging any process that could be Java or C++ running on some other location on your development machine.  Since debugging Java applications is an essential part of Java development and ability to debug your application not only saves time but also increases productivity. Local debugging is the best way to debug Java programs in my opinion and should always be preferred over remote debugging as discussed in my post How to debug Java program in Eclipse , but if local debugging is not possible and there is no way to debug your process then remote debugging Java application is the solution.  

How to Find First and Last element in LinkedList Java? Doubly linked list Example

In this article, you will learn how to get the first and last element of a linked list with the help of getFirst() and getLast() of the LinkedList class. If you have programming or even gone to a computer science course you probably know what is a linked list? It's a data structure that allows you to store objects in such a way that you can don't need a big chunk of contiguous memory like another popular data structure array. It works perfectly even if you have a fragmented heap. LinkedList is Java's implementation of this fundamental data structure. 

Difference Between java and javaw Commands from JDK

The difference between java.exe and javaw.exe commands was the recent java question asked to one of my friends. while running a java program on windows you might have noticed that they will appear in the task manager as either java.ex e or javaw.exe ,  also in JAVA_HOME /bin we see these two java commands java.exe and javaw.exe , do you know the difference between java.exe and javaw.exe? surprisingly not many java programmers know the answer to this java interview question , maybe because java developers have not paid enough attention to these commands. anyway here we will see few differences between java and java commands :

Java Program to connect Oracle Database with Example - JDBC Tutorial Sample Code

How to connect to Oracle database from Java Program using JDBC API is common to need for many Java programmer, though there is a lot of framework available which has simplified JDBC development e.g Hibernate, Spring JdbcTempate and many more, creating Java program to connect to oracle database from plain old Java is still the easiest and quickest method for testing and debugging database connectivity. The database connection program is also a common Java programming exercise in many Java programming courses in schools, colleges, and various training institutes.

Difference between ValidatorForm vs ValidatorActionForm in Struts Framework? Example

Struts provide two classes ValidatorForm and ValidatorActionForm for validating form fields. Instead of doing basic validation by using the validate() method in Action class, these classes allows you to leverage rich feature of validation framework provided by Jakarta Struts framework. You can do declarative validation by defining rules in XML config files like validation-rule.xml or validations.xml as well. Since Struts is one of the popular Web MVC frameworks, you can also use its validation framework on any Java web application implemented using Struts. Now, coming back to the question, what is the actual difference between ValidatorForm and ValidatorActionForm in Struts? They both look quite similar, right?

10 points about Java Heap Space or Java Heap Memory

10 Points about Java heap memory When I started Java programming I didn't know what is java heap or heap space in Java, I was even not aware of where does object in Java gets created, it’s when I started doing professional programming I came across error java.lang.OutOfMemoryError in Tomcat then I realized What is Heap in Java or Java Heap Space. It happens with most of the programmer because learning language is easy but learning basics are difficult since there is no formal process which can teach you every basic of programming its experience and work which reveals the secret of programming.

Top 12 Apache Web Server Interview Questions Answers for 1 to 2 Years Experienced

The Apache HTTP Server, also known as httpd , has been the most popular web server on the Internet since April of 1996. It is both free and robust and that's the reason that almost half of the world's websites  runs on Apache HTTP web server, ranging from small hobby websites to huge e-commerce giants and big banks. There are also many companies which use Apache and Tomcat to host Java web application. In a typical setup, Apache web server receives the HTTP request and depending upon the URL it either route to Tomcat or serve the static files directly from the file system.

What is interface in Java with Example - Tutorial

What is an interface in Java? Interface in java is a core part of the Java programming language and one of the ways to achieve abstraction in Java along with the abstract class. Even though the interface is a fundamental object-oriented concept ; Many Java programmers think of Interface in Java as an advanced concept and refrain from using the  interface from early in a programming career. At a very basic level  interface  in java is a keyword but same time it is an object-oriented term to define contracts and abstraction , This contract is followed by any implementation of Interface in Java . Since multiple inheritances are not allowed in Java , the  interface is the only way to implement multiple inheritances at the Type level.

String replaceAll() example - How to replace all characters and substring from String

You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java.lang.String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String. The replaceAll() function is a very useful, versatile, and powerful method and as a Java developer, you must know about it. Even though Java provides separate methods for replacing characters and replacing substring , you can do all that just by using this single method.

Java Program to Reverse an Integer Number - Example tutorial

How to reverse a number in Java without using any API or write a simple Java program to reverse a number is common programming questions asked on fresher level software engineer interviews. Reversing a number is also popular homework question on many Java programming courses in schools, colleges, and training institutes. I personally feel java program to reverse number is good programming exercise for someone who is just started learning to program in Java or any other programming language because of its simplicity and a little bit of trickiness which shows how to use operators for programming purposes rather than arithmetic purpose.

How to Measure Elapsed Execution Time in Java - Spring Framework's StopWatch Example

There are two ways to measure elapsed execution time in Java either by using System.currentTimeinMillis() or by using   System.nanoTime() . These two methods can be used to measure elapsed or execution time between two method calls or events in Java. Calculating elapsed time is one of the first things Java programmer do to find out how many seconds or millisecond a method is taking to execute or how much time a particular code block is taking. Most Java programmers are familiar with System.currentTimeInMillis() which is there from the beginning while a new version of more precise time measurement utility System.nanoTime is introduced in Java 1.5, along with several new features in a language like Generics , Enum types , autoboxing and variable arguments or varargs .

How to Invoke Method by Name in Java Dynamically Using Reflection? Example

In Java you can invoke any method by its string name dynamically using reflection API . java.lang.reflect API provides powerful reflection mechanism which can load classes by its name even if classes are not available at compile time, Can get all methods including private and public from class and allow you to invoke any method dynamically using reflection . For those who are new to Java this sound pretty strange that at runtime you provide a method name using string and Java can run that method without any code for calling the method during compilation, but Reflection is such a powerful mechanism it allows to do a lot of stuff dynamically and if you been using IDE like Netbeans or Eclipse , a J2EE framework like Spring and Struts , these all used reflection to provide powerful configuration module and several other useful features like code assist etc.

Difference Between java.util.Date and java.sql.Date in Java - JDBC Interview Question

Difference between java.util.Date and java.sql.Date in Java or why does Java have java.sql.Date if there is already a Date class in java util package is a common java interview question . There is always confusion among many Java developers familiar with both java.util.Date and java.sql.Date . Though many of them already using java.sql.Date to interface with DATE type of any relational database like MySQL , Oracle, or any other database. In this Java tutorial, we will see some differences between java.sql.Date and java.util.Date  will help to understand both of them better.

How to Convert Local Time to GMT in Java - Example Tutorial

Converting local time into GMT or any other timezone in Java is easy as Java has support for time zones. JDK has a class called java.util.Timezone which represents timezone and Java also has classes like SimpleDateFormat which can use Time zone while parsing or formatting dates . By using java.uti.TimeZone and java.text.SimpleDateFormat we can write a simple Java program to convert local time to GMT or any other time zone in Java. We have already seen examples of How to get current date and time in GMT and this Java program is an extension of that in order to convert time form one timezone to other timezones.

What is rt.jar in Java/JDK/JRE? Why it’s Important?

rt.jar stands for runtime JAR and contains the bootstrap classes, I mean all the classes from Core Java API. I have found that many Java programmer doesn't know what is rt.jar? and often confused with the role of rt.jar file or  why we use of rt.jar file in Java? No surprise, the name is a little bit cryptic.  This file always resides inside the lib directory of JRE, at least in Windows and Linux. In MacOSX it resides at a different location and also has a different name i.e. classes.jar , but that is only prior to JDK 1.7. From Java 7 release Apple has stopped distributing Java and if you separately install, it will have the same name as rt.jar .

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

ConcurrentHashMap vs Hashtable vs Synchronized Map Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is a significant difference between them, which arise from the fact that how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1 itself, which uses synchronized methods to achieve thread safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. The only difference between Hashtable and Synchronized Map is that later is not a legacy and you can wrap any Map to create it's synchronized version by using Collections.synchronizedMap() method.

Java PropertyUtils Example - getting and setting properties by name

PropertyUtils class of Apache commons beanutils library is very useful and provides you the ability to modify properties of Java object at runtime . PropertyUtils enables you to write highly configurable code where you can provide the name of bean properties and their values from configuration rather than coding in Java program and Apache PropertyUtils can set those properties on Java object at runtime. One popular example of how powerful PropertyUtils can be is display tag which provides a rich tabular display for JSP pages , it uses PropertyUtils class to get values of an object at runtime and then display it.

Top 2 System Design Interview Question from Investment Banks? Limit Order Book Example

No doubt that Data structure and algorithms are an integral part of any Programming job interview, including Java, C++, or any other programming language. In fact, Data structure and algorithms are quite a favorite one and all top-notch companies including Google, Microsoft, Amazon, and investment banks like Goldman Sachs, Citigroup, Barclays, Morgan Stanley or J.P. Morgan focus extensively on data structure and algorithms while hiring both senior and mid-level developers in Java, C++, and C# positions.

What is Effectively Final variable of Java 8? Example

Apart from the big three, Lambda expression , Stream API , and new Date and Time API , Java 8 has also introduced a new concept called the "effectively final" variable. A non-final local variable or method parameter whose value is never changed after initialization is known as effectively final. It's very useful in the context of the lambda expression. If you remember, prior to Java 8, we cannot use a non-final local variable in an anonymous class. If you have to access a local variable ( a method parameter or a variable decreed in the method itself) in the Anonymous class, you have to make it final . This restriction is relaxed a bit with lambda coming up. Java designers have taken the need to make local variable final if it's not changed once initialized.

Top 10 JSP Interview Questions Answers for Java Programmer

These JSP interview questions and answers are asked in the various J2EE interview and focus on the view part of the MVC framework. JSP or Java Server Pages is a Java technology used to render a dynamic view. Whenever you go for any Java web developer interview there are always some interview questions on JSP. This article is a collection of some JSP interview questions which has asked in the various interview to my friends and colleagues. You can easily find answers to these JSP interview questions by google but I have included my version for quick reference.

How to use EnumSet in Java with Example

EnumSet is one of the specialized implementations of the Set interface for an enumeration type, introduced in Java 1.5 along with the enumeration type itself. Programmer often stores Enum into common collection classes e.g. HashSet or ArrayList , mostly because they are unaware of this little gem. Even I wasn't aware of this class a few years ago until I come across one of the finest books for Java programmers, Effective Java . It has an Item on EnumSet, which highlights some typical use-cases for this collection class instead of using int variable and bitwise operator . Since Enum constants are unique and have pre-defined lengths, as you can not define a new enum constant at runtime; it allows Java API designers to highly optimize EnumSet.

Difference between WeakReference vs SoftReference vs PhantomReference in Java? Example

WeakReference and SoftReference were added   into Java API for a long time but not every Java programmer is familiar with it. This means there is a gap between where and how to use WeakReference and SoftReference in Java . Reference classes are particularly important in the context of How Garbage collection works . As we all know that Garbage Collector reclaims memory from objects which are eligible for garbage collection, but not many programmers know that this eligibility is decided based upon which kind of references are pointing to that object. This is also the main difference between WeakReference and SoftReference in Java .

Difference between include directive and include action in JSP Servlet? Example

D ifference between include directive and include action is one of the most popular JSP interview questions and also asked as What is the difference between page include and file include in JSP.  Similar to the  difference between forward and send redirect  and URL encoding vs URL rewriting , this is also asked at a beginner level. Here we will see page include vs file include in detail. Both include directive and include action is used to include the output of a static page e.g. HTML or a dynamic page like  jsp in side another jsp file.

3 ways to Find First Non Repeated Character in a String - Java Programming Problem Example

Write a Java program to find the first non-repeated character in a String is a common question on coding tests. Since String is a popular topic in various programming interviews, It's better to prepare well with some well-known questions like reversing String using recursion , or checking if a String is a palindrome or not. This question is also in the same league. Before jumping into the solution, let's first understand this question. You need to write a function, which will accept a String and return first non-repeated character, for example in the world "hello", except 'l' all are non-repeated, but 'h' is the first non-repeated character.

Avoid Using System.exit() on Java Web Application - Best Practice

I have recently come across a code snippet, where the programmer was using System.exit() if the application failed to acquire necessary resources after a couple of retries. His reasoning was that the application cannot function if essential resources like the database are not available or there is no disk space to write records in the File system. Ok, I hear you; but System.exit() in Java Web application, which runs inside either web server or application server, which itself is Java program is not a good idea at all. Why? because invoking System.exit() kills your JVM, invoking this from Tomcat or Jetty, will not only kill your application but the most likely server itself. This can be potentially dangerous if that server also hosts other critical applications, which is not uncommon at all.

How to Reverse Array in Place in Java? Solution With Explanation

Reversing an array sounds pretty easy, isn't it? It does sound like that, because all you need to do is create an array of the same size, iterate through the original array from end to start, and populate your new array. Boom!!, you have got an array that has elements in reverse order of the original array, but the problem is you have used an additional array here, which makes space complexity of your solution O(n) . You cannot use this solution if the array is big e.g. an array of 10 million orders and you don't have enough heap space available.

5 Difference between Application Server and Web Server in Java?

Application server and web server in Java both are used to host Java web applications. Though both the application server and web server are generic terms, the difference between the application server and the webserver is a famous J2EE interview question . From on Java J2EE perspective, the  main difference between the web server and application server is the support of EJB . In order to run EJB or host enterprise Java application (.ear) files, you need an application server like JBoss , WebLogic , WebSphere, or Glassfish , while you can still run your servlet and JSP or java web application (.war) file inside any web server like Tomcat or Jetty .

Why use Underscore in Numbers from Java? Underscore in Numeric Literals Example

JDK 1.7 release had introduced several useful features, despite most of them being syntactic sugar, there use can greatly improve readability and code quality. One such feature is the introduction of underscores in numeric literals . From Java 7 onwards you can write a long digit e.g. 10000000000 to a more readable 1 0_000_000_000 in your Java source code. One of the most important reasons for using an underscore in numeric literal is avoiding subtle mistakes that are hard to figure out by looking at code. It's hard to notice a missing zero or extra zero between 10000000000 and 1000000000 , than 10_000_000_000 and 1_000_000_000 .

Display tag Pagination, Sorting Example in JSP and Servlet

If you are a Java programmer, writing JSP pages for your web application and doesn't know much about JavaScript, jQuery, CSS, and HTML, then display tag is best for creating dynamic tables, pagination, sorting, and exporting data into PDF, Word and Excel format. Display tag is a JSP tag library, where code is written in Java but you can use them like HTML tags e.g. <display></display>  . Though the display tag is an old library, I have always used it in JSP for displaying tabular data. It comes with sample CSS as well, which is good enough for many applications. Long time back, I have shared some display tag tips and examples , and many of my readers asked me to write about how to do pagination and sorting on the  JSP page.

How to enclose a list of values into single quotes for SQL query? Microsoft Excel Example

Many times you get a list of values that you want to check in the database to confirm if they exist in your tables or to get more information bout them. For example, you got a list of 100 stocks and you want to check their last day closing prices in the database. The problem arises when values to be searched are Strings e.g. VARCHAR or CHAR because VARCHAR values need to be enclosed in the single quotes in most of the database like SQL Server, Oracle, or MySQL. If a number of values are less than 5 then it makes sense to add single quotes around them and separate them by comma manually so that you can use them on IN clause of your SQL query, but if it's more than 5 like 50 or 100 then manually enclosing them into single quotes will take a lot of time and most importantly programmers are not supposed to do such silly stuff manually.

Bitwise and BitShift Operators in Java - AND, OR, XOR, Signed Left and Right shift Operator Examples

Bitwise and Bit Shift Operators in Java are a powerful set of operators that allows you to manipulate bits on integral types like int, long, short, bytes, and boolean data types in Java. Bitwise and Bit shift operator is among the fastest operator in Java but still, many Java programmers don't familiar with bitwise and bitshift operations, especially those who don't come from C programming backgrounds. If you have already learned C or C++ before starting with Java then understanding bitwise and bitshift operators are quite easy in Java, because it's similar to the bitwise operation in C.

How to Install JDK on Windows - Java Programming Tutorial Example

Installing JDK is the first step in learning Java Programming. If you are using Windows 8 or Windows 7 Operating System, then installing JDK is quite easy as you just need to follow instructions given by the Java SE Installation wizard. The only thing which requires some attention is, choosing the correct JDK installer based upon, whether you are running with 32-bit or 64-bit Windows 8 or Windows 7 OS. JDK 7 is the latest Java version but JDK 6 is still most popular in the software and programming world. You can choose to install JDK 7 or JDK 6 based on your course material.

How to format Date and Time in SQL Server and Sybase? Examples

How to format a date in SQL Server like in the "yyyymmdd" format? Suppose you have a date and time column in Sybase or Microsoft SQL Server,  which is displaying values in "Dec  31, 2011, 12:00 AM" and you want to display it in any particular DATE format like YYYYMMDD or DDMMYYYY, how will you do that? This is also one thing you need to keep in mind when you convert a DATE , TIME, DATETIME column into CHAR or VARCHAR values.  It's easy to format dates using the convert function in Sybase or SQL Server, but it's slightly difficult to remember the cryptic formatting style codes that go with it. For example, using style code, 112 is used to format dates in the "YYYYMMDD" format e.g. "20170329".

What is JSESSIONID in Java Web application - JSP Servlet? Example

What is JSESSIONID in JSP-Servlet JSESSIONID is a cookie generated by Servlet containers like Tomcat or Jetty and used for session management in the J2EE web application for HTTP protocol. Since HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from the same client and Session management is the process to track user sessions using different session management techniques like Cookies and URL Rewriting . If a Web server is using a cookie for session management it creates and sends JSESSIONID cookie to the client and then the client sends it back to the server in subsequent HTTP requests .

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

Why character array is better than String for storing a password in Java was a recent question asked to one of my friends 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 the other is a 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 a special property of Strings like immutability and he used that to convince the interviewer. here we will explore some reasons why should you use char[] for storing passwords than String.

How to Export HTML to PDF, CSV, and Excel using Display Tag in JSP? Example

Display tag provides export options to export page into PDF, CSV, Excel, and XML in Java web application written using JSP, Servlet, Struts, or Spring MVC framework. Display tag is a tag library and you just need to use it in your JSP page to display tabular data or generate HTML tables dynamically. Earlier we have se en 10 display tag tips for getting most out of display tag and in this JSP Servlet tutorial we will see one display tag export issue, which prevents display tag export functionality to work properly.

How to Convert List of Integers to Int Array in Java - Example

So, you have a List of Integers and you want to convert them into int array? Yes, you read it write, not on Integer array but int array . Though in most practical purpose, Integer array can be used in place of int[] because of autoboxing in Java , y ou still need an int[] if your method accepts it. In Java, you can n ot typecast an Int eger array into an int array. Many Java programmer think about toArray() method from java.util.List to convert a List into Array, but unfortunately,  toArray() is useless most of the time. It doesn't allow you to convert List into primitive arrays.

Top 20 JUnit Interview Questions with Answers for Java Programmers [Java Unit Testing]

Hello guys, if you are preparing for a Java programming interview and looking for some JUnit and testing interview questions then you have come to the right place. Earlier, I have shared the  best JUnit and TDD courses  and books , and, today, I am going to share some JUnit interview questions for Java developers. There is no doubt that JUnit is the defacto standard framework for writing unit tests in Java and every professional developer must be familiar with JUnit. Not long ago, you can clear Java interviews without writing a single line of code, forget about tests but not many more. More and more companies are including coding tests and take-home tests where you need to build solutions and write code with tests on their hiring process. 

How to Configure HTTPS (SSL) in Tomcat 6 and 7 Java Web Server? Example

Setting SSL (Secure Socket Layer) in Tomcat is often a requirement, especially while developing secure web applications, which requires access over HTTPS protocol. Sinc e the  Tomcat web server doe sn't provide SSL settings by default, you need to know how to configure SSL in Tomcat, and even worse it varies between different tomcat versions. for Example SSL setup which works on tomcat 6, doesn't work as it is in tomcat 7. In this article, we will see, how to configure tomcat for HTTPS in both tomcat 6 and 7. For those programmers who are not very familiar with SSL and HTTPS here is a quick overview of SSL, certificates and HTTPS , and I suggest reading that article to get a better understanding of How SSL works and How websites are accessed securely over the internet.

How to Convert and Print Byte array to Hex String in Java? Example

We often need to convert byte arrays to Hex String in Java, In order to print byte array contents in a readable format. Since many cryptographic algorithms e.g. MD5 return the hash value as a byte array, In order to see and compare that byte array, you need to convert the byte array to Hex String. As we have seen, while generating MD5 checksum of File , there are multiple ways to convert byte array to Hexadecimal String in Java . You can either write your own method, or you can use an open-source library e.g. Apache commons-codec to create Hex String from a byte array in Java. Commons codec provides a utility class Hex , which contains an encodeHexString() method to create Hex String from a byte array .

How to Create Tabs UI using HTML, CSS, jQuery, JSP and JavaScript? Example

JSP is still a popular technology for developing view part of Struts and Spring-based Java applications, but unfortunately, it doesn't have rich UI support available in GWT,  or any other library. On another day, we had a requirement to display HTML tables inside tabs , basically, we had two tables of different data set and we need to display them in their own tabs. Users can navigate from one tab to another, and CSS should take care of which tab is currently selected, by highlighting the active tab. Like many Java developers, our hands-on HTML , CSS,  and JavaScript are a little bit tight than a web guy, and since our application is not using any UI framework, we had to rely on JSP to do this job.

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 a JDBC connection to MySQL database first time. we have touched base on ClassNotFoundException in MySQL on our earlier articles on  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.

Difference between Stack and Heap memory in Java? Example

The difference between stack and heap memory is a c ommo n programming question a sked by beginners learning Java or any other programming language. Stack and heap memory are two terms programmers start hearing once they started programming but without any clear and definite explanation. Lack of knowledge of what is a heap in Java an d what is stack memory in Java results in misconceptions related to stack and heap. To add to this confusion, a stack is also a data structure that is used to store elements in LIFO(Last In First Out) order and is available in Java API as java.util.Stack .

What is Method Reference in Java 8 Functional Programming? Example

Lambda expression allows you to reduce code compared to an anonymous class to pass behaviors to methods, method reference goes one step further. It reduces code written in a lambda expression to make it even more readable and concise. You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial

Uploading Files to the server using Servlet and JSP is a common task in Java web applications. Before coding your Servlet or JSP to handle file upload requests, you need to know a little bit about File upload support in HTML and HTTP protocol. If you want your user to choose files from the file system and upload them to the server then you need to use <input type="file"/> . This will enable us to choose any file from the file system and upload to a server. 

How to Split String in JSP? JSTL forTokens Tag Example

JSTL forTokens tag is another tag in core JSTL library to support Iteration or looping. It effectively compliments, more useful <c:forEach> tag, by allowing you to iterate over comma-separated or any delimited String. You can use this tag to split string in JSP and can operate on them individually. forTokens tag has similar attributes like forEach JSTL tag except one more attribute called delims, which specifies delimiter. For example to iterate over colon-separated String "abc:cde:fgh:ijk" , delims=":".  

How to test Exception thrown by a Java Method in JUnit? Example

One part of unit testing a Java method is checking exceptions thrown by that method. A Java unit test should verify the correct exception thrown in the exceptional case and no exception should be thrown in a normal case. In JUnit 3.XX , there was no direct support to pass or fail a test based upon the exception thrown by a Java method. JUnit4 address this issue and provides an easy, and readable way to te st exceptions thrown by a Java method. There are many situations when you need to  test the exception thrown by any method in Java . A classical example of this is testing API methods which should throw Il legalArgumentException if arguments passed to the method are not matching to pre-conditions.

What is difference between SQL, T-SQL and PL/SQL? Answer

Today, we are going to see another common and interesting SQL interview question, what is the difference between SQL, T-SQL, and PL/SQL? It is also one of the most common doubts among SQL beginners. It's common for programmers to think that why there are many types of SQL languages, why not just single SQL across DB? etc. Well, let's first understand the difference between SQL, T-SQL, and PL/SQL, and then we will understand the need for these dialects. SQL is standard for querying, inserting, and modifying data in a relational database. It is categorized into DDL and DML and is powerful enough to create database objects e.g. table, view, stored procedure, and can perform CRUD operation ( SELECT , INSERT, UPDATE, and DELETE ) query.

10 examples of displaytag in JSP, Struts and Spring

Display tag is one of the best free open source libraries for showing data in tabular format in a J2EE application using jsp, struts, or spring. it is shipped as a tag library so you can just include this in your jsp and add the corresponding jar and their dependency in class-path and you are ready to use it. The display tag is my favorite solution for displaying any tabular data because of its inherent capability in paging and sorting. It provides great support for pagination on its own but it also allows you to implement your own pagination solution. On the Sorting front, you can sort your data based on any column, implement default sorting, etc.

Top 10 JUnit Best Practices for Java Developers

JUnit best practices in Java No doubt writing good JUnit test cases is a rare skill just like writing good Code. A good, well thought and well-written JUnit test can prevent several production issues during initial development or later maintenance in Java applications. Though one can only be perfect in writing the JUnit test by practice and a level of business knowledge which is important to envision different scenarios on which a method gets called, some best practices or experience of another developer may help to guide other programs. In this Java article, I am sharing some JUnit tips and JUnit best practices that I have learned and follow while writing unit tests using JUnit for Java programs.

How to find current directory in Java with Example

صورة
Its easy to get current directory in Java by using built-in system property provided by Java environment. Current directory represent here the directory from where " java " command has launched. you can use " user.dir " system property to find current working directory in Java . This article is in continuation of my earlier post on Java e.g. How to load properties file in Java on XML format or How to parse XML files in Java using DOM parser and Why Java doesn’t support multiple inheritance . If you haven’t read them already, You may find them useful and worth reading. By the way here is a quick example of finding current directory in Java:

How to change Tomcat default port 8080? Example Steps

Tomcat default port is 8080 but many times other Java application also uses 8080 like any other web-server Resin or Jetty and starting tomcat may result in java.net.BindException:Address already in use: JVM_Bind 8080 . In order to avoid this exception you can change default port of tomcat from 8080 to some other port e.g. 8081 or 8082. Though don't change to tomcat port which is likely to be used by tomcat itself e.g. 8443 is used by tomcat https p ort. Use port which is most likely to be free. In this tomcat tutorial we will see how to change default port 8080 for http protocol in tomcat and port 8443 port for https protocol in tomcat.

Difference between List and Set in Java Collection? Example

What is the difference between List and Set in Java is a very popular Java collection interview question and an important fundamental concept to remember while using the  Collections class in Java. Both List and Set are two of the most important Collection classes Java Program use along with various Map implementations. The basic feature of List and Set are abstracted in the  List and Set interface in Java and then various implementations of List and Set adds specific features on top of that e.g. Array List in Java is a List implementation backed by Array while Linked List is another List implementation that works like linked list data-structure.

The Ultimate Guide of Synchronization in Java - Examples

Multithreading and synchronization are a very important topic for any Java programmer. Good knowledge of multithreading, synchronization, and thread-safety can put you in front of other developers, at the same time, it's not easy to master this concept. In fact, writing correct concurrent code is one of the hardest things, even in Java, which has several inbuilt synchronization utilities. In this Java synchronization tutorial we will learn what is meaning of Synchronization in Java, Why do we need Synchronization in Java, What is java synchronized keyword, examples of using Java synchronized method and blocks, What can happen in multithreading code in absence of synchronized constructs, tips to avoid mistakes, while locking critical section in Java and some of the important points about synchronization in Java .

Enhance For Loop Example and Puzzle in Java

From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator . For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of the for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics , Autoboxing,  and variable arguments , Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is a basic requirement of using a Collection in the for-each loop, not everyone can answer.