Search This Blog

Saturday, 21 February 2015

Arraylist vs Vector in Java

1.  Synchronization and Thread-Safe

Vector is  synchronized while ArrayList is not synchronized  . Synchronization and thread safe means at a time only one thread can access the code .In Vector class all the methods are synchronized .Thats why the Vector object is already synchronized when it is created .

2.  Performance

Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus     in ArrayList two or more threads  can access the code at the same time  , while Vector is limited to one thread at a time.

3. Automatic Increase in Capacity

A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList ,      it increases
its Array size by 50%  .


By default ArrayList size is 10 . It checks whether it reaches the       last  element then it will create the new array ,copy the new data of last array to new array ,then old array     is garbage collected by the Java Virtual Machine (JVM) .

4. Set Increment Size

ArrayList does not define the increment size . Vector defines the increment size .

You can find the following method in Vector Class

public synchronized void setSize(int i) { //some code  }

There is no setSize() method or any other method in ArrayList which can manually set the increment size.

5. Enumerator

Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator .While ArrayList can only use Iterator for traversing an ArrayList .

6.  Introduction in Java

java.util.Vector  class was there in java since the very first version of the java development kit (jdk).
java.util.ArrayList  was introduced in java version 1.2 , as part of Java Collections framework . In java version 1.2 , Vector class has been refactored to implement the List Inteface .

Friday, 20 February 2015

10 Articles Every Programmer Must Read

Being a Java programmer and Software developer, I have learned a lot from articles titled as What Every Programmer Should Know about ..... , they tend to give a lot of useful and in-depth information about a particular topic, which otherwise is very hard to discover. In my quest of learning I have come across some very useful articles, which I have bookmarked for reference and multiple reading. I personally think that all programmer can benefit by reading these articles, which makes me write this post and share all of these "What Every Programmer Should Know" articles with you guys. These are from my personal bookmarks. In this article, you will see classic what every programmer should know article from topics like memory, Unicode, floating point arithmetic, networking, object oriented design, time, URL Encoding, String and many more. This list is very important for beginner and newcomers, as they are the ones, who lacks practical knowledge. Since most of these post are actually driven by practical knowledge, beginner and intermediate programmers can take a lot from it. Also gaining knowledge of fundamentals early in career helps to avoid mistakes, which has done by other programmers and software developers on their course of learning. Though it’s not easy to grasp all knowledge given in these articles in just one reading. You probably won't understand some details about floating point number or get confused with subtle details of memory, but it’s important to keep these list handy and refer them time to time with a context. So Good luck and Enjoy reading these wonderful articles.  By the way, don't forget to share any What Every Programmer Should know article, if it’s not already in this list.


What Every Programmer Should Know about Memory
This is one of the classic article, which will take you through may lanes of memory, some old, some new, some known and some unknown. Despite being so conman and omnipresent, not every programmer have enough knowledge of Memory. Knowledge of memory in modern system becomes even more important if you are in space of writing high performance application. Hardware designers have come up with ever more sophisticated memory handling and acceleration techniques–such as CPU caches–but these cannot work optimally without some help from the programmer. I am still reading this article, and I can't tell you how much I have learned from this about RAM, CPU Caches e.g. L1 and L2 cache, different types of memory, direct memory access, memory controller designs and Memory in general. In short, a must read for programmers of all level of experience.


What Every Computer Scientist Should Know About Floating-Point Arithmetic
Floating point arithmetic is a tricky topic, and it’s not easy to master. Even many Java programmer doesn't know what can go wrong when comparing float/double value with == operator. Many of us often makes mistake of doing monetary calculation in float and double. This article is another gem of this series and must read for all software developers and programmers. As your experience grows, you are expected to know subtle details of common things, and floating point arithmetic is one of them. As as senior Java developer, you must know how do perform monetary calculation, when to use float, double or BigDecimal classes, how to round floating point numbers etc. Even if you know fundamentals of floating point arithmetic, You will learn something new about floating point calculation by reading this article.


What Every Developer Should know about Unicode
Character encoding is another area, where many programmer struggle, and "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" aims to fill that gap. On side note, Yes that's the full title of that article. It was written by Joel Spolsky, one of the founder of statckoverflow.com. Joel has written this post on his blog almost 10 years back, but it is still relevant in today’s world. This article will teach you about What is Unicode, What is character encoding, how characters are represented using bytes and many more. One of the best thing about this article is language and flow, even if you don't know anything about Unicode, you can easily follow. In short, one more must read for all programmers, coders and software engineers.


What Every Programmer Should know about Time
Apart from Character encoding, time and date is another area, where many programmers struggle, including me. Even senior developers lost between GMT, UTC, day light saving and between leap seconds. Frankly speaking, It's not easy to deal with time zones without making any mistake, then add day light savings and effect of that. Problems becomes worse if you using trial and error method, because you will never able to solve your problem by doing that. There are so many things which can go wrong and there are equal number of misconceptions. Things like, whether date contains time-zone or not can confuse you like hell, converting UNIX time to other time-zone can freak you out, forget about clock synchronization and delays. I hope many of your misconception about time will go away and you will build sound fundamental about Time, by reading this classic article.


What every web developer must know about URL encoding
This article describes common misconceptions about Uniform Resource Locator (URL) encoding, then attempts to clarify URL encoding for HTTP, before presenting frequent problems and their solutions. While this article is not specific to any programming language, it illustrate the problems in Java) and finish by explaining how to fix URL encoding problems in Java, and in a web application at several levels. You will learn basics of URL grammar, general URL syntax in HTTP and other protocol. This article also explores common pitfalls of URLs e.g. character encoding, reserved character at different part of URL, and URL encoding/decoding issues. If you are a Java programmer, then you will also learn about how to handle URLs in Java application, the right way. How to construct URL and using Apache commons HTTP client library. Finally it also suggest best practices or dealing with URLs e.g. you should encode URLs when you build them, making sure your URL-rewrite filters deal with your URL correctly and many more. In short, a must read article for any web developer and programmer.



