Tuesday, October 31, 2017

How to Convert Double to String to Double in Java Program with Example

Many scenarios come in day to day Java programming when we need to convert a Double value to String or vice versa. In my earlier article we have seen how to convert String to Integer and in this article, we will first see how to convert double to String and the later opposite of  that from String to double. One important thing to note is Autoboxing which automatically converts primitive type to Object type and only available from Java 5 onwards. This conversion example assumes the code is running above Java 5 version and actually tested in JDK 1.6, which makes it unable to pass Double object when the method is expecting double primitive value e.g. String.valueOf(double d) which expect a double value.

Monday, October 30, 2017

How to Stop Thread in Java Code Example

The thread is one of important Class in Java and multithreading is most widely used a feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default, a Thread stops when execution of run() method finish either normally or due to any Exception.In this article, we will How to Stop Thread in Java by using a boolean State variable or flag. Using a flag to stop Thread is a very popular way  of stopping the thread and it's also safe because it doesn't do anything special rather than helping run() method to finish itself.

Sunday, October 29, 2017

How to send HTTP request from UNIX or Linux? Use curl or wget command

You can use either curl or wget command to send HTTP request from UNIX or Linux operating system. Both commands allow you to send GET and POST request, which means you can also call REST web services.  I have a Java web application, which runs on Linux and exposes WebServices. I was writing a UNIX script to download In some data from that web service when I hit by the question, how do I make an HTTP call from UNIX? What is the UNIX command should I use? If you are also facing the same question, then you have come to right place. Basically, you can use two UNIX commands to make the HTTP request, wget, and curl. You can use curl and wget to send both GET and POST HTTP request. My use case was rather simple, I just need to make a GET call to web service to download the data, but these two commands are very powerful and provide many different options to interact with the web using HTTP right from the shell.

What is static import in Java 5 with Example

Static import in Java allows to import static members of class and use them, as they are declared in the same class. Static import is introduced in Java 5 along with other features like Generics, Enum, Autoboxing and Unboxing and variable argument methods. Many programmer think that using static import can reduce code size and allow you to freely use static field of external class without prefixing class name on that. For example without static import you will access static constant MAX_VALUE of Integer class as Integer.MAX_VALUE but by using static import you can import Integer.MAX_VALUE and refer it as MAX_VALUE. Similar to regular import statements, static import also allows wildcard * to import all static members of a class. In next section we will see Java program to demonstrate How to use static import statements to import static fields.

List of Tibco RV, EMS Tutorials , Tips from Javarevisited

Hi guys , just thought about some more topics to explain on this tibco tutorial series , let me know out of below which Tibco topics you would like to me cover first , please suggest if you have other topics in mind. I am now updating this post as most of the topics are already covered but I forgot to update this post.

I have covered difference between routing daemon and Tibco daemon in this part. basically main difference between both of them is the purpose. RVD is mainly for sending and receiving message in same network between two Tibco RV publisher and subscriber while RVRD is used to bridge two different network from two different countries, cities or even continent. Most of the investment banks has RVRD bridging there London to New-york traffic or London to Tokyo traffic. Bandwidth of these WAN networks are very important because if  you have just one slow Tibco subscriber that can bring down whole network link between two regions. We had an incident when one of out application is publishing huge amount of updates in MB and on other side we had a GUI on a slow desktop which is keep asking for resend, this problem is often referred as Tibco RV storm and its very serious issue while working with Tibco messaging. One important thing to note here is reliability parameter of tibco rv which actually defines how long publisher should hold the message if set very low can cause frequent retransmission request.

The Most Simple trick to Loss Weight - Buy A Digital Weight Machine and Check Your Weight Daily

You must be wondering why I am sharing a weight loss or physical fitness tip in my Java programming blog? Well, after reading Soft Skills: The software developer's life manual by John Sonmez, a software developer, and life coach, I found that fitness is very important for programmers and it's about time we should take it seriously.  In general, programmers and IT professionals are not the most physically active persons and hence the easy target for the life-threating disease like heart-attack and diabetic. I started my weight loss journey last year, achieved something but lost it again due to busy work schedule. In this article, I am going to share some of my experience, starting with the most simple trick to lose weight, which worked for me and helped me to lose 8Kg in 3 months.

Saturday, October 28, 2017

How to use multiple JQuery UI Date Picker or Datepicker in HTML or JSP page

