Posts

Showing posts from May, 2016

Character behaviour in Java

Today we will discuss some coding practices with characters and Strings. Can you guess the output of the below code: public static void main(String args[]) { String str="stark: 8"; String str2= "stark: "+str.length(); System.out.println("strings are equal "+str==str2); } Many people will think the output will be strings are equal true , well, its not because whenever we use "==" operator, it checks whether the references of the two strings are equal or not, it doesn't check if the values are equal or not. So now you might be thinking that the output will be  strings are equal false, again the output will be different, if you ran the program now you will see  false. It doesn't print strings are equal.  where's our string literal now ? Here the compiler will treat the statement as below: System.out.println(("strings are equal "+str)==str2); This performs the concatenation between strings are equa

Data Structures programs in Java

In this post we will look at very important subject in computer science, every computer science student must know data structure and how to implement it. Not only in theory but he/she must know how to code it. Sounds boring !!!. Forget whatever I said above, just code for fun. There's no rule to follow in tech. Here's the code: Bubble Sort in java: from the Wikipedia article: Bubble sort , sometimes referred to as  sinking sort , is a simple  sorting algorithm  that repeatedly steps through the list to be sorted, compares each pair of adjacent items and  swaps  them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a  comparison sort , is named for the way smaller elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to  insertion sort . [1]  It can be p

Working with Expression in Java

As you might have figured it out, today I am going to share some code playing with expressions, simple arithmetic, conversion and typecasting. Compound statement, typecasting and assignment. x+=i; is not equal to x=x+i; Many programmers might think that above two statement are identical, talk is cheap let me show you the code... public static void main(String args[]) { short x=0; int i=123456; System.out.println(x+=i); System.out.println(x=x+i); } Here we thought the first println will print output 123456, but thats not true, after the execution it shows -7616, the int i is too big to fit in short x, the automatically generated cast lops off the two higher-order bytes of the int value, because the JLS says... x+=i; means x=(type of x)(x+i); Here the statement gets automatically typecasted to operand x. In other words "compound assignment expressions automatically cast the result of the computation