Monday, 11 July 2022

Why System.out.println() is not throwing NullPointerException on null references?

If you are a Java programmer, you might have used ‘System.out.println’ method to print the string representation of an object. But did you get a doubt any time, ‘what happen when I pass a null reference to the System.out.println’ method.

 


Example 1: Print null reference string using System.out.println method.

String str = null;

System.out.println(str);

 

Example 2: Print null object using System.out.println method.

Object obj = null;

System.out.println(obj);

 

Example 2: Print null collection using System.out.println method.

List<String> list = null;

System.out.println(list);

 

In all the above cases, Java print the value "null" to the console. Let’s dig into the code and try to understand.

 

For the example 1, System.out.println is implemented like below.

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
}

 

As you observe above snippet, println(String x) internally calls the print method, which prints "null" for a null String :

 

For the example 2, and example 3 Java internally use ‘String.valueOf’ method which prints "null" for a null String. Implementation is given below.

 

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

 

String.valueOf method is implemented like below.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Find the below working application.

 

SysOutDemo.java

package com.sample.app;

import java.util.List;

public class SysOutDemo {

	public static void main(String[] args) {
		String str = null;
		System.out.println(str);

		Object obj = null;
		System.out.println(obj);

		List<String> list = null;
		System.out.println(list);

	}

}

Output

null
null
null



You may like

Interview Questions

Quick guide to generate random data in Java

What are the different cache eviction strategies?

How to call super class method from sub class overriding method?

Can an enum has abstract methods in Java?

Can enum implement an interface in Java?

What happen to the threads when main method complete execution

Sunday, 10 July 2022

Implement circular buffer using fixed length StringBuffer

Assume you have a fixed length string buffer, and implement a circular queue kind of functionality using it.

 

Example

String buffer with size 5 can hold 5 characters ABCDE, When I append new character ‘F’ to the existing string buffer, the resukting buffer should be BCDEF.

 

We can achieve this functionality using StringBuffer delete and append methods.

 

public StringBuffer delete(int start, int end)

Removes the characters in a substring of this sequence. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made.

 

public StringBuffer append(CharSequence s)

Appends the specified CharSequence to this sequence.

 

Example


 

Find the below working application.

 

CircularStringBuffer.java

package com.sample.app;

import java.util.StringJoiner;

public class CircularStringBuffer {

	private final int maxLength;
	private final StringBuffer stringBuffer;

	public CircularStringBuffer(int length) {
		if (length <= 0) {
			length = 10;
		}
		this.stringBuffer = new StringBuffer(length);

		this.maxLength = length;
	}

	void append(final String input) {
		final int bufferLength = stringBuffer.length();
		final int inputLength = input.length();

		if (bufferLength + inputLength > maxLength) {
			stringBuffer.delete(0, bufferLength + inputLength - maxLength);
		}
		stringBuffer.append(input, Math.max(0, inputLength - maxLength), inputLength);
	}

	@Override
	public String toString() {

		final StringJoiner joiner = new StringJoiner("->");

		for (char ch : stringBuffer.toString().toCharArray()) {
			joiner.add("" + ch);
		}

		return joiner.toString();
	}

}

App.java

package com.sample.app;

public class App {
	public static void main(String[] args) {
		CircularStringBuffer circularBuffer = new CircularStringBuffer(5);

		circularBuffer.append("A");
		System.out.println(circularBuffer);

		circularBuffer.append("B");
		System.out.println(circularBuffer);

		circularBuffer.append("C");
		System.out.println(circularBuffer);

		circularBuffer.append("D");
		System.out.println(circularBuffer);

		circularBuffer.append("E");
		System.out.println(circularBuffer);

		circularBuffer.append("F");
		System.out.println(circularBuffer);

		circularBuffer.append("G");
		System.out.println(circularBuffer);

		circularBuffer.append("H");
		System.out.println(circularBuffer);
	}
}

Output

A
A->B
A->B->C
A->B->C->D
A->B->C->D->E
B->C->D->E->F
C->D->E->F->G
D->E->F->G->H