We often needs to use multiple JQuery date picker in one HTML or JSP page, classical example is online flight booking for return trips, where you need to pick departure date and arrival date from two separate datepickers. While designing HTML forms either statically or dynamically using JSP, you may want to associate date picker with multiple input text field, paragraph or any other HTML elements. By using JQuery UI and some help from CSS ID and class selector, we can easily use multiple datepicker in one HTML page. All you need to do is, declare a CSS class say .datepicker and apply that class to all HTML elements which needs date picker, for example we have associated date picker with 4 input text fields, which has .datepicker class. By using a class, it becomes extremely easy to select all those element using JQuery class selector, and once you got all those element, you can just call datepicker() methods. This method does all the hard-work and associate a date picker object with selected items, that's it. Now you are ready to use multiple date picker in your HTML or JSP page, let's see the complete code. By the way if you are just starting with jQuery than I highly recommend Head First Query, it’s easy to read  and contain some non trivial example to learn jQuery quickly.

Grokking Algorithms By Aditya Bhargava - Book Review - Best Algorithm Book for Beginners

I have read many books on data structures and algorithms e.g. Introduction to Algorithms by Thomas H. Corman and Algorithm design manual by Steve S. Skiena, so when I come to know about this book, I thought, just another book on algorithms, but I was wrong. This is not just another book on algorithms but one of the most interesting books you will ever read on Algorithms and Data structure. Let's accept it, data structure and algorithms is interesting but at the same time they are very complex and hard to understand, especially, if not explained very well and that's where this book rocks. It explains things in very easy language and most importantly with a context, which helps to understand the topic better.

Friday, October 27, 2017

What is difference between java.sql.Time, java.sql.Timestamp and java.sql.Date - JDBC interview Question

Difference between java.sql.Time, java.sql.Timestamp and java.sql.Date  is most common JDBC question appearing on many core Java interviews. As JDBC provides three classes java.sql.Date, java.sql.Time and java.sql.Timestamp to represent date and time and you already have java.util.Date which can represent both date and time, this question poses lot of confusion among Java programmer and that’s why this is one of those tricky Java questions which is tough to answer. It becomes really tough if differences between them is not understood correctly. We have already seen some frequently asked or common JDBC questions like why JDBC has java.sql.Date despite java.util.Date and Why use PreparedStatement in Java in our last tutorials and we will see difference between java.sql.Date, java.sql.Time and java.sql.Timestamp in this article. By the way apart from these JDBC interview questions, if you are looking to get most from JDBC you can also see 4 JDBC performance tips and 10 JDBC best practices to follow. Those article not only help you to understand and use JDBC better but also help on interviews. Let’s come back to difference sql time, timestamp and sql date.

Thursday, October 26, 2017

JSTL foreach tag example in JSP - looping ArrayList

JSTL  foreach loop in JSP
JSTL  foreach tag is pretty useful while writing Java free JSP code.  JSTL foreach tag allows you to iterate or loop Array List, HashSet or any other collection without using Java code. After introduction of JSTL and expression language(EL) it is possible to write dynamic JSP code without using scriptlet which clutters jsp pages. JSTL foreach tag is a replacement of for loop and behaves similarly like foreach loop of Java 5 but still has some elements and attribute which makes it hard for first-timers to grasp it. JSTL foreach loop can iterate over arrays, collections like List, Set and print values just like for loop. In this JSP tutorial we will see couple of example of foreach loop which makes it easy for new guys to understand and use foreach loop in JSP. By the way this is our second JSP tutorial on JSTL core library, in last tutorial we have seen How to use core <c:set> tag in JSP page.

How to replace NULL with Empty String in SQL Server? ISNULL() vs COALESCE() Examples

We often need to replace NULL values with empty String or blank in SQL e.g. while concatenating String. In SQL Server, when you concatenate a NULL String with another non-null String the result is NULL, which means you lose the information you already have. To prevent this, you can replace NULL with empty String while concatenating. There are two ways to replace NULL with blank values in SQL Server, function ISNULL() and COALESCE(). Both functions replace the value you provide when the argument is NULL e.g. ISNULL(column, '') will return empty String if the column value is NULL. Similarly, COALESCE(column, '') will also return blank if the column is NULL.

Wednesday, October 25, 2017

Eclipse shortcut to System.out.println in Java program - Tips