What should every programmer know about web development?
What Every Programmer and Devleper Should know Memory, Time, Date, String,UnicodeThis is an interesting article from programmers stack exchange, about what should every programmer implementing the technical details of a web application consider before making the site public. This includes things ranging from Interface design and User Experience, Security, Web standards, Performance, Search Engine Optimization(SEO), Technology involved, and about several important resources. Since today's world is hugely dependent upon internet and programmer having their personal site, blog is quite common. Experience learned on this article will not even help in your professional work but also in your personal work. You will learn about all key technology e.g. HTTP, HTML, XML, CSS, JavaScript, browsers compatibility, tips to reduce loading time of your website, XML sitemaps, W3C specifications and several other key details.


What Every Programmer Should Know About SEO
This is another article, which is very important for web developers, programmers and blogger. SEO is too big to ignore, since many programmers are also blogger, it’s important to learn few basics of Search Engine Optimization to help Google find their content and present to other fellow programmers. Since no company can survive without web presence in today's inter-connected world, SEO becomes even more important. If you own start-up, selling any product, then SEO is something to care about. All programmers, especially web developers can largely benefit from this article. Remember, Search Engine Optimization is vast and very dynamic subject, and also varies between different search engines e.g. Google, Yahoo, and others. So, In order to master this topic you will always need to update your knowledge.


What Every C Programmer Should Know About Undefined Behaviour #1/3
C programming language have the concept of "undefined behaviour". Undefined behaviour is a broad topic with a lot of nuances and that's one reason of Why I like Java, less number of undefined behaviour, less confusion, more stability and more peace. Many seemingly reasonable things in C actually have undefined behaviour, and this is a common source of bugs in programs. Beyond that, any undefined behaviour in C gives license to the implementation (the compiler and runtime) to produce code that formats your hard drive, does completely unexpected things, or worse. Read this excellent article to deep dive on sea of undefined behaviour


What Every Programmer Need to know about networking
From the article itself "You’re a programmer. Have you ever wondered how multi-player games work? From the outside it seems magical: two or more players sharing a consistent experience across the network like they actually exist together in the same virtual world. But as programmers we know the truth of what is actually going on underneath is quite different from what you see. It turns out that it’s all an illusion." This is very interesting article about networking, written for game programmers but I think every programmer and developer can benefit from this.


What Every Java Developer Should Know about String
This is my article on java.lang.String and what I personally thing every Java programmer should know about it. String is very important in day to day programming in Java and that's why good knowledge is must for any Java developer. This article touches many important areas of String including string pool, string literal, comparing String using == vs equals(), converting bytes to String, Why String is immutable, properly concatenating Strings and many more. Advanced programmer may already know all these stuffs but even then it’s good to revise them.


What should every programmer know about security?
This question was ask by one computer programming student in StackOverFlow. Just like we learn a lot about general programming concepts e.g. operating system, algorithm, data-structure, computer architecture, and other stuff, its also important to know about security. Though Security is vast topic ranging from encryption/decryption, SSL, web security, obfuscation, authentication, authorization etc, a basic minimum knowledge is must for every programmer. I personally didn't know much about Security when I started my career, its when I start writing Servlet/JSP based Java web application, I come to know about web security and several security threats like SQL Injection, Denial of Service, XML Injection, Cross site scripting and others. As Java developer, now I follow secure Java coding practices provided by fortify, PMP and other static code analysis providers.  This article is very good collection of topics and links about Security and whether you are doing coding or not, you will surely benefit from this resource.


