Monday, November 28, 2016

HashMap - how does choosing the load factor affects the time complexity (Big Oh)?

This post is more about data structure called HashMap rather than Java.

What is a HashMap? 
HashMap is a data structure that is used to store values by first calculating a key for each value by the hashing function and then storing it. This enables to quickly find the element/value later by calculating the hash key again, usually in O(1) time. 

What is the load factor? 
HashMap stores elements in buckets. If 2 or more elements hash to the same hash key then they are stored in the same bucket - this situation is called 'collision'. These 2 elements are stored as a linked list. We should avoid collisions because when collision happens the search for that elements takes longer than O(1) time. This is okay when it happens for some elements that we're trying to store but not good if it happens for many elements. When will it happen for many elements? --> when we will have far lesser buckets than the number of elements that we need to store. We need to decide how full our HashMap should be before we enlarge it.. that fullness factor is called load factor and is given by formula n/N where n is the number of elements stored in the hashmap already and N is the number of buckets. You can consider N also to be the initial capacity of the hashmap because the whole point of this data structure is to make the search operation of O(1) and hence it's important to try our best to design it in a way that there are zero collisions. The default load factor for Java's HashMap is 0.75 with initial capacity=16.  That means it will increase the size of the hashmap (and hence rehash) when 12th element is inserted. 

How does choosing the load factor affects the performance? 
You have probably figured out this by now. 

  • More the load factor, late would be the enlarging of the hashmap buckets, so more would be the chances of collisions, so more elements would have search time greater than O(1).
  • Less the load factor (say 0.6 instead of 0.75), then we would be enlarging our hashmap capacity earlier - precisely when almost approximately 40% of buckets are still empty, this means there would be lesser collision scenarios at this stage and even lesser in the new hashmap that would be created with increased size (and hence increased buckets). 
Shoot for any questions if you have in the comments section. :)

Sunday, August 9, 2015

Mastering the Java CLASSPATH



It's important to understand how the java compiler figures out or searches for all the dependent classes it needs to compile a java file it needs to. I won't waste time in writing something that has already been explained beautifully in this article. So go ahead and read this article till you understand it. 


