Friday, November 21, 2014

Need for Immutable String in Java

While understanding String Immutability there were some answered questions as to why the designers of Java made String Immutable. We checked that String is immutable but Why so?

Well, it's difficult to go inside the brain of designers of java but based on the usage as of today we can speculate as to what would have been going on in their brain while making java immutable.

1. Easy storage and housekeeping
Strings are used a lot inside a program. A lot of Strings are repeated. For example in a College Database application, same names (Strings) are repeated again and again. Hence it makes better sense to keep a single copy of all strings at a single place (String Pool). Instead of creating new objects again and again. Garbage Collection and Storage of these high volume data becomes easy.



2. Hashcode does not change
Since Strings are immutable, their hascode won't change like other objects. Thus Strings do not calculate hashcode every time we call hashcode function, Hascode us kept cached. Since Strings are used a keys in HashMaps and other such Structures, we save a lot of time but not calculating hashcode every time we need to retrieve an Object.

3. Network Security
All passwords we enter online are strings. Bank details are passed as Strings. If they are mutable, anyone could change them over the network, which would wreak havoc. Same goes with classnames while loading a Class. 

4. Prevents Concurrency Issues
Since Strings are immutable, hence no need to synchronize. Hence no concurrency issues while using Strings.

Friday, November 14, 2014

String immutable in Java: What does it really mean?

This is one of the favourite questions at the fresher level that interviewer asks. Most of the candidates tend to gloss over this. If interviewer tends to go into this deep, most of the candidates tend to falter. At least that if what I have observed having interviewed hundreds of candidates in the past.

We will try and make this article single point of reference for Strings in Java. Hopefully we cover something that might be helpful to you. Read here, for knowing Why It was made Immutable.

Let's try and go in depth on String immutability.

Let's start by Source Code of String.java. I always say that source code is the best resource to learn a language.


How String is Immutable?
This question is self answered by the above code snippet. Member variable data type is final. Hence String Object once created becomes immutable in Java.

How come then we are able to assign same variable, a different value?
Now we are talking. Valid question. Let's check it via code,




So the question stands. What does immutability means?

Well, it can be explained by what happens internally. Variable immutable refers to a memory space which is allocated to "javaonjava. This memory allocation is what we call immutable. Same variable can point to different memory spaces.

String literals are stored separately in a String Pool. Once a String is Created, say "javaonjava". Whenever a new variable needs "javaonjava" String, a new String is not created. The old one is referenced. This is what we mean by immutability. So String Object is not immutable, String itself is immutable.

Compare it with any User defined object. When that object is updated, content is re-written on the same memory space. Hope things are getting clear now.

How to check String is immutable in Java

1. == (equals operator), is the best check.
As we read above StringPool contains single copy of a given String. So if this operator returns true on two string variables, it means they are pointing to same memory and content inside the StringPool






Thus we see, they both point to the same content.

2. No operations modify String





Thus we see neither concat, nor substring modifies the String. They simply create a new String, which is returned as we see below.





In the last example, what happens to "javaonjava" String. Well it remains in the StringPool but unreferenced. If not reused for considerable time, it could be Garbage Collected.

See the diagram below for better understanding



Tuesday, October 21, 2014

What is a Thread?

Thread relates to running of a program. A Thread is a single chain of execution within a program.



This above start to end path within a program is called a Thread. These steps can do a number of operations. For example if we are adding two numbers input by the user. This thread execution will comprise of the below steps:

1. Asking user for the input 1
2. Asking user for the input 2
3. Adding the two inputs
4. Printing the final sum.

A single program can have multiple executions in parallel. As in multiple threads. For example finding the sum of 10 input numbers.

Two separate threads can take 5 inputs separately and add them up. At the end, the two results can be added together to get the final sum. It's not that work speed increases magically. It's just a illusion, a trick by a magician.



Salient Features of a Thread
1. Thread is like a sub-process. Multiple thread paths can exist within a single process.
2. All threads share the same resources (memory, variables) within a process. This can result into conflict, hence needs to be handles carefully.
3. Apart from shared resources, each thread has its own stack space where it stores variables local to it.
4. One can argue that we can create multiple processes, then why is the need for multiple threads. You can read about it here. Multiple threads v/s Multiple processes.