Eclipse IDE provides quick shortcut keys to print System.out.println statement in Java but unfortunately not every Java programmers are familiar of that.  Even programmers with 3 to 4 year of experience sometimes doesn't know this useful Eclipse shortcut to generate System.out.println messages.  This Eclipse tips is to help those guys. Let me ask you one question, How many times you type System.out.println in your Java program?  I guess multiple time,  while doing programming, debugging and testing small stuff.  System.out.println is the most preferred way to print something on console because it doesn’t required setup like configuring Log4J or java.util.Logger . Though I recommend using logging for better information display in production code, nobody can undermine importance of System.out.println statement in Java. On the quest of learning Eclipse shortcut, some of them which I have discussed in my list of Top 30 Eclipse shortcut for Java programmers,  I found a very useful Eclipse shortcut for generating code for System.out.println statement in Java source file. 

Java program to calculate area of Triangle - Homework, programming exercise example

Calculate area of Triangle in Java
Write a Java program to calculate Area of Triangle, accept input from User and display output in Console is one of the frequently asked homework question. This is not a tough programming exercise but a good exercise for beginners and anyone who has started working in Java. For calculating area of triangle using formula 1/2(base*height), you need to use arithmetic operator. By doing this kind of exercise you will understand how arithmetic operators works in Java, subtle details which affect calculation like precedence and associativity of operator etc. Fortunately this question is not very popular on Java interview like other exercise we have seen e.g. Java program to print Fibonacci series and Java program to check for palindrome. Nevertheless its a good Java homework.

Monday, October 23, 2017

How to Implement Binary Search Tree in Java? Example

A binary search tree or BST is a popular data structure which is used to keep elements in order. A binary search tree is a binary tree where the value of a left child is less than or equal to the parent node and value of the right child is greater than or equal to the parent node. Since its a binary tree, it can only have 0, 1 or two children. What makes a binary search tree special is its ability to reduce the time complexity of fundamental operations like add, remove and search, also known as insert, delete and find. In a BST, all these operations (insert, remove and find) can be performed in O(log(n)) time. The reason for this improvement in speed is because of the unique property of binary search tree, where for each node, the data in the left child is less than (or equal) and the data in the right child is greater than (or equal) to the data in said node.

Sunday, October 22, 2017

Tibco tutorial : Certified Messagging

This is in continuation of my previous tibco tutorial. tibco rv is most widely used middleware in enterprise world heavily used in banking and many global investment bank rely on tibco rv for there high speed messaging requirement. its used by many trading application to receive high speed data e.g. Market data. in reliable mode tibco provide reliable delivery of data but not guaranteed means if sender sends data to receiver via tibco multicast network , tibco tries best to deliver that data to receiver but there is no guarantee, data could be lost if receiver is too busy to receive it , if receiver is not running or receiver is hang. In some cases its possible to recover lost data by sending "Resend Request".

Saturday, October 21, 2017

Spring Framework Certification FAQ - Frequently asked Questions Answers

If you are a Java developer, working in Spring framework and thinking to become a certified Spring professional but couldn't to do it in the past due to expensive mandatory training provided by Pivotal and its partners then there is a good news for you. From 10th May 2017, Pivotal made the Spring Core training optional for appearing to Spring certification exam, which means, now, it's not mandatory to take Spring training for Spring certifications (see here). Similar to Oracle's Java certifications, you can become a Pivotal certified Spring Professional by just buying the exam vouchers and scheduling your exam online using examlocal.com from anywhere in the world.

Friday, October 20, 2017

5 ways to add multiple JAR in to Classpath in Java

How to add JAR file to Classpath in Java
Adding JAR into classpath is a common task for Java programmer and different programmer do it on different way. Since Java allows multiple ways to include JAR file in classpath, it becomes important to know pros and cons of each approach and How exactly they work. There are 5 ways to add  jars on into classpath in Java some of them we have already seen in  How classpath works in Java and How to set Path in Java. In this post we will revisit some of those techniques and explore Java 1.6 wildcard to add multiple JAR into classpath. By the way here is 5 ways to add JAR file into classpath. In short knowledge of Path, Classpath and Classloaders are must for any Java programmer, not only from knowledge point of view but also to successfully debug and resolve issues related to Classpath e.g. NoClassDefFoundError and java.lang.ClassNotFoundException  in Java.

What is Iterator and ListIterator in Java Program with Example - Tutorial Code Sample

Iterator in Java is nothing but a traversing object, made specifically for Collection objects like List and Set. we have already aware about different kind of traversing methods like for-loop ,while loop,do-while,for each lop etc,they all are  index based traversing but as we know Java is purely object oriented language there is always possible ways of doing things using objects so Iterator is a way to traverse as well as access the data from the collection. Even with traversing with object we have Enumeration, Iterator and ListIterator in Java which we will in this Java Iterator tutorial.