Latency Numbers Every Programmer Should Know
This is the bonus article, but must read for every Programmer. In order to write high performance application in any programming language e.g. Java or C++, you ought to know fundamental latency numbers e.g. how much time it take to read a variable from memory, from L1 Cache, from L2 cache, from random read in SSD and from disk. How much time it take to lock unlock on mutex, to send a data packet from one city to another or doing a roundtrip on same data centre. These latency numbers are independent of any programming language and part of core knowledge, a developer must have to write high frequency low latency applications. Good thing about this link is that it also provides you comparative analysis of how these latency numbers have evolved over the years. You can see what these latency numbers were in 2006 and what they are now.


That's all in this list of article every Programmer must read. By reading articles titles as What Every Programmer or Developer Should know, you gain in-depth knowledge of a particular topic. Frankly speaking there are too many things to learn for programmers, learning a programming language like Java is just a tip of iceberg, but isn't it many of us have passion for learning. Programming is a challenging job, and only things which help you all along your career is fundamental knowledge e.g. things about Memory, Unicode, floating point numbers, time, security is very important for any programmer. Few things are programming language specific e.g. my post about Java String and What every C programmer should know about undefined behaviour, but they are still good to learn for many beginner and developers.


Introduction of How Android Works for Java Programmers

Android development is current buzz in Java programming world. It's the Android, which keeps Java in the fore front from last couple of years. Now, How important is to understand or learn Android for Java programmers? Well it depends, if you like application development and want to reach mass, Android offers that opportunity to you. Millions of Android phones are available and they are keep increasing, with pace, much higher than IPhone or iOS. What all these means is, it does make a lot of sense to learn Android programming for Java programmer, and this article is about that, but this is also a one of the  good reason to learn Java programming. This tutorial will give you basic idea of How Android works? not detailed but a good overview. One distinct advantage Java programmers has over others is that Android API is much like Java API, though Android doesn't support all classes available in J2SE SDK, it supports critical ones. Another advantage is that, you can use same tools e.g. IDE like Eclipse to develop Android applications, Google provides Eclipse plug-in for Android development. On opposite, if you want to go for  iOS development, A steep learning curve with Objective C and iOS SDK waits you. I think it make more sense for a C++ programmer to do Objective C and iOS, than a Java Programmer. So classic battle of Java vs C++ still continues with Smartphone application development. Any way, let's come to the topic of How Android works internally. . If you are looking for some good books to start with Android, you can also check out Professional Android 4 Application Development and Ian F. Darwin’s Android Cookbook.

How Android works

How Android works , app runs on device from Java programmersAs I said Android uses Java for application development. So you can code your Android apps using Java API provided by Google, and it compiles into class files. Similarity ends here, Android doesn't use Java Virtual machine (JVM) for executing class files, instead it uses Dalvik virtual machine, which is not a true JVM and doesn't operate on Java byte code. In order to run on Dalvik Virtual machines, class files are further compiled into Dalvik Executable or DEX format. After conversion to DEX format, class files along with other resources are bundled into Android Package (APK) for distribution and installation into various devices. Key thing to know is that, Dalvik VM is based on subset of the Apache Harmony Project for its core class library, which means it doesn't support all J2SE API. If you are using Eclipse IDE for coding Android Apps, then you don't need to worry much because, it will help you with code completion. Now let's see How Android Application runs on device?


How Android apps runs on Device

If you are familiar with Linux and concept of process, then it's easy to understand how android applications runs. By default, Each Android application is assigned a unique user id by the Android operating system. After starting android application, they run on there own process, inside there own virtual machine. Android operating system manages starting and shutting down the application process, whenever required. This means, each android application runs in isolation with other, but they can certainly request access to hardware and other system resources. If you are familiar with mobile application development, may be in J2ME, then you may know about permissions. So when an android application is installed or started, it request necessary permission required to connect internet, phone book and other system resource. User explicitly provides grant these permissions, or it may deny. All these permissions are defined in manifest file of Android application. Unlike Java Manifest file, Android manifest is an XML file, which lists all the components of apps, and settings for those components. Four major components of Android application development is Activities, Services, Content Providers and Broadcast Receivers. Activity is most common of them, as it represent a single screen in Android Application. For example, in an Android Game, you can have multiple screens for login, high score, instructions and game screen. Each of these screen represent different Activities inside your app. Similar to Java, good thing about Android is that it manages certain task on behalf of developer, one of them is creating activity object. Activities are managed by System, when you want to start an activity, you call startActivity() method which takes an Intent object. In response to this call, System can either create new activity object or reuse an existing one. Just like Garbage collection in Java, manages a critical task or reclaiming memory, Android manages starting, stopping, creating and destroying of apps by themselves. You may think it's restrictive, but it's not. Android provides life-cycle events, which you can override to interact with this process.