Some important take-aways:  

  • Java compiler and JVM both use the same technique to figure out the dependent classes they need, the only difference is javac compiler can compile the dependent java file too into a class (to use it) if it has not already done. 
  • javac -classpath "" CPTest2.java                    : This will wipe out the system classpath that you have set on your computer and as we've given an empty string that means the compiler has no way to reference any other class to help build CPTest2.java. 
  • The java compiler and run-time can search for classes not only in separate files, but also in `JAR' archives. But you've to give the complete path to the .jar file and not only upto the directory in which that .jar file is stored. 
  • Usage of system CLASSPATH variable and how to add it to the javac command in case you wanna add something more to what the system CLASSPATH variable has. 

Understanding of how javac and JVM try to figure out the dependent classes is an important understanding to resolve the famous ClassNotFound exceptions. 


Monday, February 25, 2013

If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some point the same object becomes eligible for Garbage collection, will the finalize() method be called again?


Nice question. Isn't it? :)

I urge you to think about this for a moment before hurrying to the answer.

.
.
.
finalize() will run only once. Repeat with me, finalize() will run only once! So, the answer to above question is No.


Wednesday, February 20, 2013

Understanding SQL joins once and for all


Understanding SQL joins is fundamental to any java programmer who needs to fetch data from database. SQL joins can be very confusing. Here is a very simple Venn diagram that help you understand all the important SQL joins pretty quickly.. 



SQL Joins Venn Diagram
















INNER JOIN: 
Select only those rows that have values in common in the columns specified in the ON clause. Records available in both the tables. 

LEFT, RIGHT, or FULL OUTER JOIN:  
Select all rows from the table on the left (or right, or both) regardless of whether the other table has values in common and (usually) enter NULL where data is missing.  (Note:  FULL OUTER JOIN not implemented in Access.)

CROSS JOIN:
Select all possible combinations of  rows and columns from both tables (Cartesian product). If tableA has n records and tableB has m records then a cross join will produce n x m results.. joining every records from tableA with every single record from tableB. So if tableA has 30 records and tableB has 35 records the cross join will produce 30x35 = 1050 records in the result set. (This is Not A Good join - the query may run for a very long time  and produce a huge, not very useful result set.) 
           
MINUS:
You get this by specifying a where clause saying not to include records having a match in tableB.  

Note:
There is nothing like left inner join or right inner join. They both mean inner join, they all are one and the same. 

Monday, February 11, 2013

Can we override the main method() ?


Technically the answer is NO. 

> Main method is a static method.
> Static methods belong to the class and not to the objects.
> If you extend a Parent class having main method the child class doesn't have the parent class's main method so there is no question about overriding it.
> You can write your own main method in the child class but that would be again a static method of the child class and would have nothing to do with the main method of the parent class.

Following code will compile and will execute fine...

public class Parent{
    public static void main(String args[]){
        System.out.println("In Parents main method..");
}
class child extends Parent{
  public static void main(String args[]){
        System.out.println("In childs main method..");
}
You can even call the main method of other class from one class directly as its a static method!!

Any questions??

Monday, April 19, 2010

Getting current date and time in java

When you are programming something you may need the current date and current time, say like while naming the reports you want to include the date and time at which the report was generated, so in this case you want to write code that will generate the current date and time. This is a very basic thing and every java programmer should know this.


We will be using two important classes for this...
1. java.util.Calendar
2. java.text.SimpleDateFormat


And here goes the simple code...

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy - HH:mm:ss");
System.out.println(sdf.format(cal.getTime()));
 
Instead of " : " you can have " _ " or any other such differentiator it doesn''t matter. But you need to take care of the Caps of "MM" and "HH". Also note that "YYYY" will not work. Try yourself for everything else..
 
Most importantly note that we are passing the current time as a parameter to the format function of SimpleDateFormat.
 
 
 

Tuesday, April 13, 2010

When should a class be Static? - A realistic scenario.

After learning how the word Static plays its magic, it's important to know when can that be used in a realistic scenario. I will share an experience where I learnt a classic example of when a class should be static.

I was developing a class which was going to provide some helper methods for a functionality, say like it was a class which used to do all the data gathering part. So the methods in it were connecting with the database, constructing the query on basis of the input, getting the data, filling it into a collection (e.g: Map or TreeMap) and returning it to the calling function. The functions of this class were to be called by many other classes which were not static (or non-static..it doesn't really matter.) Let's call this class as Helper class. And other calling classes as A, B and C classes.

I first made the Helper class non-static. I always questioned myself why it should be static...there is no need! And that was correct! This class could have been non-static! When it is not static, the calling class A needs to create an instance and then call the methods of the Helper class. Like this...

Helper help = new Helper();
help.getCutomerData(param1,param2,param3) ;

There was nothing technically wrong with it... but.. as we say..this was a realistic scenario.

I began to think on these lines - does the Helper class has any instance variables? does it have any state? Or is it just a class with methods which help the calling classes? Are the methods using any instance variable? Is any output of the methods stored in the instance variables??  Answer to all these questions was No. I do not need to maintain the state of that class, it was okay if I make it static and the calling function calls directly the methods of the static Helper class. Thus this class has to be made static.

The calling class can call the non-static methods of this static Helper class by this way...

Helper.getCustomerData(param1,param2,param3);

Simple! Crisp! Logical!

Saturday, September 27, 2008

Not to depend on the Dumps or Question Banks!!

Hello friends,

First my apologies for not being regular in posting exciting articles as before. I will be regular now onwards.

I am back with a piece of advice for you all. Please do not depend on the dumps/question bank or any other source which anyone provides you saying,"hey, just read these 200 questions and you will get most of the question from this only!" That sentence is partially true! But partially! You will never score high if you depend only on these question banks. Yes they claim that these are real questions from exams remembered from the people who have v the exams, and many other ways - I don't know. But it's the truth that these will only degrade you. Studying java passionately and then going and giving the exam needs guts, practice and will power to do it - lets what ever the result may be. And if you really study hard SCJP is really not that difficult! Keep this in mind!!

The number of questions repeated are very very low as compared to what the people selling these question sets say. And anyways knowledge lives forever, what if in the future you cleared SCJP with 90% and were not able to make a proper synchronized method, or unable to solve a simple NullPointerException! That will be so insulting for you! Clear the SCJP with knowledge and hard work, and it will definately pay you back!

Thursday, September 11, 2008

What are inner classes?


This topic is not for beginners or those at intermediate level. Not very difficult but may result in headache sometimes. So lets understand what are inner classes or nested classes - as some call them.


Inner class - as the name says are inside a class. Normal classes which we see are called outer classes because they are directly inside a file and not inside another class. Hey, if you are wondering whether a class can be inside a class?? Yes, it can be. But there are various complications in its use, and I suggest in real life not to use it unless they are unavoidable. But SCJP exam contains questions about such complex things..so its a very important concept. And hey its not boring, its very interesting topic... I will try to make it more interesting!

OK, let's see how a inner class looks like...

class A{
int a;

class B{
int b;

}//class B ends

}// class A ends

You can clearly see that B is inside A. When we create object of class A it doesn't mean we create object of inner class B also. We have to explicitly create object of inner class B. The inner classes can also be static! Yes, they can be. Also there can be more than one inner classes inside a class. You can create objects of them independently. Inner classes can have variables and methods as other classes... the members can be static, final etc.. The concept of Inner classes is not that simple, I thought to keep the first post easy, I will come with the difficult scenarios related to inner classes soon...

If you have any basic questions about inner classes, they do fire them in the comments section.. also try to code yourself, that is first thing to do when you don't understand anything.

Sunday, August 31, 2008

Enum - tricky ones...

I was reading something regarding enums yesterday and found two interesting things which I feel I should share with my readers. These are very simple things for those who already know it but may be surprising for those who don't...

- Enums are not expandable at runtime.
So, suppose you have somethings like
enum Car { HONDA, MERC };
then you cannot add another car say FORD as 3rd constant in the list at runtime. You can have as many references you can to point to the enum constants.

- ; is unnecessary at the end of enum definition! :)
Yeh, this is quite funny and surprising, don't know why java developers didn't do it mandatory. Exam may have questions with multiple code sentences in single line, so look out properly where ; is necessary and where it isn't. And now u know that there is no need of ; after } when the enum definition completes.

Thanks!

Sunday, August 24, 2008

Types of Variables...

Well it is important to know what are the types of variables because there behaviour and their life and death is directly related to their type! There are 6 types of variables and I classify them on basis of 2 things to make you understand better.

- Depending upon what a variable holds they are classified as
1. Primitive Variable
2. Reference Variable

- Depending upon where they are created they are classified as
1. Class variable ( also called static variables)
2. Instance variable
3. Method Parameter
4. Local Variable.

Let's go one by one to understand them. A primitive variable is one which holds the primitive e.g: an int, a char etc. A reference variable is one which holds an object of any class, it can be java API class like String or your wn created class. A class variable is one which is a static variable and inside the class definition. This variable is created when the class loads in the memory and stays there till the class is in the memory. A class variable is not attached to any instance of that class. A instance variable is a non-static member of which is attached to the specific instance of the class. It is reated when a class instance is created and stays in memory untill that instance is in the memory. A method parameter is one which we write in method definition to accept the method arguments the method call is passing to it. This thing will be clear after you see the following example. And lastly a local variable is the one which is declared inside a method body, it is also sometimes called method variable.

Lets take an example to show each type of variable and identify there types..
class City
{
static int name;
Lake l;
int road;
void getDistance(City c )
{
int distance;
}
}
Here,
distance is method variable,
c is method parameter,
road is instance variable,
l is reference variable,
name is class variable
I hope you got it now.. if not fire the doubts in comments! :)

Saturday, August 9, 2008

Some strange facts about Constructors...


Although you would have written many constructors before, I am sure you will find some suprises in following facts about constructors. To start with a constructor is nothing but a piece of code of class with same name as that of class which is called whenever an object is created of that class. Now understand following things one by one...

1.If you don't write a constructor for yourself the compiler will insert one - this is call a default constructor. Constructors can have arguments and there can be a no-argument constructor. Compiler inserted constructor will always be a no-arg constructor.

2. Constructors can take any number of arguments, even var-args i.e.: variable arguments. (More on this in a few days.)

3. Constructors cannot be marked final or static or abstract. Because final, static and abstract keywords are for methods, variables and classes. You can consider that constructors implicitly have final kind of behaviour because they are never inherited! They are not methods beware!

4. Constructors cannot have a return type! This is a very important and perhaps the only criteria to recognise quickly whether the given entity is a method or constructor. A method should have return type but a constructor should never have a return type. A method can have same name as that of the class - its perfectly legal! :)

5. Constructors are never inherited! Again...they aren't methods!! You can remember like this - "Constructors are not passed to the younger generation."

6. Whenever a object has to be created then the constructor of that class has to get called and also the constructors of all its super classes should get called. For example if A is parent of B and B is parent of C then to create an object of C we will call C's constructor which in turn will automatically call the constructors of class B and which inturn will call A's constructor and which inturn will call Object's constructor - as by default class A is child of class Object! Remember that the automatically inserted super class constructor call will be always to the no-arg constructor. If you find it a bit difficult then fire your questions in comments.

7. Constructors can use any access modifier. They can use private, protected and public access modifiers. And if nothing is written they have the default one- package level access. Start thinking why anyone would want to make a private constructor! :)

8. Constructors can be over loaded and hence there can be more than one constructors for a single class. A constructor can call other constructor by the keyword this. A call to another constructor with single argument looks like this(i); .A constructor can even explicitly call its super class constructor by keyword super. A call to parent's constructor with no argument looks like super(); . The first statement of every constructor should be a call to this or super.

9. And here's the most stuning one - Abstract classes have constructors! They are called whenever any object of its subclass is created. So the bottom line is every class has a constructor.

10. Interfaces do not have a constructor. An interface is just a contract, a contract to fulfill the implementation of some methods, remember that.

11. You can have call to both this( ) and super( ) in the same constructor. You can have them one inside other, but not both in any single constructor.

Hoossh.. that's all what I can remember right now.. curse my neurotic RAM! If I find anything else I will update the list. If you have any question, then do comment..as you have seen I reply to every question asked.
C ya,