Thursday, October 19, 2017

Regular Expression in Java to check numbers in String - Example

Regular Expression to check numeric String
In order to build a regular expression to check if String is number or not or if String contains any non digit character or not you need to learn about character set in Java regular expression, Which we are going to see in this Java regular expression example. No doubt Regular Expression is great tool in developer arsenal and familiarity or some expertise with regular expression can help you a lot. Java supports regular expression using java.util.regex.Pattern and java.util.regex.Matchter class, you can see a dedicated package java.util.regex for regular expression in Java. Java supports regex from JDK 1.4, means well before Generics, Enum or Autoboxing. If you are writing server side code in Java programming language than you may be familiar with importance of regular expression which is key in parsing certain kind of messages e.g. FIX Messages used in Electronic trading. In order to parse Repeating groups in FIX protocol you really needs understanding of regular expression in Java. Any way In order to learn validating numbers using regular expression we will start with simple example

Difference between private, protected, public and package modifier or keyword in Java

private vs public vs protected vs package in Java
Java has four access modifier namely private, protected and public. package level access is default access level provided by Java  if no access modifier is specified. These access modifiers are used to restrict accessibility of a class, method or variable on which it applies. We will start from private access modifier which is most restrictive access modifier and then go towards public which is least restrictive access modifier, along the way we will see some best practices while using access modifier in Java and some examples of using private and protected keywords.

Difference between Truncate and Delete command in SQL - Interview Questions with Example

Truncate and delete in SQL are two commands which are used to remove or delete data from a table. Though quite basic in nature both SQL commands can create a lot of trouble until you are familiar with details before using it. The difference between Truncate and delete are not just important to understand perspective but also a very popular SQL interview topic which in my opinion a definite worthy topic. What makes them tricky is the amount of data. Since most of Electronic trading system stores large amount of transactional data and some even maintain historical data, a good understanding of delete and the truncate command is required to effectively work in that environment.I have still seen people firing delete command just to empty a table with millions of records which eventually lock the whole table for doing anything and take ages to complete or Simply blew log segment or hang the machine.

Tuesday, October 17, 2017

Clean Code by Uncle Bob - Book Review - Must read for Software Engineers

Even though, the Clean Code book has been released many years ago and there are lots of good reviews already available, I couldn't resist to write my own experience about this great book. I came across this book many years ago but since then I have read it multiple times and I have recommended it to my readers, students, and fellow developers. It is one of those books which make you feel that why didn't you come across it earlier, I felt the same when I first learned about this book. The Clean Code is all about writing good quality code and how do you judge the quality of code? Well, you won't appreciate good until you have seen bad code and that's what this book do.

Monday, October 16, 2017

10 Garbage Collection Interview Questions and Answers in Java Programming

GC Interview Questions Answer in Java
Garbage collection interview questions are very popular in both core Java and advanced Java Interviews. Apart from  Java Collection and Thread  many tricky Java questions stems Garbage collections which are tough to answer. In this Java Interview article I will share some questions from GC which is asked in various core Java interviews.These questions are based upon concept of How Garbage collection works, Different kinds of Garbage collector and JVM parameters used for garbage collection monitoring and tuning. As I said GC is an important part of any Java interview so make sure you have good command in GC. One more thing which is getting very important is ability to comprehend and understand Garbage collection Output, more and more interviewer are checking whether candidate can understand GC output or not. During Java interview they may provide a snippet of GC output and ask various questions based on that e.g. Which Garbage collector is used, whether output is from major collection or minor collection, How much memory is free from GC, What is size of new generation and old generation after GC etc. I have included few Garbage collection interview questions and answers from GC output to help with that. It’s recommended to prepare questions from Java collection,  multithreading and programming along with Garbage collection to do well in Java interviews at any stage.

Sunday, October 15, 2017

How to convert decimal to binary, octal and hex String in Java Program

This article is a simple Java program which converts the decimal number to binary, octal and hexadecimal format. When it first came into my mind I though I would probably need to write whole code to convert decimal to various other radix or base numbers but when I looked Integer class and saw these two way of converting decimal to binary etc I was simply amazed. It’s indeed extremely easy to do this in java and you can also write this program or use it is.

FIX Log Viewer - Tool to view FIX messages in Readable format