That's all on How Android works.  Android is definitely worth learning for Java programmer, as it uses Java, you can reuse your existing knowledge of Java programming techniques, design patterns and best practices to code a good android app. Of course, you need to adapt some Android specific things like, but those will come along. So, what are you waiting for, go and explore more about Android and write an Android HelloWorld application. Finally you can also take a look some of the best book to start with Android development, Professional Android 4 Application Development and Android Cookbook by Ian F. Darwin.

Null in Java...

java.lang.NullPointerException and you will learn your lesson hard way. Robust programming is an art and your team, customer and user will appreciate that. In my experience, one of the main reasons of NullPointerException are not enough knowledge about null in Java. Many of you already familiar with null but for those, who are not, can learn some old and new things about null keyword. Let's revisit or learn some important things about null in Java.




What is Null in Java

As I said, null is very very important concept in Java. It was originally invented to denote absence of something e.g. absence of user, a resource or anything, but over the year it has troubled Java programmer a lot with nasty null pointer exception. In this tutorial, we will learn basic facts about null keyword in Java and explore some techniques to minimize null checks and how to avoid nasty null pointer exceptions.

1) First thing, first,  null is a keyword in Java, much like public, static or final. It's case sensitive, you cannot write null as Null or NULL, compiler will not recognize them and give error.

Object obj = NULL; // Not Ok
Object obj1 = null  //Ok

Programmer's which are coming from other language have this problem, but use of modern day IDE's has made it insignificant. Now days, IDE like Eclipse or Netbeans can correct this mistake, while you type code, but in the era of notepad, Vim and Emacs, this was a common issue which could easily eat your precious time.


2) Just like every primitive has default value e.g. int has 0, boolean has false, null is the default value of any reference type, loosely spoken to all object as well. Just like if you create a boolean variable, it got default value as false, any reference variable in Java has default value null. This is true for all kind of variables e.g. member variable or local variable, instance variable or static variable, except that compiler will warn you if you use a local variable without initializing them. In order to verify this fact, you can see value of reference variable by creating a variable and them printing it's value, as shown in following code snippet :

What is null in Javaprivate static Object myObj;
public static void main(String args[]){
    System.out.println("What is value of myObjc : " + myObj);
} 

What is value of myObjc : null

This is true for both static and non-static object, as you can see here that I made myObj a static reference so that I can use it directly inside main method, which is static method and doesn't allow non-static variable inside.


3) Unlike common misconception, null is not Object or neither a type. It's just a special value, which can be assigned to any reference type and you can type cast null to any type, as shown below :

String str = null; // null can be assigned to String
Integer itr = null; // you can assign null to Integer also
Double dbl = null;  // null can also be assigned to Double
        
String myStr = (String) null; // null can be type cast to String
Integer myItr = (Integer) null; // it can also be type casted to Integer
Double myDbl = (Double) null; // yes it's possible, no error

You can see type casting null to any reference type is fine at both compile time and runtime, unlike many of you might have thought, it will also not throw NullPointerException at runtime.


4) null can only be assigned to reference type, you cannot assign null to primitive variables e.g. int, double, float or boolean. Compiler will complain if you do so, as shown below.

int i = null; // type mismatch : cannot convert from null to int
short s = null; //  type mismatch : cannot convert from null to short
byte b = null: // type mismatch : cannot convert from null to byte
double d = null; //type mismatch : cannot convert from null to double
        
Integer itr = null; // this is ok
int j = itr; // this is also ok, but NullPointerException at runtime

As you can see, when you directly assign null to primitive error it's compile time error, but if you assign null to a wrapper class object and then assign that object to respective primitive type, compiler doesn't complain, but you would be greeted by null pointer exception at runtime. This happens because of autoboxing in Java, and we will see it in next point.


5) Any wrapper class with value null will throw java.lang.NullPointerException when Java unbox them into primitive values. Some programmer makes wrong assumption that, auto boxing will take care of converting null into default values for respective primitive type e.g. 0 for int, false for boolean etc, but that's not true, as seen below.

Integer iAmNull = null;
int i = iAmNull; // Remember - No Compilation Error