Previous                                                 Next                                                 Home

Atlas Client: Specify minimum and maximum elements in a collection type

Using ‘valuesMinCount’ and ‘valuesMaxCount’ you can set the min and maximum elements in a collection.

 

Example

"attributeDefs": [
    {
      "name": "hobbies",
      "typeName": "array<string>",
      "isOptional": false,
      "cardinality": "SET",
      "valuesMinCount": 2,
      "valuesMaxCount": 5,
      "isUnique": false,
      "isIndexable": true,
      "includeInNotification": false,
      "searchWeight": -1
    }
  ],

 

Find the below working application.

 

Create atlas-application.properties file under src/main/resources folder.

 

atlas-application.properties

 

atlas.client.readTimeoutMSecs=30000
atlas.client.connectTimeoutMSecs=30000

 

Define SpecifyMinAndMaxElementsInCollection class.

 

SpecifyMinAndMaxElementsInCollection.java

package com.sample.app.attributes;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.atlas.model.typedef.AtlasTypesDef;
import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef;

import com.fasterxml.jackson.core.JsonProcessingException;

public class SpecifyMinAndMaxElementsInCollection {

  private static final String TYPE_NAME = "DemoType5";

  private static void createType(AtlasClientV2 atlasClient) throws AtlasServiceException {
    AtlasAttributeDef attributeDef1 = new AtlasAttributeDef();
    attributeDef1.setName("hobbies");
    attributeDef1.setTypeName("array<string>");
    attributeDef1.setCardinality(AtlasAttributeDef.Cardinality.SET);
    attributeDef1.setIsIndexable(true);
    attributeDef1.setIsUnique(false);
    attributeDef1.setValuesMinCount(2);
    attributeDef1.setValuesMaxCount(5);
    
    AtlasEntityDef atlasEntityDef = new AtlasEntityDef();
    atlasEntityDef.setName(TYPE_NAME);
    atlasEntityDef.setCreatedBy("Krishna");
    atlasEntityDef.setUpdatedBy("krishna");
    atlasEntityDef.setDescription("Represent a demo specification");
    atlasEntityDef.setAttributeDefs(Arrays.asList(attributeDef1));

    Set<String> superTypes = new HashSet<>();
    superTypes.add("DataSet");
    atlasEntityDef.setSuperTypes(superTypes);

    AtlasTypesDef atlasTypesDef = new AtlasTypesDef();

    atlasTypesDef.getEntityDefs().add(atlasEntityDef);

    atlasClient.createAtlasTypeDefs(atlasTypesDef);
  }

  private static void createEntity(AtlasClientV2 atlasClient) throws AtlasServiceException {

    AtlasEntity atlasEntity = new AtlasEntity();

    atlasEntity.setTypeName(TYPE_NAME);

    atlasEntity.setAttribute("hobbies", Arrays.asList("football"));

    // Following are the mandatory attributes
    atlasEntity.setAttribute("qualifiedName", "SpecifyMinAndMaxElementsInCollection_DEMO1");
    atlasEntity.setAttribute("name", "SpecifyMinAndMaxElementsInCollection_DEMO1");

    AtlasEntity.AtlasEntityWithExtInfo atlasEntityWithExtInfo = new AtlasEntity.AtlasEntityWithExtInfo();
    atlasEntityWithExtInfo.setEntity(atlasEntity);

    atlasClient.createEntity(atlasEntityWithExtInfo);
  }

  public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {

    AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
        new String[] { "admin", "admin" });

    createType(atlasClient);
    createEntity(atlasClient);

  }
}

 

 

  

Previous                                                    Next                                                    Home

HIVE: SHOW TABLES: show all the available tables

‘SHOW TABLES’ command list all the available tables to HIVE.

hive> show tables;
OK
employee
Time taken: 0.056 seconds, Fetched: 1 row(s)

 


Previous                                                    Next                                                    Home

Print all the current week dates in Java