It's been a long time, I wrote anything related to FIX protocol, my last article was about FIX protocol dictionaries, also known as Fixionnary, one of the most important tools of the trade for Java developers and support personnel working in FIX. Today, I am going to share another useful tool called FIX Log Viewer, which allows you to view FIX engine logs in a much more readable format.

How to write Helloworld in Google Dart with Example - Dart Tutorial

Google Dart  Program Example Tutorial

Google dart is now released and its time to try google dart and see how much it offers to a programmer and whether it is suitable language to replace JavaScript or not. As a language my first impression of Google dart is great it looks so much familiar with Java my favorite programming language and this motivate me to write this hello-world example in Google Dart and execute it , run it and see how it works. Google dart has Class and Object, it has final keyword, String Class , Object class , extends keyword and many more I going to learn but it really look structure because it has google dart compiler which shows warning and error like any other structure programming language.

In this Google Dart tutorial we will see How to write Helloworld in Google Dart and How to run Google dart program using Google Dartboard Application which is a browser based application, allow you to write and run Google Dart Programs. This is the easiest and quickest way to get a feel of Google Dart language itself before trying it with HTML code. Google Dart also has compiler and html converter which allow you to convert Dart code into JavaScript and use it. We will see about how to convert Google Dart Code into JavaScript in next article. For now let's start with this step by step guide of writing Google Dart HelloWorld Example and running it.

Step by Step Guide to Write and Run Google Dart Example

I. Open http://www.dartlang.org/ in your browser.

Make sure you use Mozilla Firefox, Google Chrome or Apple Safari. Google Dartboard application won’t work on Microsoft Internet Explorer, though support is coming in may be few days or week.also if you are using Mozilla please use latest version, Google Dartboard was not working on my Mozilla Firefox 3.6 versions. Once you open this link Google Dartboard Application will be open on your browser and first example which it has is "Hello Dart" as shown in below screen.

google dart example tutorial

II. Important points about Google Dart structured programming language

Now you have two options either edit the existing program or write a new program.
Before writing new program let’s see few points about google dart language.

1. Like Java google dart program will start with main () method.

2. You can declare Variable using "var" a JavaScript style or using correct type like String or int using Java Style , for example below two code  are same.

String text = "NYSE is biggest Stock Market in world";
var text = "NYSE is biggest Stock Market in world";

It depends upon your choice whether you want to adopt javascript style or Java Style. Since I am a Java programmer I found Java Style more intuitive and easy to use.

3. You can assign incorrect type to variable e.g. in this example assigning "text" as int, your programe will run but Dart compiler will show warning related to incorrect type.

int text ="google dart compler will show warning but programme will run".

4. Instead of var or a formal type, you can use final keyword and your program will run successfully.

5. Each statement ends with semicolon ";" otherwise compiler will throw error "Unexpected token "IDENTIFIER expected" or "; expected"

6. For displaying value of variable we need to use interpolation or jsp expression language style "${var}" or else it will complain as "cannot resolve text".

7. We can display string as literal, exactly same as in Java. print() method is similar to Perl, java or any other language. For example

print("This is String literal");

III. Our first google dart program