but when you run above code snippet you will see Exception in thread "main" java.lang.NullPointerException  in your console. This happens a lot while working with HashMap and Integer key values. Code like shown below will break as soon as you run.

import java.util.HashMap;
import java.util.Map;


/**
 * An example of Autoboxing and NullPointerExcpetion
 * 
 * @author WINDOWS 8
 */

public class Test {

    public static void main(String args[]) throws InterruptedException {
        
      Map numberAndCount = new HashMap<>();

      int[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};
      
      for(int i : numbers){
         int count = numberAndCount.get(i);
         numberAndCount.put(i, count++); // NullPointerException here
      }       
    }

}

Output:
Exception in thread "main" java.lang.NullPointerException
 at Test.main(Test.java:25)

This code looks very simple and innocuous. All you are doing is finding how many times a number has appeared in a array, classic technique to find duplicates in Java array. Developer is getting the previous count, increasing it by one and putting it back into Map. He might have thought that auto-boxing will take care of converting Integer to int , as it doing while calling put method, but he forget that when there is no count exist for a number, get() method of HashMap will return null, not zero because default value of Integer is null not 0, and auto boxing will throw null pointer exception while trying to convert it into an int variable. Imagine if this code is inside an if loop and doesn't run in QA environment but as soon as you put into production, BOOM :-)


6)instanceof operator will return false if used against any reference variable with null value or null literal itself, e.g.

Integer iAmNull = null;
if(iAmNull instanceof Integer){
   System.out.println("iAmNull is instance of Integer");                             

}else{
   System.out.println("iAmNull is NOT an instance of Integer");
}

Output : iAmNull is NOT an instance of Integer

This is an important property of instanceof operation which makes it useful for type casting checks.


7) You may know that you cannot call a non-static method on a reference variable with null value, it will throw NullPointerException, but you might not know that, you can call static method with reference variables with null values. Since static methods are bonded using static binding, they won't throw NPE. Here is an example :            

public class Testing {             
   public static void main(String args[]){
      Testing myObject = null;
      myObject.iAmStaticMethod();
      myObject.iAmNonStaticMethod();                             
   }
              
   private static void iAmStaticMethod(){
        System.out.println("I am static method, can be called by null reference");
   }
              
   private void iAmNonStaticMethod(){
 System.out.println("I am NON static method, don't date to call me by null");
   }
 
}

Output:
I am static method, can be called by null reference
Exception in thread "main" java.lang.NullPointerException
               at Testing.main(Testing.java:11)


8) You can pass null to methods, which accepts any reference type e.g. public void print(Object obj) can be called as print(null). This is Ok from compiler's point of view, but behavior is entirely depends upon method. Null safe method, doesn't throw NullPointerException in such case, they just exit gracefully. It is recommended to write null safe method if business logic allows.

9) You can compare null value using ==  (equal to ) operator and !=  (not equal to) operator, but cannot use it with other arithmetic or logical operator e.g. less than or greater than. Unlike in SQL, in Java null == null will return true, as shown below :

public class Test {

    public static void main(String args[]) throws InterruptedException {
        
       String abc = null;
       String cde = null;
       
       if(abc == cde){
           System.out.println("null == null is true in Java");
       }
       
       if(null != null){
           System.out.println("null != null is false in Java"); 
       }
       
       // classical null check
       if(abc == null){
           // do something
       }
       
       // not ok, compile time error
       if(abc > null){
           
       }
    }
}

Output:
null == null is true in Java

That's all about null in Java. By some experience in Java coding and by using simple tricks to avoid NullPointerExcpetion, you can make your code null safe. Since null can be treated as empty or uninitialized value it's often source of confusion, that's why it's more important to document behavior of a method for null input. Always remember, null is default value of any reference variable and you cannot call any instance method, or access an instance variable using null reference in Java.


9 Difference between TCP and UDP Protocol - Java Network Interview Question

TCP and UDP are two transport layer protocols, which are extensively used in internet for transmitting data between one host to another. Good knowledge of how TCP and UDP works is essential for any programmer. That's why difference between TCP and UDP is one of the most popular programming interview question. I have seen this question many times on various Java interviews , especially for server side Java developer positions. Since FIX (Financial Information Exchange) protocol is also a TCP based protocol, several investment banks, hedge funds, and exchange solution provider looks for Java developer with good knowledge of TCP and UDP. Writing fix engines and server side components for high speed electronic trading platforms needs capable developers with solid understanding of fundamentals including data structure, algorithms and networking. By the way, use of TCP and UDP is not limited to one area, its at the heart of internet. The protocol which is core of internet, HTTP is based on TCP. One more reason, why Java developer should understand these two protocol in detail is that Java is extensively used to write multi-threaded, concurrent and scalable servers. Java also provides rich Socket programming API for both TCP and UDP based communication. In this article, we will learn key differences between TCP and UDP protocol, which is useful to every Java programmers. To start with, TCP stands for Transmission Control Protocol and UDP stands for User Datagram Protocol, and both are used extensively to build Internet applications.




