Posts

Showing posts with the label core java

17 Examples of Calendar and Date in Java

The java.util.Calendar class was added in Java on JDK 1.4 in an attempt to fix some flaws of the java.util.Date class. It did make some task simpler, e.g. create an arbitrary date comes easier using new GregorianCalendar(2016, Calendar.JUNE, 11) constructor, as opposed to Date class where the year starts from 1900 and Month was starting from zero. It didn't solve all the problems e.g. mutability and thread-safety of Date class still remains, but it does make life easier at that time. Now with Java 8 everything related to Date and Time has become super easy and consistent but unfortunately, it will take another 5 to 10 years before older version of Java goes away. Don't believe me, there are still applications running on JDK 1.5 which was released 12 years ago. The bottom line is it's still important to know about Date and Calendar in Java. Read more �

Difference between for loop and Enhanced for loop in Java

Though you can use both for loop and enhanced for loop to iterate over arrays and collections like a list , set , or map . There are some key differences between them. In general, enhanced for loop is much more easy to use and less error prone than for loop, where you need to manage the steps manually. At the same time, for loop is much more powerful because you get the opportunity to control over looping process. All the difference, you will learn in this article, stems from this very fact that traditional for loop gives more control that enhanced for loop but on the other hand enhanced or advanced for loop gives more convenience. Read more �

How to Split String based on delimiter in Java? Example Tutorial

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma separated String on a comma, breaking a pipe delimited String on a pipe or splitting a pipe delimited String on a pipe. It's very similar to earlier examples where you have learned how to split String in Java . The only point which is important to remember is little bit knowledge of regular expression, especially when the delimiter is also a special character in regular expression e.g. pipe (|) or dot (.) , as seen in how to split String by dot in Java . In those cases, you need to escape these characters e.g. instead of | , you need to pass \\| to the split method. Read more �

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 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. The replaceAll() method replaces each substring of this string (the String on which it is called) that matches the given regular expression with the given replacement. It internally uses classes like Pattern and Matcher from java.util.regex package for searching and replacing matching characters or substring. Read more �

How to convert double to int in Java?

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 32-bit integer, anything after the decimal point is lost. Btw, type casting 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. Read more �

Difference between extends and implements keywords in Java

Though both extends and implements keyword in Java is used to implement Inheritance concept of Object-Oriented programming, there is a subtle difference between them. The extends keyword is mainly used to extend a class i.e. to create a subclass in Java, while implements keyword is used to implement an interface in Java. The extends keyword can also be used by an interface for extending another interface. In order to better understand the difference between extends and implements , you also need to learn and understand the difference between class and interface in Java . Though both are an integral part of application development using object oriented methodology, an interface is more abstract than class hence it is used to define API or contract. Read more �

What is the real use of Method Overloading in Java or Programming?

Many programmers, including Java and C++, knows about overloading e.g. method overloading or function overloading, but if you ask them why you should overload a method? Many of them become clueless. This is a common problem of half learning i.e. you know the concept but you don't know the application. If you neither know what problem it solves nor what benefit it provides, then just knowing the concept is not good enough. You won't be able to reap all benefit if you just know the concept and never use it in practice. The most important benefit overloading provides is a cleaner and intuitive API. Read more �

Top 10 Java Swing Interview Questions Answers asked in Investment banks

The Swing API and toolkit are heavily used in developing trading application front end in Java on both large Investment banks and small broker firms. Doesn�t matter whether its front office or middle office application, you will find Java Swing GUI everywhere. The Swing-based GUI is used to develop Order entry system, Order monitoring GUI and for other tools which trader or operations can use on different trade life cycle in the front office. middle office and back office space. Due to its heavy usage, there are a lot of requirements of Java Swing developer in investment banks like Barclays, Citibank, Deutsche Bank, Nomura, JP Morgan, Morgan Stanley and Goldman Sachs etc. Though in the era of Java 8, Java FX is positioned to take over from Swing but there are still a lot of legacy application which means the requirements for Java Swing developers will not dry out soon. Read more �

Exception in thread "main" java.lang.NoClassDefFoundError: Running Java from Command line

The "Exception in thread "main" java.lang.NoClassDefFoundError: helloworldapp/HelloWorldApp" error comes when you are trying to run the HelloWorldApp Java program from the command line but either .class file is not there or Java is not able to find the class file due to incorrect classpath settings. The name of the class could be different in each case, it depends upon which class you are passing to java command for running from the command prompt. Another interesting thing to remember is that this error only comes in Java version less than or equal to Java 6 e.g. Java 1.5 or Java 1.4, if you are running in JDK 7 or Java 8 instead of this you will see "Error: could not able to find or load class HelloWorldApp" . Technically, both errors come due to same reason and their solution is also exactly same. Read more �

Spring Hello World Example using XML Config

In this Spring framework tutorial, you will learn how to write the hello world example in Spring framework. This should be the first tutorial to start learning Spring framework, as it gets the ball rolling. While coding and running this example, you learn a lot about Spring framework, Spring XSD files, necessary JAR files, and more importantly how Spring framework works.This HelloWorld program in Spring framework is an extension of classic a l Java hello world program , w ritten usin g dependency Injection design pattern by using Spring Fram ework's IOC container. Even though now you can configure Spring dependency using annotations and Java configuration, this example uses traditional XML way to configure dependency. Read more �

How to convert java.util.Date to java.sql.Timestamp?

You can convert a java.util.Date to java.sql.Timestamp value by using the getTime() method of Date class. This method return the long millisecond value from Epoch (1st January 1970 midnight) which you can pass to java.sql.Timestamp to create a new instance of Timestamp object in JDBC. Remember, java.sql.TimeStamp class is a wrapper around java.util.Date to allow JDBC to view it as SQL TIMESTAMP value. Only way to create a Timestamp instance is by passing the long time value because the second constructor of Timestamp class, which accepts individual fields e.g. year, month, date, hour, minute, second and nano is deprecated. Timestamp class can also hold up-to nano second value. Read more �

Is "Java Concurrency in Practice" still valid in era of Java 8?

One of my reader Shobhit asked this question on my blog post about 12 must read advanced Java books for intermediate programmers - part1. I really like the question and thought that many Java programmers might have the same doubt whenever someone recommends them to read Java concurrency in Practice . When this book came first in 2006, Java world was still not sure of about new concurrency changes made in Java 1.5, I think the first big attempt to improve Java's built-in support for multi-threading and concurrency. Many Java programmers were even not aware of new tools introduced in the API e.g. CountDownLatch , CyclicBarrier , ConcurrentHashMap and much more. The book offered them the seamless introduction of those tools and how they can use them to write high-performance concurrent Java applications. Read more �

How to Print Pyramid Pattern of Alphabets in Java program

In earlier programming tutorials, I have taught you how to print pyramid pattern of stars and numbers in Java, and in this tutorial, you will learn printing pyramid pattern of alphabets. If you understand the logic of previous programs then this one won't be difficult for you because we will use the same logic of printing rows and columns using nested loop in Java. Actually, pyramid pattern is nothing but a matrix where you need to print rows and columns. Though, you need to learn where to print those values and when to move to next row. Once you know this trick of advancing, you can print any kind of pyramid pattern in Java. The one, we'll see in this tutorial is the simplest of one but I'll give you some tough one for exercise to develop your creativity and coding skill. Read more �

Integer vs floating point arithmetic - Java Coding Question

I am starting a new series called Java Coding Quiz, in which I'll show you subtle Java concepts hidden in the code. This is an OCAJP or OCPJP style question but focused on teaching subtle details of Java programming language. In today's puzzle, you will learn about one of the key concepts about how floating point and integer arithmetic works in Java. This is a very important concept for any Java developer because Java behaves differently when the same operation is performed by different types of variable but of the same value. Read more �

Base64 Encoding Decoding Example in Java 8

Until Java 8, there was no standard way to Base64 encode a String in Java or decode a base64 encoded String. Java Programmers either use Apache Commons library and it's Base64 class to encode or decode binary data into base 64 encoding, as shown here , or rely on internal Sun classes e.g. sun.misc.BASE64Encoder and sun.misc.BASE64Decoder() , which were not officially part of JDK and can be removed without notification. Java 8 solves this problem by providing standard support for base64 encoding and decoding by providing a java.util.Base64 class. This class contains methods like getEncoder() and getDecoder() to provide Base64 encoder and decoder to carry out base 64 encoding of String or binary data. In this article, I'll show you some example of how to base64 encode String in Java 8. Read more �

Java Program to print pyramid pattern of stars and numbers

You can print Pyramid pattern of stars or numbers using loops and print methods in Java. There are two print method you need to know, System.out.print() and System.out.println() , the difference between print() and println() is that println adds a new line character at the end i.e. it appends \n automatically. which means next time you write something will begin at the new line. On the other hand, if you use print() then the text is appended to the same line. By using these two methods, you can print any kind of pattern in Java program e.g. pattern involving multiple stars in one line, a pattern involving stars at different lines, pyramid of numbers, a pyramid of stars, inverted pyramid pattern of numbers, stars and alphabets, and so on. Read more �

How to check if String contains another SubString in Java? contains() and indexOf() example

You can use contains() , indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accept a String and return starting position of the string if it exists, otherwise it will return -1. For example "fastfood".indexOf("food") will return 4 but "fastfood".indexOf("Pizza") will return -1 . This is the easiest way to test if one String contains another substring or not. The second method is lastIndexOf() which is similar to indexOf() but start the search from the tail, but it will also return -1 if substring not found in the String or the last position of the substring, which could be anything between 0 and length -1. Read more �

How to check if a String is numeric in Java? Use isNumeric() or isNumber()

In day-to-day programming, you often need to check if a given String is numeric or not. It's also a good interview question but that's a separate topic of discussion. Even though you can use a Regular expression to check if given String is empty or not, as shown here , they are not full proof to handle all kinds of scenarios, which common third party library like Apache commons lang will handle e.g. hexadecimal and octal String. Hence, In Java application, the simplest way to determine if a String is a number or not is by using Apache Commons lang's isNumber() method, which checks whether the String a valid number in Java or not. Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation and numbers marked with a type qualifier (e.g. 123L). Non-hexadecimal strings beginning with a leading zero are treated as octal values. Thus the string 09 will return false since 9 is not a valid octal value. However, numbers beginning with ...

How to split String in Java by WhiteSpace or tabs? Example Tutorial

You can split a String by whitespaces or tabs in Java by using the split() method of java.lang.String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces. Though this is not as straightforward as it seems, especially if you are not coding in Java regularly. Input String may contain leading and trailing spaces, it may contain multiple white spaces between words and words may also be separated by tabs. Your solution needs to take care of all these conditions if you just wants words and no empty String . In this article, I am going to show you a couple of examples to demonstrate how you can split String in Java by space. By splitting I mean getting individual words as String array or ArrayList of String, whatever you need. Read more �

How to Serialize Object in Java - Serialization Example

Serialization is one of the important but confusing concept in Java. Even experienced Java developer struggle to implement Serialization correctly. The Serialiation mechamism is provided by Java to save and restore state of an object programatically. Java provides two classes Serializable and Externalizable in java.io package to facilitate this process, both are marker interface i.e. an interface without any methods. Serializing an Object in Java means converting into a wire format so that you can either persists its state in a file locally or transfer it to another client via the network, hence it become an extrememly important concept in distributed applications running across several JVMs. There are other features in Java e.g. Remote Method Invocation (RMI) or HttpSession in Servlet API which mandates the participating object should impelment Serializable interface because they may be transffered and saved across the network. Read more �