main() {
  String tradingSecrets = "High Frequency Trading requires extremely fast computers";
  int latency = 10;
  String message = "Google Dart language";
  print('Hello world in ${message }');
  print("This is String literal just like Java");
  print( '${tradingSecrets}');


Hello world in Google Dart language
This is String literal just like Java
High Frequency Trading requires extremely fast computers

IV. Running your Google Dart program

Just press the Run button as shown in the above image, it will contact darn server and run your program, sometime you may get error as "The darn server failed to respond." but mostly you see out of your google dart program.

This is the first Google Dart tutorial there are more to come but this is good to start and get feeling of Google dart language. Google Dartboard application is easy to use and execute google dart program which reduce learning curve but converting google dart program to JavaScript and than running into HTML file like JavaScript requires little effort which we will see in next article.

Saturday, October 14, 2017

10 Example Queries of SQL Select Command

The Select command in SQL is one of the most powerful and heavily used commands. This is I guess the first command anyone learn in SQL even before CREATE which is used to create a table in SQL. SELECT is used in SQL to fetch records from database tables and you can do a lot many things using Select. For example, you can select all records, you can select few records based on the condition specified in WHERE clause, select all columns using the wild card (*) or only selecting a few columns by explicitly declaring them in a query.

How to Use Locks in Multi-threaded Java Program

Many Java programmers confused themselves like hell while writing multi-threaded Java programs e.g. where to synchronized? Which Lock to use? What Lock to use etc. I often receive request to explain about how to use Locks in Java, so I thought to write a simple Java program, which is multi-threaded and uses rather new Lock interface. Remember Lock is your tool to guard shared resource which can be anything e.g. database, File system, a Prime number Generator or a Message processor. Before using Locks in Java program, it’s also better to learn some basics. Lock is an interface from java.util.concurrent package. It was introduced in JDK 1.5 release as an alternative of synchronized keyword. If you have never written any multi-threading program, then I suggest first start with synchronized keyword because it’s easier to use them. Once you are familiar with working of multi-threading program e.g. How threads share data, how inter thread communication works, you can start with Lock facility. As I told you Lock is an interface, so we cannot use it directly, instead we need to use its implementation class. Thankfully Java comes with two implementation of java.util.concurrent.locks.Lock interface, ReentrantLock and ReentrantReadWriteLock, later provides two more inner implementation known as ReentrantReadWriteLock.ReadLock and ReentrantReadWriteLock.WriteLock. For our simple multi-threaded Java program's purpose ReentrantLock is enough.

Friday, October 13, 2017

Java Program to get input from User from Console or command line- Example Tutorial Code

How to get input from user in Java from command line or console is one of the common thing ,every one started learning Java looks for. It’s second most popular way of starting programming after HelloWorld in Java. There are so many ways to get input from User in Java including command line and Graphical user interface. For beginner simpler the example, better it is. first and foremost way of getting input from user is String[] passed to main method in Java but that only work for one time requirement and its not interactive. Another way of getting input from User is involving IO classes like InputStream to read from console or command line which can be little complicated for true beginner. Thanks to Java 5 which added a nice utility class called Scanner, has made task of getting input from user very easy. Scanner is powerful and allows you to get any kind of input from User e.g. String, int, float etc.

Jackson JSON Parsing Error - UnrecognizedPropertyException: Unrecognized field, not marked as ignorable [Solved]

While parsing JSON string received from one of our RESTful web services, I was getting this error "Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "person" (class Hello$Person), not marked as ignorable". After some research, I found that this is one of the common error while parsing JSON document using Jackson open source library in Java application. The error messages say that it is not able to find a suitable property name called "person" in our case, let's first take a look at the JSON we are trying to parse, the class we are using to represent the JSON document and the error message itself.

Error Message:
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "person" (class Hello$Person), not marked as ignorable (4 known properties: , "id", "city", "name", "phone"])

Thursday, October 12, 2017

Eclipse shortcut to remove all unused imports in Java file

How to remove all unused imports in Eclipse
Eclipse IDE gives warning "The import XXX is never used" whenever it detect unused import in Java source file and shows a yellow underline. Though unused import in Java file does not create any harm, it's unnecessary increase length and size of Java source file and if you have too many unused imports in your Java source file, those yellow underline and Eclipse warning affect readability and working. In our last post on Eclipse, we have seen dome Java debugging tips on Eclipse and in this post we will see Eclipse shortcut to remove all unused imports in Eclipse. There are many options to tackle this problem e.g. you can collapse import section of code in Eclipse or you can altogether remove all unused imports from Java file. Since Eclipse is favorite IDE of many Java programmer, who love to do things fast in shortcuts, I will also share Eclipse shortcut to remove unused imports from Java program in this article. This is one of many Eclipse shortcuts which we have discussed in our post Top 30 Eclipse keyboard shortcut for Java programmer. Let's see How to remove all unused imports from Java file in Eclipse IDE.

What is Double Brace Initialization in Java? Anti Pattern Example

Double brace initialization is a Java idiom to initialize a Collection like a list, set and map at the time of declaration. At times, you need a list of fixed elements e.g. supported products, supported currencies or some other config, and on the spot initialization reduces line of code and improves readability. Double brace initialization idiom becomes popular because there is no standard way to create and initialize Collection at the same time in Java. Unfortunately, unlike another language, Java doesn't support collection literals yet. Due to this limitation, creating an unmodifiable List with small numbers of elements requires many lines of code involving creating list, repeatedly calling add() method to add those elements and then finally wrapping it into unmodifiable list as shown below :

What is Class in Java Programming with General Example

When I first about Class in Java I just thought what is this Class in Java and from that date to now Whenever we talk about java its really incomplete without classes, every one who are little bit familiar with java knows it’s purely object oriented language means every thing we discuss in java as object .so its very important for learner or anyone who is keen to know about java should know about java class then only they can move forward on java world.
In this article we will see what Java Class, Example of Class in Java is and what makes a Java Class including members, field and method.If you have just started programming in Java or learning Please check my article How to Set Path for Java and How to set ClassPath for Java covering two important concept PATH and CLASSPATH.

