Friday, 2 September 2022

Convert an integer to string in Java

In this post, I am going to explain different ways to convert an Integer object to String in Java.

 

Approach 1: Using toString() method.

String str1 = i1.toString();

 

Approach 2: Using String.valueOf method.

String str2 = String.valueOf(i1);

 

Approach 3: Concatenate int value to an empty string.

String str3 = i1.intValue()+"";

 

Approach 4: Using StringBuilder.

String str4 = new StringBuilder().append(i1).toString();

 

Approach 5: Using StringBuffer.

String str5 = new StringBuffer().append(i1).toString();

 

Find the below working application.

 

IntegerToStringDemo.java

package com.sample.app.strings;

public class IntegerToStringDemo {

    public static void main(String[] args) {
        Integer i1 = 234;

        String str1 = i1.toString();
        String str2 = String.valueOf(i1);
        String str3 = i1.intValue() + "";

        String str4 = new StringBuilder().append(i1).toString();
        String str5 = new StringBuffer().append(i1).toString();

        System.out.println("str1 : " + str1);
        System.out.println("str2 : " + str2);
        System.out.println("str3 : " + str3);
        System.out.println("str4 : " + str4);
        System.out.println("str5 : " + str5);
    }

}

 


Output

str1 : 234
str2 : 234
str3 : 234
str4 : 234
str5 : 234

 

 

Previous                                                 Next                                                 Home

String slicing in Java

String slicing is about fetching a sub string from given string. Java String class provides subString method to fetch a sub string from given string.

 

subString method is available in below overloaded forms.

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

 

Get the substring from starting index

‘substring(int beginIndex)’ method returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. Here the beginIndex is inclusive.

String str1 = "hello world";
String subStr1 = str1.substring(6); // Return 'world'

 

'subString' method throws StringIndexOutOfBoundsException, if beginIndex is negative or larger than the length of this String object.

 

Get the substring between start and end indexes

‘substring(int beginIndex, int endIndex)’ method returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. Here the the beginning index is inclusive and endIndex is exclusive.

 

String str2 = "Java is a high level programming language";
String subStr2 = str2.substring(10, 14); // Return 'high'

'subString' method throws StringIndexOutOfBoundsException, if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

 

Find the below working application.

 

SubStringDemo1.java

package com.sample.app.strings;

public class SubStringDemo1 {

	public static void main(String[] args) {
		String str1 = "hello world";
		String subStr1 = str1.substring(6); // Return world

		System.out.println("str1 : " + str1);
		System.out.println("subStr1 : " + subStr1);

		// Throws StringIndexOutOfBoundsException if beginIndex is negative or larger
		// than the length of this String object
		try {
			str1.substring(-1);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}

		try {
			str1.substring(100);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}

		String str2 = "Java is a high level programming language";
		String subStr2 = str2.substring(10, 14); // Return 'high'

		System.out.println("\nstr2 : " + str2);
		System.out.println("subStr2 : '" + subStr2 + "'");

		// throws StringIndexOutOfBoundsException, if the beginIndex is negative, or
		// endIndex is larger than the length of this String object, or beginIndex is
		// larger than endIndex.
		try {
			str2.substring(-1, 5);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}

		try {
			str2.substring(5, 100);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}

		try {
			str2.substring(5, 1);
		} catch (StringIndexOutOfBoundsException e) {
			System.err.println(e);
		}
	}

}

 


Output

str1 : hello world
subStr1 : world
java.lang.StringIndexOutOfBoundsException: begin -1, end 11, length 11
java.lang.StringIndexOutOfBoundsException: begin 100, end 11, length 11

str2 : Java is a high level programming language
subStr2 : 'high'
java.lang.StringIndexOutOfBoundsException: begin -1, end 5, length 41
java.lang.StringIndexOutOfBoundsException: begin 5, end 100, length 41
java.lang.StringIndexOutOfBoundsException: begin 5, end 1, length 41

 

References

https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/String.html

 

Previous                                                 Next                                                 Home

Hive: bin: Return number in binary format

Signature

bin(n)

 

hive> SELECT * FROM emp;
OK
emp.id	emp.name	emp.hobbies	emp.technology_experience	emp.gender_age	emp.rating
1	Hari	["Football","Cricket"]	{"Java":"3.4Yrs","C":"4.5Yrs"}	{"gender":"Male","age":30}	-1.5
2	Chamu	["Trekking","Watching movies"]	{"Selenium":"5.6Yrs"}	{"gender":"Feale","age":38}	3.0
3	Sailu	["Chess","Listening to music"]	{"EmbeddedC":"9Yrs"}	{"gender":"Femle","age":32}	2.5
4	Gopi	["Cricket"]	{"Datastage":"11Yrs"}	{"gender":"Male","age":32}	-0.7
Time taken: 0.052 seconds, Fetched: 4 row(s)
hive> ;
hive> ;
hive> SELECT name,gender_age.age,bin(gender_age.age) from emp;
OK
name	age	_c2
Hari	30	11110
Chamu	38	100110
Sailu	32	100000
Gopi	32	100000
Time taken: 0.054 seconds, Fetched: 4 row(s)

 

Previous                                                    Next                                                    Home

Atlas client: Create glossary

AtlasClientV2 provides 'createGlossary' method to create a glossary.

 

Signature