Difference between TCP vs UDP Protocol

I love to compare two things on different points, this not only makes them easy to compare but also makes it easy to remember differences. When we compare TCP to UDP, we learn difference in how both TCP and UDP works, we learn which provides reliable and guaranteed delivery and which doesn't. Which protocol is fast and why, and most importantly when to choose TCP over UDP while building your own distributed application. In this article we will see difference between UDP and TCP in 9 points, e.g. connection set-up, reliability, ordering, speed, overhead, header size, congestion control, application, different protocols based upon TCP and UDP and how they transfer data. By learning these differences, you not only able to answer this interview question better but also understand some important details about two of the most important protocols of internet.


1) Connection oriented vs Connection less
TCP handshake process SYN, SYN-ACK and ACK
First and foremost difference between them is TCP is a connection oriented protocol, and UDP is connection less protocol. This means  a connection is established between client and server, before they can send data. Connection establishment process is also known as TCP hand shaking where control messages are interchanged between client and server. Attached image describe the process of TCP handshake, for example which control messages are exchanged between client and server. Client, which is initiator of TCP connection, sends SYN message to server, which is listening on a TCP port. Server receives and sends a SYN-ACK message, which is received by client again and responded using ACK. Once server receive this ACK message,  TCP connection is established and ready for data transmission. On the other hand, UDP is a connection less protocol, and point to point connection is not established before sending messages. That's the reason, UDP is more suitable for multicast distribution of message, one to many distribution of data in single transmission.


2) Reliability
TCP provides delivery guarantee, which means a message sent using TCP protocol is guaranteed to be delivered to client. If message is lost in transits then its recovered using resending, which is handled by TCP protocol itself. On the other hand, UDP is unreliable, it doesn't provide any delivery guarantee. A datagram package may be lost in transits. That's why UDP is not suitable for programs which requires guaranteed delivery.


3) Ordering
Apart from delivery guarantee, TCP also guarantees order of message. Message will be delivered to client in the same order, server has sent, though its possible they may reach out of order to the other end of the network. TCP protocol will do all sequencing and ordering for you. UDP doesn't provide any ordering or sequencing guarantee. Datagram packets may arrive in any order. That's why TCP is suitable for application which need delivery in sequenced manner, though there are UDP based protocol as well which provides ordering and reliability by using sequence number and redelivery e.g. TIBCO Rendezvous, which is actually a UDP based application.


4) Data Boundary
TCP does not preserve data boundary, UDP does. In Transmission control protocol, data is sent as a byte stream, and no distinguishing indications are transmitted to signal message (segment) boundaries. On UDP, Packets are sent individually and are checked for integrity only if they arrived. Packets have definite boundaries which are honoured upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent. Though TCP will also deliver complete message after assembling all bytes. Messages are stored on TCP buffers before sending to make optimum use of network bandwidth.


5) Speed
In one word, TCP is slow and UDP is fast. Since TCP does has to create connection, ensure guaranteed and ordered delivery, it does lot more than UDP. This cost TCP in terms of speed, that's why UDP is more suitable where speed is a concern, for example online video streaming, telecast or online multi player games.


6) Heavy weight vs Light weight
Because of the overhead mentioned above, Transmission control protocol is considered as heavy weight as compared to light weight UDP protocol. Simple mantra of UDP to deliver message without bearing any overhead of creating connection and guaranteeing delivery or order guarantee keeps it light weight. This is also reflected in their header sizes, which is used to carry meta data.


7) Header size
TCP has bigger header than UDP. Usual header size of a TCP packet is 20 bytes which is more than double of 8 bytes, header size of UDP datagram packet. TCP header contains Sequence Number, Ack number, Data offset, Reserved, Control bit, Window, Urgent Pointer, Options, Padding, Check Sum, Source port, and Destination port. While UDP header only contains Length, Source port, Destination port, and Check Sum. Here is how TCP and UDP header looks like :

TCP Header Format

UDP Header Format 



8) Congestion or Flow control
TCP does Flow Control. TCP requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control. On the other hand, UDP does not have an option for flow control.


