Tips and Tricks for Java Programmers

Java CP SeptemberQueue CodingIsLife

Although practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging. First of all, Java is not at all bad for competitive coding. Keeping a few points in mind you can be the best coder in Java :-

Taking Inputs
For taking inputs, Scanner class is a good option but when it comes to efficiency with respect to time, BufferedReader wins the competition. So if you want your code to be time efficient, BufferedReader is the better option.

Collections in Java
A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
So, the biggest question in your mind is Why Collections?
The answer is again related to efficiency. The collections in Java takes less time as compared to arrays.
Also there are collections in which duplicates are not allowed, so surely collections can help us in many problems.

Sorting and Searching
Java already have inbuilt methods for sorting and searching, so folks, don't waste your time writing custom methods for searching and sorting.
For arrays,
We can use Arrays.sort() for sorting the array and also we can use Arrays.binarySearch() for searching an element in an array.
For collections,
We can use Collections.sort() for sorting any collection and we can use Collections.binarySearch() for searching any element in the collection.
--These methods will surely save our time when writing the code.

Some more tricks to ignore TLE verdict
Using bitwise operators also consumes less space and time.
For example, when we want to divide a number by 2^k, we have one more option i.e
n = n >> k;
which will be more efficient than normal whereas when we want to multiply a number by 2^k, we have the better option with us i.e
n = n << k;

Another example is, finding whether a number is even or odd:
System.out.println((a & 1) == 0 ? \"EVEN\" : \"ODD\" );
However, this trick is not that useful but it is sometimes efficient with big numbers.

Note: Don't declare your class public because in many compilers it results in CE/RTE verdict.

Upvote  8   Downvote
Created On: September 16, 2018 1:43 PM

There are no comments!

Create an account or login to write a comment

Supported by our Coding Partner