Tuesday, August 19, 2014

Quick Sort

QuickSort works on the concept of dividing and proceeding.

An array is divided into two segments, One containing all small elements, other containing all higher elements (from a pivot element). The two segments are in-turn QuickSorted to get the sorted output.

Quick Sort Steps
1. Select an element as pivot (preferable the last element).
2. Shift the pivot such that all elements before it are smaller and after it after bigger (Pivot reaches correct position)

3. Sort the two segments (Before Pivot and After Pivot) separately.

INPUT
2
6
7
5
3
1
8
4

PROCESSING (4 is the pivot)
2
6
7
5
3
1
8
4

2
8
7
5
3
1
4
6

2
1
7
5
3
4
8
6

2
1
3
5
4
7
8
6

2
1
3
4
5
7
8
6

Pivot (4) is in place now. Time to QuickSort separate segments

2
1
3

5
7
8
6

1
2
3

5
7
6
8

5
6
7
8

FINAL RESULT
1
2
3
4
5
6
7
8


Coming Soon: Quick Sort Java Code


Tuesday, June 10, 2014

Top Java Strings Interview Questions

The favourite of the interview questions when it comes to Java. In my entire career I don't recall how many String questions have I asked and how many have I answered. It's like an ocean. The more you soak, the deeper you get.

This importance comes from the fact that Java designers too gave special significance to Strings. Strings are stored separately and plays and important roles in all programs. 

1. Where is String stored in Java?

String are considered special data type in Java. They stored StringPool which is a separate storage space on Java Heap.

2. What do we mean by "Spring is Immutable"?

All member variable data type is final. Hence String Object once created becomes immutable in Java. 

String literals are stored separately in a String Pool. Once a String is Created, say "javaonjava". Whenever a new variable needs "javaonjava" String, a new String is not created. The old one is referenced. This is what we mean by immutability. So String Object is not immutable, String itself is immutable.

Compare it with any User defined object. When that object is updated, content is re-written on the same memory space.

3. Is String a primitive Data Type?

No, String is not a primitive data type. String is a user defined data type. java.lang.String. 
Just like all other objects, Strings extend java.lang.Object. 
As we see in the String class, private final char value[]; stores the data of the String Object.

4. Is String in Java the same as in C?

No, In C, String is just a character array, terminated by null.
In Java String is a Class Object with multiple methods, like equals() to compare Strings, concat() to add two Strings, split() to split a String etc.

5. What does toString() method does?

toString() is an Object level method (java.lang.Object). It returns the String representation of any Object.

6. We see that String class is defined as final. Why?

The answer is the same, to make it immutable. As to Why, there are multiple reasons as to Why Java Designers made String final.

7. Can String be converted to int?

Yes. We have a special function parseInt() in Integer class for this purpose. Check the below code,


8. Can String be used with Switch/Case?