9) Usage and application
Where does TCP and UDP are used in internet? After knowing key differences between TCP and UDP, we can easily conclude, which situation suits them. Since TCP provides delivery and sequencing guaranty, it is best suited for applications that require high reliability, and transmission time is relatively less critical. While UDP is more suitable for applications that need fast, efficient transmission, such as games. UDP's stateless nature is also useful for servers that answer small queries from huge numbers of clients. In practice, TCP is used in finance domain e.g. FIX protocol is a TCP based protocol, UDP is used heavily in gaming and entertainment sites.


10) TCP and UDP based Protocols
One of the best example of TCP based higher end protocol is HTTP and HTTPS, which is every where on internet. In fact most of the common protocol you are familiar of e.g. Telnet, FTP and SMTP all are based over Transmission Control Protocol. UDP don't have any thing as popular as HTTP but UDP is used in protocol like DHCP (Dynamic Host Configuration Protocol) and DNS (Domain Name System). Some of the other protocol, which is based over User Datagram protocol is Simple Network Management Protocol (SNMP), TFTP, BOOTP and NFS (early versions).


That's all about difference between TCP and UDP protocol. Always remember to mention that TCP is connection oriented, reliable, slow, provides guaranteed delivery and preservers order of messages, while UDP is connection less, unreliable, no ordering guarantee, but fast protocol. TCP overhead is also much higher than UDP, as it transmits more meta data per packet than UDP. It's worth mentioning that header size of Transmission control protocol is 20 bytes, compared to 8 bytes header of User Datagram protocol. Use TCP, if you can't afford to lose any message, while UDP is better for high speed data transmission, where loss of single packet is acceptable e.g. video streaming or online multi player games. While working in TCP/UDP based application on Linux, it's also good to remember basic networking commands e.g. telnet and netstat, they help tremendously to debug or troubleshoot any connection issue.

Thursday, 22 January 2015

Must know about Strings in JAVA

1) Strings are not null terminated in Java.
 
Unlike C and C++, String in Java doesn't terminate with null character. Instead String are Object in Java and backed by character array. You can get the character array used to represent String in Java by calling toCharArray() method of java.lang.String class of JDK.

2) Strings are immutable and final in Java
 
Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method,  It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality. Now if you are puzzled why String is immutable or final in Java. checkout the link.

3) Strings are maintained in String Pool
 
Advanced Java String tutorial and example programmers As I Said earlier String is special class in Java and all String literal e.g. "abc"  (anything which is inside double quotes are String literal in Java) are maintained in a separate String pool, special memory location inside Java memory, more precisely inside PermGen Space. Any time you create a new String object using String literal, JVM first checks String pool and if an object with similar content available, than it returns that and doesn't create a new object. JVM doesn't perform String pool check if you create object using new operator.
You may face subtle issues if you are not aware of this String behaviour , here is an example

String name = "Scala"; //1st String object
String name_1 = "Scala"; //same object referenced by name variable
String name_2 = new String("Scala") //different String object
//this will return true
if(name==name_1){
System.out.println("both name and name_1 is pointing to same string object");
}
//this will return false
if(name==name_2){
System.out.println("both name and name_2 is pointing to same string object");
}

if you compare name and name_1 using equality operator "==" it will return true because both are pointing to same object. While name==name_2 will return false because they are pointing to different string object. It's worth remembering that equality "==" operator compares object memory location and not characters of String. By default Java puts all string literal into string pool, but you can also put any string into pool by calling intern() method of java.lang.String class, like string created using new() operator.

4) Use Equals methods for comparing String in Java
 
String class overrides equals method and provides a content equality, which is based on characters, case and order. So if you want to compare two String object, to check whether they are same or not, always use equals() method instead of equality operator. Like in earlier example if  we use equals method to compare objects, they will be equal to each other because they all contains same contents. Here is example of comparing String using equals method.

String name = "Java"; //1st String object
String name_1 = "Java"; //same object referenced by name variable
String name_2 = new String("Java") //different String object
if(name.equals(name_1)){
System.out.println("name and name_1 are equal String by equals method");
}
//this will return false
if(name==name_2){
System.out.println("name_1 and name_2 are equal String by equals method");
}

You can also check my earlier post difference between equals() method and == operator for more detail discussion on consequences of comparing two string using == operator in Java.

5) Use indexOf() and lastIndexOf() or matches(String regex) method to search inside String
 
String class in Java provides convenient method to see if a character or sub-string or a pattern exists in current String object. You can use indexOf() which will return position of character or String, if that exist in current String object or -1 if character doesn't exists in String. lastIndexOf is similar but it searches from end. String.match(String regex) is even more powerful, which allows you to search for a regular expression pattern inside String. here is examples of indexOf, lastIndexOf and matches method from java.lang.String class.