Using ‘java.util.Calendar’ class, we can get all the current week dates in Java.

 


CurrentWeekDates.java

package com.sample.app;

import java.util.Calendar;
import java.util.Date;

public class CurrentWeekDates {

	private static void printAllCurrentWeekDates() {
		Calendar calendar = Calendar.getInstance();

		for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
			calendar.set(Calendar.DAY_OF_WEEK, i);
			System.out.println("Date " + calendar.getTime());
		}

	}

	public static void main(String[] args) {
		System.out.println("today : " + new Date() +"\n\n");
		printAllCurrentWeekDates();
	}

}

Sample Output

today : Mon Jul 11 09:56:33 IST 2022


Date Sun Jul 10 09:56:33 IST 2022
Date Mon Jul 11 09:56:33 IST 2022
Date Tue Jul 12 09:56:33 IST 2022
Date Wed Jul 13 09:56:33 IST 2022
Date Thu Jul 14 09:56:33 IST 2022
Date Fri Jul 15 09:56:33 IST 2022
Date Sat Jul 16 09:56:33 IST 2022


 

Previous                                                 Next                                                 Home

How to get current weeks Tuesday date

Following program return the current weeks Tuesday date.

 


CurrentWeekTuesdayDate.java

package com.sample.app;

import java.util.Calendar;

public class CurrentWeekTuesdayDate {

	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
		
		System.out.println("Date " + calendar.getTime());

	}

}

Output

Date Sat Jul 09 21:11:19 IST 2022


 

Previous                                                 Next                                                 Home

What happen to the threads when main method complete execution

As per Java documentation, JVM exits only when all the non-daemon threads complete their execution. Even the main method complete execution, all the non-daemon and daemon threads will continue their operations as long as, there is atleast one non-daemon thread running.

 


What is daemon thread?

Daemon threads are low priority threads, which are mainly used for background processing

 

How to make a thread Daemon?

Signature

public final void setDaemon(boolean on)

 

When you set the setDaemon to true for a thread, then it acts as a daemon thread.

 

How to know whether a thread is daemon or not

isDaemon() method returns true if this thread is a daemon thread; false otherwise.

 

Let’s experiment the same with below example.

 

DaemonThreadsDemo.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

public class DaemonThreadsDemo {

	static void sleep(int noOfSeconds) {
		try {
			TimeUnit.SECONDS.sleep(noOfSeconds);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {

		Runnable runnable1 = new Runnable() {

			int counter = 0;

			@Override
			public void run() {
				while (counter < 5) {
					counter++;
					sleep(1);
					System.out.println(Thread.currentThread().getName() + " is running");
				}

				System.out.println(Thread.currentThread().getName() + " is exiting");
			}

		};

		Runnable runnable2 = new Runnable() {

			@Override
			public void run() {
				while (true) {
					sleep(1);
					System.out.println(Thread.currentThread().getName() + " is running");
				}
			}

		};

		Thread t1 = new Thread(runnable1, "Non-Daemon thread");

		Thread t2 = new Thread(runnable2, "Daemon thread");
		t2.setDaemon(true);

		t1.start();
		t2.start();

		System.out.println("Main thread finished execution....");

	}

}

 

Output

Main thread finished execution....
Daemon thread is running
Non-Daemon thread is running
Non-Daemon thread is running
Daemon thread is running
Non-Daemon thread is running
Daemon thread is running
Non-Daemon thread is running
Daemon thread is running
Daemon thread is running
Non-Daemon thread is running
Non-Daemon thread is exiting

 

From the output, you can confirm that JVM exits as long as there is no non-daemon thread running.

 

From java doc, A program terminates all its activity and exits when one of two things happens:

 

a.   All the threads that are not daemon threads terminate.

b.   Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.

 

 

  

You may like

Interview Questions

Implement a Closeable iterator in Java

Quick guide to generate random data in Java

What are the different cache eviction strategies?

How to call super class method from sub class overriding method?

Can an enum has abstract methods in Java?

Can enum implement an interface in Java?