A serious drawback of Switch-Case was it just worked with expressions that evaluated to int (int, short, byte, char, Enum). Not anymore. With Java 7 it can take Strings too. Isn’t is awesome?
String fruit = "apple";
switch (fruit) {
case "orange":


9. How to compare two Strings?

There are multiple ways to compare Strings. But the one that we should follow is equals(). equals() checks if the data is equal. "==" just checks if String Objects are same or not.

10. What is String Pool in Java?

String Pool is a separate storage area on Heap Memory where String Objects are stored. Once a String is Created, say "javaonjava". Whenever a new variable needs "javaonjava" String, a new String is not created. The old one is referenced from String Pool

11. Why is char array preferred over String when it comes to saving password?

Strings as we now know are immutable. They are stored in String Pool and can't be erased till Garbage Collection kicks in. Hence application is susceptible to password leaks. Whereas in char[], each index can be set to null, when we want to erase the password.

12. What is intern() method used for?

In earlier versions of java, String created by new(), was not created in String Pool. intern() method, used to move it to String Pool.

13. Is String Thread safe?

Should be simple to answer by now. Since String is immutable, it cannot be modified. What is immutable is Thread Safe.

14. Differentiate between String/StringBuffer/StringBuilder.

String
immutable
thread safe
StringBuffer
mutable
thread safe
StringBuilder
mutable
not thread safe

Saturday, April 19, 2014

Overloading main() in Java

A common fresher interview goes like, Can we overloading main() in Java?
It's a very tricky question on the face of it. But if we just recollect basics, it won't be too hard to answer.

Answer is Yes, we can very much do.

By default we use String args[] as the method argument for main(). We can have multiple mains with different arguments types.





Error Cases
1. main(String args[]) is missing



Monday, March 10, 2014

Why we need Threads

As the time progress, man is becoming more and more impatient. In today's world of instant food, we want instant results. Gone are the time of batch processing and waiting days for a result. We like the program to finish execution asap. 

This is the major reason why we need threads. Threads aid in executing the program faster than before.

In real life also we do multiple things at the same time. A background process of breathing/heartbeat goes on while we perform daily chores. In office we type and talk at the same time. Similarly we like our program to do multi-tasking. This is achieve via Threads.



Before are few scenarios when usefulness of Threads become evident.

Case 1: Website and User Experience (Background Processing)
Consider a website running on a single thread. It takes an input from the user. While it is processing that input, what happens to the website? Use sees a hanged website. So much for user experience.

Solution: When website takes and input, a separate thread can work in background and do the processing, while user experience remains unhindered, enriching the overall quality.

Case 2: Query to a Database (Asynchronous Processing)
Consider a database call from a program. While database is taking its time to respond, the program is sitting is doing no processing. This slows down the overall execution.

Solution: Database query can be done by a separate thread, which waits for the result to be back. Overall it looks asynchronous. Program keeps on doing it's independent processing whilst, a separate thread id waiting for the Database results to be back.

Case 3: Multiple Processors
With the advent of multiple processors, single threaded programs are anyways at a loss. Parallel executions can occur in separate processors. To utilize that, multi-threaded code is a must.

Case 4: Simple Code
Just like recursion, which is difficult to understand but code becomes extremely simple. Same is the case with multiple threads. Code becomes extremely simple to write and modular. If we can divide our execution in separate paths, we should go for threads.

Programming example of multi-threading making things easier is Multithreaded QuickSort.


Saturday, February 8, 2014

Multiple threads v/s Multiple processes

A legitimate question occurs that is thread is just like a process, why don't we create multiple processes? Why do we create multiple threads?

There are a few reasons.

Consider it just like an evolutionary process. First there were just processes. It lead to the below shortcomings.

1. If we create multiple processes which should share same resources, coding for it was a cumbersome process. 
2. Memory wise too, creating a new processes requires more resources, than creating a separate thread, as essentials (memory, files etc) are shared by all threads.

It lead to the creation of threads. The code remains a single unit. And multiple sub-processes are spawned. 

You can consider it like, if 2 small packages can be bundled up and send via courier. Why to send two different couriers.

Two different couriers require:
1. Creating two separate records and tracking numbers.
2. Two separate outer packing material is required.
3. Packing material comes in standard size, hence small package are also packed into big envelopes, which is wastage.

Single courier
1. If delivery address is same, it's better to package them together.
2. Single record and tracking.
3. Single packing material and less wastage.

Three Elephants v/s One Elephant and Two rats

Understand it by another example. When we can do with one elephant and two small rats. It is better than three big elephants.



Thursday, January 2, 2014

Primitive Data Types Java

Total 8 primitive types are supported by Java.

Data types is nothing but a way to assign different size of memory space to different data. Depending on the size required to store the data, memory space is allocated to it.

To make things easy, In Java we call such memory spaces by name as below,

Data Type
Size
Default Value
Min
Max
boolean
1 bit
false
false
true
char
2 byte
'\u0000'
'\u0000' (or 0)
'\uffff' (or 65,535)
byte
1 byte
0
-128 (-2^7)
127 (2^7 -1)
short
2 byte
0
-32,768 (-2^15)
32,767 (2^15 -1)
int
4 byte
0
- 2,147,483,648 (-2^31)
2,147,483,647 (2^31 -1)
long
8 byte
0L
-9,223,372,036,854,775,808
(-2^63)
9,223,372,036,854,775,807
(2^63 -1)
float
4 byte
0.0f


double
8 byte
0.0d