public AtlasGlossary createGlossary(AtlasGlossary glossary) throws AtlasServiceException

 

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

 

JsonUtil.java

package com.sample.app.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonUtil {
	public static String marshal(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}

	public static <T> T unmarshal(Class<T> clazz, String json)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (T) mapper.readValue(json, clazz);
	}

	public static String prettyPrintJson(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
		return mapper.writeValueAsString(obj);
	}
}

 

CreateGlossary.java

package com.sample.app.glossary;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.glossary.AtlasGlossary;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sample.app.util.JsonUtil;

public class CreateGlossary {

	public static void main(String[] args) throws AtlasServiceException, JsonProcessingException {
		AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
				new String[] { "admin", "admin" });

		AtlasGlossary atlasGlossary = new AtlasGlossary();
		atlasGlossary.setName("myGlosary1");
		atlasGlossary.setShortDescription("Demo Glossary");
		atlasGlossary.setLongDescription("Demo GLossary.......");

		AtlasGlossary persistedGlossary = atlasClient.createGlossary(atlasGlossary);

		System.out.println(JsonUtil.prettyPrintJson(persistedGlossary));

	}
}

Output

{
  "guid" : "c71a18b9-9f24-4451-8acc-a9a4d55cf1a0",
  "qualifiedName" : "myGlosary1",
  "name" : "myGlosary1",
  "shortDescription" : "Demo Glossary",
  "longDescription" : "Demo GLossary......."
}

You can confirm the same by login to Atlas UI.


      Create a glossary category
      Create glossary term
      Get All glossaries
      Get the glossary by guid
      Get Detailed Glossary including terms and categories
      Get glossary term by guid
      Get the terms in a glossary
      get term headers in a glossary
      Get glossary category by id
      Get all the categories in a glossary by glossary id
      Get glossary category headers in a glossary by glossary id
      Get terms in a category
      Get related terms of this term
      Update glossary by id
      Partial or patch update of glossary by id
      Update glossary term by id
      Partial or patch update of term by id
      Update glossary category by id
      Partial or patch update of glossary category
      Delete glossary by id
      Delete glossary term by id
      Delete glossary category by id
      Get entities assigned with a term
      Assign term to entities
      detach or remove term from an entity

Previous                                                    Next                                                    Home

Hive: atan(n): Return arc tangent of a number

Signature

atan(n)

 

hive> SELECT atan(109);
OK
_c0
1.5616222722497866
Time taken: 0.049 seconds, Fetched: 1 row(s)

 

 

Previous                                                    Next                                                    Home

Atlas Client : Faceted search on entity attributes

By supplying entity filters, we can perform search on entity attirbutes.

 

Example

SearchParameters searchParameters = new SearchParameters();
searchParameters.setTypeName("DataSet");
searchParameters.setOffset(0);
searchParameters.setLimit(10);

SearchParameters.FilterCriteria attributeFilter = new SearchParameters.FilterCriteria();
attributeFilter.setAttributeName("name");
attributeFilter.setAttributeValue("Attr");
attributeFilter.setOperator(org.apache.atlas.model.discovery.SearchParameters.Operator.STARTS_WITH);

searchParameters.setEntityFilters(attributeFilter);

AtlasSearchResult atlasSearchResult = atlasClient.facetedSearch(searchParameters);

 

Above snippet return at most 10 entities that has the name starts with Attr.

 

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

 

FacetedSearchOnAttributes.java

package com.sample.app.search;

import java.util.Arrays;
import java.util.List;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.discovery.AtlasSearchResult;
import org.apache.atlas.model.discovery.SearchParameters;
import org.apache.atlas.model.instance.AtlasEntityHeader;

public class FacetedSearchOnAttributes {

  private static void printAtlasSearchResult(AtlasSearchResult atlasSearchResult, String message) {
    System.out.println("\n" + message);
    System.out.println("________________________________________");
    List<AtlasEntityHeader> entityHeaders = atlasSearchResult.getEntities();

    for (AtlasEntityHeader atlasEntityHeader : entityHeaders) {
      System.out.println("\t" + atlasEntityHeader.getAttribute("name"));
    }
  }

  public static void main(String[] args) throws AtlasServiceException {
    AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
        new String[] { "admin", "admin" });

    SearchParameters searchParameters = new SearchParameters();
    searchParameters.setTypeName("DataSet");
    searchParameters.setOffset(0);
    searchParameters.setLimit(10);

    SearchParameters.FilterCriteria attributeFilter = new SearchParameters.FilterCriteria();
    attributeFilter.setAttributeName("name");
    attributeFilter.setAttributeValue("Attr");
    attributeFilter.setOperator(org.apache.atlas.model.discovery.SearchParameters.Operator.STARTS_WITH);

    searchParameters.setEntityFilters(attributeFilter);

    AtlasSearchResult atlasSearchResult = atlasClient.facetedSearch(searchParameters);

    printAtlasSearchResult(atlasSearchResult, "Get all the first 10 in a ‘DataSet’ type");
  }
}

Sample Output

Get all the first 10 in a ‘DataSet’ type
________________________________________
  AttributeWithSetOfStrings_DEMO1
  AttributeTypeMap_DEMO1
  AttributeWithListOfStrings_DEMO1
  AttributeDefaultValue_DEMO1


Previous                                                    Next                                                    Home