Category: Java Core

Unordered Data using HashMap in Java

Understanding through Code import java.util.HashMap; import java.util.Map; public class HashMapDemo { public static void main( String[] args ){ Map<String, String> map = new HashMap<>(); map.put("India", "First"); map.put("US", "Second"); map.put("Canada", "Third"); System.out.println(map); map.put("Russia", "Fourth"); System.out.println(map); String mapString = map.get("US"); System.out.println("The US stands at: " +mapString); System.out.println(mapString); map.remove("Russia"); } } Output {Canada=Third, US=Second, India=First} {Canada=Third, US=Second, India=First, Russia=Fourth} The US stands at: Second Second Notes HashMap is unordered data collection. HashMap is implementation of Map. Just like ArrayList is an implementation of List. Maps are in Key, Value pairs. You can look up an item in HashMap with the help of Key.

Resizable Array in Java with ArrayList

Understanding through Code import java.util.List; import java.util.ArrayList; public class ArrayListDemo { public static void main( String[] args ){ List<String> list = new ArrayList<>(); list.add("India"); list.add("US"); list.add("Canada"); System.out.println(list); list.add("Russia"); System.out.println(list); list.remove(1); System.out.println(list); String nation = list.get(0); System.out.println("The first nation is: " +nation); int pos = list.indexOf("Canada"); System.out.println("Canada is at: " +pos); } } Output [India, US, Canada] [India, US, Canada, Russia] [India, Canada, Russia] The first nation is: India Canada is at: 1 Notes Collection framework is a set of interfaces or classes that make management of data easy. The two most commonly used frameworks are: ArrayList and HashMap. <String> is ... Read more

Passing Arguments in Java

Passing Values to Methods Passing to a method by copy The method receives a copy of variable. Passing to a method by reference. The method receives a reference to the original object. That is, any changes made to the object within the method will be reflected outside the method In Java, variables are always passed by copy Passing Primitive Values void incValue( int i ) { i++; System.out.println("Inside method values of i is: " +i); } int iOriginal = 10; System.out.println("iOriginal before: " +iOriginal); incValue(iOriginal); System.out.println("Original after: " +iOriginal); After running the above pseudo code we find that: Original before: ... Read more

Method Overloading in Java

Functions are called methods in Java You can create a number of methods with same name in Java. But, you must distinguish them by: Number of arguments Arguments data type Understanding through Code import java.util.Scanner; public class MethodOverloading { public static void main( String[] args ){ String s1 = getInput("Enter value 1: "); String s2 = getInput("Enter value 2: "); String s3 = getInput("Enter value 3: "); double result = addValues(s1, s2); System.out.println("The answer is: " +result); double result1 = addValues(s1, s2, s3); System.out.println("The answer for 3 values is: " +result1); double result2 = addValues(s1, s2, s3, s1, s2, s3); ... Read more

Try and Catch in Java

Exception When your code can throw an exception (error on run time), you can wrap that code in try and catch block. Example: ArrayIndexOutOfBoundsException Code public class TryAndCatch { public static void main( String[] args ){ String str = "Hello"; char[] charArr = str.toCharArray(); try { char lastChar = charArr[charArr.length]; System.out.println(lastChar); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); //System.out.println("Index number out of scope"); } } } Output java.lang.ArrayIndexOutOfBoundsException: 5 at TryAndCatch.main(TryAndCatch.java:8) Multiple Catch Blocks public class TryAndCatch { public static void main( String[] args ){ String str = "Hello"; char[] charArr = str.toCharArray(); try { char lastChar = charArr[charArr.length - 1]; System.out.println(lastChar); ... Read more

Date and Time in Java

Understanding through code import java.text.DateFormat; import java.time.LocalDateTime; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.GregorianCalendar; public class DateTime { public static void main( String[] args ){ Date date = new Date(); System.out.println(date); GregorianCalendar gc = new GregorianCalendar(2010, 5, 15); gc.add(GregorianCalendar.DATE, 1); Date date1 = gc.getTime(); System.out.println(date1); DateFormat df = DateFormat.getDateInstance(DateFormat.FULL); System.out.println(df.format(date1)); LocalDateTime ldt = LocalDateTime.now(); System.out.println(ldt); LocalDate ld = LocalDate.of(2010, 5, 15); System.out.println(ld); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy"); System.out.println(dtf.format(ld)); } } Output Mon May 01 00:47:49 IST 2017 Wed Jun 16 00:00:00 IST 2010 Wednesday, 16 June, 2010 2017-05-01T00:47:50.722 2010-05-15 5/15/2010 Notes Date API is the first API for date and ... Read more

String Operations in Java

Understanding through Code public class StringOps { public static void main( String[] args ){ String str1 = "Hello this is AI talking."; System.out.println("Length of string: " +str1.length()); System.out.println("Position (Index) of substring: " +str1.indexOf("AI")); String substr = str1.substring(14); //for verification System.out.println(substr); String str2 = "Aloha "; //string with spaces System.out.println("Length of string with spaces: " +str2.length()); String str3 = str2.trim(); //removes whitespace System.out.println(str3.length()); } } Output Length of string: 25 Position (Index) of substring: 14 AI talking. Length of string with spaces: 15 5  

String Builder

Why String Builder? public class StringBuild { public static void main( String[] args ){ String str1 = "Hi"; String str2 = "There"; String str3 = str1 + ", " +str2 + "!"; } } The above code introduces 3 different string objects. This leads to unnecessary memory consumption due to the multiple object creation. At such point you should use StringBuilder public class StringBuild { public static void main( String[] args ){ String str1 = "Hi"; String str2 = "There"; String str3 = str1 + ", " +str2 + "!"; StringBuilder sb = new StringBuilder("Hi"); sb.append(", "); sb.append("There"); sb.append("!"); System.out.println(sb); ... Read more

Primitive Values to Strings in Java

Understanding through Code import java.text.NumberFormat; public class PrimitiveToString { public static void main( String[] args ){ int intVal = 24; String intToStr = Integer.toString(intVal); System.out.println(intToStr); boolean boolVal = true; String boolToStr = Boolean.toString(boolVal); System.out.println(boolToStr); long longVal = 12_400; NumberFormat formatter = NumberFormat.getNumberInstance(); String longValFormatted = formatter.format(longVal); System.out.println(longValFormatted); } } Output 24 true 12,400 Notes 12_400 is same as 12400 for the compiler. The underscore helps to make it more readable. Using underscore as separators was introduced in Java V7. NumberFormat is part of different package and not java.lang. So we need to import the package.

Objects And Strings In Java

About Objects Object in Java is an instance of a Java class. When you create a variable and point it at an object. The variable isn’t the object itself, instead it is just a reference to the object Non-primitive variables are references to objects. Objects can have multiple references. That is, they point to single object. For instance, in memory some values assigned to that object changes. This value change is reflected in all of its references. Example public class ObjectInJavaExample { public String color; public static void main( String[] args ){ ObjectInJavaExample candy = new ObjectInJavaExample(); candy.color = "Red"; ... Read more