Posts

Arrays class usage in Java

 Java provides the “Arrays” class to perform sorting , searching and comparing arrays.   Sorting: Let’s see simple example: int rollNumbers[] = {23,12,59}; Arrays.sort(rollNumbers); for(int i=0; i<rollNumbers.length; i++){ System.out.print(rollNumbers[i] + " "); } The result is 12,23,59 as expected. Guess the output of the below example: String rollNumbers[] = {"10","9","100"}; Arrays.sort(rollNumbers); for(String rollNumber: rollNumbers){ System.out.print(rollNumber + " "); } The result is 10, 100, 9. Here String sorts in alphabetical order, and 1 sorts before 9. Numbers sort before letters, and uppercase sorts before lowercase. Searching: Arrays class has binarySearch() method to search an element. The input parameters are sorted array and search element. The output is depend on the scenario: If the target element found in sorted array then the result is the index of match int[] rollNumbers={23,12,59}; Arrays.sort(rollNumbers

How intern() method works in Java

 The intern() returns the value from the string pool if it is there.Otherwise,it adds the value to the string pool. The string pool also known as the intern pool,is a location in the Java virtual machine that collects the strings.The string pool contains literal values and constants that appear in our program. String customerName="hemanth"; Here customerName is a reference variable and we have assigned a value “hemanth” using literal. So it goes into the string pool. String managerName= new String("hemanth"); Here managerName is a reference variable and we have created a string using new operator. So it does not go into the string pool. Wi t h this knowledge, can you guess what will be the output of the below statement? String customerName="hemanth"; String managerName= new String("hemanth"); System.out.println(customerName==managerName);// Here == look for //whether the references are referring to the same object or not. I hope you guesse

About “var” Keyword In Java

 Starting in Java 10, We have the option of using the keyword “var” instead of the type for local variables under certain conditions. As we know very well, If we need to declare an integer variable to hold the age of a customer then we will do as follows in Java: int age= 32; Here the type of age is Integer and int is the keyword. Similarly, If we need to declare a String variable to hold the name of a customer then we will declare as follows: String customerName = “Hemanth”; Here the type of customerName is String. The abov e two statements we can rewrite as follows: var age = 32; var customerName = “Hemanth”;   The formal name of this feature is local variable type inference. When we type var, we are instructing the compiler to determine the type for us. The compiler looks at the code on the line of the declaration and uses it to infer the type. In other languages like JavaScript, var to mean a variable that can take on any type at runtime. In Java, var is still a specific t