Class in Java Programming Example

What is Java Class?

Java class is nothing but a template for object you are going to create or it’s a blue print by using this we create an object. In simple word we can say it’s a specification or a pattern which we define and every object we define will follow that pattern.

What does Java Class Consist

§          When we create class in java the first step is keyword class and then name of the class or identifier we can say.
§          Next is class body which starts with curly braces {} and between this all things related with that class means their property and method will come here.

Template is:

Class (name of the class) {

(Here define member of class)


Access level of class:

Java class has mainly two type of access level:

Default: class objects are accessible only inside the package.

Public: class objects are accessible in code in any package.

What are members of Class?

When we create a class its totally incomplete without defining any member of this class same like we can understand one family is incomplete if they have no members.
What is Class in Java Program with Example
Field: field is nothing but the property of the class or object which we are going to create .for example if we are creating a class called computer then they have property like model, mem_size, hd_size, os_type etc

Method: method is nothing but the operation that an object can perform it define the behavior of object how an object can interact with outside world .startMethod (), shutdownMethod ().

Access Level of members: Access level is nothing but where we can use that members of the class.
Each field and method has an access level:
  • private: accessible only in this class
  • package or default: accessible only in this package
  • protected: accessible only in this package and in all subclasses of this class
  • public: accessible everywhere this class is available

Real world example of Class in Java Programming:

In real world if we want to understand about the class everything of same quality  can be visualize as a class e.g. men,women,birds ,bicycles ,cars or  we can say vehicle .
The entire vehicle will make one class they have the property like no_of_wheels, color, model, brand etc.now we can think changeGear () and speedOfvehicle (), applyBreak () etc as a method on that class. Similarly all human being also can be one class now their member will be a men ,women ,child.,isAlive() ,isDeath() can be their method or behavior of that class .again we can make Men or women a separate class and define their property and method accordingly,
In short in java every problem we get solution can be think in terms of class and object.

One Java class example:

Class Stock {
Public commodity;
Public price;
Public void buy (int no_of commodity) {}
Public boolean sale () {}

In this example Stock is called Class and commodity, price are field and buy() and sale() are two methods defined inside class. To access elements of Class you need to create an instance of class Stock. You can create instance of Class using keyword new as shown below

Stock highBetaStock = new Stock();

For calling method of Stock just call by using instance.


Further Learning
Java Fundamentals, Part 1 and 2
SOLID Principles of Object Oriented Design
Head First Design Pattern

In short in java everything must be thinking in terms of java class its nothing but a template they have their own members and methods for accessing those members. The entire member has their own visibility which is decided by the developer where they want to use those objects.

Related Java Tutorials

What are builtin Properties in ANT >> Tutorial Example

This is the fourth article of series "ant tutorial for beginners" here I have included some more fundamental concept in form of Q/A to provide you clear and concise description and situation where you apply these concept. Please let me know if you have any questions , comments I will be happy to reply those .

What are built in properties available in ant ?
Built in properties are those which ant provides by default , you need not have to declare these property you can just use it. You can divide them in two parts

Wednesday, October 11, 2017

Google Dart: New Programming language to replace JavaScript

Google Dart: Structured Web Programming language 

Google has launched its much awaited mysterious DART web programming language. Ahh another programming language…, why does google launched a new language Google DART? What I read from the web is that google is trying to replace JavaScript as main web scripting language. Over the years from Netscape Era JavaScript has evolved, formed a large based of Developers and has existing codes, framework, and utilities, so I am not sure how far Google DART can go but this is a serious attempt to replace JavaScript much in the line of Chrome which was launched to replace Internet Explorer and What we see now is they are living happily with their own market share though Chrome is growing and snatching market share from other browsers.

Tuesday, October 10, 2017

Effective Java, 3rd Edition Now Available - Covers JDK 7, 8, and 9 -Must Read Book for Java Programmers in 2018

Hello guys, I have an interesting news to share with you today. After a long wait of almost 10 years, Effective Java 3rd edition is finally coming this year, hopefully, December 2017. The Effective Java 2nd Edition was released in May 2008 and updated for Java SE 6, but it been, good 10 years now and there is a lot of interest from Java developers around the world for Effective Java 3rd edition after Java SE 8 release and I am very happy to inform you guys that, finally, all our wishes are granted and Effective Java 3rd edition is set to arrive this year. It will not only cover Java 9 release but also all the changes from Java 7 and Java 8.

Top 30 Eclipse Keyboard Shortcuts for Java Programmer

This tutorial is about 30 Eclipse keyboard shortcuts, this list is by no means complete and I will suggest you guys to share eclipse shortcuts listed other than here to make this more useful. Eclipse is the most used Java development IDE and knowing Eclipse shortcuts not only improve your productivity but also makes you more efficient. You will have more time for things you like to do. Using keyboard shortcuts also helps to impress colleagues and shows that you have a good hold on tools you used for Java Development. If you are a Java developer, who use Eclipse as its main IDE for all coding, development, and debugging purpose, then I also suggest you to take a look at The Java Developer's Guide to Eclipse, 2nd Edition, one of the best book to learn how to use Eclipse from Java programmer's perspective.

Monday, October 9, 2017

How to write build.xml and run build in Apache ANT

This is the second article on Apache ANT tutorials for beginners series As I have always said that I like the short , clear and concise tutorial which tells about few concept but in a clear and concise manner and put weight on fundamentals . I try to adopt same theory while writing my blog post while writing my experience coupled with the concept which is important for a software developer point of view.

SQL Server JDBC Error: The TCP/IP connection to the host Failed

I had installed SQL SERVER 2014 Express edition and I was trying to connect to SQL SERVER from Java program using JDBC, but I was repeatedly getting following error:

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "connect timed out. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".Error while closing connection !!null

Top 10 JSP Interview Questions Answers for Java Programmer

This JSP interview questions and answers are asked in the various J2EE interview and focus on view part of 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 is 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 question by google but I have included my version for quick reference. I would love to hear back from you and please share some JSP interview questions asked to you guys on the interview; I can include those in the main post for everybody’s benefit.

Right way to Close InputStream and OutputStream in Java

For some unknown reasons many Java programmers are not very comfortable with IO package. I don't know why, but I have found them much more comfortable with java.lang and java.util than java.io. One possible reason of this could be that, writing IO code require a bit of C++ like programming, which involves doing clean-up, releasing resources once done etc. Since Java made coding a lot easier by taking care of memory management, unknowingly it also introduced bad practice of not releasing resource after use e.g. database connections, socket connection, files, directory, printers, scanners or any other scarce resource.

Sunday, October 8, 2017

How SubString method works in Java - Memory Leak Fixed in JDK 1.7

Substring method from String class is one of most used method in Java, and it's also part of an interesting String interview question  e.g. How substring works in Java or sometime asked as how does substring creates memory leak in Java. In order to answer these questions, you knowledge of  implementation details is required. Recently one of my friend was drilled on substring method in Java during a Java interview, he was using substring() method from long time, and of course all of us has used this, but what surprises him was interviewer's obsession on Java substring, and deep dive till the implementation level. Though String is a special class in Java, and subject of many interview questions e.g. Why char array is better than String for storing password . In this case it was, substring method, which took center stage. Most of us rather just use substring(..), and than forgot. Not every Java programmer go into code, and see how exactly it's working. To get a feel of how his interview was let's start .

How to build project using Apache ANT ? ANT Build Tutorials for Beginners

Apache Ant tutorials for beginners

Hi Guys, today I would like to share some of my experience while working with ant build tool in form of short ant tutorials, ant is one tool which has gained its place in almost everywhere, it’s integral part of any project’s build system and provide foundation for complex, extensible build environment. I have been using ANT from my early programming days and I have seen some of the best designed build environments around ANT. In these ant tutorials for beginners we will see what is ant build tool? How to use ANT for building project? Fundamentals of ANT build tool, setting up ant build environment etc. I have created a series of ant tutorials and you can check next part of ant tutorials by following links ant tutorial part 2 and ant tutorial part 3

Saturday, October 7, 2017

Differences between @RequestParam and @PathVariable annotations in Spring MVC?

The Spring MVC framework, one of the most popular frameworks for developing a web application in Java world also provides several useful annotations to extract data from the incoming request and mapping the request to controller e.g. @RequestMapping, @RequestParam, and @PathVariable. Even though both @RequestParam and @ParthVariable is used to extract values from the HTTP request, there is a subtle difference between them, which makes them a useful question from interview and spring certification point of view. We'll examine the subtle difference between @RequestParam and @PathVaraible in this article. As the name suggests @RequestParam is used to get the request parameters from URL, also known as query parameters, while @PathVariable extracts values from URI.