Saturday, July 12, 2025

Binary Search vs Contains Performance in Java List - Example

There are two ways to search an element in a List class, by using contains() method or by using Collections.binarySearch() method. There are two versions of binarySearch() method, one which takes a List and Comparator and other which takes a List and Comparable. This method searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If List is not sorted, then results are undefined. If the List contains multiple elements equal to the specified object, there is no guarantee which one will be returned. This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access).

Monday, July 7, 2025

What is Type Casting in Java? Casting one Class to other class or interface Example

Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or interface. Since Java is an Object-oriented programming language and supports both Inheritance and Polymorphism, It’s easy that Super class reference variable is pointing to SubClass objects but the catch here is that there is no way for Java compiler to know that a Superclass variable is pointing to SubClass object. This means you can not call a method that is declared in the subclass. In order to do that, you first need to cast the Object back into its original type. This is called type casting in Java. You can type cast both primitive and reference type in Java. The concept of casting will be clearer when you will see an example of type casting in the next section.

What is Object in Java and Object Oriented Programming? Example Tutorial

Object in Java
Object in Java programming language or any other Object-oriented programming language like C++ is the core of the OOPS concept and that's why the name. Class and Object along with Inheritance, Polymorphism, Abstraction and Encapsulation form the basis of any Object-oriented programming language e.g. Java. Objects are instances of Class, Class defines blueprints and Objects are things that are created based upon that blueprint. Object is also known as instances in Java, e.g. When we say an instance of String class, we actually mean an Object of String class. The object has state and behavior in Java.