1) Java String :
concat() vs + operator for concatenation

intern()
private String str1 = new String("Hello");
private String str2 = "Hello";
System.out.println(str1 == str2); //false
private String str3 = str1.intern();
System.out.println(str3 == str2); //true
As you can see, both str1 and str2 have the same content, but they are not equal initially. We then use the intern() method so that str2 and str3 use the same memory pool.
2) Java Comments :
Single line comment : A single line comment starts and ends in the same line. To write a single line comment, we can use the // symbol.
//Printing oh yeah
System.out.println("Oh yeah");
Multi-line comment: When we want to write comments in multiple lines, we can use multi-line comment. To write multi-line comment, we can use /*…*/ symbol.
/* This is the example for multi-line comment
*/ This will print "Oh yeah"
System.out.println("Oh yeah");
Comment will still execute:
public class StrangeCoder {
public static void main(String str[]) {
// \u000d System.out.println("Strange Coder");
}
}
This comment will get execute because of Unicode character “\u000d” and java compiler parses this unicode character as a new line. Java allows using Unicode characters without encoding.
3) Java 7 and above :
Numeric Literals in Java :
A numeric literal is a character string selected from the digits, the plus sign, the minus sign, and the decimal point. Java allows you to use underscore in numeric literals. This feature was introduced in Java 7. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your source code.
public class StrangeCoder {
public static void main(String str[]) {
int x = 123_45;
System.out.println(x);
}
}
Check if number is even or odd without using % operator:
System.out.println((a & 1) == 0 ? "EVEN" : "ODD" );
Since integer numbers are represented as 2’s complement and even number has 0 as their LSB, if we perform a bitwise AND between 1 and number, the result will be zero. This would be enough to check if a number is even or odd in Java., We need to check whether the last bit is 1 or not. If the last bit is 1 then the number is odd, otherwise always even.
input : 5 // odd
00000101
& 00000001
--------------
00000001
--------------
input : 8 //even
00001000
& 00000001
--------------
00000000
--------------
Swapping of 2 numbers using XOR:
//Quick way to swap a and b
a ^= b;
b ^= a;
a ^= b;
Fast Multiplication or Division by 2:
n = n << 1; // Multiply n with 2
n = n >> 1; // Divide n by 2

Leave a comment