String str = "Java is best programming language";
if(str.indexOf("Java") != -1){
     System.out.println("String contains Java at index :" + str.indexOf("Java"));
}
if(str.matches("J.*")){
     System.out.println("String Starts with J");
}
str ="Do you like Java ME or Java EE";
if(str.lastIndexOf("Java") != -1){
      System.out.println("String contains Java lastly at: " + str.lastIndexOf("Java"));
}

As expected indexOf will return 0 because characters in String are indexed from zero. lastIndexOf returns index of second “Java”, which starts at 23 and matches will return true because J.* pattern is any String starting with character J followed by any character because of dot(.) and any number of time due to asterick (*).
Remember matches() is tricky and some time non-intuitive. If you just put "Java" in matches it will return false because String is not equals to "Java" i.e. in case of plain text it behaves like equals method. See here for more examples of String matches() method.
Apart from indexOf(), lastIndexOf() and matches(String regex) String also has methods like startsWith() and endsWidth(), which can be used to check an String if it starting or ending with certain character or String.

6) Use SubString to get part of String in Java
 
Java String provides another useful method called substring(), which can be used to get parts of String. basically you specify start and end index and substring() method returns character from that range. Index starts from 0 and goes till String.length()-1. By the way String.length() returns you number of characters in String, including white spaces like tab, space. One point which is worth remembering here is that substring is also backed up by character array, which is used by original String. This can be dangerous if original string object is very large and substring is very small, because even a small fraction can hold reference of complete array and prevents it from being garbage collected even if there is no other reference for that particular String. Read How Substring works in Java for more details. Here is an example of using SubString in Java:
String str = "Java is best programming language";
    
//this will return part of String str from index 0 to 12
String subString = str.substring(0,12);
    
System.out.println("Substring: " + subString);

7) "+" is overloaded for String concatenation
 
Java doesn't support Operator overloading but String is special and + operator can be used to concatenate two Strings. It can even used to convert int, char, long or double to convert into String by simply concatenating with empty string "". internally + is implemented using StringBuffer prior to Java 5 and StringBuilder from Java 5 onwards. This also brings point of using StringBuffer or StringBuilder for manipulating String. Since both represent mutable object they can be used to reduce string garbage created because of temporary String. Read more about StringBuffer vs StringBuilder here.
     
8) Use trim() to remove white spaces from String
 
String in Java provides trim() method to remove white space from both end of String. If trim() removes white spaces it returns a new String otherwise it returns same String. Along with trim() String also provides replace() and replaceAll() method for replacing characters from String. replaceAll method even support regular expression. Read more about How to replace String in Java here.

9) Use split() for splitting String using Regular expression
 
String in Java is feature rich. it has methods like split(regex) which can take any String in form of regular expression and split the String based on that. particularly useful if you dealing with comma separated file (CSV) and wanted to have individual part in a String array. There are other methods also available related to splitting String, see this Java tutorial to split string for more details.

10) Don't store sensitive data in String
 
String pose security threat if used for storing sensitive data like passwords, SSN or any other sensitive information. Since String is immutable in Java there is no way you can erase contents of String and since they are kept in String pool (in case of String literal) they stay longer on Java heap ,which exposes risk of being seen by anyone who has access to Java memory, like reading from memory dump. Instead char[] should be used to store password or sensitive information. See Why char[] is more secure than String for storing passwords in Java for more details.


11) Character Encoding and String

Apart from all these 10 facts about String in Java, the most critical thing to know is what encoding your String is using. It does not make sense to have a String without knowing what encoding it uses. There is no way to interpret an String if you don't know the encoding it used. You can not assume that "plain" text is ASCII. If you have a String, in memory or stored in file, you must know what encoding it is in, or you cannot display it correctly. By default Java uses platform encoding i.e. character encoding of your server, and believe me this can cause huge trouble if you are handling Unicode data, especially if you are converting byte array to XML String. I have faced instances where our program fail to interpret Strings from European language e.g. German, French etc. because our server was not using Unicode encodings like UTF-8 or UTF-16. Thankfully, Java allows you to specify default character encoding for your application using system property file.encoding. See here to read more about character encoding in Java

That's all about String in Java. As I have said String is very special in Java, sometime even refer has God class. It has some unique feature like immutability, concatenation support, caching etc, and to become a serious Java programmer, detailed knowledge of String is quite important. Last but not the least don't forget about character encoding while converting a byte array into String in Java. Good knowledge of java.lang.String is must for good Java developers.

Blog Archive